简体   繁体   中英

How do you return a Func<Func<string, int>, int>

I recently figured out how to return methods/functions from methods, for example:

public static Func<string, int> Parse() {
    return x => Int32.Parse(x);
}

Out of pure curiosity I wanted to know how far I can go. Is it possible to somehow return a Func<Func<string, int>, int> ?

public static Func<Func<string, int>, int> PlusSomething(this Func<string, int> parser) {
    return x => x + parser; //Obviously doesn't work
}



The closest thing I managed to do was

public static Func<string, int, int> PlusSomething(this Func<string, int> parser) {
    return (x, y) => parser(x) + y;
}

Since it is not very clear what you want to achieve I am going to do a bit of guess work.

A Func<Func<string, int>, int> is a function that takes a function and returns an int.

One possibility is that you want to return a function that takes a function f , applies it to a string and returns an int. In this case you have to specify somewhere on what you want to apply the function f . Either when you generate the function

public static Func<Func<string, int>, int> PlusSomething(string s) {
    return f => f(s);
}

either when you apply the function

public static Func<Func<string, int>, int, int> PlusSomething() {
    return f, s => f(s);
}

Looking at your second example it seems to me (I may be wrong) that you actually want to return a function that takes a int and return a function.

public static Func<int, Func<string, int>> PlusSomething(Func<string, int> parser) {
    return x => (y => x + parser(y));
}

This would allow something like

var gen = PlusSomething(parser);
var parsePlus4 = gen(4);
int x = parsePlus4("8"); // x == 12

To answer the question as it is stated - yes, it is possible to have a function with the described signature as follows.

public static
Func<Func<string,int>,int>
PlusSomething(this Func<string, int> parser)
{
    return x => 1;
}

However it is unclear what the desired result is and how the input should relate to the desired output; syntactically it is possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM