Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return unfiltered list if filter function results in empty list

Tags:

scala

How do I return the original, unfiltered list if calling filter on it returns an empty list and return the filtered list otherwise?

scala> val l = List(1,2,3)
scala> l.filter(_ == 4)
res1: List[Int] = List() // would like this to be List(1,2,3)
scala> l.filter(_ == 3)
res: List[Int] = List(3) // want to maintain this behavior
like image 740
mplis Avatar asked Nov 02 '22 10:11

mplis


1 Answers

Appropriate answer was already mentioned in comments. Still, if you don't want to bother with subclasses, you can write implicit for this fun:

scala> val l = List(1,2,3)
l: List[Int] = List(1, 2, 3)

scala> case class ListFilter[T](list: List[T]) {
   def filterOrSelf(f: T => Boolean) = list.filter(f) match {
      case Nil => list 
      case l => l
   }
}
defined class ListFilter

scala> implicit def toListFilter[T](list: List[T]) = ListFilter(list)
toListFilter: [T](list: List[T])ListFilter[T]

scala> l.filterOrSelf(_ == 4)
res0: List[Int] = List(1, 2, 3)

scala> l.filterOrSelf(_ == 3)
res1: List[Int] = List(3)
like image 159
Bask.ws Avatar answered Nov 08 '22 04:11

Bask.ws