hi this is a small pice of code I made in delphi I put together that can calculate RPN expressions.
at the moment it only works with basic operators, no function support as of yet also all operators and numbers need to be seperated with a space.
Hope you find it usfull.
Module file
myRpn.pas
Code
Code:
//Reverse Polish Notation by Ben A.k.a DreamVB Version 1.0
//Small module to calculate RPN expresions.
unit myRpn;
interface
uses
SysUtils, Classes, math;
const
MAX_STACK = 1000;
function RPN(expr: string): Double;
var
m_Stack: array[0..MAX_STACK] of Double;
m_sp: Integer;
implementation
function Pop: Double;
begin
if m_sp < 0 then
m_sp := 0;
Result := m_Stack[m_sp];
DEC(m_sp);
end;
procedure Push(value: Double);
begin
INC(m_sp);
m_Stack[m_sp] := value;
end;
function IsNumber(value: string): Boolean;
begin
//Test if string is a number.
try
StrToFloat(value);
Result := True;
except
Result := False;
end;
end;
function RPN(expr: string): Double;
var
Val: Double;
a, b: Double;
Que: TStringList;
I: Integer;
Token: string;
begin
//Split the string.
Que := TStringList.Create;
with Que do
begin
Delimiter := ' ';
StrictDelimiter := True;
DelimitedText := expr;
end;
//END OF SPLIT STRING
for I := 0 to Que.Count - 1 do
begin
//Get token
Token := Que[I];
//Test if we have a number.
if IsNumber(Token) then
begin
//Push number onto the stack
Push(StrToFloat(Token));
end;
//Deal with the operators.
if (Token = '+')
or (Token = '-')
or (Token = '/')
or (Token = '*')
or (Token = '^') then
begin
case Token[1] of
'+':
begin
Val := (Pop + Pop);
Push(Val);
end;
'-':
begin
Val := -(Pop - Pop);
Push(Val);
end;
'*':
begin
Val := (Pop * Pop);
Push(Val);
end;
'/':
begin
a := Pop;
b := Pop;
Push((b / a));
end;
'^':
begin
a := Pop;
b := Pop;
Push(power(b, a));
end;
end;
end;
end;
//Return result.
Result := Pop;
end;
end.
Example
Code:
//10+2 *(5+16) / 2 - (2+2) *2=23
ShowMessage(FloatToStr(RPN('10 2 5 16 + * 2 / + 2 2 + 2 * - ')));