Created
October 4, 2008 02:51
-
-
Save kig/14703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(* | |
let s = Stream.of_string "foo\nbar\nbaz" in | |
let lines = Stream.refoldl (fun s c -> if c = '\n' then Done s else Acc (s ^. c)) s in | |
Stream.iter print_string lines; | |
print_newline ();; | |
foobarbaz | |
*) | |
type 'a accum = Acc of 'a | Done of 'a | |
let some x = Some x | |
let (@.) f g x = f (g x) | |
let maybe v f x = match x with None -> v | Some y -> f y | |
let optMap f x = match x with None -> None | Some y -> Some (f y) | |
module Stream = | |
struct | |
include Stream | |
let nextOpt st = try Some (next st) with Failure -> None | |
let rec foldlB f init st = | |
match nextOpt st with | |
| None -> init | |
| Some x -> | |
begin match f init x with | |
| Acc a -> foldlB f a st | |
| Done b -> b | |
end | |
let rec foldl f init st = foldlB (fun s i -> Acc (f s i)) init st | |
let map f st = from (fun _ -> optMap f (nextOpt st)) | |
let refoldl f init st = | |
from (fun _ -> | |
match peek st with | |
| None -> None | |
| Some x -> Some (foldlB f init st)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment