1

Is it possible to add some new syntax into javascript? Like if I want it to have a synatx like:

mul>10>20 and it result 200 or if say mul(2)(3) and it result as 6 ? It is possible? I saw similar question somewhere to do this? So I am not sure if it is possible or not? If not in JS is it possible in other languages like C, Java, Python ? My understanding is that all these languages are only able to add some functionality for new objects and even those new objects can only have operators and syntax that a language itself already have? So am I correct or this is possible to add new syntax to these langauges?

Hafiz
  • 4,187
  • 12
  • 58
  • 111

3 Answers3

12

The answer to your broader question is write into the language you're working with, meaning aim to solve your problems with the tools that are available to you.

However, the second example you've given is actually already a fairly common pattern known as currying. You can extend Javascript to achieve this with the following:

Function.prototype.curry = function() {
    var fn = this, args = Array.prototype.slice.call(arguments);
    return function() {
      return fn.apply(this, args.concat(
        Array.prototype.slice.call(arguments)));
    };
  };

So assuming mul(a, b) is:

function mul(a, b) {
    return a * b;
}

You can use mul.curry(2)(3)

Here's a Fiddle

For a much more in-depth explanation of this design pattern, check out http://ejohn.org/blog/partial-functions-in-javascript/

monners
  • 5,174
  • 2
  • 28
  • 47
  • Sorry to be picky, but partial application != curry. – elclanrs Dec 30 '13 at 00:35
  • if anyone want to see how Array.prototype.slice.call() works then it can be seen at http://stackoverflow.com/questions/7056925/how-does-array-prototype-slice-call-work – Hafiz Jan 01 '14 at 22:03
  • but how can it be argument range independent ? means i don't know how whether it will be `mul(2)(3)` or `mul(2)(3)(1)(9)` – Hafiz Jan 01 '14 at 22:44
1

In Python

mul(2)(3)

means call mul with argument 2, then call the return value from that with argument 3 (which assumes that it's a function). You can't redefine that syntax, but you could make your function work with it:

def mul(arg):
    return lambda x: x * arg

To allow chaining (i.e. mul (2)(3)(4)) I would go for a class:

import operator

class op(object):

    def __init__(self, op, arg):
        self.op = op
        self.value = self._get_val(arg)

    def _get_val(self, arg):
        try:
            return arg.value
        except AttributeError:
            return arg

    def __repr__(self):
        return str(self.value)

    def __call__(self, arg):
        self.value = self.op(self.value, 
                             self._get_val(arg))
        return self

    def __getitem__(self, key):
        self.value = self.op(self.value, 
                             -1 * self._get_val(key))
        return self


class mul(op):

    def __init__(self, arg):
        super(mul, self).__init__(operator.mul, arg)

I have added a bonus feature, square brackets make the argument negative (mul(2)[3] == -6). This only pretends to return a number; I leave implementing the rest of the necessary magic methods as an exercise for the reader.

You couldn't make mul>x>y do anything other than return x > y (True or False), as the function object mul will evaluate as larger than any integers.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
0

Currying will allow you to do this:

function mul(num1) {
  return function (num2) {
    return num1 * num2;
  }
}

mul(2)(3); // 6

Multiple argument version (need to specify end of args with empty parens):

function mul (num1) {
  var vals = [num1];
  var fn = function (num2) {
    if (num2) {
      vals.push(num2);
      return fn;
    }else{
      var res = 1;
      vals.forEach(function (el) {
        res *= el;
      });
      return res;
    }
  }

  return fn;
}

console.log(mul(2)(3)(4)()); // 24
vivekvasani
  • 338
  • 2
  • 3
  • I already did this but it will never know when it is last argument, so can never do anything that is required at end. :) – Hafiz Dec 30 '13 at 01:12
  • Do you mean that you want to have more than 2 arguments? If so, I made an edit to show how you can do that. – vivekvasani Dec 30 '13 at 01:51