scala map方法

递归方法:

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]的内部方法,所以通常形式是这样的:

def map[B,That](f:B=>That):Seq[That]={

...

}

尾递归的实现模式:

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)

}


}

你可能感兴趣的:(scala map方法)