higher-order function first-order function

Higher-order function

From Wikipedia, the free encyclopedia
Not to be confused with  Functor (category theory).

In mathematics and computer science, a higher-order function (also functionalfunctional form or functor) is a function that does at least one of the following:

All other functions are first-order functions. In mathematics higher-order functions are also termed operators or functionals. The differential operator in calculus is a common example, since it maps a function to its derivative, also a function.

In the untyped lambda calculus, all functions are higher-order; in a typed lambda calculus, from which most functional programming languages are derived, higher-order functions that take one function as argument are values with types of the form {\displaystyle (\tau _{1}\to \tau _{2})\to \tau _{3}}(\tau _{1}\to \tau _{2})\to \tau _{3}.


General examples[edit]

The map function, found in many functional programming languages, is one example of a higher-order function. It takes as arguments a function f and a list of elements, and as the result, returns a new list with f applied to each element from the list. Another very common kind of higher-order function in those languages which support them are sorting functions which take a comparison function as a parameter, allowing the programmer to separate the sorting algorithm from the comparisons of the items being sorted. The C standard function qsort is an example of this.

Other examples of higher-order functions include foldfunction composition, and integration.


Direct support[edit]

The examples are not intended to compare and contrast programming languages, but to serve as examples of higher-order function syntax

In the following examples, the higher-order function twice takes a function, and applies the function to some value twice. If twice has to be applied several times for the same f it preferably should return a function rather than a value. This is in line with the "don't repeat yourself" principle.

Python[edit]
Further information:  Python (programming language)
>>> def twice(function):
...     return lambda x: function(function(x))

>>> def f(x):
...     return x + 3

>>> g = twice(f)
    
>>> print g(7) 
13
JavaScript[edit]
Further information:  JavaScript
var twice = function(f, v) {
    return f(f(v));
};

var f = function(v) {
    return v + 3;
};

console.log(twice(f, 7)); // 13
Go[edit]
Further information:  Go (programming language)
func twice(f func(int) int, v int) int {
	return f(f(v))
}

func main() {
	f := func(v int) int {
		return v + 3
	}
	twice(f, 7) // returns 13
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值