gpt4 book ai didi

scala - 将 Either 与 Scala "for"语法一起使用

转载 作者:行者123 更新时间:2023-12-03 01:20:12 25 4
gpt4 key购买 nike

据我了解,Scala“for”语法与 Haskell 的单子(monad)“do”语法极其相似。在 Scala 中,“for”语法通常用于 ListOption。我想将它与 Either 一起使用,但默认导入中不存在必要的方法。

for {
foo <- Right(1)
bar <- Left("nope")
} yield (foo + bar)

// expected result: Left("nope")
// instead I get "error: value flatMap is not a member..."

此功能可以通过某些导入来使用吗?

有一个小问题:

for {
foo <- Right(1)
if foo > 3
} yield foo
// expected result: Left(???)

对于列表,它是List()。对于Option,它将是None。 Scala 标准库是否提供了解决方案? (或者scalaz?)如何?假设我想为 Either 提供我自己的“monad 实例”,我该怎么做?

最佳答案

它在 scala 2.11 及更早版本中不起作用,因为 Either 不是 monad。尽管有人谈论右偏它,但您不能在 for-compression 中使用它:您必须获得 LeftProjectRightProjection,如下所示:

for {
foo <- Right[String,Int](1).right
bar <- Left[String,Int]("nope").right
} yield (foo + bar)

顺便说一下,它返回Left("nope")

在 Scalaz 上,您可以将 Either 替换为 Validation。有趣的事实:Either 的原作者是 Tony Morris,Scalaz 的作者之一。他想让要么偏右,但被同事说服了。

关于scala - 将 Either 与 Scala "for"语法一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10866710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com