Commit abbc0f5d authored by Pietro Abate's avatar Pietro Abate

Add list library with new syntax

parent f1235de1
type t( 'a ) = [ 'a* ]
let length (l : t( 'a ) ) : Int =
let aux (l : ['a*])(res : Int) : Int = match l with
| [] -> res
| [_; rest] -> aux rest (res + 1) in
aux l 0
let hd (['a+] -> 'a) [el _*] -> el
let tl (t( 'a ) -> ['a*])
| [] -> []
| [_; rest] -> rest
let nth (l : t( 'a ))(n : Int) : 'a =
let aux (l : ['a*])(n : Int) : 'a = match l with
| [] -> raise "Failure \"List.nth\""
| [el; rest] -> if n >> 0 then aux rest (n - 1) else el in
if n << 0 then raise "Invalid_argument \"List.nth\"" else aux l n
let rev (l : t( 'a )) : t( 'a ) =
let aux (l : ['a*])(res : t('a)) : ['a*] = match l with
| [] -> res
| [el; rest] -> aux rest ([el] @ res) in
aux l []
let append (l1 : t( 'a ))(l2 : t( 'a )) : t( 'a ) = l1 @ l2
let rev_append (l1 : t( 'a ))(l2 : t( 'a )) : t( 'a ) = (rev l1) @ l2
let concat (l : [(t( 'a ))*]) : t( 'a ) =
let aux (l : [(t( 'a ))*])(res : t( 'a )) : t( 'a ) = match l with
| [] -> res
| [el; rest] -> aux rest (res @ el) in
aux l []
let flatten = concat
(* Iterators *)
let iter (f : ('a -> []))(l : t( 'a )) : [] = match l with
| [] -> []
| [el; rest] -> f el; iter f rest
let iteri (f : (Int -> 'a -> []))(l : t( 'a )) : [] =
let aux (f : (Int -> 'a -> []))(l : t( 'a ))(pos : Int) : [] = match l with
| [] -> []
| [el; rest] -> f pos el; aux f rest (pos + 1)
in
aux f l 0
let mapf (f : 'a -> 'b)(l : t( 'a )) : t( 'b ) =
let aux (f : 'a -> 'b)(l : t( 'a ))(acc : t( 'b )) : t( 'b ) = match l with
| [] -> acc
| [el; rest] -> aux f rest (acc @ [(f el)]) in
aux f l []
let mapi (f : Int -> 'a -> 'b)(l : t( 'a )) : t( 'b ) =
let aux (f : Int -> 'a -> 'b)(l : t( 'a ))(pos : Int)(acc : t( 'b )) : t( 'b ) =
match l with
| [] -> acc
| [el; rest] -> aux f rest (pos + 1) (acc @ [(f pos el)]) in
aux f l 0 []
let rev_map (f : 'a -> 'b)(l : t( 'a )) : t( 'b ) = rev (mapf f l)
(* List scanning *)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment