2015-08-24 75 views
3
let rec getElement list index = match list with 
| [] -> raise OutOfBoundException 
| first::elems -> if index = 0 then first else getElement elems index-1;; 

我不明白为什么这个函数类型(INT列表 - > INT - > INT),而不是(' 列表 - > INT - >“一)。 我需要编写返回列表中第n个元素的函数,它具有泛型类型(具有由用户定义的类型exp:http://pastebin.com/UefshcLa)。ocaml的推断int类型列表,而不是 '一个列表

如何编写该功能?为什么Ocaml推断该列表是int列表而不是'列表?

+1

您还可以看看功能'nnth',它可以完成与您的功能相同的工作。 – alifirat

回答

10

OCaml解释为(getElement elems index) - 1,因为功能应用程序比-强。

let rec getElement list index = match list with 
| [] -> raise OutOfBoundException 
| first::elems -> if index = 0 then first else getElement elems (index-1);; 
相关问题