tags:

views:

143

answers:

4

Dynamic should be able to handle math without making me have to think about it but even in trivial cases I'm running into some issues. Consider this really simple function::

 public static T DynamicFactorial<T>(T input)
  {
   dynamic num = input;
   dynamic res = 1; 
   for (; num > 1; res *= num, num -=1) ;
   return res;
  }

This is a function that should handle taking any numeric type and performing a factorial on it. Unfortunately, this gives me the following exception, when I try to compute DynamicFactorial(5UL):

Operator '*=' cannot be applied to operands of type 'int' and 'ulong'

Please don't say I can turn this code into a recursive call, as this is an example. My problem is that if you are trying to use dynamic to use unary assignment operator, it doesn't make sense to force me to know my types being computed at compile time. A "potential" solution is to do this::

  public static T DynamicFactorial<T>(T input)
  {
   dynamic num = input;
   T ONE = (T)(1 as dynamic); 
   dynamic res = ONE; 
   for (; num > ONE; res *= num, num -=ONE) ;
   return res;
  }

This works, but holy hell is this ugly and requires me to create a constant of the type I plan on actually using, which is crappy to say the least.

+2  A: 

I don't think this is a bug. The type of res is inferred from 1 which is, by default, of type int.

Ondrej Tucny
I'd agree with you if I had used the `var` keyword. Since I used dynamic I'd expect it to use the DLR to figure out the correct type to use for the assignment, to have done a cast on the other type. Even If I change it to 1UL, it'll blow up on `DynamicFactorial(5)`, for the error of *= cannot be applied to operands of type 'ulong' and 'int'
Michael B
The DLR can't get over fundamental type incompatibilities (what happens if you use `-1` instead of `1`?)
Adam Robinson
+3  A: 

Looks like you misunderstand how dynamic works. It adds some dynamic features to C#, but it doesn't mean that C# forgot about type strictness anymore. dynamic means that dispatch will be in runtime. But real type of variable is not dynamic at all. It is as usual inferred in compile time, but there are special types like ExpandoObject that can make use of dynamic dispatch. Primitive types do not and behave as usual. 1 is inferred to be int, so then your dynamic is just int. And from that point exception is pretty valid. dynamic in your example is useless, it will not expand. You should define your sum variable at compile time or use BigNum if you want to make it expandable.

Andrey
+1  A: 

Its not dynamics that are painful here, because they work as they should. The type of res in your first example is inferred from the constant 1 which is an integer.

The problem here is that in .Net there is no base type for all the numbers, so you can't just restrict the generic parameter T and use it instead of dynamics here.

Grzenio
+15  A: 

The fundamental design principle of "dynamic" is that the analysis at runtime is exactly the same as the analysis would have been at compile time if the compiler had been given the runtime types.

So let's take a modified version of your code:

 ulong input = whatever;
 dynamic num = input; 
 dynamic res = 1;  
 res = res * num;

That should behave at runtime exactly as though the compiler had known the types of everything marked as "dynamic". It should behave exactly as

 ulong input = whatever;
 object num = input; 
 object res = 1;  
 res = (int)res * (ulong)num;

And that program gives an error at compile time, so logically the dynamic version must give the same error at runtime.

Dynamic should be able to handle math without making me have to think about it

Absolutely not. That is not a design principle of the dynamic feature. The purpose of the dynamic feature is to simplify interaction of C# code with code in libraries designed to interact with dynamic languages, either modern libraries (like those designed for Python and Ruby), or legacy libraries (like those designed for COM automation via VB6 or VBScript). Doing VB-style type promotion on results of arithmetic expressions was not at all on our minds when we designed this feature, and as you've discovered, it does so badly.

Let me make this perfectly clear: dynamic is not about making C# a dynamic language, which seems to be what you think it is about. Dynamic is about making C# a statically typed language that interoperates well with libraries designed for dynamic languages. If what you want is a language with dynamic arithmetic, consider Visual Basic or Python.

(Incidentally, some might wonder why int + ulong is not legal in C#. There are seven nonlifted numeric addition operators in C#: int+int, uint+uint, long+long, ulong+ulong, float+float, double+double and decimal+decimal. Of these seven, which one is the best? int+int, uint+uint and long+long are out because the ulong might not fit. ulong+ulong is out because the int might be negative. That leaves float, double and decimal. Float is better than double (because it is more specific) so double goes away. But converting a ulong to float is neither better nor worse than converting a ulong to decimal. Since we have an ambiguity here we produce an error. Insert a cast to resolve the ambiguity if for some bizarre reason you have to add an int to a ulong.)

Finally, I note that there are ways to do what you want. I haven't actually tried it but this would probably work:

public static T DynamicFactorial<T>(T input) 
{ 
    dynamic num = input; 
    dynamic one = default(T);
    one++;
    dynamic res = one;  
    while (num > one)
    {
        res *= num;
        num--;
    }
    return res; 
} 

This will work for any type where the default is zero and there are ++, --, and * operators defined on it.

However, this is gross, slow, and an abuse of generics. Are you really going to want to compute factorials of ushort? Factorial is an easy function to define and you're probably not going to need more than half a dozen versions of it, tops. I say just write it half a dozen times rather than saving a tiny number of keystrokes by abusing generics and dynamic.

Eric Lippert
This is an excellent explanation. However, I still think dynamic makes C# more like a dynamic language. Consider two classes, A and B which both are implicitly convertible to each other. `object o = new B();``A a = (A)o;` is a compilation error as the cast doesn't work. But if o is declared `dynamic` it works just fine, making it the swiss army knife approach and sort of like CType in VB.
Michael B
@Michael, I believe if `o` were dynamic, the expression would evaluate to `A a = (A)(B)o;` at runtime, which is also the legal compile-time way to write the code with `o` as `object`.
Anthony Pegram
@Michael: @Anthony is correct. Remember, dynamic means "act at runtime as though the types were known at compile time". If the runtime type of o is dynamic, then the runtime engine should behave as the compiler would have had o's type been B at compile time.
Eric Lippert