Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Parsing a postfix expression in C#, my naive approach

By , 21 Dec 2010
Rate this:
Please Sign up or sign in to vote.
For those who like dense code, here is a sample Smile | :)
 
- Make the dictionary static readonly, init directly
- Swap the arguments in the lambda expressions and call by direct pop from the stack
- Make the regex simpler and put the logic of parsing into the Exec (the regex only tokenizes the string)
- Use Linq extensions for iterating over the matches (debatable, though)
 
This code is not really good code - but it shows some alternate techniques.
 
Have fun!
 
Andi
 
class RPNCalc
{
    private static readonly Dictionary<string, Func<int, int, int>> oper = new Dictionary<string, Func<int, int, int>>()
    {
        { "+", (b,a) => a + b }, { "-", (b,a) => a - b }, { "*", (b,a) => a * b }, { "/", (b,a) => a / b }
    };
    private Stack<int> stack = new Stack<int>();
    private string Exec
    { set { stack.Push(oper.ContainsKey(value) ? oper[value](stack.Pop(), stack.Pop()) : int.Parse(value)); } }
    public int Calc(string s)
    { new Regex(@"\s*(\d+|[-+*/])\s*").Matches(s).Cast<Match>().ToList().ForEach(m=>Exec=m.Value); return stack.Peek(); }
}
 
class Program
{
    static void Main(string[] args)
    {
        string expr = "23 5-12*";
        RPNCalc objCalc = new RPNCalc();
        Console.WriteLine("Expr: {0} = {1}", expr, objCalc.Calc(expr));
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Andreas Gieriet
Founder eXternSoft GmbH
Switzerland Switzerland
I feel comfortable on a variety of systems (UNIX, Windows, cross-compiled embedded systems, etc.) in a variety of languages, environments, and tools.
I have a particular affinity to computer language analysis, testing, as well as quality management.
 
More information about what I do for a living can be found at my LinkedIn Profile and on my company's web page (German only).
Follow on   LinkedIn

Comments and Discussions

 
GeneralReason for my vote of 5 Nice. PinmvpCPallini2-Jun-11 22:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 21 Dec 2010
Article Copyright 2010 by Andreas Gieriet
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid