简体   繁体   English

在scala中使用foldLeft反转

[英]reverse using foldLeft in scala

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

I am not sure how List[A] in foldLeft is of type B. Can anyone clear the process happening in this functions? 我不确定foldLeft中的List [A]是如何处于类型B的。任何人都可以清除此函数中发生的过程吗?

This reverse implementation is calling foldLeft with A as it's first type argument ( foldLeft#A = A ) and List[A] as it's second type argument ( foldLeft#B = List[A] ). 这种反向实现主叫foldLeftA因为它是第一种类型的参数( foldLeft#A = A )和List[A]作为它的第二个类型参数( foldLeft#B = List[A] Here is a type annotated version that makes this very explicit: 这是一个类型注释版本,使其非常明确:

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

Also Cons (if it is a Cons from standard library) creates a stream instead of list. Cons (如果它是标准库中的Cons )也会创建一个流而不是列表。 Probably You want to use :: instead: 可能你想使用::而不是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM