【发布时间】:2021-05-14 17:11:27
【问题描述】:
我试图理解 SML 中函数的递归调用,其目的是找到列表中的最高整数值。由于教育原因,此功能不好。
fun bad_max(xs: int list) =
if null xs (*if the list is empty, returns 0 which is bad style*)
then 0
else if null (tl xs) (*if the list has only one element this is the max*)
then hd xs
else if hd xs > bad_max(tl xs) (*not clear how this happens*)
then hd xs
else bad_max( tl xs)
我知道由于重复的递归调用,上面的函数以非常慢的方式提供了正确的结果。
我不明白最后一个 else if 和最后一个 else 究竟是如何发生的。
我真的很想念像 trace 这样的工具,以便查看函数参数在递归调用中的变化。显然,Standard ML does not 有一个工具。
我想了解通话后究竟发生了什么:
bad_max([1,7,3,4])
结果是正确的7。
不过,这究竟是怎么发生的?
1 > bad_max([7,3,4])
7 > bad_max([3,4])
3 > bad_max([4])
3 > 4
(*which is false*)
(*what is the next step? Does the function come back to the int of 7?*)
7 > 3 (*which is true!*)
(*or does the program go to the ELSE recursive call and restart the process such as?*)
7 > bad_max([3,4])
对不起,如果我的疑问不清楚。很难用文字来表达。我试图通过上面的标识来表达我对递归调用语义的怀疑。
我真的在寻找编程语言 Racket 中存在的库跟踪之类的东西。
> (define (f x) (if (zero? x) 0 (add1 (f (sub1 x)))))
> (trace f)
> (f 10)
>(f 10)
> (f 9)
> >(f 8)
> > (f 7)
> > >(f 6)
> > > (f 5)
> > > >(f 4)
> > > > (f 3)
> > > > >(f 2)
> > > > > (f 1)
> > > >[10] (f 0)
< < < <[10] 0
< < < < < 1
< < < < <2
< < < < 3
< < < <4
< < < 5
< < <6
< < 7
< <8
< 9
<10
10
我什至尝试将 SML 代码改编为 Racket只是以使用 Trace 库并消除我的疑问。我的球拍技巧很生疏,但显然不可能在球拍中重现 SML 代码的相同行为。以下代码抛出错误:
#lang racket
(require racket/trace rackunit)
(define (bad_max lista)
(cond ((empty? lista) 0)
((empty? (cdr lista)) car lista)
((> (car lista) (bad_max (cdr lista))) (car lista))
(else (bad_max (cdr lista)))))
(bad_max '(1 7 3 4))
这个疑问的有趣之处在于,对我来说,关于列表最大值的错误解决方案比正确的解决方案更难理解。
====
更新:
感谢 Sorawee 的评论,我能够修复上面的球拍代码:
#lang racket
(require racket/trace rackunit)
(define (bad_max lista)
(cond ((empty? lista) 0)
((empty? (cdr lista)) (car lista))
((> (car lista) (bad_max (cdr lista))) (car lista))
(else (bad_max (cdr lista)))))
(trace bad_max)
(bad_max '(1 7 3 4))
【问题讨论】:
-
您的 Racket 代码不起作用的原因是您忘记了
car lista周围的括号。应该是(car lista)。
标签: debugging recursion racket trace sml