user10392439
user10392439

Reputation:

Trying to write a generic filter function in Scala

The code that i have written is mentioned below

def genericFilter[A,B](f:(A) => B, list:Seq[A]):Seq[B] = {  
  for { x <- list ; if(f(x)!=false) } yield f(x)  
}

I'm trying to write the filter function but the output of the function is always yielding a Sequence like

Seq[Boolean] = List(true, true)

I'm not able to print the values of the list

Upvotes: 0

Views: 629

Answers (2)

Shankar Shastri
Shankar Shastri

Reputation: 1154

More Functional: You can use foldRight for traversing the list and filtering based on condition.

val l = List.tabulate(10)(_ + 1)
def filter[T](l: List[T])(op: T => Boolean): List[T] = {
  l.foldRight(List[T]())((b, a) => if(op(b)) b :: a else a)
}
filter(l)(_ > 3)

Upvotes: 3

mukesh210
mukesh210

Reputation: 2892

Try following:

    def genericFilter[A](f:(A) => Boolean, list:Seq[A]):Seq[A] = {
    for { x <- list ; if(f(x)) } yield x
  }

println(genericFilter((x:Int)=>x%2==0, Seq(1,2,3,4)))

It will print the list containing elements that satisfy function f.

Upvotes: 2

Related Questions