scala - 从任一序列中只获取正确的值

标签 scala

此代码打印 List(1, 2, ())

    def f1(i:Int): Either[String,Int] = if (i > 0) Right(1) else Left("error 1") 
    def f2(i:Int): Either[String,Int] = if (i > 0) Right(2) else Left("error 2") 
    def f3(i:Int): Either[String,Int] = if (i > 0) Right(3) else Left("error 3") 

    val seq = Seq(f1(1),f2(1),f3(-1))

    val x = seq.map { f => if (f.isRight) f.right.get }
    println(x)

我需要一个由 isRight 过滤的数组为真,消除任何其他值。在上面的例子中,我需要的结果是 List(1, 2) .如何实现?

最佳答案

使用 collect和模式匹配以选择您感兴趣的案例。

seq.collect { case Right(value) => value}

让我们试穿

Scala REPL
scala> :paste
// Entering paste mode (ctrl-D to finish)

    def f1(i:Int): Either[String,Int] = if (i > 0) Right(1) else Left("error 1")
    def f2(i:Int): Either[String,Int] = if (i > 0) Right(2) else Left("error 2")
    def f3(i:Int): Either[String,Int] = if (i > 0) Right(3) else Left("error 3")

    val seq = Seq(f1(1),f2(1),f3(-1))


// Exiting paste mode, now interpreting.

f1: (i: Int)Either[String,Int]
f2: (i: Int)Either[String,Int]
f3: (i: Int)Either[String,Int]
seq: Seq[Either[String,Int]] = List(Right(1), Right(2), Left(error 3))

scala> seq.collect { case Right(value) => value }
res0: Seq[Int] = List(1, 2)

函数式编程是关于表达式而不是语句


val x = seq.map { f => if (f.isRight) f.right.get }

以下返回 Unit如果 f 不对。所以,你得到 Unit作为第三个值。
if (f.isRight) f.right.get

功能方式是使用还有其他部分。但是在这种情况下,没有有意义的 else 情况。

关于scala - 从任一序列中只获取正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49200676/

相关文章:

scala - 如何将 Akka Streams Merge 的输出通过管道传输到另一个 Flow?

scala - 如何在Slick中设置MySQL连接的socketTimeout?

mysql - join 在超过 5 个数据帧的 Spark 1.5.2 中不起作用

Scala 类型关键字 : how best to use it across multiple classes

java - Scala:检查列表是否为空

scala - Slick 3.1.1 模糊隐式值涉及过滤器和隐式 CanBeQueryCondition

scala - 使用 Scala/Apache Spark 对数据进行分组

scala - 如何知道使用 IntelliJ Idea 修改的 Scala 文件是否已保存以及是否已 checkin CVS?

Scala DSL - 嵌套 block 引用父

javascript - 创建一个 Axios 帖子以使用 Dropzone 发送上传的文件,以便 Scala 函数处理相应的请求