Skip to content

Instantly share code, notes, and snippets.

@igstan
Created November 26, 2022 05:13
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 igstan/9aa678bd5218faf910ff12fdc45fd9ee to your computer and use it in GitHub Desktop.
Save igstan/9aa678bd5218faf910ff12fdc45fd9ee to your computer and use it in GitHub Desktop.
module Seq = struct
include Seq
let rec fold_right : 'a Seq.t -> 'b -> ('a -> 'b Lazy.t -> 'b Lazy.t) -> 'b Lazy.t =
fun seq acc f ->
match seq () with
| Seq.Nil -> lazy acc
| Seq.Cons (a, rest) -> f a (lazy (Lazy.force (fold_right rest acc f)))
let map : ('a -> 'b) -> 'a Seq.t -> 'b Seq.t =
fun f seq ->
Lazy.force (fold_right seq Seq.empty (fun a acc ->
lazy (fun () -> cons (f a) (Lazy.force acc) ())
))
(* https://stackoverflow.com/a/15885135/58808 *)
let take : int -> 'a Seq.t -> 'a Seq.t =
fun n seq ->
Lazy.force (fold_right (zip seq (ints 0)) Seq.empty (fun (a, i) acc ->
if i = n
then lazy empty
else lazy (cons a (Lazy.force acc))
))
end
let () =
let doubled = Seq.repeat 1 |> Seq.map (fun i -> i * 2) in
let first_3 = Seq.take 3 doubled in
Seq.iter (fun i -> print_int i; print_newline ()) first_3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment