scala: adicionando um método à lista?
Eu estava pensando em como adicionar um método 'partitionCount' às Listas, por exemplo: (não testado, sem vergonha com base no List.scala):
Preciso criar minha própria subclasse e um conversor implícito de tipo
(Minha tentativa original teve muitos problemas, então aqui está uma baseada na resposta da @ Easy):
class MyRichList[A](targetList: List[A]) {
def partitionCount(p: A => Boolean): (Int, Int) = {
var btrue = 0
var bfalse = 0
var these = targetList
while (!these.isEmpty) {
if (p(these.head)) { btrue += 1 } else { bfalse += 1 }
these = these.tail
}
(btrue, bfalse)
}
}
e aqui está uma versão um pouco mais geral que é boa para Seq: [...]:
implicit def seqToRichSeq[T](s: Seq[T]) = new MyRichSeq(s)
class MyRichList[A](targetList: List[A]) {
def partitionCount(p: A => Boolean): (Int, Int) = {
var btrue = 0
var bfalse = 0
var these = targetList
while (!these.isEmpty) {
if (p(these.head)) { btrue += 1 } else { bfalse += 1 }
these = these.tail
}
(btrue, bfalse)
}
}