Skip to content

Instantly share code, notes, and snippets.

@dtipson
Created July 18, 2016 01:28
Show Gist options
  • Select an option

  • Save dtipson/3b168249cc700957e8d6c033a8bbaabe to your computer and use it in GitHub Desktop.

Select an option

Save dtipson/3b168249cc700957e8d6c033a8bbaabe to your computer and use it in GitHub Desktop.
const Nothing = new (class Nothing {
constructor() {}
ap() { return this; }
map() { return this; }
chain() { return this; }
reduce(f, x){ return x; }
getOrElse(x){ return x; }
concat(x){ return x; }
cata({Nothing}){ return Nothing(); }//this is NOT the Nothing type constructor here, btw, but a string method!
cataTap({Nothing}){ if(Nothing){ Nothing(); } return this; }
sequence(of){ return of(this); }
traverse(of){ return of(this); }
toString(){ return 'Nothing'; }
})();
@dtipson

dtipson commented Jul 18, 2016

Copy link
Copy Markdown
Author

Note that while this creates a single instance of the Nothing type (why would you ever need to create another!) doing something like Nothing instanceof Nothing obviously cannot work (the same keyword can't BOTH be the constructor AND the resulting instance).

Most implementations of the Nothing type require creating a new instance of Nothing, i.e. Nothing(), when you want to use a Nothing. Or, if you want to reuse one instance, assigning it to some other keyword, like const nothing = new Nothing()... or using a slightly different name for the constructor and avoiding the new keyword, i.e. const Nothing = x => new _Nothing()).

This version can just be (re)used immediately, retaining the main keyword and logging Nothing {} to console (useful for debugging types).

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