在一个示例中,foldl和foldr如何工作? [英] How do foldl and foldr work, broken down in an example?

查看:44
本文介绍了在一个示例中,foldl和foldr如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我是新来的Scheme/racket/lisp.我正在练习创建自己的函数,语法和递归,因此我想制作自己的 foldl foldr 函数,它们的功能与预定义版本完全相同.我做不到,因为我只是不了解这些功能是如何工作的.我在这里看到过类似的问题,但我仍然不明白.分解一些示例会有所帮助!这是我的(不正确的)过程:

Okay, I am new with scheme/racket/lisp. I am practicing creating my own functions, syntax, and recursion, so I want to make my own foldl and foldr functions that do exactly what the predefined versions do. I can't do it because I just don't understand how these functions work. I have seen similar questions on here but I still don't get it. Some examples broken down would help! Here is my (incorrect) process:

(foldl-0'(1 2 3 4))我执行 0-(4-3-2-1)并得到2,这是正确的答案

(foldl - 0 '(1 2 3 4)) I do 0 -(4-3-2-1) and get 2 which is the right answer

(foldl-0'(4 3 2 1))我执行 0-(1-2-3-4)并得到8,但它应该是-2.

(foldl - 0 '(4 3 2 1)) I do 0-(1-2-3-4) and get 8 but it should be -2.

(folder-0'(1 2 3 4))我执行 0-(1-2-3-4)并再次得到8,但是它应该为-2.

(foldr - 0 '(1 2 3 4)) I do 0-(1-2-3-4) and get 8 again, but it should be -2.

(文件夹-0'(4 3 2 1))我执行 0-(4-3-2-1)并得到2这是正确的答案

(foldr - 0 '(4 3 2 1)) I do 0-(4-3-2-1) and get 2 which is the right answer.

我在做什么错了?

推荐答案

让我们看一下:(文件夹-0'(1 2 3 4)).

在这里,文字'(1 2 3 4)构造了一个列表,其元素为数字1、2、3和4.让我们使列表的结构明确:

Here the literal '(1 2 3 4) constructs a list whose elements are the numbers 1, 2, 3, and, 4. Let's make the construction of the list explicit:

(cons 1 (cons 2 (cons 3 (cons 4 empty))))

人们可以将 folder 视为一个函数,该函数将 cons 替换为函数 f ,并将其替换为值 v .

One can think of foldr as a function that replaces cons with a function f and empty with a value v.

因此

(foldr f 0 (cons 1 (cons 2 (cons 3 (cons 4 empty)))))

成为

           (f 1    (f 2    (f 3    (f 4 v)))))

如果函数f为-并且值 v 为0,则将得到:

If the function f is - and the value v is 0, you will get:

(- 1 (- 2 (- 3 (- 4 0)))))

我们可以计算出结果:

  (- 1 (- 2 (- 3 (- 4 0))))
= (- 1 (- 2 (- 3 4)))
= (- 1 (- 2 -1))
= (- 1 3)
= -2

请注意,(文件夹为空的a-list)会生成 a-list 的副本.

Note that (foldr cons empty a-list) produces a copy of a-list.

另一方面,函数 foldl 使用另一侧的值:

The function foldl on the other hand uses the values from the other side:

> (foldl cons empty '(1 2 3 4))
'(4 3 2 1)

换句话说:

(foldl f v '(1 2 3 4))

成为

(f 4 (f 3 (f 2 (f 1 v)))).

如果 f 是函数-,并且值为0,则得到:

If f is the function - and the value is 0, then we get:

  (- 4 (- 3 (- 2 (- 1 0))))
= (- 4 (- 3 (- 2 1)))
= (- 4 (- 3 1))
= (- 4 2)
= 2

请注意,(folds cons empty a-list)产生了与 a-list 相反的结果.

Note that (foldl cons empty a-list) produces the reverse of a-list.

这篇关于在一个示例中,foldl和foldr如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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