views:

144

answers:

4

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?

+1  A: 

Little hint: Use folds to compute the resulting list in a functional/immutable fashion.

Dario
+2  A: 

I'd just filter twice.

object Whatever {
  def groupBy[T](in: Seq[T], p: T => Boolean) : Map[Boolean,List[T]] = {
    Map( false -> in.filter(!p(_)).toList , true -> in.filter(p(_)).toList )
  }
}
Rex Kerr
Really nice implementation!
Geo
+4  A: 

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.

Daniel
Very cool! Didn't know a builtin existed. Thanks Daniel!
Geo
@Geo You may also want to look at `splitAt` and `span`, which do something similar but with different criteria. The first divides between `take` and `drop`, while the second divides between `takeWhile` and `dropWhile`.
Daniel
+3  A: 

Here's an example using foldLeft.

scala> def group[T, U](in: Iterable[T], f: T => U) = {
     |   in.foldLeft(Map.empty[U, List[T]]) {
     |     (map, t) =>
     |       val groupByVal = f(t)
     |       map.updated(groupByVal, t :: map.getOrElse(groupByVal, List.empty))
     |   }.mapValues(_.reverse)
     | }
group: [T,U](in: Iterable[T],f: (T) => U)java.lang.Object with scala.collection.DefaultMap[U,List[T]]

scala> val ls = List(1, 2, 3, 4, 5)
ls: List[Int] = List(1, 2, 3, 4, 5)

scala> println(group(ls, (_: Int) % 2))
Map(1 -> List(1, 3, 5), 0 -> List(2, 4))

Scala 2.8 offers this in the standard library:

scala> println(ls.groupBy((_: Int) % 2)) // Built into Scala 2.8.
Map(1 -> List(1, 3, 5), 0 -> List(2, 4))
retronym