Is it possible to define an infix function?

后端 未结 5 962
不思量自难忘°
不思量自难忘° 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:07

    Javascript doesn't include an infix notation for functions or sections for partial application. But it ships with higher order functions, which allow us to do almost everything:

    // applicator for infix notation
    const $ = (x, f, y) => f(x) (y);
    
    // for left section
    const $_ = (x, f) => f(x);
    
    // for right section
    const _$ = (f, y) => x => f(x) (y);
    
    // non-commutative operator function
    const sub = x => y => x - y;
    
    
    // application
    
    console.log(
      $(2, sub, 3),   // -1
      $_(2, sub) (3), // -1
      _$(sub, 3) (2)  // -1
    );

    As you can see I prefer visual names $, $_ and _$ to textual ones in this case. This is the best you can get - at least with pure Javascript/ES2015.

提交回复
热议问题