Algebraic to RPN
02-24-2017, 09:27 PM (This post was last modified: 02-25-2017 03:10 PM by Han.)
Post: #1
 Han Senior Member Posts: 1,882 Joined: Dec 2013
Algebraic to RPN
The code below takes an algebraic expression and converts it to an RPN string. The program itself is not all that useful (in my opinion) but it hopefully provides to those interested in programming expressions a bit of insight into how expressions are built.

For example, in the CAS view, type:

CRPN(x^2-4*x)

to obtain "x 2 ^ 4 x * - +"

EDIT: Joe Horn pointed out to me that the "+" appeared extraneous -- which was also my initial reaction. As it turns out, the CAS treats subtraction as a sequence of negation followed by addition. So the "-" operator is actually the negation operator, which can be verified by typing f:=neg(x) in the CAS view, and extracting the operation using f[1]. I never really gave this much thought, but it is neat to see how expressions are handled on a lower level.

Code:
#pragma mode( separator(.,;) integer(h32) ) #cas CRPN(f):= begin   local rpn, op, par, n, j, g;   rpn:="";   op:="";   par:="";   if (type(f) <> DOM_SYMBOLIC) then     rpn:=string(f);     return(rpn);   end;   op:=string(f[1]);   n:=size(op);   op:=MID(op,2,n-2);   n:=dim(f) + 1;   for j from 2 to n do     g:=f[j];     if (type(g) <> DOM_SYMBOLIC) then       par:=string(g);     else       par:=CRPN(g);     end;     if (j > 2) then rpn:=rpn + " "; end;     rpn:=rpn + par;     if ((j > 2) or (n == 2)) then       rpn:=rpn + " " + op;     end;   end;   return(rpn); end; #end

Graph 3D | QPI | SolveSys
 « Next Oldest | Next Newest »

 Messages In This Thread Algebraic to RPN - Han - 02-24-2017 09:27 PM RE: Algebraic to RPN - ggauny@live.fr - 02-25-2017, 12:19 PM RE: Algebraic to RPN - compsystems - 02-25-2017, 02:05 PM RE: Algebraic to RPN - Han - 02-25-2017, 03:15 PM RE: Algebraic to RPN - compsystems - 02-26-2017, 02:59 PM RE: Algebraic to RPN - tcab - 07-29-2018, 07:46 AM RE: Algebraic to RPN - Joe Horn - 07-29-2018, 12:10 PM RE: Algebraic to RPN - Komanguy - 07-28-2018, 08:33 PM

User(s) browsing this thread: 1 Guest(s)