2015-08-24 72 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);; 
相關問題