我刚开始学习函数式编程(使用Scheme语言)。我读到高阶函数是接受另一个函数作为参数,或者返回另一个函数,或者两者兼而有之的函数。因此,我试图将以下代码转换为高阶函数:
;; define two procedures - one for calculating square & one for finding double of a number
(define (square x) (* x x ))
(define (double x) (+ x x ))
(square 5)
=> 25
(double 5)
=> 10现在我想出了下面的一个:
;; Implementation 2:
(define (applyToItself f x) (f x x ) )
(define (square x) (applyToItself * x ))
(define (double x) (applyToItself + x ))
(square 5)
=> 25
(double 5)
=> 10我创建了一个函数applyToItself,它接受一个函数和一个值,并通过在传入值上应用传入函数返回计算值。现在,平方和双函数只使用带有*和+的applyToItself。
最后,我发现了另一种实现方法:
;;Implementation 3:
(define (applyToItself f) (lambda(x) (f x x )) )
(define square (applyToItself * ))
(define double (applyToItself + ))
(square 5)
=> 25
(double 5)
=> 10这个applyToItself实现现在只接收一个函数,并返回另一个函数,而不是计算值。
我的问题是:
applyToItself都是高阶函数吗?发布于 2016-03-31 13:47:37
square和double存在,就需要存在这些变量。
有些编译器有一种叫做lambda提升的优化技术,因此一些编译器实际上会将版本3重写到版本2,作为编译过程的一部分,使最终结果完全相同。
有时,当生成过程的过程进行一些初始化时,比如进行查找,那么在版本3中只会发生一次,而在版本2中,它将完成每个应用程序的计算。map对列表中的每个元素进行平方(map (applyToItself * ) '(1 2 3)) ; ==> (1 4 9)
https://stackoverflow.com/questions/36334578
复制相似问题