Ocaml类型错误对于枚举示例

时间:2016-10-09 00:00:47

标签: f# functional-programming ocaml

您好我是OCaml的新手而且我正在尝试学习尾递归的基本语法。我编写了以下代码以获取列表并返回包含元素及其索引的双重列表。例如 [" b";" c";" dd";] - > [(" b",0); (" c",1); (" dd",2)]

我写了以下代码:

let enumerateWithTail lst =
  let rec inside lst acc index =
  match lst with
  | [] -> acc
  | x::xs -> inside xs (x,index)::acc (index+1)
 in inside lst [] 0;;

这不起作用,但我的教授的例子(至少我认为它非常相似)有效。我的教授代码是:

let enumerate lst =
  let rec aux lst acc =
    match lst with
    | [] -> acc
    | x::xs -> let (eList, index) = acc
               in aux xs ((x, index)::eList, index+1)
  in List.rev(fst(aux lst ([], 0)))

有人可以解释为什么我的代码会出错: 此表达式的类型为' a *' b        但是期望表达式类型为列表

提前致谢!

1 个答案:

答案 0 :(得分:6)

问题是优先考虑的问题。函数应用程序的优先级高于任何运算符,包括::,因此:

inside xs (x,index)::acc (index+1)

被解释为:

(inside xs (x,index)) :: (acc (index+1))

而你想要的是:

inside xs ((x,index)::acc) (index+1)
相关问题