2015-12-17 73 views
1

myMap应该带两个curried函数。 1)通用列表 2)评估List的每个元素的函数。在Scala中实现MyMap(高阶函数)

将函数应用于每个元素后,myMap的返回值为List。

def myMap (f: Int=>Int) (L:List[Int]) : List[Int] = 
    { 
     var xx = L 
     if(L.isEmpty) Nil 
     val (head::tail) = xx 
     f(head) :: myMap (f) (tail) 
    } 

它给了我不变的警告。

+0

DEF MYMAP(F:INT =>内部)(L:列表[INT]):列表[INT] = { 变种XX = L 如果(L.isEmpty)无 VAL(头::尾巴)= xx f(head):: myMap(f)(tail) } – Sagar0921

+0

1 - 没有理由创建'xx'。只需使用'L'。 (除非你应该避免使用国会大厦字母变量名。)2 - 你的'if'语句没有'else'子句,所以所有的代码都会被执行,无论L是否为空。 – jwvh

+1

3)不要通过提问SO –

回答

0

这是一个可行的解决方案

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) 
    } 
} 
+0

非常感谢。它工作完美。 – Sagar0921

0

如果您添加缺少的封锁其他

您的解决方案会工作3210
def myMap (f: Int=>Int) (L:List[Int]) : List[Int] = { 
    var xx = L 
    if(L.isEmpty) Nil 
    else { 
    val (head::tail) = xx 
    f(head) :: myMap (f) (tail) 
    } 
}