Folktale/Fantasyland库中Maybe未按预期工作的问题咨询
Hey there! I’ve run into this exact confusion before when jumping from Frisby’s textbook examples to real-world functional libraries—let’s break down what’s going on and fix it.
The Core Gap: Textbook vs. Library Maybe Behavior
Frisby’s custom Maybe in the book is built for teaching clarity: it automatically treats null and undefined as "missing" values. So Maybe.of(null) returns a Nothing, and calling .map() on a Nothing skips running your function entirely—no errors, just a Nothing result like you expected.
But folktale and fantasy-land-compliant Maybe types follow stricter, more precise semantics:
Maybe.of(value)(orMaybe.Just(value)) wraps any value—includingnullandundefined—into aJustinstance. These libraries seenullas a valid, present value (it’s just a null value), not a "missing" one.- A
Nothingis only created explicitly withMaybe.Nothing()(check your library’s docs for the exact syntax).
That’s why your code throws an error: Maybe.of(null) gives you a Just(null), so .map() tries to run match(/a/ig) on null—which naturally fails with a TypeError.
Fixes to Match the Book’s Example
To get the behavior Frisby demonstrates using these libraries, you need a small helper to automatically convert null/undefined to Nothing. Here’s how:
1. Create a Safe Maybe Wrapper
// Adjust syntax slightly if using an older version of folktale const safeMaybe = (value) => value == null ? Maybe.Nothing() : Maybe.Just(value);
2. Use the Wrapper Instead of Direct Maybe.of
Now this will behave exactly like the book’s examples:
safeMaybe('Malkovich Malkovich').map(str => str.match(/a/ig)); // Returns Just(['a', 'a']) as expected safeMaybe(null).map(str => str.match(/a/ig)); // Returns Nothing (no error thrown—perfect!)
Why Libraries Work This Way
Fantasy-land’s spec defines Maybe as a type for "optional presence", not "non-null values". So Just(null) means "we have a value, and that value is null", while Nothing means "there is no value at all". This is a more granular distinction than the simplified teaching implementation in Frisby’s book.
内容的提问来源于stack exchange,提问作者Bill Johnston

