Last active
July 29, 2020 08:25
-
-
Save htsign/3ce2229a25a972a438c0a2bf9df28f4f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I concern about
'a Stream.t
is mutable.