Skip to content

Instantly share code, notes, and snippets.

@htsign
Last active July 29, 2020 08:25
Show Gist options
  • Save htsign/3ce2229a25a972a438c0a2bf9df28f4f to your computer and use it in GitHub Desktop.
Save htsign/3ce2229a25a972a438c0a2bf9df28f4f to your computer and use it in GitHub Desktop.
module Option = struct
let bind (f : 'a -> 'b option) : 'a option -> 'b option = function None -> None | Some x -> f x
let map (f : 'a -> 'b) : 'a option -> 'b option = function None -> None | Some x -> Some (f x)
end
module Stream = struct
include Stream
let map (f : 'a -> 'b) (strm : 'a Stream.t) : 'b Stream.t =
Stream.from (fun _ ->
let x : 'a option =
try Some (Stream.next strm)
with Stream.Failure -> None
in
Option.map f x)
let filter (f : 'a -> bool) (strm : 'a Stream.t) : 'a Stream.t =
let rec aux () =
try
let x = Stream.next strm in
if f x then Some x else aux ()
with Stream.Failure -> None
in
Stream.from (fun _ -> aux ())
let take (n : int) (strm : 'a Stream.t) : 'a Stream.t =
Stream.from (fun x ->
if x >= n then None else
try Some (Stream.next strm) with Stream.Failure -> None)
end
let (%>) f g x = g (f x)
let () =
let is_even n = n mod 2 = 0 in
let double = ( * ) 2 in
Stream.from (fun n -> Some n)
|> Stream.filter is_even
|> Stream.take 5
|> Stream.map (double %> string_of_int)
|> Stream.iter print_endline
@htsign
Copy link
Author

htsign commented Jul 29, 2020

I concern about 'a Stream.t is mutable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment