C# ambiguity in Func + extension methods + lambdas - c#

I've been trying to make my way through this article:
http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx
... And something on page 1 made me uncomfortable. In particular, I was trying to wrap my head around the Compose<>() function, and I wrote an example for myself. Consider the following two Func's:
Func<double, double> addTenth = x => x + 0.10;
Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%";
No problem! It's easy to understand what these two do.
Now, following the example from the article, you can write a generic extension method to compose these functions, like so:
public static class ExtensionMethods
{
public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
this Func<TFirstOutput, TLastOutput> toPercentString,
Func<TInput, TFirstOutput> addTenth)
{
return input => toPercentString(addTenth(input));
}
}
Fine. So now you can say:
string x = toPercentString.Compose<double, double, string>(addTenth)(0.4);
And you get the string "50%"
So far, so good.
But there's something ambiguous here. Let's say you write another extension method, so now you have two functions:
public static class ExtensionMethods
{
public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>(
this Func<TFirstOutput, TLastOutput> toPercentString,
Func<TInput, TFirstOutput> addTenth)
{
return input => toPercentString(addTenth(input));
}
public static Func<double, string> Compose<TInput, TFirstOutput, TLastOutput>(this
Func<double, string> toPercentString,
Func<double, double> addTenth)
{
return input => toPercentString(addTenth(input + 99999));
}
}
Herein is the ambiguity. Don't these two function have overlapping signatures? Yes. Does this even compile? Yes. Which one get's called? The second one (which clearly gives you the "wrong" result) gets called. If you comment out either function, it still compiles, but you get different results.
It seems like nitpicking, but there's something that deeply offends my sensibilities here, and I can't put my finger on it. Does it have to do with extension methods? Does it have to do with lambdas? Or does it have to do with how Func<> allows you to parameterize the return type? I'm not sure.
I'm guessing that this is all addressed somewhere in the spec, but I don't even know what to Google to find this.
Help!

There's nothing ambiguous here. The second one will get called whenever it is an exact match. Whenever the match is not exact, you get the first function, because by default it is going to be an exact match for everything else.
If you create a Func<double, string>, and another that is Func<double, double>, call .Compose while explicitly specifying <double, double, string>, the compiler has enough information to determine that the second version is going to be an exact match and therefore it is the one used.
But consider this foolish example:
Func<string, string> doubleString = s => s + s;
Func<DateTime, string> dateToString = date => date.ToString();
Func<DateTime, string> composedFunction = doubleString.Compose(dateToString);
Console.WriteLine(composedFunction(DateTime.Now));
Which version gets called? What's the result? The first version, and the output is the date as a string concatenated to itself.
On the other hand, if you had a more realistic example using Func<double, string> and Func<double, double> and weren't as explicit with the call to Compose, which version gets called?
Func<double, string> toPercentString = d => d.ToString("0.0%");
Func<double, double> addTenth = d => d + 0.1;
Console.WriteLine(toPercentString.Compose(addTenth)(0.8));
The first one, because the compiler determines it to be the exact match versus the second. Since I'm not Eric Lippert or Jon Skeet, I'll not even attempt to explain the binding on that one.
static void DoSomething(float f, double d) { }
static void DoSomething(double d, float f) { }
...
DoSomething(1, 1);
This is ambiguous (and doesn't compile because of it).

I don't see what this has to do with delegates, generics, or extension methods; your fundamental problem seems to be with overloading (and specifically, method overload resolution when there are multiple candidates). Consider:
public static class Test {
public static void Method(string s) {
Console.WriteLine("String version: " + s);
}
public static void Method(object o) {
Console.WriteLine("Object version: " + o.ToString());
}
public static void Main(string[] args) { Method("my string"); }
}
In Main, which method gets called? Is there ambiguity? Overload resolution kicks during compilation and one method is determined to be a better fit (the method taking a string). Just as in your case, commenting out the first overload will result in code which compiles but calls the other overload. The same thing happens if the second method is defined as:
public static void Method<T>(T t) {
Console.WriteLine("Generic version: " + t.ToString());
}
Although this is a candidate for overload resolution, the overload taking a string is an exact match and is preferred.

Related

confused about return methods and voids in C#

Want feedback if i`m correct here?
Use void if you are not returning anything in a method,
otherwise
Name your data types used in the method criteria before method name.
use Return in the method before the calculation or output.
So something like this.
static int MyMethod(int x)
{
return 5 + x;
}
static void Main(string[] args)
{
Console.WriteLine(MyMethod(3));
}
// Outputs 8 (5 + 3)
What if my method has ints and doubles?
Do I write as follows? (another words do I have to mention every type i`m using prior to the method name?
static int double myMethod (int x, double y)
Even with that I dont know when is a method void? It seems my methods all return values.
Isnt the following returning the values of the arguments? So why should I label it void?
static void MyMethod(string fname, int age)
{
Console.WriteLine(fname + " is " + age);
}
static void Main(string[] args)
{
MyMethod("Liam", 20);
MyMethod("Jenny", 25);
MyMethod("Tom", 31);
}
I can only think that a void means there is no new calculation being done in the actual method body, passing arguments into a method and spitting them out for user viewing does not mean its "returning a value", I dont know what i`m talking about.
Let's be completely clear about what these bullets mean.
Use void if you are not returning anything in a method, otherwise
In this context, "return" means that the method provides an output that can be assigned to a variable by the caller. For example
int Return10()
{
return 10;
}
...allows the caller to do this:
int x = Return10();
Console.WriteLine(x); //Outputs "10"
A method should "return" void when its results cannot be assigned. For example, if the results are printed on the screen.
void Print10()
{
Console.WriteLine("10"); //Prints 10 to the screen
}
...which allows the caller to do this:
Print10();
You cannot assign it because it doesn't return anything. This doesn't work:
int x = Print10(); //Compiler error
Name your data types used in the method criteria before method name.
A method can return exactly one value or object. So "types" here is wrong. You can only specify one type.
Use return in the method before the calculation or output.
This is a little misleading. The return keyword should be followed by an expression which can be assigned.
int Return10()
{
return 10 + 10; //Is okay because it's an expression and could be assigned
}
int Return10()
{
var x = 10 + 10;
return x; //This is also okay; in fact it does exactly the same thing as the previous example
}
int Return10()
{
return Console.WriteLine("10"); //Compiler error; can't be assigned to anything.
}
By the way, a method can also output something and return it:
int WriteAndReturn10()
{
int x = 10;
Console.WriteLine(x);
return x;
}
I am going to address the following
What if my method has ints and doubles? Do I write as follows?
(another words do I have to mention every type i`m using prior to the
method name?
There are no built in ways or syntax to return more than one type from a method as the return parameter.. This is basically historical and has been this way since dinosaurs roamed the earth.
However, there are lots of options that achieve the same result. For instance, you could use a custom struct, you could use out parameters, you could use a class, or a delegate parameter of some kind. However, a modern succinct approach might be to use a Value Tuple:
static (int someInt, double someDouble) myMethod (int x, double y)
{
return (x,y);
}
Fun Fact : even though this looks like you a returning more than one type, you are actually just invoking a special syntax that wraps your return parameters in a single type of struct
Usage
var result = myMethod(1,2.2);
Console.WriteLine(result.someInt);
Console.WriteLine(result.someDouble);
Or if you want to get fancy, you can use the newer deconstructed syntax
var (someInt, someDouble) = myMethod(1,2.2);
Console.WriteLine(someInt);
Console.WriteLine(someDouble);
Additional Resources
return (C# Reference)
Methods (C# Programming Guide)
Tuple types (C# reference)
out parameter modifier (C# Reference)
ref (C# Reference)
Using Delegates (C# Programming Guide)

How to wrap a Func<T1...Tn> with unknown number and type of parameters in C#?

Suppose I have this class:
public class Function {
public int argc; //number of arguments of the function
public float[] argv;
public Func<float> f; //attribute to store a function (e.g. Sin(x) or Pow(a, b))
}
I want to create instances of Function that hold different functions, like Sin(x) or Pow(a, b), but I don't know how to bind an existing function (with any number of arguments) to a Func. Obviously its declaration would not always be Func<float> but Func<float, float>, Func<float, float, float>, etc.
I've looked for Func, delegate, Action but still didn't figure out how to have this "function capsule" that can hold and execute functions with different number of arguments. For simplicity I consider the only input and output type is float.
I'm thinking about using something like Func<List<float>> but I want to know if there is a better option.
I want to suggest an answer that fits more accurately the scenario described by the OP. The key is in the usage of Delegate.DynamicInvoke which lets you pass an indefinite number of arguments to a delegate.
public class Function<TReturn> {
private readonly object[] _argv;
private readonly Delegate _func;
public Function(Delegate func, params object[] args) {
_func = func;
_argv = args;
}
public TReturn Run() {
object v = _func.DynamicInvoke(_argv);
return (TReturn)v;
}
}
And its usage lets you decide dynamically the number of arguments you wish to pass:
var s = new Function<double>((Func<double, double>)(x => Math.Sin(x)), 1 );
Console.WriteLine(s.Run()); // prints 0.8414709848078965
var p = new Function<double>((Func<double, double, double>)((a, b) => Math.Pow(a, b)), 2, 3);
Console.WriteLine(p.Run()); // prints 8
var d = new Function<string>((Func<string, double, string>)((a, b) => a + b.ToString()), "hello, ", 42);
Console.WriteLine(p.Run()); // prints "hello, 42"
Note that type checking is only performed at run-time when calling Function.Run() and not when constructing the Function object because of its dynamic nature. If you know for sure that all passed arguments will always be of the same type, you could enforce that statically by adding a TArg generic type.

How do I pass variable arguments to a function that calls specific functions based on the number of arguments?

This is a follow up question to How do I pass a function pointer delegate for a different class in c#
I have a class
public class ClassA
{
public void Foo()
{
Console.WriteLine("Foo()");
}
public void Foo(int x, int y)
{
Console.WriteLine("Foo(" + x.ToString() + ", " + y.ToString() + ")" );
}
public void Foo(int x, int y, int z)
{
Console.WriteLine("Foo(" + x.ToString() + ", " + y.ToString() + ", " + z.ToString() + ")" );
}
}
In another method, I would like to call the class functions of classA like this:
ClassA obj = new ClassA();
TakesFun(obj.Foo);
TakesFun(obj.Foo, 1, 2);
TakesFun(obj.Foo, 1, 2, 3);
What should be the syntax of TakesFun? I would like to make it generic to take in many/any/none arguments and call the appropriate function based on the number of arguments?
Obviously below function syntax is wrong, but I am looking for one function similar to that.
public static void TakesFun<TParam>(Action<TParam[]> action, params TParam[] paramList)
{
Console.WriteLine("TakesFun");
action(paramList);
}
EDIT1: ClassA Foo functions were just an example. I would like to call more complicated functions which can take any kind of argument.
Like for eg:
public void CleanList(List<int> l)
{
l.Clear();
}
In another method, I would like to call the class functions of classA like this:
TakesFun(obj.Foo);
You go on to note that TakesFun is a single method that takes an Action, rather than a collection of overloaded methods.
You can't always get what you want, and you'll have to learn to live with the disappointment. C# does not support the feature you want.
You are converting obj.Foo from a method group form to a delegate form, and that requires that C# performs overload resolution by comparing the delegate in the formal parameter list of TakesFun with the collection of methods named Foo, and then choose the best one.
Since there is no "best one" at compile time, this will fail.
Find another way to solve your problem. Your question sounds very much like what we call an "XY problem". That is, you have some real problem, you have a crazy idea about how to solve it that will never work, and now you're asking a question about your crazy idea. Ask a question about the real problem. There's a better way to solve it than this, almost certainly.
Now, if we relax some of the constraints of your problem then we can do it. In particular, if we relax the constraint that there be only one TakesFun and that it be variadic, then we can do it. I note that TakesFun is in fact the function application operation:
static void Apply(Action action) => action();
static void Apply<A>(Action<A> action, A a) => action(a);
static void Apply<A, B>(Action<A, B> action, A a, B b) => action(a, b);
static void Apply<A, B, C>(Action<A, B, C> action, A a, B b, C c) => action(a, b, c);
... and so on, as many as you need
And now the magic of overload resolution solves your problem:
Apply(obj.Foo, 1, 2, 3); // Works fine
Overload resolution deduces that Apply means Apply<int, int, int>, that the Action is Action<int, int, int> and that the Foo meant is the one that takes three integers.
C# type inference is pretty good, but you have to use it within the bounds that we designed into the language.
UPDATE: Based on your comments it sounds like you are trying to re-invent the task parallel library. I would investigate the TPL to see if it already meets your needs.
In C# we represent the notion of a unit of work that will be performed in the future as Task; there is a huge library and built-in language support for composing workflows out of tasks, scheduling their continuations to various threads, and so on. Use this work rather than attempting to invent it yourself.
If for example you wanted to create unstarted tasks that represent future work you would do it like this:
static Task TaskFactory(Action action) => new Task(action);
static Task TaskFactory<A>(Action<A> action, A a) => new Task(()=>action(a));
static Task TaskFactory<A, B>(Action<A, B> action, A a, B b) => new Task(()=>action(a, b));
and so on. Now you can do:
Task t = TaskFactory(obj.Foo, 1, 2);
and get back a t that when started will execute the action. You can then say what you want to happen when the task is complete:
t.ContinueWith(task => Console.WriteLine("Task complete!"));
and then start it up:
t.Start();
There are mechanisms for creating tasks that are already started and run on worker threads. There are mechanisms for scheduling tasks or their completions to run on particular threads. And so on; this is a huge topic. Ask another question if you have questions about that.

Can you chain the result of one delegate to be the input of another in C#?

I am looking for a way to chain several delegates so the result from one becomes the input of the next. I am trying to use this in equation solving program where portions are done by different methods. The idea is that when you are building the equation the program adds the delegates and chains them in a particular order, so it can be solved properly. If there is a better way to approach the problem please share.
This might help:
public static Func<T1, TResult> Compose<T1, T2, TResult>(Func<T1, T2> innerFunc, Func<T2, TResult> outerFunc) {
return arg => outerFunc(innerFunc(arg));
}
This performs function composition, running innerFunc and passing the result to outerFunc when the initial argument is supplied:
Func<double, double> floor = Math.Floor;
Func<double, int> convertToInt = Convert.ToInt32;
Func<double, int> floorAndConvertToInt = Compose(floor, convertToInt);
int result = floorAndConvertToInt(5.62);
Func<double, int> floorThenConvertThenAddTen = Compose(floorAndConvertToInt, i => i + 10);
int result2 = floorThenConvertThenAddTen(64.142);
Yes this is possible - you need to ensure that the return type of the delegate is one that is the parameter type of the delegate being invoked.
A lot of LINQ is built this ways, though you may want to take a look at expressions.
The type of API you are describing is called a Fluent API. Take a look at the preceeding article for a good tutorial.
With regard to delegate chaining, take a look at the LINQ extension methods in .NET 3.5, in particular how lambda functions (delegates) passed to a function result in an IEnumerable result which can then be chained with another extension method + lambda.
In your specific case you might need to create a class called a Functor to accept a delegate and return another Functor which too can be operated on by delegates.
Best regards,
using GetInvocationlist you can achieve this.
Delegate[] chain = chained.GetInvocationList();
int res = 10;
for( int i = 0; i < chain.Length; i++ )
{
//Call chain[i]
res = chain[i](res);
}
I have been working on a similar problem myself which involved invoking a sequence of delegates and passing the output of one delegate to the next (and so on...) so thought you might be interested to see the code I developed as a proof-of-concept:
static class Program
{
private static IList<Func<int, int>> delegateList =
new List<Func<int, int>>()
{
AddOne, AddOne, AddOne, AddOne, AddOne,
AddOne, AddOne, AddOne, AddOne, AddOne,
};
static void Main(string[] args)
{
int number = 12;
Console.WriteLine("Starting number: {0}", number);
Console.WriteLine("Ending number: {0}",
delegateList.InvokeChainDelegates(number));
Console.ReadLine();
}
public static int AddOne(int num) { return num + 1; }
public static T InvokeChainDelegates<T>(this IEnumerable<Func<T, T>> source,
T startValue)
{
T result = startValue;
foreach (Func<T, T> function in source)
{
result = function(result);
}
return result;
}
}
The sequence has to contain delegates of the same type so is not as powerful as the already accepted answer but with a few tweaks, both bits of code could be combined to provide a powerful solution.

Action/Func vs Methods, what's the point?

I know how to use Action and Func in .NET, but every single time I start to, the exact same solution can be achieved with a regular old Method that I call instead.
This excludes when an Action or Func is used as an argument for something I don't control, like LINQ's .Where.
So basically my question is...why do these exist? What do they give me extra and new that a simple Method doesn't?
I think other answers here talk about what an Action/Func is and its use. I will try to answer how to choose between Action/Func and method. The differences first:
1) From a raw performance point of view, delegates are slower compared to direct method calls, but it's so insignificant that worrying about it is a bad practice.
2) Methods can have overloads (same function names with different signatures) but not Action/Func delegates since they are declared as variables and by C# rules you cant have two variables with the same name in a given scope.
bool IsIt() { return 1 > 2; }
bool IsIt(int i) { return i > 2; } //legal
Func<bool> IsIt = () => 1 > 2;
Func<int, bool> IsIt = i => i > 2; //illegal, duplicate variable naming
3) Consequently, Action/Func are reassignable and can point to any function, while methods once compiled remain to be the same forever. It is semantically wrong to use Func/Action if the method it points to never changes during run time.
bool IsIt() { return 1 > 2; } //always returns false
Func<bool> IsIt = () => 1 > 2;
IsIt = () => 2 > 1; //output of IsIt depends on the function it points to.
4) You can specify ref/out parameters for normal methods. For eg, you can have
bool IsIt(out string p1, ref int p2) { return 1 > 2; } //legal
Func<out string, ref int, bool> IsIt; //illegal
5) You cannot introduce new generic type parameter for Action/Func (they are generic already btw, but the type arguments can only be a known type or types specified in the parent method or class), unlike methods.
bool IsIt<A, R>() { return 1 > 2; } //legal
Func<bool> IsIt<A, R> = () => 1 > 2; //illegal
6) Methods can have optional parameters, not Action/Func.
bool IsIt(string p1 = "xyz") { return 1 > 2; } //legal
Func<string, bool> IsIt = (p1 = "xyz") => 1 > 2; //illegal
7) You can have params keyword for parameters of a method, not so with Action/Func.
bool IsIt(params string[] p1) { return 1 > 2; } //legal
Func<params string[], bool> IsIt = p1 => 1 > 2; //illegal
8) Intellisense plays well with parameter names of methods (and accordingly you have cool XML documentation available for methods), not so with Action/Func. So as far as readability is concerned, regular methods win.
9) Action/Func have a parameter limit of 16 (not that you can't define your own ones with more) but methods support more than you will ever need.
As to when to use which, I would consider the following:
When you are forced to use one based on any of the above points, then you anyway have no other choice. Point 3 is the most compelling I find upon which you will have to base your decision.
In most normal cases, a regular method is the way to go. It's the standard way of refactoring a set of common functionality in C# and VB.NET world.
As a rule of thumb, if the function is more than a line, I prefer a method.
If the function has no relevance outside a specific method and the function is too trivial, like a simple selector (Func<S, T>) or a predicate (Func<bool>) I would prefer Action/Func. For eg,
public static string GetTimeStamp()
{
Func<DateTime, string> f = dt => humanReadable
? dt.ToShortTimeString()
: dt.ToLongTimeString();
return f(DateTime.Now);
}
There could be situations where Action/Func makes more sense. For instance if you have to build a heavy expression and compile a delegate, its worth doing it only once and caching the compiled delegate.
public static class Cache<T>
{
public static readonly Func<T> Get = GetImpl();
static Func<T> GetImpl()
{
//some expensive operation here, and return a compiled delegate
}
}
instead of
public static class Cache<T>
{
public static T Get()
{
//build expression, compile delegate and invoke the delegate
}
}
In the first case when you call Get, GetImpl is executed only once, where as in the second case, (expensive) Get will be called every time.
Not to forget anonymous method itself will have certain limits unrelated to Func/Action, making the use little different. Also see this for a related question.
Action and Func are framework-provided Delegate types. Delegates allow functions to be treated like variables, meaning that you can (among other things) pass them from method to method. If you have ever programmed in C++, you can think of Delegates as function pointers that are restricted by the signature of the method they refer to.
Action and Func specifically are generic delegates (meaning they take type parameters) with some of the most common signatures- almost any method in most programs can be represented using one or the other of those two, saving people a lot of time manually defining delegates like we did in .net prior to version 2. In fact, when I see code like this in a project, I can usually safely assume that the project was migrated from .net 1.1:
// This defines a delegate (a type that represents a function)
// but usages could easily be replaced with System.Action<String>
delegate void SomeApplicationSpecificName(String someArgument);
I'd recommend that you look into delegates some more. They are a hugely powerful feature of the C# language.
I use them to create an array of functions. For instance, I may have a ComboBox full of actions that could be taken. I populate the ComboBox with items of a class or structure:
public class ComboBoxAction
{
private string text;
private Action method;
public ComboBoxAction(string text, Action method)
{
this.text = text;
this.method = method;
}
public override string ToString()
{
return this.text;
}
public void Go()
{
this.method();
}
}
Then when someone selects an item, I can call the action.
CType(ComboBox1.SelectedItem, ComboBoxAction).Go()
This is far easier than having a Select statement determine which method to call based on the ComboBox's text.
There's plenty of cases where a Func can help where a Method wouldn't.
public void DoThing(MyClass foo, Func<MyClass, string> func)
{
foo.DoSomething;
var result = func(foo);
foo.DoStringThing(result);
}
So you can specify a different Func whenever you call this method - the DoThing method doesn't need to know what's being done, just that whatever it is will return a string.
You can do this without using the Func keyword by using the delegate keyword instead; it works much the same way.
One great use of action and func are when we need to perform some operation (before or after a method), irrespective of what the method is. For example, we need to retry the method 10 times if exception occurs.
Consider the following method – its return type is generic. So it can be applied on func with any return type.
public static T ExecuteMultipleAttempts<T>(Func<T> inputMethod, Action additionalTask, int wait, int numOfTimes)
{
var funcResult = default(T);
int counter = 0;
while (counter < numOfTimes)
{
try
{
counter++;
funcResult = inputMethod();
//If no exception so far, the next line will break the loop.
break;
}
catch (Exception ex)
{
if (counter >= numOfTimes)
{
//If already exceeded the number of attemps, throw exception
throw;
}
else
{
Thread.Sleep(wait);
}
if (additionalTask != null)
{
additionalTask();
}
}
}
return funcResult;
}

Categories