Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting. However, operators and functions present very differently when writing c# code.

It's easy to put a lambda or a named function in a variable, pass it to a function, etc. However, if you want to do that to an operator such as "+", the first thing to do is to wrap it in a lambda - e.g.

  // invalid
  // Func<int, int, int> plus = + ;
  
  // works in a wrapper fn
  Func<int, int, int> plusFn = (a, b) => a + b;

Related, if you have a function which is generic for some type T, you can call functions of type Func<T> on the values in it, but you can't use operators like + - c# just isn't generic on operators, though it can be on functions.

  public T ApplySomeFunc<T>(Func<T, T> func, T value)
  {
    // this works
    return func(value);

    // this does not
    //return value + value;
  }
I know that the language has no way to specify that the type T has a "+" operator so that's not going to work; but this catches people out regularly, when they try and fail to make math functions that are generic over all numeric types. However, you can do something similar with the "dynamic" type, at the cost or run-time-dispatch.


> Interesting. However, operators and functions present very differently when writing c# code.

Aye, but that's more of a limitation of C#'s syntax

> However, if you want to do that to an operator such as "+", the first thing to do is to wrap it in a lambda - e.g.

That's pretty much what a section (the parens around the operators) does in F# or Haskell.

> I know that the language has no way to specify that the type T has a "+" operator so that's not going to work

Well it's not so much that "operators and functions present very differently when writing C# code" but that "methods and functions present very differently when writing C# code" and that operators are (static) methods more than functions in C#.

Also that C# has no numeric tower[0] so there's indeed no way to say a type is a generic number (whether that number's an int, a double or a decimal). If there was a root `Number` type you could write something along the lines of:

    public T AddNumbers<T> where T:Number(T value)
    {
        // works because all numbers have a `+`
        return value + value;
    }
which is exactly what you write in Haskell:

    addNumbers :: (Num a) => a -> a -> a
    addNumbers a b = a + b
[0] Haskell has a pretty complete/complex one, starting from Num[1] which implements only a few basic operations: (+), (-), (*), negation and conversion from integer.

[1] http://hackage.haskell.org/packages/archive/base/latest/doc/...




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: