# unicaml

### Site Tools

ex-l6-sol

Esercizi sulle liste:

1. .
1. .
`let length l = List.fold_right (fun a b -> 1 + b) l 0;;`
2. .
```let count el l  = List.fold_right (fun a b -> if (a = el)
then 1 + b else b) l 0;;```
3. .
`let rev l = List.fold_right (fun a b -> b@[a]) l [];;`
4. .
`let append l1 l2 = List.fold_right (fun a b -> a::b) l1 l2;;`
2. .
```let rec split n l = if n=0 then ([],l) else match l with
[] -> ([],[])
| x::xl -> let (l1,l2) = split (n-1) xl in (x::l1,l2);;

let rec merge (l1,l2) cmp = match (l1,l2) with
([],l2) -> l2
| (l1,[]) -> l1
| (x::x1,y::y2) ->
if (cmp x y < 0)
then x::(merge(x1,l2) cmp)
else y::(merge(l1,y2) cmp);;

let rec sort l cmp = match l with
[] -> []
| [x] -> [x]
| _ -> let (l1,l2) = (split ((length l) / 2) l)
in merge (sort l1 cmp,sort l2 cmp) cmp;;```
3. .

Esercizi sui tipi varianti (tagged unions):

1. .
```type 'a partial = None | Some of ('a);;
let rec fibR n = match n with
1 -> 1
|2 -> 1
|_ -> fibR (n-1) + fibR (n-2) ;;

let fib n = match n with
n when n<=0 -> None
| n -> Some (fibR n);;```
2. .
1. .
```let is_complete (Mazzo l) =
(List.length l) = 40 &&
not (dup l) &&
List.fold_right (fun x y -> (is_card_correct x) && y) l true;;```
2. .
```let seme_of_int = function
1 -> Picche
| 2 -> Cuori
| 3 -> Denari
| 4 -> Fiori
| _ -> failwith "seme_of_int: numero non gestito";;
let suitify n = List.map (fun x -> Carta(n, seme_of_int x)) (range 1 4);;
let new_mazzo = fun () ->
Mazzo (List.flatten (List.map suitify (range 1 10)));;```
3. .
```let partition (Mazzo l) =
let seme_filter s = List.filter (fun (Carta(n,x)) -> x=s) in
(Mazzo(seme_filter Picche l),
Mazzo(seme_filter Cuori l),
Mazzo(seme_filter Denari l),
Mazzo(seme_filter Fiori l));;```