Commit 72fbfebd authored by POTTIER Francois's avatar POTTIER Francois

Added [Seq.first].

parent 5f7713cb
(* Sequences with constant time concatenation and linear-time conversion
to an ordinary list. *)
(* We maintain the invariant that the left-hand side of [SConcat] is never
an empty sequence. This allows a slight improvement in [first]. *)
type 'a seq =
| SZero
| SOne of 'a
......@@ -13,7 +16,12 @@ let singleton x =
SOne x
let append xs ys =
SConcat (xs, ys)
match xs with
| SZero ->
ys
| SOne _
| SConcat _ ->
SConcat (xs, ys)
let rec elements xs accu =
match xs with
......@@ -33,3 +41,15 @@ let rec concat xss =
empty
| xs :: xss ->
append xs (concat xss)
let rec first xs =
match xs with
| SZero ->
(* We disallow applying [first] to an empty sequence. *)
assert false
| SOne x ->
x
| SConcat (xs1, _) ->
(* Our invariant guarantees [xs1] is nonempty. *)
first xs1
......@@ -8,3 +8,4 @@ val singleton: 'a -> 'a seq
val append: 'a seq -> 'a seq -> 'a seq
val elements: 'a seq -> 'a list
val concat: 'a seq list -> 'a seq
val first: 'a seq -> 'a (* sequence must be nonempty *)
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