Exercise : Lists.
- Write a function switch with type α list → α list which switches the 1st and 2nd elements of the list, the 3rd and 4th elements, the 5th and 6th elements, and so on.
switch []
[] switch [1]
[1] switch [1 ; 2]
[2 ; 1] switch [1 ; 2 ; 3]
[2 ; 1 ; 3] switch [1 ; 2 ; 3 ; 4]
[2 ; 1 ; 4 ; 3] switch [1 ; 2 ; 3 ; 4 ; 5]
[2 ; 1 ; 4 ; 3 ; 5] switch [1 ; 2 ; 3 ; 4 ; 5 ; 6]
[2 ; 1 ; 4 ; 3 ; 6 ; 5] - Write a function unpair with type (α × α) list → α list which returns all elements of a list of pairs.
unpair []
[] unpair [ (3,4) ]
[3 ; 4] unpair [ (3,4) ; (10,11) ]
[3 ; 4 ; 10 ; 11] unpair [ (3,4) ; (10,11) ; (20,30) ]
[3 ; 4 ; 10 ; 11 ; 20 ; 30] - Write a function remove_succ with type int list → int list which removes all elements x if the following element is x+1.
remove_succ []
[] remove_succ [ 10 ]
[ 10 ] remove_succ [ 10 ; 20 ]
[ 10 ; 20 ] remove_succ [ 10 ; 20 ; 21 ]
[ 10 ; 21 ] remove_succ [ 10 ; 20 ; 21 ; 22 ; 23 ; 24; 100 ; 101 ; 110 ]
[ 10 ; 24 ; 101 ; 110 ] remove_succ [ 20 ; 21 ; 22 ; 21 ; 22 ; 23 ]
[ 22 ; 23 ] - Write a function combine with type α list → β list → (α × β) list which makes a list of pairs from two lists having the same size. Raise an exception with
failwith
if the lists have different sizes.combine [ 10 ; 20 ; 30 ] [ 4 ; 5 ; 6 ]
[ (10, 4) ; (20, 5) ; (30, 6) ] combine [ 10 ; 20 ; 30 ] [ 4 ; 5 ; 6 ; 9 ]
Failure "..." - Write a function keep with type α list → bool list → α list taking two lists of the same length and which keeps only the elements of the first list for which the corresponding boolean is true in the second list. It fails if the lists have different lengths.
keep [ 1 ; 2 ; 3 ; 4 ; 5 ] [ true ; true ; false ; false ; false ]
[ 1 ; 2 ] keep [ 1 ; 2 ; 3 ; 4 ; 5 ] [ false ; false ; false ; false ; false ]
[] keep [ 1 ; 2 ; 3 ; 4 ; 5 ] [ false ; true ; false ; true ; false ]
[ 2 ; 4 ] - Write a function map2 with type (α → β → γ) → α list → β list → γ list which takes a two-argument function and two lists of the same length, and applies the function with one argument taken from each list. It fails if the lists have different lengths.
map2 (-) [ 100 ; 200 ; 300] [ 1 ; 2 ; 3 ]
[99 ; 198 ; 297] map2 (fun a b -> a ^ string_of_int b) [ "AA" ; "BB" ] [ 20 ; 30 ]
[ "AA20" ; "BB30" ] - Write a function interleave with type α list → α list → α list which builds a new list by taking alternatively an element from each list. It does not fail if the lists have different sizes.
interleave [ 10 ] [ 1 ; 2 ; 3 ; 4 ]
[10 ; 1 ; 2 ; 3 ; 4] interleave [ 10 ; 20 ; 30 ; 40 ] [ 1 ; 2 ; 3 ; 4 ; 5 ]
[10 ; 1 ; 20 ; 2 ; 30 ; 3 ; 40 ; 4 ; 5] interleave [] [ 1 ; 2 ; 3 ; 4 ; 5 ]
[1 ; 2 ; 3 ; 4 ; 5]