遞歸方法:
def map[A,B](seq:Seq[B],f:B=>A):Seq[A]={
seq match {
case Nil=>Nil
case a +: as =>map(as,f)+:f(a)
}
}
由于是Seq[B]的內(nèi)部方法,所以通常形式是這樣的:
def map[B,That](f:B=>That):Seq[That]={
...
}
尾遞歸的實(shí)現(xiàn)模式:
def _map[A,B](seq:Seq[B],f:B=>A):Seq[A]={
def go(as:Seq[A],seq:Seq[B]):Seq[A]={
seq match {
case Nil=>as
case?b +:?bs =>go(as +: f(b),bs)
}
go(Nil,seq)
}
}