阅读Frisbys guide to functional programming,目前正在阅读关于Maybe的章节。在appendix中,该书建议使用folktale或fantasyland。
然而,在这两个库中,Maybe似乎并不像书中描述的那样工作。
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)在这个从书中复制的示例中,第一条语句工作正常,但第二条语句得到了一个TypeError。这似乎完全违背了Maybe的目的。还是我误解了什么?
发布于 2019-08-19 15:46:02
更新:2019年8月
很高兴你问了这个问题,我最初也对行为上的差异感到惊讶。正如其他人所回应的那样,这归结于Frisby Mostly Adequate Guide implementation的编码方式。“不规则的”实现细节与isNothing的函数实现屏蔽使用Maybe.of传入的空的或未定义的value的方式有关。
get isNothing() {
return this.$value === null || this.$value === undefined;
}如果您提到其他实现-那么使用Maybe.of()创建Maybe确实允许您传入null或undefined作为Just用例的值,并实际打印,例如Maybe.Just({ value: null })
相反,当使用民间故事时,使用Maybe.fromNullable()创建Maybe,它将根据输入的值分配一个Just或Nothing。
以下是提供的代码的工作版本:
const Maybe = require("folktale/maybe");
const {
flip,
concat,
toUpper,
path,
pathOr,
match,
prop,
add
} = require("ramda");
console.log(Maybe.of("Malkovich Malkovich").map(match(/a/gi)));
//-> folktale:Maybe.Just({ value: ["a", "a"] })
console.log(Maybe.fromNullable(null).map(match(/a/gi)));
//-> folktale:Maybe.Nothing({ })最后,这里是一个可能的演示实现,编码为使用fromNullable (类似于民间故事实现)。我从一本我认为是极力推荐的书-- Functional Programming In JavaScript by Luis Atencio中获取了这个参考实现。他花了第五章的大部分时间来清楚地解释这一点。
/**
* Custom Maybe Monad used in FP in JS book written in ES6
* Author: Luis Atencio
*/
exports.Maybe = class Maybe {
static just(a) {
return new exports.Just(a);
}
static nothing() {
return new exports.Nothing();
}
static fromNullable(a) {
return a !== null ? Maybe.just(a) : Maybe.nothing();
}
static of(a) {
return Maybe.just(a);
}
get isNothing() {
return false;
}
get isJust() {
return false;
}
};
// Derived class Just -> Presence of a value
exports.Just = class Just extends exports.Maybe {
constructor(value) {
super();
this._value = value;
}
get value() {
return this._value;
}
map(f) {
return exports.Maybe.fromNullable(f(this._value));
}
chain(f) {
return f(this._value);
}
getOrElse() {
return this._value;
}
filter(f) {
exports.Maybe.fromNullable(f(this._value) ? this._value : null);
}
get isJust() {
return true;
}
toString () {
return `Maybe.Just(${this._value})`;
}
};
// Derived class Empty -> Abscense of a value
exports.Nothing = class Nothing extends exports.Maybe {
map(f) {
return this;
}
chain(f) {
return this;
}
get value() {
throw new TypeError("Can't extract the value of a Nothing.");
}
getOrElse(other) {
return other;
}
filter() {
return this._value;
}
get isNothing() {
return true;
}
toString() {
return 'Maybe.Nothing';
}
};https://stackoverflow.com/questions/50512370
复制相似问题