Skip to content

Instantly share code, notes, and snippets.

@lilactown
Last active September 17, 2017 15:18
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 lilactown/b251c70ce370919ffe6c1bfdd47ba12d to your computer and use it in GitHub Desktop.
Save lilactown/b251c70ce370919ffe6c1bfdd47ba12d to your computer and use it in GitHub Desktop.
external _unfold : ('a => Js.t 'whatever) => 'a => stream 'b = "unfold" [@@bs.module "most"];
module Unfold = {
type t 'value 'seed =
| Value 'value 'seed
| Done;
};
external convertUnfoldValue : Js.t {. _done : bool} => Js.t {. seed : 'a, value : 'b} =
"%identity";
/* Creates a stream from a generating function and a seed */
let unfold f seed =>
_unfold
(
fun x =>
switch (f x) {
| Unfold.Done => convertUnfoldValue {"_done": true}
| Unfold.Value value seed => {"value": value, "seed": seed}
}
)
seed;
@yawaramin
Copy link

A few suggestions:

  • The callback can have the type 'a => Js.t 'whatever
  • You can use a more general casting function external cast : Js.t 'a => Js.t 'b = "%identity"; instead of convertUnfoldValue
  • In either branch of the switch, use cast to force the value to the right type
  • You can 'eta-reduce' unfold, i.e. you can get rid of the seed parameter. I.e. let unfold f seed => ... seed; is equivalent to let unfold f => ...;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment