views:

126

answers:

5

Hi, first question here, apologies in advance for any foul-ups.

I'm implementing an interpreter for a toy language in C#, and in order to do math in that language I'd like to implement a function like this:

public static object Add( object a, object b )
{
  // return the sum of a and b
  // each might be int, double, or one of many other numeric types
}

I can imagine a very silly and bad implementation of this function with tons of branches based on the types of a and b (using the is operator) and a bunch of casts, but my instinct is that there is a better way.

What do you think a good implementation of this function would be?

Thanks in advance for any insight.

A: 

Hmm interesting, I would use the typeof() operator on the objects coming in and test those against the types you will allow Add operations to be performed on. I'd also imagine you'll throw an exception if oddball types are attempting to be added together?

Ideally however if your only going to allow adding of int, float, double, etc, I would really just create overloaded version of the Add method to handle those various cases.

Capital G
Agree with overloading
Pieces
+5  A: 

Convert your values to the most wide type, for example, to decimal. All types like int, double, short etc. implements IConvertible interface ( http://msdn.microsoft.com/en-us/library/system.iconvertible_members.aspx). It exposes ToDecimal method, which could be used to convert value to Decimal type. Also Convert class is very useful

decimal aop = Convert.ToDecimal(a);
decimal bop = Convert.ToDecimal(b);
decimal sum = aop + bop;
return Convert.ChangeType(sum, typeof(a)); // Changing type from decimal to type of the first operand.
STO
This is an interesting extension/variation on the "just make everything a decimal" idea. Thanks for sharing this.
+1  A: 

One thing you can do is write your own object base for the toy language. It can be either a real class or an interface. That way, you can make sure that all your classes have some kind of functionality for all operations (even if it's only to throw a runtime NotSupported exception). You can do this using interface or abstract functions for the really common things (like ToString or Equals), or using message-passing or some other method for uncommon operations.

(p.s. I cross-posted with STO, but I like STO's idea for numeric types.)

TechNeilogy
+1  A: 

the easiest way to do it right away would be to just test for the types as you said.

But since this is for a toy language implementation (good for you!) then i would suggest using a better abstraction than object to pass around values in your interpreter. maybe make a LanguageNameObject base class and then you can add all the helper methods you want to help you implement this method. Basically the Object class is a bad abstraction for you to work with.... so build a better one!

luke
+11  A: 

If:

  • you just want an easy-to-program solution
  • your little language has the same arithmetic rules as C#
  • you can use C# 4
  • you don't care particularly about performance

then you can simply do this:

public static object Add(dynamic left, dynamic right)
{
    return left + right;
}

Done. What will happen is when this method is called, the code will start the C# compiler again and ask the compiler "what would you do if you had to add these two things, but you knew their runtime types at compile time?" (The Dynamic Language Runtime will then cache the result so that the next time someone tries to add two ints, the compiler doesn't start up again, they just re-use the lambda that the compiler handed back to the DLR.)

If you want to implement your own rules for addition, welcome to my world. There is no magic road that avoids lots of type checks and switches. There are literally hundreds of possible cases for addition of two arbitrary types and you have to check them all.

The way we handle this complexity in C# is we define addition operators on a smaller subset of types: int, uint, long, ulong, decimal, double, float, all enums, all delegates, string, and all the nullable versions of those value types. (Enums are then treated as being their underlying types, which simplifies things further.)

So for example when you're adding a ushort to a short we simplify the problem by saying that ushort and short are both special cases of int, and then solve the problem for adding two ints. That massively cuts down on the amount of code we have to write. But believe me, the binary operator overload resolution algorithm in C# is many thousands of lines of code. It's not an easy problem.

If your toy language is intended to be a dynamic language with its own rules then you might consider implementing IDynamicMetaObjectProvider and using the DLR mechanisms for implementing arithmetic and other operations like function calling.

Eric Lippert
Eric, I appreciate this thoughtful and informative answer. I definitely didn't expect anything of this quality when I asked the question!Kind thanks.