Last active
February 25, 2019 21:08
-
-
Save Szer/ffcd576a794904d968869244b172ae38 to your computer and use it in GitHub Desktop.
This file contains 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
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