球拍中折叠的展开形式 [英] Expanded form of fold in Racket

查看:58
本文介绍了球拍中折叠的展开形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例来自 http://www.cse.unsw.edu.au/~en1000/haskell/hof.html:

(foldr / 7 (list 34 56 12 4 23))
(foldl / 7 (list 34 56 12 4 23))

球拍输出:

5 193/196
5 193/196

在这种情况下,foldl 和 foldr 的完整(扩展)形式是什么?它不是以下内容:

What would be the full (expanded) form of foldl and foldr in this case? It is not the following:

> (/ (/ (/ (/ (/ 7 34) 56) 12) 4) 23)
1/300288

我已经修改了上述问题,因为在另一个问题 为什么 foldl 在 Racket 中以一种奇怪的方式定义?.

I have modified above question since implementation of fold in Racket vs Haskell has been explained in another question Why is foldl defined in a strange way in Racket?.

如果我清楚地理解答案,可以使用线程"模块非常清楚地显示扩展形式,其中语句按执行顺序出现(_表示前一条语句的输出):

If I understand the answers clearly, the expanded form can be shown very clearly using "threading" module, where statements appear in order of execution (_ indicates output of previous statement):

折叠:

(require threading)
; expanded form of (foldl / 7 (list 34 56 12 4 23))
; FROM LEFT TO RIGHT: 
(~> 7
    (/ 34 _)
    (/ 56 _)
    (/ 12 _)
    (/ 4  _)
    (/ 23 _) )

文件夹:

; expanded form of (foldr / 7 (list 34 56 12 4 23))
; FROM RIGHT TO LEFT: 
(~> 7
    (/ 23 _)
    (/ 4  _)
    (/ 12 _)
    (/ 56 _)
    (/ 34 _) )

两种情况的输出是一样的:

The output in both cases is same:

5 193/196
5 193/196

在以下示例中也给出了正确答案(foldl 和 foldr 不同):

It gives correct answers (which are different for foldl and foldr) in following example also:

; FROM LEFT TO RIGHT:
(foldl - 0 '(1 2 3 4))
(~> 0
    (- 1 _)  ; 1-0=1
    (- 2 _)  ; 2-1=1
    (- 3 _)  ; 3-1=2
    (- 4 _)) ; 4-2=2

; FROM RIGHT TO LEFT: 
(foldr - 0 '(1 2 3 4))
(~> 0
    (- 4 _)  ; 4-0=4
    (- 3 _)  ; 3-4=-1
    (- 2 _)  ; 2-(-1)=3
    (- 1 _)) ; 1-3=-2

输出:

2
2
-2
-2

在共同语言中,似乎:

The sent function takes 2 arguments, 

the first argument is from the list, one after the other 
(left to right or right to left depending on foldl and foldr), 

the second argument is init first and 
then the output of previous calculation.

推荐答案

Haskell 的 foldrfoldl 并不完全等同于 Racket 的.另外,div 是整数除法,所以你应该在 Racket 中使用 quotient.但即便如此,

Haskell's foldr and foldl are not exactly equivalent to Racket's. Also, div is integer division, so you should use quotient in Racket. But even then,

(foldr quotient 7 (list 34 56 12 4 23)) => 8
(foldl quotient 7 (list 34 56 12 4 23)) => quotient: undefined for 0

您可以仔细阅读有关 foldl 和 foldr 如何工作的文档,但我喜欢参考 教学语言:

You could read the documentation carefully on how foldl and foldr work, but I like to refer to the docs for the teaching languages:

(foldr f base (list x-1 ... x-n)) = (f x-1 ... (f x-n base))
(foldl f base (list x-1 ... x-n)) = (f x-n ... (f x-1 base))

就这样了

(quotient 34 (quotient 56 (quotient 12 (quotient 4 (quotient 23 7)))))
(quotient 23 (quotient 4 (quotient 12 (quotient 56 (quotient 34 7)))))

这篇关于球拍中折叠的展开形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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