KoreanFoodie's Study

OCaml Library module "List" implementation 본문

Tutorials/Ocaml

OCaml Library module "List" implementation

GoldGiver 2019. 9. 17. 20:39

These are OCaml Library module "List" implementation. Useful when we handle list data type in OCaml.

let rec length l = match l with
  | [] -> 0
  | _::t -> 1 + length t

(* tail-recursive version of length *)
let length' l =
  let rec f l result = match l with
    | [] -> result
    | _::t -> f t (result+1)
  in
  f l 0

let hd l = match l with
  | [] -> raise (Failure "hd")
  | h::_ -> h

let tl l = match l with
  | [] -> raise (Failure "tl")
  | _::t -> t

let rec nth l n =
  if n<0 then raise (Invalid_argument "Mylist.nth")
  else match l with
    | [] -> raise (Failure "nth")
    | h::t -> if n=0 then h else nth t (n-1)

let rec rev l = match l with
  | [] -> []
  | h::t -> rev t@[h]

(* tail-recursive version of rev *)
let rev' l =
  let rec f l result = match l with
    | [] -> result
    | h::t -> f t (h::result)
  in
  f l []

(* same as operator @ *)
let append l1 l2 = l1@l2

let rec append' l1 l2 = match l1 with
  | [] -> l2
  | h::t -> h::append' t l2

let rec rev_append l1 l2 = match l1 with
  | [] -> l2
  | h::t -> rev_append t (h::l2)

let rec flatten l = match l with
  | [] -> []
  | h::t -> h@flatten l

let rec iter f l = match l with
  | [] -> ()
  | h::t -> f h;iter f t

let rec map f l = match l with
  | [] -> []
  | h::t -> f h::map f t

let rev_map f l =
  let rec loop l result = match l with
    | [] -> []
    | h::t -> loop t ((f h)::result)
  in
  loop l []

let rec fold_left f a l = match l with
  | [] -> a
  | h::t -> fold_left f (f a h) t

let rec fold_right f l b = match l with
  | [] -> b
  | h::t -> f h (fold_right f t b)

let rec fol_all f l = match l with
  | [] -> true
  | h::t -> if f h then fol_all f t else false

let rec exists f l = match l with
  | [] -> false
  | h::t -> if f h then true else exists f t

let rec mem a l = match l with
  | [] -> false
  | h::t -> if a=h then true else mem a t

let rec find f l = match l with
  | [] -> raise Not_found
  | h::t -> if f h then h else find f t

let rec filter f l = match l with
  | [] -> []
  | h::t -> if f h then h::filter f t else filter f t

let partition f l =
  let rec p l (l1,l2) = match l with
    | [] -> (l1,l2)
    | h::t -> if f h then p t (h::l1, l2) else p t (l1, h::l2)
  in
  p l ([],[])
Comments