Skip to content

Instantly share code, notes, and snippets.

@dagoof
Created May 31, 2018 06:30
Show Gist options
  • Save dagoof/96ebbe6fecd64f8f7256fc1eb86fed50 to your computer and use it in GitHub Desktop.
Save dagoof/96ebbe6fecd64f8f7256fc1eb86fed50 to your computer and use it in GitHub Desktop.
module Nonempty : sig
type 'a t
val init : 'a -> 'a t
val create : 'a -> 'a list -> 'a t
val head : 'a t -> 'a
val extend : 'a t -> 'a list -> 'a t
val replace: 'a t -> 'a list -> 'a t
val merge: 'a t -> 'a t -> 'a t
val of_list : 'a list -> 'a t option
val to_list : 'a t -> 'a list
val map : ('a -> 'b) -> 'a t -> 'b t
end = struct
type 'a t = Nonempty of 'a * 'a list
let create t more =
Nonempty (t, more)
let init a =
create a []
let head (Nonempty (t, more)) = t
let extend (Nonempty (t, more)) extras =
create t (more @ extras)
let replace t replacement =
create (head t) replacement
let of_list = function
| [] -> None
| t :: more -> Some (create t more)
let to_list (Nonempty (t, more)) =
t :: more
let merge a b =
extend a @@ to_list b
let map f (Nonempty (t, more)) =
create (f t) (List.map f more)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment