The idea of this exercise is to write functions that iterate on lists, using the fold_left
and fold_right
functions from the List
module.
-
Write a function
filter : ('a -> bool) -> 'a list -> 'a list
that takes a predicatep
(a function returning a boolean) and a listl
and returns all the elements ofl
that satisfyp
(for whichp
returnstrue
). -
Define, using
List.fold_right
, a functionpartition : ('a -> bool) -> 'a list -> 'a list * 'a list
that takes a predicatep
and a listl
, and that partitionsl
byp
. It returns a pair of two lists(lpos,lneg)
, wherelpos
is the list of all elements ofl
that satisfyp
, andlneg
is the list of all elements that do not satisfyp
.
One way of sorting a list is as follows:
- The empty list is already sorted.
- If the list
l
has a headh
and a restr
, then a sorted version ofl
can be obtained in three parts:- first a sorted version of all elements of
r
that are smaller or equal toh
, - then
h
, - then a sorted version of all elements of
r
that are greater thanh
.
- first a sorted version of all elements of
- Write a function
sort:'a list-> 'a list
that implements this algorithm, using the function partition of the previous question. This sorting algorithm is also known as Quicksort where the pivot is always the first element of the list.
let filter p l =
"Replace this string with your implementation";;
let partition p l =
"Replace this string with your implementation";;
let rec sort = function _ ->
"Replace this string with your implementation";;