Exercise 4.1ish - Implementing Filter with Map

16 views
Skip to first unread message

Glendon Klassen

unread,
Apr 20, 2018, 12:43:57 PM4/20/18
to scala-functional
Hi all,

I'm working through chapter 4 and have implemented filter like this:
def filter(f: A => Boolean): Option[A] = this map(f) match {
   
case Some(true) => this
   
case _ => None
 
}

but the answer key has it like this:
def filter(f: A => Boolean): Option[A] = this match {
   
case Some(a) if f(a) => this
   
case _ => None
 
}

Is there something inefficient/wrong about the way I've done it or is this just one of the possible implementations?

Thanks!
gjk

pagoda_5b

unread,
Apr 23, 2018, 9:45:44 AM4/23/18
to scala-functional
possibly your implementation will need to make one additional call after pattern matching... but I don't know enough about the internals to tell if there's some rewrite rule to optimize it away (I doubt so).

In any case I wouldn't worry too much, the result should be correct anyway

ivano
Reply all
Reply to author
Forward
0 new messages