Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Maybe.map是否应该尊重映射值?_Javascript_Functional Programming - Fatal编程技术网

Javascript Maybe.map是否应该尊重映射值?

Javascript Maybe.map是否应该尊重映射值?,javascript,functional-programming,Javascript,Functional Programming,对于Maybe.Just monad,如果我们用一个返回null的函数映射它,它仍然会返回null,但我认为它应该是空的,否则它就失去了保护null的能力。我是对的,还是还有其他原因 Maybe.fromNuallable({noname: ''}) // return Just({noname: ''}) .map(prop('name')) // return Just(undefined), but I think it should return Nothing() .map(x=>

对于Maybe.Just monad,如果我们用一个返回null的函数映射它,它仍然会返回null,但我认为它应该是空的,否则它就失去了保护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));
};

嗯,我可能错了,但是
map
来自函子。所以它是在简单的态射上运行的,而不是克莱斯利箭头。您需要使用
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)

下面是用于教学的
Maybe
(aka
选项
)数据类型的一个大大简化的实现:

类选项{
构造函数(x){this.x=x}
isNone(){返回this.x==null | | this.x==undefined}
map(f){返回this.isNone()?this:this.of(f(this.x))}
ap(ftor){返回this.isNone()?this:ftor.map(this.x)}
of(x){return Option.of(x)}
展平(){返回this.isNone()?this:this.x}
chain(mf){返回this.isNone()?this:this.map(mf.flatte()}
}
Option.of=x=>新选项(x);
const o=新选项({}),
p=新选项({name:“foo”});
const prop=key=>o=>new选项(o[key]),
len=道具(“长度”);
// 
设r1=o.map(prop(“name”)).map(x=>x.map(len)),
r2=p.map(prop(“name”)).map(x=>x.map(len));
控制台日志(r1);
控制台日志(r2);
设r3=o.chain(prop(“name”)).chain(len);
r4=p.链(道具(“名称”)).链(透镜);
控制台日志(r3);

控制台日志(r4)谢谢你的回答。我认为“绑定”相当于“链”(在幻想世界中定义)。“bind”对内部值应用传递函数并返回一个monad(在本例中,可能是)。因此,如果我担心函数会生成空值,我应该使用“bind”而不是“map”。@Ron right。似乎在幻想世界中定义的
链是
bind
map
aka
fmap
是不够的,因为您想要处理内部空值和未定义的ans-Maybes。所以你需要单子的全部能力来将M[M[A]]粉碎成M[A]。@LUH3417这看起来是一个有效的用例。为什么“误用”?我可能错了,但很多书都告诉我,也许/或者是处理错误/异常的功能性方法。此外,如果对象(我指的是对象{name:'john'})被传入,而我无法控制它是否是正确的方案,又如何呢。@Ron你是对的
Maybe/other
用于处理预期的异常(可能发生)。如果无法控制对象方案,则这不是运行时异常。我想我需要仔细研究一下这个问题,然后重写/删除我的答案。谢谢你的努力。我正在学习FP,它看起来很简单,但当我尝试在现实世界中使用它时,会出现很多问题。我重写了我的答案,以便更好地说明这个主题——主要是为了我自己。也许它对其他函数也有帮助。非常有帮助,谢谢,特别是最后一句话切中要害:每个可能返回null/undefined的函数都应该返回一个选项类型,以便此行为变得明确