我已经编写了以下Scala代码:
case class A(x: Int, out: List[Int])
def isIn: Int => List[Int] => Boolean =
x => l => l.filter { _ == x }.nonEmpty
def filterTest4: (Int, List[A]) => List[List[Int]] = (x, a) =>
for (l <- a; if (isIn(x)(l.out))) yield l.out functrion filterTest4运行得很好,但是使用了for & yield,这是我不太喜欢的,因此希望看到另一种方式。如果有人提供建设性的意见/答案,我将非常高兴。请记住,我大概3天前才开始用Scala写东西。
发布于 2017-02-15 22:28:49
我刚刚找到了map函数,它的用法如下:
def filterTest5: (Int, List[A]) => List[List[Int]] = (x, a) =>
a.filter { a2 => isIn(x)(a2.out) }.map { a2 => a2.out }我想这就足够了。
发布于 2017-02-15 23:06:59
或者,按照其他人的建议,您可以使用结合了map和filter的collect。您还可以对case类进行解构,以直接访问out。
def filterTest5: (Int, List[A]) => List[List[Int]] = (x, a) => a.collect {
case A(_, out) if isIn(x)(out) => out
}https://stackoverflow.com/questions/42252013
复制相似问题