English 中文(简体)
三. 实施集团的其他方式 采用的方法?
原标题:Alternative way of implementing a groupBy method in Scala?

一. 实施<代码>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   
    }
}

但是,我看上去看上去看一字(我看着吗? )。 您能否提出一些改进建议?

EDIT:在我收到关于包装的“hint”之后,我就这样执行了:

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

你认为什么?

最佳回答

如果您想按顺序排列(即<代码>的功能)。 T => Boolean,然后,你可能想这样做:

in partition p

如果你真的想要绘制地图,那么:

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

之后,你可能再次想要这样做。 在这种情况下,双重解决办法是罚款的。

问题回答

此处使用<代码>的范例 见。

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

我只过滤两次。

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

Little hint: Use ,以功能/可变的方式对清单进行计算。





相关问题
Using flag to identify spoken language

In the webapp I am doing, I need to identify language people are speaking. I wanted to use flag to do that. But I have some problems. For example, if you speak French, you can put the French flag. ...

Detecting the browser language of choice with PHP

I m trying to implement this code to have different files to load for german, spanish or english browser languages of choice. The case is that with my spanish IE I still get the english file. <?...

热门标签