Skip to content

Instantly share code, notes, and snippets.

@shajra
Created April 6, 2019 14:52
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 shajra/7b8fe5783c7500b2b4cafbec8411b815 to your computer and use it in GitHub Desktop.
Save shajra/7b8fe5783c7500b2b4cafbec8411b815 to your computer and use it in GitHub Desktop.
A OO-style encoding of sum types in Nix
let
build = match: rec {
inherit match;
map = f: match nothing (a: just(f a));
bind = f: match nothing (a: f a);
isJust = f: match false (a: true);
isNothing = f: match true (a: false);
show = match "Nothing" (a: "Just ${toString a}");
toList = match [] (a: [a]);
};
just = a: build (ifNothing: ifJust: ifJust a);
nothing = build (ifNothing: ifJust: ifNothing);
in {
inherit just nothing;
usage = {
mappingNothing =
(nothing.map (a: a + 1)).toList;
mappingJust =
((just 1).map (a: a + 1)).toList;
bindingNothing =
(nothing.bind (a: if a > 0 then just (a + 1) else nothing)).toList;
bindingJust =
((just (1)).bind (a: if a > 0 then just (a + 1) else nothing)).toList;
bindingJust' =
((just (-1)).bind (a: if a > 0 then just (a + 1) else nothing)).toList;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment