-
-
Save susisu/82613db613ebb53c2249e4a0d8abac17 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
module Iterator: sig | |
type 'a t | |
val next: 'a t -> 'a option | |
end = struct | |
type 'a t | |
type 'a res = { | |
_done: bool [@bs.as "done"]; | |
value: 'a; | |
} [@@bs.deriving abstract] | |
external _next: 'a t -> 'a res = "next" [@@bs.send] | |
let next iter = | |
let x = _next iter in | |
if _doneGet x then None else Some (valueGet x) | |
end | |
module type Iterable = sig | |
type ('a, 'b) t | |
type ('a, 'b) value | |
val iterator: ('a, 'b) t -> ('a, 'b) value Iterator.t | |
end | |
module Iteration (I: Iterable): sig | |
val iterate: ('a, 'b) I.t -> f:(('a, 'b) I.value -> unit) -> unit | |
end = struct | |
let iterate iterable ~f = | |
let iterator = I.iterator iterable in | |
let rec loop () = | |
match Iterator.next iterator with | |
| Some x -> f x; loop () | |
| None -> () | |
in loop () | |
end | |
module Array = struct | |
module Iterable: Iterable with type ('a, 'b) t = 'b array and type ('a, 'b) value = 'b = struct | |
type ('a, 'b) t = 'b array | |
type ('a, 'b) value = 'b | |
let iterator = [%raw {| x => x[Symbol.iterator]() |}] | |
end | |
include Iteration (Iterable) | |
end | |
module String = struct | |
module Iterable: Iterable with type ('a, 'b) t = string and type ('a, 'b) value = string = struct | |
type ('a, 'b) t = string | |
type ('a, 'b) value = string | |
let iterator = [%raw {| x => x[Symbol.iterator]() |}] | |
end | |
include Iteration (Iterable) | |
end | |
module Map = struct | |
type ('k, 'v) map | |
module Iterable: Iterable with type ('a, 'b) t = ('a, 'b) map and type ('a, 'b) value = 'a * 'b = struct | |
type ('a, 'b) t = ('a, 'b) map | |
type ('a, 'b) value = 'a * 'b | |
let iterator = [%raw {| x => x[Symbol.iterator]() |}] | |
end | |
include Iteration (Iterable) | |
end | |
let () = | |
Array.iterate [|1; 2; 3|] ~f:(fun n -> | |
Js.log (n + 1) | |
) | |
let () = | |
Array.iterate [|"foo"; "bar"; "baz"|] ~f:(fun msg -> | |
Js.log (msg ^ "!") | |
) | |
let () = | |
String.iterate "nya" ~f:(fun c -> | |
Js.log (c ^ "?") | |
) | |
let () = | |
let m: (string, int) Map.map = [%raw {| | |
new Map([ | |
["foo", 1], | |
["bar", 2], | |
]) | |
|}] in | |
Map.iterate m ~f:(fun (k, v) -> | |
Js.log (k ^ " -> " ^ (string_of_int v)) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment