Is it possible to define an infix function?

后端 未结 5 971
不思量自难忘°
不思量自难忘° 2021-02-08 09:21

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

or



        
5条回答
  •  时光取名叫无心
    2021-02-08 10:22

    ES6 enables a very Haskell/Lambda calculus way of doing things.

    Given a multiplication function:

    const multiply = a => b => (a * b)
    

    You can define a doubling function using partial application (you leave out one parameter):

    const double = multiply (2)
    

    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)
    

    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));

提交回复
热议问题