一. 实施<代码>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)
})
}
你认为什么?