简体   繁体   中英

Alternative way of implementing a groupBy method in Scala?

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?

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.

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))

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 )
  }
}

小提示:使用折叠以函数/不可变的方式计算结果列表。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM