Skip to content

Instantly share code, notes, and snippets.

@kevinmeredith
Created January 23, 2017 18:00
Show Gist options
  • Select an option

  • Save kevinmeredith/fec1dbad563cf5e19f12c68bb3380cc7 to your computer and use it in GitHub Desktop.

Select an option

Save kevinmeredith/fec1dbad563cf5e19f12c68bb3380cc7 to your computer and use it in GitHub Desktop.
Generic Filter?
trait Element[A, B] {
val input: A
val filteredValue: Option[B]
}
def filterFn[A, B](queryFilterValues: List[B])(implicit ev: A => Element[A, B]): List[A] => List[A] =
elements => {
queryFilterValues match {
case _ :: _ => elements.flatMap { e =>
ev(e).filteredValue match {
case Some(v) => if(queryFilterValues.contains(v) ) List(e.input) else List.empty
case None => List.empty
}
}
case Nil => elements.map(_.input)
}
}
case class Person(name: Option[String])
object Person {
implicit def personToElement(p: Person) = new Element[Person, String] {
val input = p
val filteredValue = p.name
}
}
val joe = Person( Some("joe") )
val nameFilters = List( "jane", "joe", "will" )
scala> filterFn[Person, String]( nameFilters )
res7: List[Person] => List[Person] = <function1>
scala> res7( List(joe) )
res8: List[Person] = List(Person(Some(joe)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment