这是一个可行的解决方案
def myMap(f: Int => Int)(list: List[Int]): List[Int] = {
list match {
case Nil => Nil
case head :: tail =>
f(head) :: myMap(f)(tail)
}
}
你的代码(除了格式化)的问题数。
,不要使用大写字母瓦尔斯
你var
是没有意义的,你永远不会修改它,这种分配是没用反正,你可以简单地使用你的论点。
你如果需要的东西,otherways不会magicly返回Nil
你可以用通用型取代int此函数通用
def myMap[A](f: A => A)(list: List[A]): List[A] = {
list match {
case Nil => Nil
case head :: tail =>
f(head) :: myMap(f)(tail)
}
}
为了让您若其他解决方案的工作,你可以做到这一点:
def myMap[A](f: A => A)(list: List[A]): List[A] = {
if (list.isEmpty) {
Nil
} else {
val (head :: tail) = list
f(head) :: myMap(f)(tail)
}
}
DEF MYMAP(F:INT =>内部)(L:列表[INT]):列表[INT] = { 变种XX = L 如果(L.isEmpty)无 VAL(头::尾巴)= xx f(head):: myMap(f)(tail) } – Sagar0921
1 - 没有理由创建'xx'。只需使用'L'。 (除非你应该避免使用国会大厦字母变量名。)2 - 你的'if'语句没有'else'子句,所以所有的代码都会被执行,无论L是否为空。 – jwvh
3)不要通过提问SO –