【问题标题】:OCaml expression type issueOCaml 表达式类型问题
【发布时间】:2011-11-28 11:47:14
【问题描述】:

我正在尝试制作一个 OCaml 函数,它将字符串中的 'a' 的数量添加到给定的参数中。

let rec count_l_in_word (initial : int) (word : string) : int=
    if String.length word = 0 then initial else
    if word.[0] = 'a' then 
        count_l_in_word initial+1 (Str.string_after word 1)
    else count_l_in_word initial (Str.string_after word 1)

我在第 4 行收到一条错误消息,提示“此表达式的类型为 string -> int 但此处与 int 类型一起使用”。我不知道为什么它期望表达式'count_l_in_word initial+1'是一个int。它真的应该期望整行 'count_l_in_word initial+1 (Str.string_after word 1)' 是一个 int。

谁能帮忙解决这个问题

【问题讨论】:

    标签: functional-programming ocaml currying


    【解决方案1】:
    count_l_in_word initial+1 (Str.string_after word 1)
    

    被解析为

    (count_l_in_word initial) + (1 ((Str.string_after word) 1))
    

    所以你需要添加一些括号:

    count_l_in_word (initial + 1) (Str.string_after word 1)
    

    【讨论】:

    • 谢谢,我想我必须小心优先。我让它工作了
    • IIRC 的规则是函数应用的优先级高于任何运算符。这在 FP 语言中很常见。
    • 不会被解析成(count_l_in_word initial) + (1 ((Str.string_after word) 1))吗?
    • @newacct:你是对的。我没想到解析器会生成一个以1 作为函数的函数应用程序:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多