Reputation: 143
I have made this code:
let rec foo1 z = function
| [] -> []
| x::xs when x = z -> x::(foo1 x xs)
| x::xs -> foo1 z xs
but I want a more complex version of this function with a new function which is of type int -> int -> bool
as first argument. This function will test the integer argument against all the elements of the list, the elements that yields true when the operator is applied should be placed in the return list
Example:
let eq x y = x = y
let lt x y = x < y
let gt x y = x > y
foo2 eq 2 [1;2;4;2;5] => [2;2]
foo2 lt 2 [1;2;4;2;5] => [4;5]
foo2 gt 2 [1;2;4;2;5] => [1]
Upvotes: 0
Views: 186
Reputation: 41290
/// Pass a function as an argument
let rec filterByVal fn z = function
| [] -> []
| x::xs when fn z x -> x::(filterByVal fn z xs)
| _::xs -> filterByVal fn z xs
/// Use anonymous functions
filterByVal (fun z x -> z = x) 2 [1;2;4;2;5] // [2; 2]
filterByVal (fun z x -> z < x) 2 [1;2;4;2;5] // [4; 5]
filterByVal (fun z x -> z > x) 2 [1;2;4;2;5] // [1]
/// Or use symbolic infix functions
filterByVal (=) 2 [1;2;4;2;5]
filterByVal (<) 2 [1;2;4;2;5]
filterByVal (>) 2 [1;2;4;2;5]
Upvotes: 4