Skip to content Skip to sidebar Skip to footer

Is It Possible To Define An Infix Function?

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 a `foo` b instead of a.foo b or, when foo is glob

Solution 1:

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

Given a multiplication function:

constmultiply = a => b => (a * b)

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

constdouble = 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){
  returnx =>this(f(x))
}

constmultiply = a => b => (a * b)
const double = multiply (2)
const doublethreetimes = (double) ['∘'] (double) ['∘'] (double)

console.log(doublethreetimes(3));

Solution 2:

Solution 3:

You can with sweet.js. See:

  1. http://sweetjs.org/doc/main/sweet.html#infix-macros
  2. http://sweetjs.org/doc/main/sweet.html#custom-operators

Sweet.js extends Javascript with macros.

It acts like a preprocessor.

Solution 4:

This is definitely not infix notation but it's kinda close : /

let plus = function(a,b){return a+b};

let a = 3;
let b = 5;
let c = a._(plus).b// 8

I don't think anyone would actually want to use this "notation" since it's pretty ugly, but I think there are probably some tweaks that can be made to make it look different or nicer (possibly using this answer here to "call a function" without parentheses).

Infix function

// Add to prototype so that it's always there for youObject.prototype._ = function(binaryOperator){

  // The first operand is captured in the this keywordlet operand1 = this; 

  // Use a proxy to capture the second operand with "get"// Note that the first operand and the applied function//   are stored in the get function's closure, since operand2//   is just a string, for eval(operand2) to be in scope,//   the value for operand2 must be defined globallyreturnnewProxy({},{
    get: function(obj, operand2){
        returnbinaryOperator(operand1, eval(operand2))
    }
  })
}

Also note that the second operand is passed as a string and evaluated with eval to get its value. Because of this, I think the code will break anytime the value of operand (aka "b") is not defined globally.

Post a Comment for "Is It Possible To Define An Infix Function?"