The filter Function
Learn the higher-order function abstraction filter for filtering out elements of a list based on a given predicate.
We'll cover the following...
Another crucial function abstraction is filter
. We can use it to filter out the elements of a list based on a given condition.
The filter
function on lists
Let’s write a function evens
that returns only even numbers from an integer list.
Press + to interact
(** [print_int_list] prints an integer list [l] to the console. *)let print_int_list l = print_string ("[" ^ (String.concat "; " (List.map string_of_int l)) ^ "]")(** [even x] is [true] if [x] is an even number and [false] otherwise. *)let even x = x mod 2 = 0(** [evens l] is a list all even numbers from an input list [l]. *)let rec evens l = match l with| [] -> []| hd :: tl -> if even hd then hd :: evens tl else evens tl(** Printing the result of 'evens [1; 2; 3; 4; 5]' to the console. *)let _ = print_int_list (evens [1; 2; 3; 4; 5])
We write another function, positives
, that returns only positive numbers from a list of integers.
Press + to interact
(** [print_int_list] prints an integer list [l] to the console. *)let print_int_list l = print_string ("[" ^ (String.concat "; " (List.map string_of_int l)) ^ "]")(** [positive x] is [true] if [x > 0] and [false] otherwise. *)let positive x = x > 0(** [positives l] is a list all positive numbers from an input list [l]. *)let rec positives l =match l with| [] -> []| hd :: tl -> if positive hd then hd :: positives tl else positives tl(** Printing the result of 'positives [-1; 0; 1; 2; 3]' to the console. *)let _ = print_int_list (positives [-1; 0; 1; 2; -3; 4])
Obviously, evens
and positives
share a common pattern. The real difference is the function that checks the head of the list and decides whether it belongs to the result or not. We can factor out the common pattern as a higher-order function called filter
, which accepts a ...