groupBy
의 구현을 생각해 냈습니다.스칼라에서 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
}
}
하지만 Scalish가 아닌 것 같습니다 (찾고있는 단어입니까?). 어쩌면 개선을 제안 할 수 있을까요?
편집 : 접는 방법에 대한 "힌트"를받은 후 다음과 같이 구현했습니다.
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)
})
}
어떻게 생각하십니까?
폴드 구현에 특히 유용합니다. 부울을 제네릭 유형 U로 바꿀 수 있고 접이식 글꼴이 계속 작동 할 수 있습니다. –