td4
This commit is contained in:
parent
aec4f1bcce
commit
363950478d
97
td4/td4.ml
Normal file
97
td4/td4.ml
Normal file
@ -0,0 +1,97 @@
|
||||
(* Exercice 1 *)
|
||||
let rec rev_h l acc = match l with
|
||||
| [] -> acc
|
||||
| a::q -> rev_h q (a::acc)
|
||||
;;
|
||||
let rec rev l = rev_h l [];;
|
||||
|
||||
let rec for_all f l = match l with
|
||||
| [] -> true
|
||||
| a::q -> f a && for_all f q
|
||||
;;
|
||||
|
||||
let rec exists f l = match l with
|
||||
| [] -> false
|
||||
| a::q -> f a || exists f q
|
||||
;;
|
||||
|
||||
let rec mem x l = match l with
|
||||
| [] -> false
|
||||
| a::q -> a=x || mem x q
|
||||
;;
|
||||
|
||||
(* Exercice 2 *)
|
||||
let rec map f l = match l with
|
||||
| [] -> []
|
||||
| a::q -> f a::map f q
|
||||
;;
|
||||
|
||||
let rec iter f l = match l with
|
||||
| [] -> ()
|
||||
| a::q -> let () = f a in iter f q
|
||||
;;
|
||||
|
||||
let rec filter f l = match l with
|
||||
| [] -> []
|
||||
| a::q ->
|
||||
if f a then
|
||||
a::filter f q
|
||||
else
|
||||
filter f q
|
||||
;;
|
||||
|
||||
let rec fold_right f l acc = match l with
|
||||
| [] -> acc
|
||||
| a::q -> f a (fold_right f q acc)
|
||||
;;
|
||||
|
||||
let rec fold_left f acc l = match l with
|
||||
| [] -> acc
|
||||
| a::q -> fold_left f (f acc a) q
|
||||
;;
|
||||
|
||||
(* Exercice 3 *)
|
||||
let rec print_list print l =
|
||||
print_string "[";
|
||||
List.iter (fun a -> print a; print_string ",") l;
|
||||
print_string "]"
|
||||
;;
|
||||
|
||||
(* Exercice 4 *)
|
||||
let for_all f l = List.fold_left (fun acc a -> acc && f a) true l;;
|
||||
|
||||
let exists f l = List.fold_left (fun acc a -> acc || f a) false l;;
|
||||
|
||||
let mem x l = exists (fun a -> a=x);;
|
||||
|
||||
(* Exercice 5 *)
|
||||
let fact n =
|
||||
let rec l n =
|
||||
if n > 0 then
|
||||
n::l (n-1)
|
||||
else []
|
||||
in
|
||||
List.fold_left (fun acc a -> acc * a) 1 (l n)
|
||||
;;
|
||||
|
||||
(* Exercice 6 *)
|
||||
let init n f = if n = 0 then [||] else
|
||||
let res = Array.make n (f 0) in
|
||||
for i = 1 to n do
|
||||
res.(i) <- f i
|
||||
done;
|
||||
res
|
||||
;;
|
||||
|
||||
let copy t = init (Array.length t) (fun i -> t.(i));;
|
||||
|
||||
let mem x t =
|
||||
let b = ref false in
|
||||
let i = ref 0 in
|
||||
let n = Array.length t in
|
||||
while !i < n && (not !b) do
|
||||
b := t.(!i) = x;
|
||||
i := !i+1;
|
||||
done;
|
||||
!b
|
||||
;;
|
||||
Loading…
Reference in New Issue
Block a user