0

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]

1 Answer 1

4
/// 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]
Sign up to request clarification or add additional context in comments.

2 Comments

That I didn't know, do you know if there is any way to do the same thing but without defining the eq, lt and gt functions?
Can this only be done with integers or can it be anything else?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.