对于Maybe.Just monad,如果我们用一个返回null的函数映射它,它仍然会返回Just with null,但我认为它应该是Nothing,否则它会失去防御null的能力。我是对的,还是有其他原因可以这样?
Maybe.fromNuallable({noname: ''}) // return Just({noname: ''})
.map(prop('name')) // return Just(undefined), but I think it should return Nothing()
.map(x=>x.length) // failed here
我检查了Maybe.map的所有实现(falktale和ramda.fantasy),它是如下:
Just.prototype.map = function(f) {
return this.of(f(this.value));
};
答案 0 :(得分:1)
好吧,我可能错了,但map
来自Functors。所以它操作简单的态射而不是kleisli箭头。您需要使用bind
和某种返回monad的函数
// maybeProp:: String -> A -> Maybe[B]
const maybeProp = name => val => Maybe.fromNullable(val[name])
Maybe
.fromNullable({noname: ''})
.bind(maybeProp('name'))
.map(x => x.length)
答案 1 :(得分:1)
以下是用于教学的 presentFilterCategories(event: Event) {
this.viewCtrl.dismiss().then(() => {
this.nav.push(CategoryPage, {
ev: event,
employeeModel: this.employeeModel,
fromSearch: true
})
});
}
(又名Maybe
)数据类型的大大简化的实现:
Option

class Option {
constructor(x) { this.x = x }
isNone() { return this.x === null || this.x === undefined }
map(f) { return this.isNone() ? this : this.of(f(this.x)) }
ap(ftor) { return this.isNone() ? this : ftor.map(this.x) }
of(x) { return Option.of(x) }
flatten() { return this.isNone() ? this : this.x }
chain(mf) { return this.isNone() ? this : this.map(mf).flatten() }
}
Option.of = x => new Option(x);
const o = new Option({}),
p = new Option({name: "foo"});
const prop = key => o => new Option(o[key]),
len = prop("length");
//
let r1 = o.map(prop("name")).map(x => x.map(len)),
r2 = p.map(prop("name")).map(x => x.map(len));
console.log(r1);
console.log(r2);
let r3 = o.chain(prop("name")).chain(len);
r4 = p.chain(prop("name")).chain(len);
console.log(r3);
console.log(r4);
和o
是p
类型并实现了仿函数,applicative functor和monad接口Option
和prop
是Kleisli箭头,即返回monad的函数(在这种情况下为len
monad)Option
)将prop
/ len
应用于o
/ p
时,会产生嵌套的{{1} } type(请参阅map
/ Option
)r1
(monadic接口)应用Kleisli箭头,这是r2
和chain
的序列(请参阅map
/ { {1}})flatten
/ r3
的函数都应返回r4
类型,以便此行为变得明确