epicours/Algo/Courses/Chapter 7 - High Order (exercises).md

811 B

Ex 1.2

# 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 = <fun>

(*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 = <fun>

Ex 2.1

# let rec map f = function
	| [] -> []
	|e::t -> f e::map f t ;;
val map : ('a -> 'b) -> 'a list -> 'b list = <fun>

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 = <fun>

Ex 2.3

# let rec exists p = function
	| [] -> true
	| e::t -> p e || for_all p t;;
val exists: ('a -> bool) -> 'a list -> bool = <fun>