Search code examples
reboloperator-precedencerebol3mathematical-expressions

Fixing the Rebol3 example calculator to use normal math operator precedence


In the example calculator:

REBOL [title: "Calculator"]
do %r3-gui.r3
stylize [
    btn: button [
        facets: [init-size: 50x50]
        actors: [on-action:[set-face f join get-face f get-face face]]
    ]
]
view [
    hgroup [
        f: field return
        btn "1"  btn "2"  btn "3"  btn " + "  return
        btn "4"  btn "5"  btn "6"  btn " - "  return
        btn "7"  btn "8"  btn "9"  btn " * "  return
        btn "0"  btn "."  btn " / "   btn "=" on-action [
            attempt [set-face f form do get-face f]
        ]
    ]
]

...the resulting program doesn't (as Rebol traditionally doesn't) evaluate mathematical expressions with * having a higher precedence than +. E.g. 2 + 3 * 4 gives 20 instead of 14.

I thought I had read somewhere that Rebol3 contained a new function that would evaluate math expressions more the way folks are used from nearly every other context. Is that true? If so, can the above code be made to use it without a significant amount of change?


Solution

  • I'm not sure there's a specific function in Rebol 3 that evaluates operators according to formal precedence (I'd be pleased to be corrected), though there are attempts in the wild to implement such a function. If you were to locate such a function, you can just change the evaluator from do to do-expression (where do-expression is said function) in the on-action block of your "=" button.