Anonymous user
Arithmetic evaluation: Difference between revisions
→{{header|TXR}}: New implementation with AST construction and evaluation.
(→{{header|TXR}}: Works with released functionality.) |
(→{{header|TXR}}: New implementation with AST construction and evaluation.) |
||
Line 2,984:
=={{header|TXR}}==
Use TXR text pattern matching to parse expression to a Lisp AST, then evaluate with <code>eval</code>:
<lang txr>@(next :args)
@(
▲@(define genreg (r))
@(cases)@\▼
@{op /[*]/}@(bind nod @(intern op *user-package*))@\
@(end)@\▼
@(end)
@(define
@(
@(bind nod @(intern op *user-package*))@\
▲ @(local n)@\
@(ws)@{n /[0-9]+/}@(ws)@\▼
@(bind code `@reg=@n@nl`)@\▼
@(end)
@(define
▲ @(cases)@\
@(bind nod
▲ @(or)@\
▲ @(end)@\
@(end)
@(define
@(
@(cases)@\
@(
@(cases)@(mulop op)@(term nod2)@(bind nod (op nod1 nod2))@\
@(genreg reg)@\▼
@(
@(or)@\
@(
@(end)@\
@(end)
@(define expr (
@(local
@(term
@(cases)@(addop op)@(expr nod2)@(bind nod (op nod1 nod2))@\
▲ @(cases)@\
@(or)@\▼
@(end)@\
@(end)
@(cases)
@ {source (expr e)}
@ (output)
source: @source
AST: @(format nil "~s" e)
value: @(eval e nil)
@ (end)
@ (maybe)@(expr e)@(end)@bad
@ (output)
erroneous suffix "@bad"
@ (end)
@(end)</lang>
Run:
<
source: 3 + 3/4 * (2 + 2) + (4*4)
AST: (+ 3 (+ (trunc 3 (* 4 (+ 2 2))) (* 4 4)))
value: 19</pre>
|