Commits

Anonymous committed cb3ab57

Added [sentinel]. Added [?x] optional argument to [limit].

Comments (0)

Files changed (2)

             | Z -> Lazy.force (flatten tl)
     end
 
-let rec limit n s =
-    if n < 0 then invalid_arg "Cf_seq.limit: n < 0";
-    lazy begin
+let limit =
+    let rec loop ?x n s =
         match Lazy.force s with
-        | P (hd, tl) when n > 0 -> P (hd, limit (pred n) tl)
-        | _ -> Z
-    end
+        | Z -> Z
+        | P (hd, tl) when n > 0 -> P (hd, lazy (loop (pred n) tl))
+        | _ ->
+            match x with
+            | None -> Z
+            | Some x -> raise x
+    in
+    fun ?x n s ->
+        if n < 0 then invalid_arg "Cf_seq.limit: n < 0";
+        lazy (loop ?x n s)
 
 let shift =
     let rec loop n = function
         if n < 0 then invalid_arg "Cf_seq.shift: n < 0";
         lazy (loop n (Lazy.force s))
 
+let rec sentinel x z =
+    lazy begin
+        match Lazy.force z with
+        | Z -> raise x
+        | P (hd, tl) -> P (hd, sentinel x tl)
+    end
+
 let reverse =
     let rec loop stack = function
         | P (hd, tl) -> loop (hd :: stack) (Lazy.force tl)
 
 (** [limit n s] returns the sequence of all the elements in [s], up to [n]
     elements in number and no more.  Raises [Invalid_argument] if [n < 0].
+    If [?x] is provided, then the exception is raised if the sequence is
+    evaluated past the limit.
 *)
-val limit: int -> 'a t -> 'a t
+val limit: ?x:exn -> int -> 'a t -> 'a t
 
 (** [shift n s] returns the sequence of all the elements in [s] after the first
     [n] elements are discarded.  Returns the empty sequence if [s] has fewer
 *)
 val shift: int -> 'a t -> 'a t
 
+(** [sentinel x s] returns a sequence identical to [s] except that [x] is raised
+    by evaluating to the end.  This is intended for use in incremental sequence
+    processing.
+*)
+val sentinel: exn -> 'a t -> 'a t
+
 (** [reverse s] evaluates the entire sequence and composes a list of the
     elements in reverse order.  Tail recursive.
 *)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.