2017-05-02 67 views
0

的第n個元素我有一個返回給定的字符串時列表的功能:OCaml的 - 故障打印一覽

let input_string_to_list input = 
    Str.split (Str.regexp "\n") input 

我也有應該返回一個列表的第n個元素的函數:

let rec get_nth = function 
    | h::_, 0 -> h 
    | h::t, n -> get_nth(t, n - 1) 
;; 

然後我試圖打印列表的第n個元素(應該是一個字符串):

print_string (get_nth (input_to_set_strings input) n) 

但是我得到這個錯誤在編譯:

Error: This expression has type string list but an expression was expected of type ('a -> 'b) list * int 

我不理解,我已經溜了,我是相當新的函數式編程,任何幫助表示讚賞,感謝。

+1

'List.nth'存在於stdlib中,順便說一句。 – gsg

回答

1

get_nth預計一個元組,而不是兩個單獨的參數,所以它應該被稱爲像

get_nth ([1;2;3;4], 2) 
你的情況

print_string (get_nth ((input_to_set_strings input), n)) 

+1

我會補充說,不安全的函數不是那種慣用的 - 你也可以定義'let get_nth ln = let rec f = function ... in f(l,n)'作爲修補程序 –

+1

@ÉtienneMillon或'let rec get_nth lst n =匹配lst,n用...',但我寧願使用'List.nth' :) – Stas