Skip to content

Instantly share code, notes, and snippets.

@Szer
Last active February 25, 2019 21:08
Show Gist options
  • Save Szer/ffcd576a794904d968869244b172ae38 to your computer and use it in GitHub Desktop.
Save Szer/ffcd576a794904d968869244b172ae38 to your computer and use it in GitHub Desktop.
type StreamCons<'a> =
| Nil
| Cons of 'a * Stream<'a>
and Stream<'a> = Lazy<StreamCons<'a>>
let inline force (l: Lazy<_>) = l.Force()
let rec toStream l : Stream<_> =
lazy match l with
| [] -> Nil
| h::t -> Cons(h, toStream t)
let makeInfinite s : Stream<_> =
let rec inner s' =
lazy match s' with
| Lazy Nil -> inner s |> force
| Lazy (Cons (x, xs)) -> Cons(x, inner xs)
inner s
let rec skip n s : Stream<_> =
lazy match n,s with
| 0, s -> force s
| _, Lazy Nil -> Nil
| n, Lazy (Cons (_, xs)) -> skip (n-1) xs |> force
let rec take n s : Stream<_> =
lazy match n,s with
| 0, _ | _, Lazy Nil -> Nil
| n, Lazy (Cons (x, xs)) -> Cons(x, take (n-1) xs)
let rec toList s =
match s with
| Lazy Nil -> []
| Lazy (Cons (x, xs)) -> x :: toList xs
let shift n l =
l
|> toStream
|> makeInfinite
|> skip n
|> take l.Length
|> toList
shift 2 [1..5] // [3; 4; 5; 1; 2]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment