在 Scala 中实现 MyMap(高阶函数)

Implement MyMap (Higher Order Function) in Scala

myMap 应该采用两个柯里化函数。 1) 通用列表 2) 计算 List 的每个元素的函数。

Return myMap 的值在对每个元素应用 Function 后是 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)
     }

它给我不可变的警告。

这是一个可行的解决方案

def myMap(f: Int => Int)(list: List[Int]): List[Int] = {
  list match {
    case Nil => Nil
    case head :: tail =>
      f(head) :: myMap(f)(tail)
  }
}

您的代码(除了格式化)有很多问题。

不要对 val 使用大写字母

你的 var 毫无意义,因为你从未修改过它,这个赋值无论如何也没有用,因为你可以简单地使用你的参数。

你的 if 需要一个 else,否则它不会神奇地 return 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)
  }
}

要使您的 if else 解决方案有效,您可以这样做:

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

如果您添加缺少的 else 块,您的解决方案就会起作用

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