let rec memberof (l : float list) (item : float) : bool =
match l with
| hd::tl when hd = item -> true
| hd::tl -> memberof tl item
| [] -> false
或
let rec memberof (l : float list) (item : float) : bool =
match l with
| hd::tl ->
if hd = item then
true
else
memberof tl item
| [] -> false
或
let rec memberof (l : float list) (item : float) : bool =
match l with
| [] -> false
| hd :: tl ->
hd = item
|| memberof tl item
测试用例
let test001 = memberof [1.0; 2.0; 3.0] 0.0
printfn "test001: %A" test001
let test002 = memberof [1.0; 2.0; 3.0] 1.0
printfn "test002: %A" test002
let test003 = memberof [1.0; 2.0; 3.0] 2.0
printfn "test003: %A" test003
let test004 = memberof [1.0; 2.0; 3.0] 3.0
printfn "test004: %A" test004
let test005 = memberof [] 0.0
printfn "test005: %A" test005
哪些输出
val test001 : bool = false
val test002 : bool = true
val test003 : bool = true
val test004 : bool = true
val test005 : bool = false
问题
let rec memberof l =
match (l:float list) with
| [] -> false
| (a:float)::b -> (a)=(memberof b)->bool
是吗
| (a:float)::b -> (a)=(memberof b)->bool
用
正确地把列表分开
(a:float)::b
然而
(a)=(memberof b)->bool
不对。
使用列表上的递归函数,您想要拉出列表的头部并处理头部。然后你想再次调用该函数,这次将列表的尾部作为新的列表变量传递,例如
memberof tl item
由于这是一个predicate,我们只需要在达到所需的真或假时停止。在此示例中,当找到 true 时,函数可以结束,因此无需为列表的其余部分调用 memberof。
对于您要求的特定签名
val memberof : item:'a * list:'a list -> bool when 'a : 相等
let rec memberof ((item : 'a), (list : 'a list)) : bool when 'T : equality =
match list with
| hd::tl ->
if hd = item then
true
else
memberof (item, tl)
| [] -> false