【发布时间】:2015-11-17 21:48:07
【问题描述】:
我有一个函数,它返回一个 Either 实例,其中左侧表示异常/错误,而第二侧存储返回值。
如果 Either 实例已被实例化到 Error 分支,我想立即返回。如果实例已被 Right 实例化,我想将其包装在 Maybe 中并继续(因为它作为 Maybe 进入函数,并且只有在它是 Nothing 时才会被查找)。
这是根据我的测试用例工作的:
- isNothing 传入 :: 查找错误
- isNothing 传入 :: 查找成功
- isJust(22) 被传入(不执行查找)
代码感觉还可以,但我不认为我可能缺少 Folktale data.either 库的一些细节。
// from data.monad
const someValue = Maybe.Nothing()
// ...snip...
if (someValue.isNothing) {
// from data.either :: Either.Left | Either.Right
const possiblySomeValue = yield lookupSomeValue()
if(possiblySomeValue.isLeft) {
return possiblySomeValue
} else {
someValue = Maybe.Just(possiblySomeValue.get())
}
}
我正在将 ES6(Node 4.1)与 Folktale 结合起来:data.either 和 data.maybe。我的目标是提高我对如何以这种风格正确写作的理解
更新问题有点复杂,我背靠背独立查找,我觉得可以链接在一起:
// from data.monad
const someValue = Maybe.Nothing()
// ...snip...
if (someValue.isNothing) {
// from data.either :: Either.Left | Either.Right
const possiblySomeValue = yield lookupSomeValue()
if(possiblySomeValue.isLeft) {
return possiblySomeValue
} else {
someValue = Maybe.Just(possiblySomeValue.get())
}
}
// from data.monad
const someValue2 = Maybe.Nothing()
// ...snip...
if (someValue2.isNothing) {
// from data.either :: Either.Left | Either.Right
const possiblySomeValue2 = yield lookupSomeValue2()
if(possiblySomeValue2.isLeft) {
return possiblySomeValue2
} else {
someValue2 = Maybe.Just(possiblySomeValue2.get())
}
}
它的背靠背发生使代码超级丑陋...
【问题讨论】:
标签: javascript monads maybe either folktale