Skip to content

Instantly share code, notes, and snippets.

@kig
Created October 4, 2008 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kig/14703 to your computer and use it in GitHub Desktop.
Save kig/14703 to your computer and use it in GitHub Desktop.
(*
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