commit 498263096784c9857cf714050ba9d21f81df073e Author: Simon Cruanes Date: Sun Jan 27 23:17:29 2013 +0100 sequence type diff --git a/sequence.ml b/sequence.ml new file mode 100644 index 0000000..4e0afaf --- /dev/null +++ b/sequence.ml @@ -0,0 +1,31 @@ + +(** {2 Transient iterators, that abstract on a finite sequence of elements. *) + +(** Sequence abstract iterator type *) +type 'a sequence = { + seq_fun: ('a -> unit) -> unit; +} + +(** Build a sequence from a iter function *) +let from_iter f = { + seq_fun = f; +} + +(** Consume the sequence, passing all its arguments to the function *) +let iter f seq = seq.seq_fun f + +(** Fold over elements of the sequence, consuming it *) +let fold f init seq = + let r = ref init in + seq.seq_fun (fun elt -> r := f !r elt); + !r + +(** Map objects of the sequence into other elements, lazily *) +let map f seq = + let seq_fun' k = seq.seq_fun (fun x -> k (f x)) in + { seq_fun=seq_fun'; } + +(** Filter on elements of the sequence *) +let filter p seq = + let seq_fun' k = seq.seq_fun (fun x -> if p x then k x) in + { seq_fun=seq_fun'; } diff --git a/sequence.mli b/sequence.mli new file mode 100644 index 0000000..7c4f7f4 --- /dev/null +++ b/sequence.mli @@ -0,0 +1,20 @@ + +(** {2 Transient iterators, that abstract on a finite sequence of elements. *) + +type 'a sequence + (** Sequence abstract iterator type *) + +val from_iter : (('a -> unit) -> unit) -> 'a sequence + (** Build a sequence from a iter function *) + +val iter : ('a -> unit) -> 'a sequence -> unit + (** Consume the sequence, passing all its arguments to the function *) + +val fold : ('b -> 'a -> 'b) -> 'b -> 'a sequence -> 'b + (** Fold over elements of the sequence, consuming it *) + +val map : ('a -> 'b) -> 'a sequence -> 'b sequence + (** Map objects of the sequence into other elements, lazily *) + +val filter : ('a -> bool) -> 'a sequence -> 'a sequence + (** Filter on elements of the sequence *)