为什么是高阶程序? [英] Why higher order procedures?
问题描述
因此,如果一种语言提供更高阶的过程,那么我可以拥有返回过程的过程.类似的东西:
So if a language provides higher order procedure then I can have procedure that returns procedure. Something like:
(define (Proc a b c)
(lambda (x) ( #| method body here in terms of a b c and x |# )))
要创建新程序,我会执行以下操作:
To create new procedure, I would just do something like:
(define ProcA (Proc a1 b1 c1)) ; Would create ProcA that has 1 argument
通过定义采用 4 个而不是 3 个参数的 Proc
并调用此过程来定义 ProcA
,可以在不支持高阶过程的语言中完成类似的任务,喜欢:
Similar task could be done in a language which does not support higher order procedure by defining Proc
that takes 4 instead of 3 arguments and calling this procedure to define ProcA
, like:
(define (Proc a b c x) ( #| method body -- does not return any procedure |# )
(define (ProcA x) (Proc a1 b1 c1 x))
那么为什么对高阶过程有如此多的模糊呢?我错过了什么吗?
So why is there so much fuzz about higher order procedure? Am I missing something?
推荐答案
有一个很好的观察结果,即返回另一个函数的函数与接受两个参数的函数相同.这被称为咖喱".换句话说,从 A 到 B 的函数是逻辑蕴涵的证明,即 A 蕴涵 B,或者:
It's a good observation that a function that returns another function is the same as a function that takes two arguments. This is called "Currying". Put another way, a function from A to B is proof of a logical implication, that A implies B, or:
A => B.
如您所见,如果 A 暗示 B 暗示 C,则 A 和 B 暗示 C,或者:
As you note, if A implies that B implies C, then A and B implies C, or:
(A => (B => C)) <==> ((A, B) => C)
但是高阶函数不一定是返回另一个函数的函数.高阶函数是将另一个函数作为参数的函数.这是一个重要的区别,HOF 是非常强大的编程工具.
But a higher order function is not necessarily a function that returns another function. A higher-order function is a function that takes another function as its argument. This is an important difference, and HOFs are immensely powerful programming tools.
例如,考虑这个 Haskell 函数:
For example, consider this Haskell function:
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : (map f xs)
这个高阶函数接受一个函数 f
并将其应用于列表中的每个元素.在没有 HOF 的语言中,你可以用循环或类似的东西来做这个函数所做的事情,但在有 HOF 的语言中,你可以用这样的简单调用为列表中的每个元素调用 f
:
This higher-order function takes a function f
and applies it to every element in a list. In languages without HOFs, you would do what this function does with a loop or something similar, but in a language that has HOFs, you can call f
for every element in the list with a simple call like this:
map f myList
当然,语言中的控制构造可以让您近似高阶函数,但是具有高阶函数的语言可以让您发明自己的控制构造.方案当然有资格.
Sure, control constructs in languages let you approximate higher-order functions, but a language that has higher-order functions lets you invent your own control constructs. Scheme certainly qualifies.
这篇关于为什么是高阶程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!