JavaScript是否支持部分功能应用程序? [英] Does JavaScript support partial function application?

查看:67
本文介绍了JavaScript是否支持部分功能应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读维基百科关于First-Class函数的文章,有一个很好的函数式编程各个方面的语言支持表: http://en.wikipedia.org/wiki/First-class_function#Language_support



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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆