【发布时间】:2021-12-12 07:30:27
【问题描述】:
在 Stone 的 Algorithms for Functional Programming 中,他给出了递归定义谓词的设计模式,在 Scheme 中是
(define (check stop? continue? step)
(rec (checker . arguments)
(or (apply stop? arguments)
(and (apply continue? arguments)
(apply (pipe step checker) arguments)))))
其中pipe 是作者按图解顺序组合两个函数的函数((pipe f g) x = (g (f x))。
因此,例如,要测试一个函数是否是 2 的幂,您可以定义
(define power-of-two? (check (sect = <> 1) even? halve))
其中(sect = <> 1) 是作者的柯里化符号,相当于lambda x: x == 1。
很明显,很多谓词可以递归实现,但它不会有用。显然有些递归谓词不会使用这种模式,比如树上的谓词。
有哪些经典的谓词适合这种模式?我想测试一下康托集中是否有东西,但这和上面的几乎一样。
【问题讨论】:
-
这个问题似乎更适合Computer Science。
标签: recursion design-patterns functional-programming scheme