对Ocaml代码中隐式参数的解释
我不理解下面的OCaml代码,因为我不确定extract_ident函数如何推断一元参数是string_lexer,但它没有明确指定它,以及如何将它传递到extract。我知道你可以有一个没有匹配构造的函数,模式匹配中的类型是最后一个参数,但我不明白字符串_lexer参数是如何隐式传递到提取的对Ocaml代码中隐式参数的解释,ocaml,Ocaml,我不理解下面的OCaml代码,因为我不确定extract_ident函数如何推断一元参数是string_lexer,但它没有明确指定它,以及如何将它传递到extract。我知道你可以有一个没有匹配构造的函数,模式匹配中的类型是最后一个参数,但我不明白字符串_lexer参数是如何隐式传递到提取的 type string_lexer = {string:string; mutable current:int; size:int } ;; let init_lex s = {string=s, cu
type string_lexer = {string:string; mutable current:int; size:int } ;;
let init_lex s = {string=s, current=0; size=String.length s} ;;
let forward cl = cl.current <- cl.current+1 ;;
let forward_n cl n = cl.current <- cl.current+n ;;
let extract pred cl =
let st = cl.string and pos = cl.current in
let rec ext n = if n<cl.size && (pred st.[n]) then ext (n+1) else n in
let res = ext pos in
cl.current <- res; String.sub cl.string pos (res-pos) ;;
let extract_int =
let is_int = function '0'..'9' -> true | _ -> false
in function cl -> int_of_string (extract is_int cl);;
let extract_ident =
let is_alpha_num = function
'a'..'z' | 'A'..'Z' | '0'..'9' | '_' -> true
| _ -> false
in extract is_alpha_num ;;
type string_lexer={string:string;可变电流:int;大小:int};;
让init_lex s={string=s,current=0;size=string.length s};;
向前送cl=cl电流为真
|_u->false
在摘录中是_alpha_num;;
答案的第一部分是咖喱和部分应用。当你写作时
let f x y = ...
然后,fx
是另一个参数(y
)的函数
在您的示例中,OCaml可以为extract_ident
推断此参数的类型,因为它通过部分应用程序转发到extract
,并且该函数对其cl
参数执行cl.string
和cl.current
。记录标签唯一地确定相应的记录类型。(如果范围内有多个具有相同标签的记录类型,则最后一个记录类型获胜,尽管最新的OCaml版本为与您的示例无关的情况增加了一些额外的智能性。)