Skip to content

Instantly share code, notes, and snippets.

@hughfdjackson
Last active November 30, 2017 22:05
Show Gist options
  • Select an option

  • Save hughfdjackson/6062159 to your computer and use it in GitHub Desktop.

Select an option

Save hughfdjackson/6062159 to your computer and use it in GitHub Desktop.
// is maybe a functor if it doesn't try-catch?
// Functor law (in haskell):
fmap id = id
fmap (p . q) = (fmap p) . (fmap q)
// in js:
func.map(_.identity) === _.identity(func)
func.map(_.compose(a, b)) === func.map(b).map(a)
// consider this, though:
var unpackX = function(o){ return o.x }
var unpackY = function(o){ return o.y }
var unpackXY = _.compose(unpackY, unpackX)
unpackXY({ x: { y: 3 } }) //= 3
unpackXY('foo') //= error: undefined is not an object
// Maybe maps over an object unless it holds `null` or `undefined` - the js 'nothing' values.
// in this case, there is no try-catch gaurds in map.
Maybe('foo').map(unpackXY) //= error - undefined is not an object
Maybe('foo').map(unpackX).map(unpackY) //= no error - undefined causes a skip.
@nordfjord
Copy link
Copy Markdown

nordfjord commented Nov 30, 2017

Maybe is an abstract supertype of the types Just and Nothing and as such maybe is not a functor.

Just('foo').map(unpackXY) === Just('foo').map(unpackX).map(unpackY)
Nothing('foo').map(unpackXY) === Nothing('foo').map(unpackX).map(unpackY)

Both Just and Nothing are functors

The way you normally use Maybe is with a method like fromNullable which returns either a Just or Nothing
meaning you need to chain not map over it in order to do these multiple step procedures.

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