【问题标题】:reverse using foldLeft in scala在scala中使用foldLeft反转
【发布时间】:2017-05-26 21:51:10
【问题描述】:
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 类型的。任何人都可以清除此函数中发生的过程吗?

【问题讨论】:

    标签: scala functional-programming


    【解决方案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]
      )
    

    【讨论】:

      【解决方案2】:

      同样Cons(如果它是来自标准库的Cons)创建一个流而不是列表。可能您想改用::

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

      【讨论】:

        猜你喜欢
        • 2013-06-12
        • 1970-01-01
        • 1970-01-01
        • 2021-08-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-07
        • 2011-05-09
        相关资源
        最近更新 更多