I've come up with this implementation of groupBy
:
object Whatever
{
def groupBy[T](in:Seq[T],p:T=>Boolean) : Map[Boolean,List[T]] = {
var result = Map[Boolean,List[T]]()
in.foreach(i => {
val res = p(i)
var existing = List[T]() // how else could I declare the reference here? If I write var existing = null I get a compile-time error.
if(result.contains(res))
existing = result(res)
else {
existing = List[T]()
}
existing ::= i
result += res -> existing
})
return result
}
}
but it doesn't seem very Scalish ( is that the word I'm looking for? ) to me. Could you maybe suggest some improvements?
EDIT: after I received the "hint" about folding, I've implemented it this way:
def groupFold[T](in:Seq[T],p:T=>Boolean):Map[Boolean,List[T]] = {
in.foldLeft(Map[Boolean,List[T]]()) ( (m,e) => {
val res = p(e)
m(res) = e :: m.getOrElse(res,Nil)
})
}
What do you think?