繁体   English   中英

cons 运算符的 OCaml 列表问题

[英]OCaml list issue with cons operator

这是我的代码:

let rec intersection l1 l2 res = 
match l1 with
    | [] -> res
    | h1 :: t1 ->
    (
        match l2 with
        | [] -> []
        | h2 :: t2 ->
        if member h1 l2 = true then 
            intersection t1 l2 h1::res 
        else 
            intersection t1 l2 res
    )

问题在于h1::res部分,它会引发以下错误:

错误:此表达式的类型为“a 列表,但预期的表达式为“a 类型”类型变量“a”出现在“a 列表”内

但是,如果我用[h1]@res替换h1::res则代码有效,我没有得到这个问题的确切原因,请帮忙。

注意: member 是一个自定义函数,如果元素属于列表 l2,则返回 true,否则返回 false。

您的问题是intersection t1 l2 h1::res的优先级。 OCaml 正在尝试评估intersection t1 l2 h1 ,然后将其计算为res ,它是一个列表类型。 您需要手动指定运算符优先级。 你可以这样做

intersection t1 l2 (h1::res)

或者,您可以使用Pervasives 模块中应用程序运算符 如文档中所述, g @@ f @@ xg (f (x))

intersection t1 l2 @@ h1::res

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM