Haskell's infix operator for Javascript

寵の児 提交于 2019-12-13 03:23:51

问题


Is there an equivalent construct in Javascript. If not, how would you create one?

Here's a straightforward explanation of what the infix operator does in Haskell:

What does the : infix operator do in Haskell?


回答1:


JavaScript doesn't have a list type, but it has Arrays.

You can use...

var newArr = [val].concat(arr);

Alternatively, you could use unshift() to prepend to an array, but it mutates the original.

JavaScript doesn't have a : operator, operator overloading or methods that look like operators, so you can't get a similar syntax as Haskell.




回答2:


I saw Leila Hamon already linked to this article on emulating infix operators in JS.

But I thought an example may be useful to others.

Here is how you could hack the Number and Boolean prototypes to handle chained infix expressions such as 4 < 5 < 10.

You could extend this further by applying more methods to more prototypes. It is a little bit ugly but could be useful for making queries less verbose.

//Usage code
(4) .gt (6) .gt (4) //false

(100) .lt (200) .lt (400) . gt(0) . gt(-1)//true

(100) [ '>' ] (50) [ '<' ] (20)//false



//Setup Code
(function(){

  var lastVal = null;


  var nP = Number.prototype
  var bP = Boolean.prototype

  nP.gt = function(other){
    lastVal = other;
    return this > other;
  }

  nP.lt = function(other){
    lastVal = other;
    return this < other;
  }

  bP.gt = function(other){
    var result = lastVal > other;
    lastVal = other;
    return result;
  }

  bP.lt = function(other){
    var result = lastVal < other;
    lastVal = other;
    return result;
  }

  bP['<'] = bP.lt
  bP['>'] = bP.gt
  nP['<'] = nP.lt
  nP['>'] = nP.gt


})()



回答3:


It's not the prettiest, but it may help with readability in places where you want infix so your code reads like prose

function nfx(firstArg, fn, secondArg){
    return fn(firstArg, secondArg);
}

// Usage

function plus(firstArg, secondArg) {
    return firstArg + secondArg;
}

nfx(1, plus, 2);


来源:https://stackoverflow.com/questions/11571088/haskells-infix-operator-for-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!