问题
I'm trying to figure out how to code this.
Implement in F# a function that tests whether an element is a member of a given list. Here is the type I want.
val memberof : ’a * ’a list -> bool when ’a : equality
Here are examples of the function in action.
memberof 1 [1;2;3];; error FS0003: This value is not a function and cannot be applied
memberof (1,[1;2;3]);; val it : bool = true
memberof (1, []);; val it : bool = false
memberof (1,[2;3;4]);; val it : bool = false
heres what i've put together...
let rec memberof l =
match (l:float) with
| a.Item(l) -> l -> bool + (memberof l)
or
let rec memberof l =
match (l:float list) with
| [] -> false
| (a:float)::b -> (a)=(memberof b)->bool
回答1:
let rec memberof (l : float list) (item : float) : bool =
match l with
| hd::tl when hd = item -> true
| hd::tl -> memberof tl item
| [] -> false
or
let rec memberof (l : float list) (item : float) : bool =
match l with
| hd::tl ->
if hd = item then
true
else
memberof tl item
| [] -> false
or
let rec memberof (l : float list) (item : float) : bool =
match l with
| [] -> false
| hd :: tl ->
hd = item
|| memberof tl item
Test cases
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
Which outputs
val test001 : bool = false
val test002 : bool = true
val test003 : bool = true
val test004 : bool = true
val test005 : bool = false
The problem with
let rec memberof l =
match (l:float list) with
| [] -> false
| (a:float)::b -> (a)=(memberof b)->bool
is that
| (a:float)::b -> (a)=(memberof b)->bool
is pulling the list apart correctly with
(a:float)::b
however
(a)=(memberof b)->bool
is not right.
With recursive functions over a list you want to pull off the head of the list and process the head. Then you want to call the function again, this time passing the tail of the list as the new list variable, e.g.
memberof tl item
Since this is a predicate, we only need to stop once we reach a desired true or false. In this example when true is found the function can end, so no need to call memberof
for the remainder of the list.
For the particular signature you requested
val memberof : item:'a * list:'a list -> bool when 'a : equality
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
来源:https://stackoverflow.com/questions/35047736/f-recursive-functions-test-whether-an-element-is-a-member-of-a-given-list