Scala向右折叠和向左折叠 [英] Scala fold right and fold left

查看:162
本文介绍了Scala向右折叠和向左折叠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习函数式编程和Scala,因此我正在阅读Chiusano和Bjarnason撰写的"Scala中的函数式编程".我在理解列表的情况下无法理解向左折叠和向右折叠的方法有什么困难.我在这里环顾四周,但没有找到适合初学者的东西.因此,本书提供的代码是:

I am trying to learn functional programming and Scala, so I'm reading the "Functional Programming in Scala" by Chiusano and Bjarnason. I' m having trouble understanding what fold left and fold right methods do in case of a list. I've looked around here but I haven't find something beginner friendly. So the code provided by the book is:

def foldRight[A,B](as: List[A], z: B)(f: (A, B) => B): B = as match {
  case Nil => z
  case Cons(h, t) => f(h, foldRight(t, z)(f))
}

def foldLeft[A,B](l: List[A], z: B)(f: (B, A) => B): B = l match {
  case Nil => z
  case Cons(h,t) => foldLeft(t, f(z,h))(f)
}

Cons和Nil在哪里

Where Cons and Nil are:

case class Cons[+A](head: A, tail: List[A]) extends List[A]
case object Nil extends List[Nothing]

那么左右折叠实际上是做什么的呢?为什么需要作为实用程序"方法?还有许多其他使用它们的方法,我也很难理解它们,因为我没有两者.

So what do actually fold left and right do? Why are needed as "utility" methods? There are many other methods that use them and I have trouble to understand them as well, since I don't get those two.

推荐答案

根据我的经验,锻炼直觉的最佳方法之一就是在非常简单的示例中查看其工作原理:

According to my experience, one of the best ways to workout the intuition is to see how it works on the very simple examples:

List(1, 3, 8).foldLeft(100)(_ - _) == ((100 - 1) - 3) - 8 == 88
List(1, 3, 8).foldRight(100)(_ - _) == 1 - (3 - (8 - 100)) == -94

如您所见,foldLeft/Right只是将列表的元素和上一个应用程序的结果传递给第二括号中的操作. 还应该提到的是,如果将这些方法应用于相同的列表,则仅当所应用的操作是关联的时,它们才会返回相等的结果.

As you can see, foldLeft/Right just passes the element of the list and the result of the previous application to the the operation in second parentheses. It should be also mentioned that if you apply these methods to the same list, they will return equal results only if the applied operation is associative.

这篇关于Scala向右折叠和向左折叠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆