An alternative way to implement the groupBy method in Scala?

I came up with this implementation 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 that doesn't seem very Scalish (is that what I'm looking for?) for me. Could you suggest some improvements?

EDIT: after I received the “clue” about folding, I implemented it as follows:

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?

+3
source share
4 answers

If you want to group a predicate (i.e. a function T => Boolean), then you probably just want to do this:

in partition p

If you really want to create a map from it, then:

val (t, f) = in partition p
Map(true -> t, false -> f)

Then again, you may need exercise. In this case, the folded solution is excellent.

+4
source

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 :

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

.

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 )
  }
}
+2
source

A little hint: use folds to compute the resulting list in a functional / immutable way.

+1
source

Source: https://habr.com/ru/post/1730101/


All Articles