在Scala中使用foldLeft进行反转

4
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个回答

2

这个反转的实现方式在调用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]
  )

2

此外,如果它是标准库中的 Cons,它将创建一个流而不是列表。可能您想使用 :: 代替:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接