Sta*_*low 5 scheme closures abstraction programming-languages functional-programming
因此,如果一种语言提供更高阶的程序,那么我可以有返回程序的程序.就像是:
(define (Proc a b c)
(lambda (x) ( #| method body here in terms of a b c and x |# )))
Run Code Online (Sandbox Code Playgroud)
要创建新程序,我会做类似的事情:
(define ProcA (Proc a1 b1 c1)) ; Would create ProcA that has 1 argument
Run Code Online (Sandbox Code Playgroud)
类似的任务可以用不支持高阶过程的语言来完成,方法是定义Proc4个而不是3个参数并调用这个过程来定义ProcA,如:
(define (Proc a b c x) ( #| method body -- does not return any procedure |# )
(define (ProcA x) (Proc a1 b1 c1 x))
Run Code Online (Sandbox Code Playgroud)
那么为什么有关高阶程序的模糊呢?我错过了什么吗?
可以很好地观察到返回另一个函数的函数与带有两个参数的函数相同.这被称为"Currying".换句话说,从A到B的函数是逻辑蕴涵的证明,A暗示B,或:
A => B.
Run Code Online (Sandbox Code Playgroud)
如你所知,如果A暗示B暗示C,则A和B暗示C,或:
(A => (B => C)) <==> ((A, B) => C)
Run Code Online (Sandbox Code Playgroud)
但是更高阶函数不一定是返回另一个函数的函数.高阶函数是一个以另一个函数作为参数的函数.这是一个重要的区别,HOF是非常强大的编程工具.
例如,考虑一下这个Haskell函数:
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : (map f xs)
Run Code Online (Sandbox Code Playgroud)
此高阶函数接受一个函数f并将其应用于列表中的每个元素.在没有HOF的语言中,你可以用循环或类似的东西做这个函数,但是在一个有HOF的语言中,你可以f用这样一个简单的调用来调用列表中的每个元素:
map f myList
Run Code Online (Sandbox Code Playgroud)
当然,语言中的控件构造可以让您接近高阶函数,但是具有高阶函数的语言可以让您创建自己的控件构造.方案当然有资格.