Converting between Func with different # of type args - c#

Are there built in methods for converting between the various types of Func delegates? That is, suppose you need a Func, but you have a Func (and you have the value that should be passed in for the T parameter). For example:
static TREsult Foo<TResult>(Func<TResult> f)
{
// ...
TResult result = f();
// ...
return result;
}
static int MyFunc(int i)
{
return i;
}
void CallFoo()
{
Func<int> func = ConvertFunc(MyFunc, 1); // Does this family of methods exist?
int j = Foo(func);
}
I've written my own, like this:
static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
{
return () => f1(t);
}
static Func<TResult> ConvertFunc<T1, T2, TResult>(Func<T1, T2, TResult> f2, T1 t1, T2 t2)
{
return () => f2(t1, t2);
}
// etc.
But I'm wondering if a family of methods like this exists (or even if there's a better way to do this).
Essentially, I'm doing this for a case where there is some boiler plate code in a method followed by a function call (where the number and types in the function will vary, but the return type is the same), followed by more boiler plate code.
All opinions welcome! Thanks.

static Func<TResult> ConvertFunc<T, TResult>(Func<T, TResult> f1, T t)
{
return () => f1(t);
}
This kind of code to me looks a bit dangerous - not that by itself is anything wrong but need to be careful. You are using closure to embed an input variable in the function. But this could lead to difficult bugs since if the variable changes between converting Func and running it, the result would be different.
I am just curious what would be the benefit. Are you trying to hide away input parameter from the consumer of the function? As long as the variable is a local one passed to it, would be fine.
In terms of a solution, there would not be one since .NET has created 16 different generic Func<> exactly for the same reason.
You can perhaps use reflection to implement a solution but you would be paying a penalty for calling the functions. MethodInfo.GetGenericArguments() would give you the types and you then can use MethodInfo.MakeGenericMethod() to create new ones.
Update
Just to illustrate my point:
static int Double(int number)
{
return number * 2;
}
static void Main(string[] args)
{
int i = 2;
Func<int> f = () => Double(i);
i = 3;
Console.WriteLine(f()); // prints 6 and not 4
}

Related

How to cast Predicate<T> to Func<T, bool> [duplicate]

I have a class with a member Predicate which I would like to use in a Linq expression:
using System.Linq;
class MyClass
{
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression);
}
private IEnumerable<Instrument> m_instrumentList;
private Predicate<Instrument> m_filterExpression;
}
As I read that "Predicate<T> is [...] completely equivalent to Func<T, bool>" (see here), I would expect this to work, since All takes in as argument: Func<Instrument, bool> predicate.
However, I get the error:
Argument 2: cannot convert from 'System.Predicate<MyNamespace.Instrument>' to 'System.Type'
Is there a way to convert the predicate to an argument that this function will swallow?
The two types represent the same logical signature, but that doesn't mean they're just interchangable. A straight assignment won't work, for example - but you can create a new Func<T, bool> from the Predicate<T, bool>. Sample code:
Predicate<string> pred = x => x.Length > 10;
// Func<string, bool> func = pred; // Error
Func<string, bool> func = new Func<string, bool>(pred); // Okay
This is a bit like having two enum types with the same values - you can convert between them, but you have to do so explicitly. They're still separate types.
In your case, this means you could write:
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(new Func<T, bool>(m_filterExpression));
}
The lambda expression approach suggested by other answers will work too, of course.
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(i => m_filterExpression(i));
}
You can convert a predicate to a method by calling Invoke. All delegates have this member. Delegates don't have structural identity, but methods can be converted to matching delegates. This fix has a minor performance cost, as it adds an extra layer of indirection. However, most solutions to this problem have that problem. Eric Lippert discusses this in more detail at https://web.archive.org/web/20140625132124/http://blog.coverity.com/2014/06/18/delegates-structural-identity/ .
In your specific case, replace return m_instrumentList.All(m_filterExpression); with return m_instrumentList.All(m_filterExpression.Invoke);
Sample code demonstrating the actual problem.
void Main()
{
Predicate<int> t1 = Foo;
Func<int,bool> t2 = Foo;
Predicate<int> t3 = t2.Invoke; //Legal
Func<int,bool> t4 = t1.Invoke; //Legal
Predicate<int> t5 = t2; //Illegal
Func<int,bool> t6 = t1; //Illegal
}
bool Foo(int x)
{
return x > 20;
}
return m_instrumentList.All(i => m_filterExpression(i));
Since there are a lot of answers i will add one more just for fun.
If you want your code to compile you can use extention methods
//Original Code
class MyClass4
{
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression);
}
private IEnumerable<Instrument> m_instrumentList;
private Predicate<Instrument> m_filterExpression;
}
Add this class in the same namespace
public static class MyExtentions
{
public static bool All(this IEnumerable<Instrument> enumer, Predicate<Instrument> pred)
{
return enumer.All(e => pred(e));
}
}
As Brian said, you can convert a predicate to a method via Invoke:
public bool DoAllHaveSomeProperty()
{
return m_instrumentList.All(m_filterExpression.Invoke);
}

How can I find out the type of data from the generic type

I have a method in which I send two arguments of the same type and I need to fold them. For example, if these are numbers, then return only the sum, and if the lines are the concatenation of these lines. How can I do it? And if I pass a type that cannot be folded, then I need to throw an exception.
public class Calcul<T>
{
public static T Add(T c1, T c2)
{
}
}
Servy said in a comment:
Don't make the method generic if it's not actually generic, and don't say the method can accept any type if it can't in fact accept any type. As you've already been told, if you want to handle a finite number of specific types, have overloads for each of those types.
to which you replied:
Alas, I showed the teacher, but he said that it was not that. He said that it should be something like an abstract calculator where for each type T you can define the operation N
You can have your method with that signature and no if blocks at all, but the Add method can't be static. You have to pass in a Func<T1, T2, TResult> where T1, T2, and TResult are the same (T):
public class Calculator<T>
{
private readonly Func<T, T, T> _func;
public Calculator(Func<T, T, T> func)
{
_func = func;
}
public T Add(T a, T b)
{
return _func(a, b);
}
}
You'd use it like this:
Func<int, int, int> intAddition = (a, b) => a + b;
var intCalculator = new Calculator<int>(intAddition);
Console.WriteLine(intCalculator.Add(1, 2)); // writes 3
Func<string, string, string> stringAddition = (a, b) => a + b;
var stringCalculator = new Calculator<string>(stringAddition);
Console.WriteLine(stringCalculator.Add("Hello ", "world")); // writes "Hello world"
Online example: https://dotnetfiddle.net/8NOBsv
This way you get to specify the logic of the Add method, and you don't have loads of overloaded methods (or awful type-checking logic inside the method like if ( typeof(T) == typeof(string) ), etc.
You can typeof(T) to get the type information always. Using that, you can use conditional statements to work your way through the logic
Example:
var type = typeof(T);
if (type == int)
{ do something ;}
Generics are used for cases like : 2 different types following the same operations but taking different input types and output types. The underlying usage is that they have the same processes. If you are using type specific processes much, then its better to overload your functions to suit your need.
Reading more into your use case:
Try overloading methods.
private static int doSomething(int n1, int n2)
{
return (n1) + (n2);
}
private static float doSomething(float n1, float n2)
{
return (n1) - (n2);
}
Here's a generic way that works as long as T supports the + operator. However, it uses runtime checking. As far as I can tell there is no way to use type constraints to check this at compile time.
Adapted from: https://stackoverflow.com/a/5997156/6713871
public class Calcul<T>
{
public static T Add(T c1, T c2)
{
return (dynamic)c1 + (dynamic)c2;
}
}
As others have said you should probably use overloads. However it's possible to do something like this
static class Calc<T>
{
public static T Add(T a, T b)
{
if (typeof(T) == typeof(int))
{
return (T)(object)((int)(object)a + (int)(object)b);
}
if (typeof(T) == typeof(uint))
{
return (T)(object)((uint)(object)a + (uint)(object)b);
}
throw new ArgumentOutOfRangeException($"Type {typeof(T).Name} is not supported.");
}
}
And call it with:
Calc<int>.Add(1 , 2); // returns 3
Calc<double>.Add(2d, 3d).Dump(); // throws exception

How to refactor multiple extensions with different Func parameters with same result

I am new to Func/Action/Predicate and want to know what is the best way to refactor my code as I will potentially have a lot of repeated code.
I have created 2 extension methods which take a Func parameter (always returning bool):
public static void MyExtension<T>(this T obj, Func<T, bool> predicate)
{
do
{
//function code
} while (predicate(obj));
}
public static void MyExtension<T1, T2>(this T1 obj, T2 OtherObject, Func<T1, T2, bool> predicate)
{
do
{
//function code
} while (predicate(obj, OtherObject));
}
What I want, is to only code the do/while loop once as I might have a lot of functions which will only generate a different Func but will all want to run the same do/while loop.
I was thinking something like this, which takes any Func parameter and runs it on each loop. The code in the loop doesn't care about the types passed into the Func.
public static void DoLoop(Func predicate)
{
do
{
//function code
} while (predicate);
}
But this clearly doesnt work. Does anyone know how to resolve this, or am I doing something fundamentally wrong?
The end result is I want to call the code like below:
var Obj = new MyObj();
Obj.MyExtension((x) => x.Prop1.Contains("string"));
var OtherObj = new MyObj();
Obj.MyExtension(OtherObj, (x,y) => x.Prop1.Contains("string") && y.Prop1.Contains("other"));
Thanks.
Since your generic methods are parameterized on a different number of generic types, you need to keep all function signatures in place in order for the calling code to compile. However, you can move the implementation into a common helper method to reduce repeated code:
// This is your single implementation
private static void DoLoop(Func<bool> predicate) {
do {
//function code
} while (predicate());
}
// These are the wrappers
public static void MyExtension<T>(this T obj, Func<T, bool> predicate) {
DoLoop(() => predicate(obj));
}
public static void MyExtension<T1, T2>(this T1 obj, T2 OtherObject, Func<T1, T2, bool> predicate) {
DoLoop(() => predicate(obj, OtherObject));
}
Wrappers construct parameter-less predicate, and pass it to the private DoLoop method, which provides the implementation.

C# Continuation Monad Implementation

I have been working on allowing function chaining. I have created a class called continuationmonad which takes a value, and a function from a => b. This allows me to use fmap and bind to chain these together. I have also used lazy to allowed calls to be defered where possible.
Is this class really the continuation monad or is it something else. I am finding it hard to find good literature which is not is Haskell.
Also any comments on how to improve / correct this.
using NUnit.Framework;
using System;
namespace Monads
{
public class Continuation<Input, Output>{
public Continuation(Input value, Func<Input,Output> function){
this.value = new Lazy<Input>( () => value);
this.function = function;
}
public Continuation(Lazy<Input> value, Func<Input,Output> function){
this.value = value;
this.function = function;
}
public Continuation<Output, Result> FMap<Result>(Func<Output, Result> map){
return new Continuation<Output, Result>(new Lazy<Output>( () => Run() ), x => map(x));
}
public Continuation<Output,Result> Bind<Result>(Func<Output, Continuation<Output, Result>> f){
return f(Run());
}
public Output Run(){
return function(value.Value);
}
private Func<Input, Output> function;
private Lazy<Input> value;
}
public static class ContinuationExtension{
public static Continuation<A,B> Unit<A,B>(this Func<A,B> f, A value){
return new Continuation<A, B>(value,f);
}
public static Continuation<A,B> Unit<A,B>(this A value,Func<A,B> f){
return new Continuation<A, B>(value,f);
}
}
[TestFixture]
public class MonadTests
{
public Continuation<int,int> Wrapped(int value){
return new Continuation<int,int>(value, x => x * 10);
}
[Test]
public void ContinuationMonadTests()
{
var number = 42;
var result = number.Unit(x => x + 8).FMap(x => x * 2).Bind(Wrapped).Run();
Console.WriteLine(result);
}
}
}
This is not the continuation monad. You are much closer to the Haskell Monad instance for functions.
You aren't getting anything that you couldn't get just from using Lazy<>. Since you have provided the input when you build an instance of your class, you aren't building functions, you are building values that are determined by a computation that hasn't been evaluated yet. Lazy<> delays the evaluation of computation until the value is needed.
Let's put together something like the Haskell Monad instance for functions in c#. LINQ syntax has established the convention for Monads in c#. They should have:
a Select extension method analogous to a Haskell Functor's fmap
a SelectMany extension method analogous to Haskell's Monad's >>=
an additional SelectMany that LINQ syntax uses. This takes an additional function that combines the value from two steps together.
Unfortunately, there's no convention for what the analog of a Monad's return should be called; we'll call ours Constant. Unfortunately, Constant won't be very convenient because c#'s type inference won't be able to figure out the types.
public static class Function
{
public static Func<TIn, TOut> Constant<TIn, TOut>(TOut result)
{
return x => result;
}
public static Func<TIn, TOut> Select<TIn, TMid, TOut>(
this Func<TIn, TMid> func,
Func<TMid, TOut> proj)
{
return x => proj(func(x));
}
public static Func<TIn, TOut> SelectMany<TIn, TMid, TOut>(
this Func<TIn, TMid> func,
Func<TMid, Func<TIn, TOut>> proj)
{
return x => proj(func(x))(x);
}
public static Func<TIn, TOut> SelectMany<TIn, TMid1, TMid2, TOut>(
this Func<TIn, TMid1> func,
Func<TMid1, Func<TIn, TMid2>> proj1,
Func<TMid1, TMid2, TOut> proj2)
{
return x => {
var mid1 = func(x);
var mid2 = proj1(mid1)(x);
return proj2(mid1, mid2);
};
}
}
Note that defining these extension methods only lets you interact with something like it's a Monad, it doesn't let you write code that's generic over the specific Monad being used. There's a sketch of how to do that in the second half of this answer.
This might be a bit opinion based but I'll try to give you my 5ct anyway.
Let's have a look at your class and their instances:
It includes a value and a function where you (tried) to make it all a lazy.
From a theoretical view I can see no difference to Lazy<T> on first glance:
You can surely convert one of your Continuation<Input,Output> to just a Lazy<Output>.
The same is true for the reverse: given some lazy value a you can make a instance with just
new Continuation(a, x => x)
So to me it seems that you just reinvented Lazy (which is an monad, in Haskell you would call it Identity.
The Cont monad is not really easy to crasp but it's really more related to .net-Events or .net-Observables. The datastructure itself would be like
Func<Func<Input,Output>, Output>
Where you pass in a continuation Func<Input,Output> to some internal calculation and then the struture than will call it when it has calculated an input Input to get the final result.
This might be a bit cryptic but one .net application are the Async workflows F# uses and which stood model for C#s async/await behaviour in some sense.
I have some material I used for a talk on a simpified version of this monad in C# on github maybe you'll find it interesting.
I have created a very comprehensive introduction to the Continuation monad that you can Find Here Discovering the Continuation Monad in C#
Also you can find a.Net Fiddle here
I Repeat it in summary here
Starting from an initial Function
int Square(int x ){return (x * x);}
Use Callback and remove return type
public static void Square(int x, Action<int> callback)
{
callback(x * x);
}
Curry the Callback
public static Action<Action<int>> Square(int x)
{
return (callback) => { callback(x * x); };
}
Generalize the returned Continuation
public static Func<Func<int,T>,T> Square<T>(int x)
{
return (callback) => { callback(x * x); };
}
Extract the Continuation Structure Also Known As the Return Method of the monad. That is Give me a value and i will give you a Monad for this value
//((U→ T) → T)
delegate T Cont<U, T>(Func<U, T> f);
public static Cont<U, T> ToContinuation<U, T>(this U x)
{
return (callback) => callback(x);
}
square.ToContinuation<Func<int, int>, int>()
Add The bind Monadic method and thus Complete the Monad.That is Give me a Two Monads and i will combine them to a new monad
((A→ T) → T)→( A→((B→ T) → T))→ ((B→ T) → T)
public static Cont<V, Answer> Bind<T, U, V, Answer>(
this Cont<T, Answer> m,
Func<T, Cont<U, Answer>> k,
Func<T, U, V> selector)
{
return (Func<V, Answer> c) =>
m(t => k(t)(y => c(selector(t, y))));
}

Eliminate duplicate code introduced by Func and Action

There is a generic function with a return type.
TResult Invoke<TResult>(Func<string, TResult> callback)
{
string message = Generate_some_string();
return callback(message);
}
And also there is a similar one without a return type since there is no Func.
void Invoke(Action<string> callback)
{
string message = Generate_some_string();
callback(message);
}
But these are duplicate code. Once Invoke changes, Invoke has to be changed correspondingly. Is there any way to eliminate the duplicate code?
Thanks,
Jim
You could try something like this:
void Invoke(Action<string> callback)
{
Invoke<int>(s=>{callback(s);return 0;});
}
That way all your logic stays in the Func version and your Action version should never have to change.
Another option would be to create a ToFunc conversion routine, and place the onus on your callers to change their action into a func:
public static Func<TIn, TResult> ToFunc<TIn, TResult>(this Action<TIn> a)
{
return input =>
{
a(input);
return default(TResult);
};
}

Categories