Alternative way of implementing a groupBy method in Scala?
language-features, scala
Solution
If you want to group by a predicate (ie, a function of `T => Boolean`), then you probably just want to do this:
in partition p
If you truly want to create a map out of it, then:
val (t, f) = in partition p
Map(true -> t, false -> f)
Then again, you may just want the exercise. In that case, the fold solution is fine.
Problem
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?