# unicaml

### Site Tools

ex-l5-sol
1. .
`let foo f (a,b) c = (a^"" , f a + b);;`
2. .
`let foo f g x = f x + g (x+1);;`
3. .
```let rec length l acc = match l with
[] -> acc
| hd::tl -> length tl (acc +1);;```
4. .
```let rec f l = match l with
[] -> true
| hd::[] -> true
| hd1::hd2::tl -> if (hd1>hd2) then false else f (hd2::tl);; ```
5. .
```let rec flatten l = match l with
[] -> []
| hd::tl -> hd @ flatten tl;;```
6. Senza filter
```let rec count l el = match l with
[] -> 0
| hd::tl -> (if (el=hd) then 1 else 0) + count tl el;;```

Con filter

` let count  el l = List.length (List.filter (fun x -> x = el) l);;`
7. .
```let rec nth n l = match l with
[] -> failwith "Lista troppo corta"
| hd::tl -> if n = 1 then hd else nth (n-1) tl;;```
8. .
```let rec take n l = match l with
[] -> []
| hd::tl-> if n=1 then [hd] else hd::take (n-1) tl;;```

Alternativa:

```let take n l =
List.map snd (List.filter (fun x-> (fst x)<=n) (addidx l));;```
9. .
```let rec split l = match l with
[] ->([],[])
| (a,b)::tl -> let (l1,l2) = split tl in (a::l1,b::l2);;```

Alternativa:

```let split l = (List.map fst l, List.map snd l);;
split  [("a",1);("b",2);("c",3)];;```
10. .
1. .
``` let search el l =
List.length (List.filter (fun x-> x=el) l) > 0  ;;```
2. .
```let evenidx l =
List.map snd ( List.filter (fun x-> (fst x)mod 2 = 0) (addidx l));;```
11. `'inteRevert`' inverte le cifre di un intero
```let intRevert n = if n < 10 then n
else let rec intrev n acc = if n=0  then acc
else let resto = n mod 10
in let cifra = acc*10 + resto
in intrev (n/10) cifra  in intrev n 0 ;;
let ispalindrome n = (n = intRevert n);;```

Alternativa con utilizzo delle liste: `'intToList`' trasforma un intero nella lista delle sue cifre

```let rec intToList n = if n < 10 then [n] else
let cifra = n mod 10 in  (listaCifreRec (n / 10)) @[cifra] ;;```

`'reverse`' inverte una lista

```let reverse l =
let rec reverse' l acc = match l with
[] -> acc
| hd::tl -> reverse' tl acc@[hd]
in reverse' l [];;```
```let ispalindrome n = let l = intToList n
in l = reverse l;;```