Hello, jetroy!
[EMAIL PROTECTED] wrote:
>
> How do you link up the BNF definition with the parse statement?
>
REBOL parse rules are conceptually similar to BNF, but you can (and
must) embed REBOL code to take action on the parsed data -- unless,
of course, you just want a pass/fail syntax check.
>
> I can't seem to find any simple examples. Thanks!
>
I'm not sure if this qualifies as "simple", but here's an example.
=======================================================================
REBOL []
polydiff: function [
expr [string!]
][
alpha dig numb whsp gap coeff varbl expon result
][
alpha: charset [#"a" - #"z"]
dig: charset [#"0" - #"9"]
numb: [some dig]
whsp: charset " ^/^-"
gap: [any whsp]
either parse/all expr [
gap [copy coeff numb | none (coeff: 1)]
gap copy varbl alpha
gap ["**" gap copy expon numb | none (expon: 1)]
gap end
][
coeff: to-integer coeff
expon: to-integer expon
coeff: coeff * expon
expon: expon - 1
result: copy ""
either expon = 0 [
append result coeff
][
if coeff <> 1 [append result coeff]
append result varbl
if expon <> 1 [append result join "**" expon]
]
result
][
""
]
]
=======================================================================
used as in
>> polydiff "2x**3"
== "6x**2"
>> polydiff " 2 x ** 3 "
== "6x**2"
>> polydiff "x"
== "1"
>> polydiff "2x"
== "2"
>> polydiff "2x**2"
== "4x
Notes:
* gap is there to gobble up optional whitespace
* copy is there to save what matched into a word for later use
* the alternatives with none set coefficient and exponent to default
values if they are missing
* the dozen or so lines for a successful parse are there to simplify
the result expression by avoiding coefficient of 1, exponents of
0 or 1
>
> parse str [
> factor (result: join result [ digit "*x**" digit - 1 ] ) ;this
> doesn't work
> ]
>
One reason why it doesn't work is that you're trying to use the word
digit as if it were a variable containing the digit matched.
It's not. It's just a test of whether a character is a digit.