Skip to content

Instantly share code, notes, and snippets.

@getify
Last active March 3, 2023 09:23
Show Gist options
  • Save getify/2dc45c9a82cfd93358fbffd21bdd601d to your computer and use it in GitHub Desktop.
Save getify/2dc45c9a82cfd93358fbffd21bdd601d to your computer and use it in GitHub Desktop.
is Maybe a "monad?
// is Just(..) a monad? Well, it's a monad constructor.
// Its instances are certainly monads.
function Just(v) {
return { map, chain, ap };
function map(fn) {
return Just(fn(v));
}
function chain(fn) {
return fn(v);
}
function ap(monad) {
monad.map(v);
}
}
// is Nothing() a monad? Well, it's a monad constructor.
// Its instances are certainly monads.
function Nothing() {
return { map: Nothing, chain: Nothing, ap: Nothing };
}
// This is how Maybe(..) is usually implemented.
// But Maybe(..) here doesn't construct pure/valid monad instances,
// since its map() does a value-type check, which is a no-no.
function Maybe(v) {
return { map, chain, ap };
function map(fn) {
if (v == null) return Nothing();
return Just(fn(v));
}
function chain(fn) {
return fn(v);
}
function ap(monad) {
return monad.map(v);
}
}
var identity = v => v;
var prop = k => o => o[k];
var myObj = { something: { other: { and: 42 } } };
Maybe( myObj )
.map( prop("something") )
.map( prop("other") )
.map( prop("and") )
.chain( identity ); // 42
// This is a more "pure" / accurate implementation of Maybe:
// But, is Maybe here a monad? It's not even a constructor of a monad,
// it's a namespace that holds methods that can make different kinds
// of monads.
var Maybe = { Just, Nothing, of: Just };
var identity = v => v;
// we moved the empty check from Maybe into prop()
var isEmpty = v => v == null;
var prop = k => o => isEmpty(o[k]) ? Nothing() : Maybe.of(o[k]);
var myObj = { something: { other: { and: 42 } } };
Maybe.of( myObj )
.chain( prop("something") )
.chain( prop("other") )
.chain( prop("and") )
.chain( identity ); // 42
@harmenjanssen
Copy link

I find this extremely useful and I'm very happy I stumbled upon this.
I've read a lot of functional programming resources, mostly in the context of Javascript, and am still working though http://haskellbook.com/, but this is so well put it filled me up with inspiration and the sense that I get it.

Thanks a lot, @glebec!

@glebec
Copy link

glebec commented May 9, 2019

Happy to hear that @harmenjanssen.

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