## Ex 1.2 ```Ocaml # let sum n = if n < 0 then invalid_arg "n<0" else let rec sumrc n = if n=0 then 0 else n + sum(n-1) in sumrc n;; val sum : int -> int = (*Correction*) let sigma f n = if n<0 then invalid_arg "n<0" else let rec sig = function | 0 -> f0 | n -> fn + sig (n-1) in sig n;; val sigma: (int -> int) -> int -> int = ``` ## Ex 2.1 ``` # let rec map f = function | [] -> [] |e::t -> f e::map f t ;; val map : ('a -> 'b) -> 'a list -> 'b list = ``` ## Ex 2.2 ``` # let rec for_all p = function | [] -> true | e::t -> p e && for_all p t;; val for_all: ('a -> bool) -> 'a list -> bool = ``` ## Ex 2.3 ``` # let rec exists p = function | [] -> true | e::t -> p e || for_all p t;; val exists: ('a -> bool) -> 'a list -> bool = ``` ## Ex 2.4 ``` # let rec find p = function | [] -> true | e::t -> if p e then e else find p t;; val exists: (bool -> bool) -> bool list -> bool = ``` ## Ex 2.5 ```Ocaml # let rec filter p : function | [] -> [] | e::t -> if p e then e::filter p t else filter p t;; val filter: ('a -> bool) -> 'a list -> 'a ``` ## Ex 2.6 ```Ocaml let rec partition p l = match l with | [] -> ([], []) | h==t> let (l1, l2) = partition p t in if p h then (h::l1,l2) else (l1, h::l2);; val partition : ('a -> bool) -> 'a list -> 'a list * 'a list = ``` ## Ex 2.7 ``` # let less2 p k l1 l2 = if k < 0 then invalid_arg "k needs to be positive" else let rec less p k l1 l2 acc = match (l1, l2) with | ([],[]) -> acc < k | (e::t, e::t2) -> if p e e2 then less p k t t2 (acc + 1) else less p k t t2 acc in less p k l1 l2 0;; val less2 : ('a -> 'b -> bool) -> int -> 'a list -> 'b list -> bool =