Reputation: 183
I have written the following Scala code:
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
The functrion filterTest4 works perfectly fine, however uses the for & yield, which I do not really like and thus would like to see another way. I would be very happy, if someone offered a constructive comment / answer. Please be nice and keep in mind I just started writing in Scala maybe 3 days ago.
Upvotes: 0
Views: 86
Reputation: 108159
Alternatively, as other suggested, you can use collect
, which combines map
and filter
. Also you can destructure the case class to access out
directly.
def filterTest5: (Int, List[A]) => List[List[Int]] = (x, a) => a.collect {
case A(_, out) if isIn(x)(out) => out
}
Upvotes: 1
Reputation: 183
I just found the map function, which could be used like this:
def filterTest5: (Int, List[A]) => List[List[Int]] = (x, a) =>
a.filter { a2 => isIn(x)(a2.out) }.map { a2 => a2.out }
I think that does the job.
Upvotes: 1