Skip to content

Instantly share code, notes, and snippets.

@idkjs
Last active February 28, 2021 20:23
Show Gist options
  • Save idkjs/165bb731de21927e82b9367e2cb45832 to your computer and use it in GitHub Desktop.
Save idkjs/165bb731de21927e82b9367e2cb45832 to your computer and use it in GitHub Desktop.
UnboxedAnyVariantConstructor
/** Compatible with OCaml standard library */
/** https://discord.com/channels/235176658175262720/235199119747055616/705145905971462275 */
module type Iter = {
type t('a);
let iter: ('a => unit, t('a)) => unit;
};
module JsIterable = {
type t('a);
type iterator('a);
type symbol;
[@bs.scope "Symbol"] [@bs.val] external iterator: symbol = "";
[@bs.get_index] external getIterator: (t('a), symbol) => (. unit) => iterator('a) = "";
[@bs.send] external next: iterator('a) => {. "_done": bool, "value": option('a) } = "";
let rec iter(iterator, f) = {
let curr = next(iterator);
if (!curr##_done) {
switch (curr##value) {
| Some(value) => f(value)
| None => ()
};
iter(iterator, f);
};
};
let iter(f, t) = {
let iterator = getIterator(t, iterator)(.);
iter(iterator, f);
};
};
[|1,2,3,4|] |> Obj.magic |> JsIterable.iter(Js.log);
@ocaml.doc(" Compatible with OCaml standard library ")
@ocaml.doc(
" https://discord.com/channels/235176658175262720/235199119747055616/705145905971462275 "
)
module type Iter = {
type t<'a>
let iter: ('a => unit, t<'a>) => unit
}
module JsIterable = {
type t<'a>
type iterator<'a>
type symbol
@scope("Symbol") @val external iterator: symbol = ""
@get_index external getIterator: (t<'a>, symbol, . unit) => iterator<'a> = ""
@bs.send
external next: iterator<'a> => {"_done": bool, "value": option<'a>} = ""
let rec iter = (iterator, f) => {
let curr = next(iterator)
if !curr["_done"] {
switch curr["value"] {
| Some(value) => f(value)
| None => ()
}
iter(iterator, f)
}
}
let iter = (f, t) => {
let iterator = getIterator(t, iterator)(.)
iter(iterator, f)
}
}
[1, 2, 3, 4] |> Obj.magic |> JsIterable.iter(Js.log)
@unboxed
type rec any = Any('a): any
let foo = input =>
switch input {
| "a" => Any(["a"])
| "b" => Any(true)
| _ => raise(Invalid_argument(input))
}
<!-- https://discord.com/channels/235176658175262720/235199119747055616/802615090876645396 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment