Skip to content

Instantly share code, notes, and snippets.

@rizo
Last active July 7, 2020 00:53
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 rizo/8797f4da6815b6535d032499c7cb6078 to your computer and use it in GitHub Desktop.
Save rizo/8797f4da6815b6535d032499c7cb6078 to your computer and use it in GitHub Desktop.
type ('a,'r) iter =
| Done of 'r
| Cont of ('a option -> ('a,'r) iter)
let head = let k x = Done x in Cont k
let len () =
let rec k acc x =
match x with | Some _ ->
Cont (k (1 + acc)) | None -> Done acc in
Cont (k 0)
let rec el xs i =
match i with
| Done r -> r
| Cont k ->
(match xs with
| [] ->
(match k None with
| Done r -> r
| _ -> failwith "protocol")
| x::xs -> el xs (k (Some x)))
let () = Js.log (el [1; 2; 3] (len ()))
type ('a,'r) iter =
| Done of 'r
| Cont of ('a option -> 'r -> 'r * ('a,'r) iter)
type ('a,'r) ii =
{s: 'r;i:('a,'r) iter}
let len () =
let rec k x acc =
match x with
| Some _ ->
acc +1, Cont k
| None -> acc, Done acc in
{s=0;i=Cont k}
let el xs ii =
let rec go xs s i =
match i with
| Done r -> r
| Cont k ->
match xs with
| [] ->
(match k None s with
| _, Done r -> r
| _ -> failwith "protocol")
| x::xs ->
let s, i = k (Some x) s in
go xs s i in
go xs ii.s ii.i
let () = Js.log (el [1; 2; 3] (len ()))
type ('a,'r) iter =
| Done of 'r
| Cont of ('a option -> 'r -> 'r)
type ('a,'r) ii =
{s: 'r;i:('a,'r) iter}
let len () =
let k x acc =
match x with
| Some _ -> acc + 1
| None -> acc in
{s=0;i=Cont k}
let el xs ii =
let rec go xs s =
match ii.i with
| Done r -> r
| Cont k ->
match xs with
| [] -> k None s
| x::xs ->
let s = k (Some x) s in
go xs s in
go xs ii.s
let () = Js.log (el [1; 2; 3] (len ()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment