lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Jul 5, 2016 at 3:09 PM, Soni L. <fakedme@gmail.com> wrote:
>
>
> On 05/07/16 06:34 PM, Sean Conner wrote:
>>
>> It was thus said that the Great Soni L. once stated:
>>>
>>>
>>> On 05/07/16 05:18 PM, Sean Conner wrote:
>>>>
>>>> It was thus said that the Great Soni L. once stated:
>>>>>
>>>>> As you may or may not know by now, regex can do basic arithmetic, with
>>>>> unary integers.[1] Can LPeg do better, say with binary integers, or
>>>>> binary floats, or even full-blown decimal?
>>>>
>>>>    Yup.  You can do the regex approach with a substitution capture
>>>> (lpeg.Cs()) or even a full blown calculator (there's an example on the
>>>> LPeg
>>>> web page).
>>>
>>> Too bad it's not pure LPeg, instead deferring to a Lua function for it.
>>
>>    What?  Is not lpeg.Cf() LPeg, just because it accepts a Lua function as
>> a
>> parameter?  So,
>>
>>         lpeg.R"09" / { ['o'] = 0 , ['1'] = 1 , ['2'] = 2 ... }
>>
>> is fine, but not?
>>
>>         lpeg.R"09" / tonumber
>>
>>    If LPeg allows it, it's LPeg.
>>
>>    But okay, fine!  If you restrict the domain to single digits, then:
>>
>>           lpeg.P"0+0" * lpeg.Cc(0)
>>         + lpeg.P"0+1" * lpeg.Cc(1)
>>         + lpeg.P"0+2" * lpeg.Cc(2)
>>         + lpeg.P"0+3" * lpeg.Cc(3)
>>         ... and so on.  Go crazy with this.
>>
>>    -spc (Stop moving the goal posts!)
>>
>>
>>
>>
> The goal is to never run Lua code for it. Perl regex can run Perl code, but
> the linked math-with-regex thingy doesn't use that and that's the whole
> point. If someone ports LPeg to a different programming language, a LPeg
> that calls Lua code will stop working.
>
> Also, if this was a codegolf or programming puzzle and you weren't allowed
> to use the language's built-in addition subtraction etc, you could do it
> with regex instead.
>
> --
> Disclaimer: these emails may be made public at any given time, with or
> without reason. If you don't agree with this, DO NOT REPLY.
>
>

So, I don't know LPeg, but I can make some foundational observations:
(I'm using Perl syntax for capture references because that's what I
know. Substitute the appropriate LPeg construction.)

digit: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
number: (number?) (digit)

>From here, you can have the number production multiply \1 (which might
be empty) by "!!!!!!!!!!" and concatenate the unary representation of
\2, and thereby convert an arbitrary place-value decimal string into a
unary representation.

With a unary representation, you can then use the same tricks as the
regexp version. For example:

sum: (number) + (number)

This can be replaced by \1\2.

The only remaining challenge is converting the final output back to a
decimal number.

unary: ((?:!!!!!!!!!!)*)(!{0,9})

Replace \1 with @ and \2 with the appropriate decimal notation, then
replace @ with ! and repeat the process until \1 fails to match
anything.

/s/ Adam