JavaScript是否支持部分功能应用程序? [英] Does JavaScript support partial function application?
问题描述
JavaScript被列为没有部分功能的应用程序。但是,还有一些技巧可以创建一个函数,该函数返回一个函数,其中某些参数存储在闭包中,即:
pre $ var add = function(a,b){
return a + b;
},
apply = function(fn,a){
返回函数(b){
return fn(a,b);
}
},
addFive = apply(add,5);
console.log(addFive(2)); //打印7
这不是部分函数应用吗?如果没有,请问有人可以提供另一种语言的部分功能应用程序的例子,并解释它是如何不同?
谢谢!
部分应用程序是不同的。 这是一个Haskell示例:
add :: Int - > Int - > Int
add xy = x + y
addOne = add 1
add
是一个函数,它接受两个 Int
并返回一个 Int
,表示为 Int - > Int - > INT
。如果您对语法不熟悉,请使用Javascript,大致如下: @param int x
* @param int y
* @return int
* /
函数add(x,y){
return x + y;
}
加1
来电此函数只有一个参数,它返回一个新函数,该函数接受一个 Int
并返回一个 Int
( Int - > Int
)。 add
函数没有被明确设计为高阶函数,而是部分应用了它。
Reading through the Wikipedia article on First-Class functions, there is a nice table of language support for various aspects of functional programming: http://en.wikipedia.org/wiki/First-class_function#Language_support
JavaScript is listed as not having partial function application. However, there are techniques for creating a function that returns a function that with some of the parameters stored in a closure, ie:
var add = function(a, b){
return a + b;
},
apply = function(fn, a){
return function(b){
return fn(a, b);
}
},
addFive = apply(add, 5);
console.log(addFive(2)); // prints 7
Is this not partial function application? If not, could someone please provide an example of partial function application in another language and explain how it is different?
Thanks!
What you show is an example of higher order functions, functions that take functions as arguments and/or return functions.
Partial application is something different. Here a Haskell example:
add :: Int -> Int -> Int
add x y = x + y
addOne = add 1
add
is a function that takes two Int
and returns an Int
, denoted as Int -> Int -> Int
. If you're unfamiliar with the syntax, in Javascript this would roughly look like this:
/**
* @param int x
* @param int y
* @return int
*/
function add(x, y) {
return x + y;
}
add 1
calls this function with only one parameter, which returns a new function that takes one Int
and returns an Int
(Int -> Int
). The add
function was not explicitly designed to be a higher order function, it was simply partially applied.
这篇关于JavaScript是否支持部分功能应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!