Tuesday, March 19, 2013

What is 3+2*2 ?

You might know that 3+2*2 is 7 and not 10. At least for mathematicians.

Now all people aren't mathematicians, and neither are computers as it turn out. Somebody painstakingly told the computer how to do this correctly.

OK

How does this work? Well for anything a computer reads there is a parser that transforms text to another text which is closer to what a computer understands.

Since I lately been telling my computer that it's a Panda I have to talk panda language to it.

In this case you can't say 3+2*2 but have to say
---  plus(3, times(2, 2))

You could say. 2.times(2).plus(3) buy that's another story.

From here on it gets technical, you can skip it if you want, most will. The ones who might understand it may say it's bullocks too! That's fine. Go watch star wars then instead!

- - -

So I was thinking that a parser essentially need backtracking for simplicity of implementation. It also needs a way to choose between alternatives.

Since my language Panda already does backtracking I only need a way to implement choice. In SQL is called OR. I don't have it. Then it struck me that OR is just a kind of enumeration and invocation of different code paths!

I just need a way of listing the appropriate functions that are the choices and then apply them to the given arguments. Turns out I already have this by reflection on functions. That is I can find all functions in my system matching a certain name or parameters, and then call each of those functions.

You can for example say:

   func('number_number_number').call(4,3)

And it will give you 1.3333 4 3 1 7 12
Which are the results of divide, max, min, minus, plus, times.

It's not Beatiful, but it isn't too bad either.

I wrote a simple expression parser, handling priorities of operators correctly.

This is how its used.

'3+2*2'.syntax.expr.empty.gen.panda
This gives 7!

.syntax generates a syntax structure
.expr parses the expression
.empty requires that after parsing the expression the state is empty
.gen returns the generated code as of previously given
.panda takes that code and gives it to panda, that, hmmmm, will parse it, generate internal code, then JavaScript code which then will be run.

Time to sleep.