]> matita.cs.unibo.it Git - fireball-separation.git/blob - ocaml/listx.ml
ecc8a920f1019c94abe3238780dccf21618c2473
[fireball-separation.git] / ocaml / listx.ml
1 (* Non-empty lists *)
2 type 'a listx =
3   | Nil of 'a
4   | Cons of ('a * 'a listx)
5
6 let rec fold_left f acc l =
7   match l with
8   | Nil x -> f acc x
9   | Cons (x, l') -> fold_left f (f acc x) l'
10
11 let hd =
12  function
13   | Nil x
14   | Cons (x,_) -> x
15
16 let rec map f =
17   function
18   | Nil x -> Nil (f x)
19   | Cons (x, l') -> Cons (f x, map f l')
20
21 let rec append l =
22   function
23   | Nil x -> Cons (x, l)
24   | Cons (x, l') -> Cons (x, append l l')
25
26 let rec length = function
27   | Nil _ -> 1
28   | Cons (_, xs) -> 1 + (length xs)
29
30 let rec assoc x = function
31   | Nil (y,t)
32   | Cons ((y,t),_) when x=y -> t
33   | Nil _ -> raise Not_found
34   | Cons (_,l) -> assoc x l
35
36 let rec to_list =
37  function
38     Nil x -> [x]
39   | Cons (x,l) -> x::to_list l
40
41 let rec from_list =
42  function
43     [] -> raise (Failure "from_list: empty list")
44   | [x] -> Nil x
45   | x::l -> Cons(x,from_list l)
46
47 let rec split_nth n l =
48  match n,l with
49     0,_ -> []
50  | 1,Nil x -> [x]
51  | n,Cons (hd,tl) -> hd::split_nth (n-1) tl
52  | _,_ -> raise (Failure "split_nth: not enough args")
53
54 let rec max =
55   function
56   | Nil x -> x
57   | Cons (x, l) -> Pervasives.max x (max l)
58
59 (*
60 let rec nth i l = match l, i with
61  | Cons (x, _), 1  -> x
62  | _, n when n <= 0 -> raise (Invalid_argument "Listx.nth")
63  | Cons (_, xs), n -> nth (n-1) xs
64  | Nil x, 1        -> x
65  | Nil _, _        -> raise (Invalid_argument "Listx.nth")
66 ;;
67 *)
68