我应该如何检查一个数字是否在 OCaml 的列表中?

How should I check whether a number is in a list in OCaml?

为什么我的代码是错误的?

# let ls = [1;2];;

val ls : int list = [1; 2]

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

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

# inList 1 ls;;

错误:此表达式的类型为 int,但表达式应为类型 'a -> 布尔值

List.exists 的第一个参数是一个函数,如果元素是您要查找的元素,则 return 为真,否则为假。您提供的是 int 1,它不是函数。

您需要这样的函数 looking_for

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

函数 looking_for 应该 return true 如果 x 是您正在寻找的(即,如果它等于 a),否则为 false。

嗯,如你所见:

# 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