Click here to Skip to main content
15,880,891 members
Articles / Programming Languages / C#
Tip/Trick

Shunting Yard in C#

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
12 Mar 2013CPOL 15.7K   270   8   2
An implementation of the Shunting yard algorithm.

Introduction

The Shunting yard algorithm takes an expression, e.g., 3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3 and evaluates it in RPN.

Background

I was looking for a Shunting yard algorithm in C# for a web development project to lexical analyse XHTML code. As I was unable to find anything I spent some time writing code to solve my problem. I think others can use it as well.

An good article on the Shunting yard algorithm can be found at Wikipedia http://en.wikipedia.org/wiki/Shunting-yard_algorithm .

Using the code

To use the code we have to make a new class inheriting from my class ShuntingYardBase<Result,Input>, where Result is the type returned from the code, and Input is the type of source, normally String, but can be any type including your own list of classes.

Then we have to implement some virtual functions:

This is from my demo code - a simple math evaluator.

C#
public override double Evaluate(double result1, char opr, double result2)
{
    if (!Oprs.ContainsKey(opr))
        throw new Exception("Wrong operator!!");
    switch (opr)
    {
        case '+':
            return (double)result1 + result2;
        case '-':
            return (double)result1 - result2;
        case '*':
            return (double)result1 * result2;
        case '/':
            return (double)result1 / result2;
        case '^':
            return Math.Pow(result1, result2);
    }
    return base.Evaluate(result1, opr, result2);
}

After implementing all the virtual functions (see the code example), use the object:

C#
ShuntingYardSimpleMath SY = new ShuntingYardSimpleMath();
String s = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3";
Console.WriteLine("input: {0}", s); Console.WriteLine();
List<String> ss = s.Split(' ').ToList();
SY.DebugRPNSteps += new ShuntingYardBase<double, string>.DebugRPNDelegate(SY_DebugRPNSteps);
SY.DebugResSteps += new ShuntingYardBase<double, string>.DebugResDelegate(SY_DebugResSteps);
Double res = SY.Execute(ss, null);
bool ok = res == 3.0001220703125;
Console.WriteLine("input: {0} = {1} {2}", s, res, (ok ? "Ok" : "Error"));
Console.ReadKey();

Points of Interest

It is interesting that this code also can be used to lexical analyze source code, C# , HTML, etc.

License

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


Written By
Software Developer
Denmark Denmark
Software developer

Comments and Discussions

 
QuestionNo Code? Pin
FatCatProgrammer10-Dec-12 3:45
FatCatProgrammer10-Dec-12 3:45 
AnswerRe: No Code? Pin
Søren Gullach12-Dec-12 2:54
Søren Gullach12-Dec-12 2:54 
Yes, operator precedence i acounted fore!!

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

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