【问题标题】:Explanation for the implicit argument in my Ocaml code我的 Ocaml 代码中隐式参数的解释
【发布时间】:2013-12-26 11:45:02
【问题描述】:

我不理解以下 OCaml 代码,因为我不确定 extract_ident 函数在未明确指定时如何推断一元参数是 string_lexer 并且它是如何传递到 extract 中的。我知道你可以有一个没有 ma​​tch 构造的函数,模式匹配中的类型是最后一个参数,但我不明白如何将 string_lexer 参数传递给提取隐式?

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 ;;

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    答案的第一部分是currying和部分应用。当你写

    let f x y = ...
    

    那么f x 是另一个参数 (y) 的函数。

    在您的示例中,OCaml 可以推断extract_ident 的此参数的类型,因为它通过部分应用程序转发到extract,并且该函数在其cl 参数上执行cl.stringcl.current。记录标签唯一确定相应的记录类型。 (如果范围内有多个具有相同标签的记录类型,则最后一个获胜,尽管最新的 OCaml 版本为与您的示例无关的案例增加了一些额外的智能。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多