Utils: add a few primitives

This commit is contained in:
Gabriel Alfour 2018-01-31 23:21:54 +01:00 committed by Benjamin Canou
parent 126df22a3f
commit aeb910b9f9
4 changed files with 21 additions and 0 deletions

View File

@ -27,6 +27,10 @@ let unopt_map ~f ~default = function
| None -> default | None -> default
| Some x -> f x | Some x -> f x
let unopt_exn err = function
| Some x -> x
| _ -> raise err
let first_some a b = match a, b with let first_some a b = match a, b with
| None, None -> None | None, None -> None
| None, Some v -> Some v | None, Some v -> Some v

View File

@ -22,6 +22,9 @@ val unopt: default:'a -> 'a option -> 'a
(** [unopt_map f d x] is [y] if [x] is [Some y], [d] if [x] is [None] **) (** [unopt_map f d x] is [y] if [x] is [Some y], [d] if [x] is [None] **)
val unopt_map: f:('a -> 'b) -> default:'b -> 'a option -> 'b val unopt_map: f:('a -> 'b) -> default:'b -> 'a option -> 'b
(** [unopt_exn exn x] is [y] if [x] is [Some y], or raises [exn] if [x] is [None] *)
val unopt_exn : exn -> 'a option -> 'a
(** First input of form [Some x], or [None] if none **) (** First input of form [Some x], or [None] if none **)
val first_some: 'a option -> 'a option -> 'a option val first_some: 'a option -> 'a option -> 'a option

View File

@ -133,3 +133,11 @@ let select n l =
| x :: xs -> loop (pred n) (x :: acc) xs | x :: xs -> loop (pred n) (x :: acc) xs
in in
loop n [] l loop n [] l
let shift = function
| [] -> []
| hd :: tl -> tl@[hd]
let rec product a b = match a with
| [] -> []
| hd :: tl -> (List.map (fun x -> (hd , x)) b) @ product tl b

View File

@ -13,6 +13,12 @@ val remove: int -> 'a list -> 'a list
(** [repeat n x] is a list of [n] [x]'s **) (** [repeat n x] is a list of [n] [x]'s **)
val repeat: int -> 'a -> 'a list val repeat: int -> 'a -> 'a list
(** [shift (hd :: tl)] computes [tl @ [hd]] *)
val shift : 'a list -> 'a list
(** [product a b] computes the cartesian product of two lists [a] and [b]. *)
val product : 'a list -> 'b list -> ('a * 'b) list
(** [take_n n l] returns the [n] first elements of [l]. When [compare] (** [take_n n l] returns the [n] first elements of [l]. When [compare]
is provided, it returns the [n] greatest element of [l]. *) is provided, it returns the [n] greatest element of [l]. *)
val take_n: ?compare:('a -> 'a -> int) -> int -> 'a list -> 'a list val take_n: ?compare:('a -> 'a -> int) -> int -> 'a list -> 'a list