在scala中使用foldLeft反转

时间:2017-05-26 13:37:22

标签: scala functional-programming

def foldLeft[A, B] (as: List[A], z: B) (f: (B, A) => B) : B = as match {
  case Nil => z
  case Cons(x, xs) => foldLeft(xs, f(z, x))(f)
}

def reverse[A] (as: List[A]): List[A] =
  foldLeft(as, List[A]())((h, acc) => Cons(acc, h))

我不确定foldLeft中的List [A]是如何处于B类的。任何人都可以清除此函数中发生的过程吗?

2 个答案:

答案 0 :(得分:1)

此反向实现正在调用foldLeft A作为其第一个类型参数(foldLeft#A = A)和List[A]作为其第二类型参数(foldLeft#B = List[A])。这是一个带注释的类型,使其非常明确:

def reverse[A] (as: List[A]): List[A] =
  foldLeft[A, List[A]](as = as: List[A], z = List[A]())(
    (h: List[A], acc: A) => Cons(acc, h): List[A]
  )

答案 1 :(得分:1)

同样Cons(如果它是标准库中的Cons)会创建一个流而不是列表。您可能想要使用::代替:

def reverse[A] (as: List[A]): List[A] =
    foldLeft(as, List[A]())((acc, h) => h :: acc)