This commit is contained in:
Rhiannon Morris 2020-12-06 11:31:27 +01:00
parent a2030efaca
commit 58db497e5d
2 changed files with 19 additions and 18 deletions

30
seq.ml
View File

@ -1,33 +1,34 @@
include Stdlib.Seq
type 'a span = Empty_seq | Span of 'a list * 'a t
let for_all p = fold_left (fun acc x -> acc && p x) true
let exists p = fold_left (fun acc x -> acc || p x) false
let span' p seq =
let rec go acc = function
| Nil -> begin
match acc with
| [] -> Empty_seq
| _::_ -> Span (List.rev acc, empty)
| [] -> None
| _::_ -> Some (List.rev acc, empty)
end
| Cons (x, xs) ->
if p x then
go (x :: acc) (xs ())
else
Span (List.rev acc, cons x xs) in
Some (List.rev acc, cons x xs) in
go [] (seq ())
let%test_module _ = (module struct
let (@=) sp (l2, s2) =
match sp with
| Span (l1, s1) -> l1 = l2 && List.of_seq s1 = s2
| Empty_seq -> false
| Some (l1, s1) -> l1 = l2 && List.of_seq s1 = s2
| None -> false
let%test _ =
span' (fun x -> x < 4) (List.to_seq [1;2;3;4;5;6;7]) @=
([1;2;3], [4;5;6;7])
let%test _ =
span' (fun _ -> true) (List.to_seq []) = Empty_seq
span' (fun _ -> true) (List.to_seq []) = None
let%test _ =
span' (fun x -> x < 0) (List.to_seq [1;2;3;4;5;6;7]) @=
@ -36,9 +37,7 @@ end)
let break' p = span' (Fun.negate p)
let from_span = function
| Empty_seq -> [], empty
| Span (lst, seq) -> lst, seq
let from_span = Option.value ~default:([], empty)
let span p seq = from_span (span' p seq)
let break p seq = from_span (break' p seq)
@ -51,12 +50,13 @@ let rec drop_while p seq =
if p x then drop_while p xs else cons x xs
let chunks ~sep =
unfold (fun seq ->
match break' sep seq with
| Empty_seq -> None
| Span (lst, seq) -> Some (lst, drop_while sep seq))
let drop_snd (lst, seq) = lst, drop_while sep seq in
unfold (fun seq -> break' sep seq |> Option.map drop_snd)
let line_chunks' = chunks ~sep:(fun s -> s = "")
let is_space c = c = ' ' || c = '\t' || c = '\n'
let all_space str = String.to_seq str |> for_all is_space
let line_chunks' = chunks ~sep:all_space
let line_chunks ?(join=" ") seq = map (String.concat join) (line_chunks' seq)
let%test_module _ = (module struct

View File

@ -1,9 +1,10 @@
include module type of Stdlib.Seq
type 'a span = Empty_seq | Span of 'a list * 'a t
val for_all: ('a -> bool) -> 'a t -> bool
val exists: ('a -> bool) -> 'a t -> bool
val span': ('a -> bool) -> 'a t -> 'a span
val break': ('a -> bool) -> 'a t -> 'a span
val span': ('a -> bool) -> 'a t -> ('a list * 'a t) option
val break': ('a -> bool) -> 'a t -> ('a list * 'a t) option
val span: ('a -> bool) -> 'a t -> 'a list * 'a t
val break: ('a -> bool) -> 'a t -> 'a list * 'a t