是否可以定义中缀函数? [英] Is it possible to define an infix function?
问题描述
是否可以在CoffeeScript(或纯JavaScript)中定义自己的infix函数/运算符?例如我想打电话
Is it possible to define my own infix function/operator in CoffeeScript (or in pure JavaScript)? e.g. I want to call
a foo b
或
a `foo` b
代替
a.foo b
或者,当foo是全局函数时,
or, when foo is global function,
foo a, b
有没有办法做到这一点?
Is there any way to do this?
推荐答案
ES6启用了一种非常Haskell/Lambda演算方法.
ES6 enables a very Haskell/Lambda calculus way of doing things.
赋予乘法功能:
const multiply = a => b => (a * b)
您可以使用部分应用程序定义一个加倍函数(省略一个参数):
You can define a doubling function using partial application (you leave out one parameter):
const double = multiply (2)
您可以将double函数与其自身组合,从而创建一个四倍函数:
And you can compose the double function with itself, creating a quadruple function:
const compose = (f, g) => x => f(g(x))
const quadruple = compose (double, double)
但是,确实,如果您希望使用中缀符号怎么办?正如史蒂夫·拉达维奇(Steve Ladavich)指出的那样,您确实需要扩展原型.
But indeed, what if you would prefer an infix notation? As Steve Ladavich noted, you do need to extend a prototype.
但是我认为可以使用数组表示法而不是点表示法来完成一些更优雅的操作.
But I think it can be done a bit more elegant using array notation instead of dot notation.
我们使用正式符号来表示功能∘":
Lets use the official symbol for function composition "∘":
Function.prototype['∘'] = function(f){
return x => this(f(x))
}
const multiply = a => b => (a * b)
const double = multiply (2)
const doublethreetimes = (double) ['∘'] (double) ['∘'] (double)
console.log(doublethreetimes(3));
这篇关于是否可以定义中缀函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!