2016-10-09 94 views
3

你好,我是OCaml的新手我想了解尾遞歸的基本語法。我寫了下面的代碼,以獲得一個列表並返回包含元素及其索引的雙重列表。例如 [「b」;「c」;「dd」;] - > [(「b」,0); (「c」,1); (「DD」,2)]Ocaml類型錯誤枚舉示例

我寫了下面的代碼:

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 但預計C類名單」的表達

謝謝提前!

回答

6

問題是優先。功能應用的優先級高於任何運營商,包括::,所以這樣的:

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

被解釋爲:

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

,而你想要的是:

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

該優先發布已經到來最近反覆在這裏。 OCaml的教師應該注意;這可能需要儘早解釋。 –