Loading ...
Sorry, an error occurred while loading the content.

Getting reference to an operator's function

Expand Messages
  • Matthew Taylor
    Here is a lisp procedure that simply adds a to the absolute value of b : (define (a-plus-abs-b a b) ((if ( b 0) + -) a b)) I think this is beautiful, and I
    Message 1 of 1 , Mar 9, 2010
    • 0 Attachment
      Here is a lisp procedure that simply adds 'a' to the absolute value of 'b':

      (define (a-plus-abs-b a b)
      ((if (> b 0) + -) a b))

      I think this is beautiful, and I am trying to find the best way of writing this in JavaScript. But my JavaScript code is not beautiful:

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

      function minus(a,b) {
      return a - b;
      };

      function aPlusAbsB(a,b) {
      return (b > 0 ? plus : minus)(a,b);
      }

      The main problem is that I cannot use the + and - symbols as references to the functions they really represent as I can with lisp. Anyone know a more graceful way of doing something like this, or have I hit a language boundary?

      Obviously, I can do this:

      function aPlusAbsB(a,b) {
      return a + Math.abs(b);
      }

      , but this is more of a thought experiment than a pragmatic question. I guess my main question is this: Is there any way I can get reference to the core functions in the JavaScript language and treat them as Function objects?


      Thanks,

      matthew taylor
    Your message has been successfully submitted and would be delivered to recipients shortly.