4

I want to be able to write a J-like language using the mathjs math.parser() function result.

Let's say I want to define an operator # that returns the length of an array. Ideally it would work like this:

a = [1, 2, 3]
#a             // yields 3

Then, for fun, an operator $ that takes two arrays and combines them.

a = [1, 2, 3, 4]
b = [4, 5, 6]
a $ b            // yields [1, 2, 3, 4, 4, 5, 6]

How might I do these things with mathjs? If I cannot do them, what tool might I use instead?

Why it's different

I want to be able to use it like this:

var parser = math.parser();
parser.eval("a = [1,2,3]; #a");
Conor O'Brien
  • 987
  • 2
  • 16
  • 40
  • Possible duplicate of [How would I extend the JavaScript language to support a new operator?](http://stackoverflow.com/questions/20762338/how-would-i-extend-the-javascript-language-to-support-a-new-operator) – Downgoat Mar 27 '16 at 18:28
  • 1
    @Vihan It's sort of related, but I specifically want to use them in the `parser#eval` method. – Conor O'Brien Mar 27 '16 at 18:30

1 Answers1

4

The expression parser of math.js doesn't support adding custom operators, so you will have to clone the project and adjust the code of the parser for that:

https://github.com/josdejong/mathjs/blob/master/src/expression/parse.js

Note that right now the # character is used as start of a comment in the parser.

If you want to create your own parser for your own specific syntax, you could do so using a parser generator like jison or peg.

Thaum Rystra
  • 740
  • 7
  • 14
Jos de Jong
  • 6,602
  • 3
  • 38
  • 58