2016-09-27 84 views
0

爲什麼我的代碼錯了?我該如何檢查數字是否在OCaml的列表中?

# let ls = [1;2];;

VAL LS:INT列表= [1; 2]

# let inList a l = List.exists a l;;

VAL INLIST:( '一個 - >布爾) - >' 列表 - > BOOL =

# inList 1 ls;;

錯誤:此表達式具有int類型但一個表達 'a - > bool

回答

1

好吧,你可以看到:

# let inList a l = List.exists a l;; 

val inList : ('a -> bool) -> 'a list -> bool

所以a'a -> bool類型,這意味着a是列表中的每個元素的謂詞。

你想寫什麼

let inList a l = List.mem a l

val inList : 'a -> 'a list -> bool

TL; DR RTFM ;-) http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html

+0

就是這樣! List.mem。 –

1

List.exists的第一個參數是一個函數,如果元素是您正在查找的元素,則返回true,否則返回false。你正在提供int 1,這不是一個函數。

你需要一個功能looking_for這樣的:

let inList a l = 
    let looking_for x = ... in 
    List.exists looking_for l 

功能looking_for應該如果x是你要找的內容(即,如果它等於a),否則爲false返回true。

+0

謝謝!這有點複雜。 –

+0

在習慣了更高階的函數之後,它們是該工具包中非常有用的一部分。但是你可以使用'List.mem'來解決你的問題。它像你期待的那樣工作。 –

相關問題