Reading Frisbys guide to functional programming, currently on the chapter about Maybe
. In the appendix the book suggests using either folktale or fantasyland.
However in both libraries Maybe
doesn't seem to be work as described in the book.
const Maybe = require('folktale/maybe')
// const Maybe = require('fantasy-options')
const {
flip, concat, toUpper, path, pathOr, match, prop
} = require('ramda')
console.log(
Maybe.of('Malkovich Malkovich').map(match(/a/ig))
)
// Just(['a', 'a'])
Maybe.of(null).map(match(/a/ig))
//******************************
// TypeError: Cannot read property 'match' of null
//******************************
// Nothing
Maybe.of(
{ name: 'Boris' }
).map(prop('age')).map(add(10))
// Nothing
Maybe.of(
{ name: 'Dinah', age: 14 }
).map(prop('age')).map(add(10))
// Just(24)
In this example copied from the book, the first statement works correctly, but the second gets a TypeError
. This seems to completely go against the purpose of Maybe
. Or am I misunderstanding something?
Update: August 2019
Pleased you asked this question, I was also surprised initially at the difference in behaviour. As others have responded, it comes down to the way the Frisby Mostly Adequate Guide implementation was coded. The "irregular" implementation detail is related to the way in which
isNothing
s function implementation is shielding the null or undefinedvalue
passed in usingMaybe.of
:If you refer to other implementations - then using
Maybe.of()
to create yourMaybe
does allow you to pass in anull
orundefined
for theJust
case's value and actually print for exampleMaybe.Just({ value: null })
Instead, when using Folktale, create the
Maybe
usingMaybe.fromNullable()
which will allocate aJust
orNothing
according to the value input.Here's a working version of the code provided:
Finally, here's a demonstration implementation of Maybe, codified to use
fromNullable
(similar to the Folktale implementation). I took this reference implementation from what I consider a highly recommended book - Functional Programming In JavaScript by Luis Atencio. He spends much of Chapter 5 explaining this clearly.