| Here's the problem: Take a list representing a mathematical expression in postfix (aka RPN) and evaluate it. (2 2 +) => 4 or
(2 2 + 9 1 - /) => 1/2.
Pattern-matching args I feel make this very clean because you don't have to pick apart the arguments using destructuring-bind or whatnot.Here's an implementation in mathematica: (2 underscores mean one or more elements; 3 underscores mean zero or more elements) (* start with an empty stack *)
rpn[lst_] := rpn[lst, {}]
(* all done; return what's on the stack *)
rpn[{}, {x_}] := x
(* extra stuff on the stack *)
rpn[{}, {_, __}] := ERROR1
(* divide by zero *)
rpn[{Divide, ___}, {0, ___}] := ERROR2
(* pop, pop, push... *)
rpn[{a_Symbol, b___}, {x_, y_, r___}] :=
rpn[{b}, {a[y,x], r}]
(* just push... *)
rpn[{a_, b___}, {s___}] := rpn[{b}, {a,s}]
Call it like so: rpn[{2,2,Plus,9,1,Subtract,Divide}] => 1/2
|