Lambda expression with a void input - c#

Ok, very silly question.
x => x * 2
is a lambda representing the same thing as a delegate for
int Foo(x) { return x * 2; }
But what is the lambda equivalent of
int Bar() { return 2; }
??
Thanks a lot!

The nullary lambda equivalent would be () => 2.

That would be:
() => 2
Example usage:
var list = new List<int>(Enumerable.Range(0, 10));
Func<int> x = () => 2;
list.ForEach(i => Console.WriteLine(x() * i));
As requested in the comments, here's a breakdown of the above sample...
// initialize a list of integers. Enumerable.Range returns 0-9,
// which is passed to the overloaded List constructor that accepts
// an IEnumerable<T>
var list = new List<int>(Enumerable.Range(0, 10));
// initialize an expression lambda that returns 2
Func<int> x = () => 2;
// using the List.ForEach method, iterate over the integers to write something
// to the console.
// Execute the expression lambda by calling x() (which returns 2)
// and multiply the result by the current integer
list.ForEach(i => Console.WriteLine(x() * i));
// Result: 0,2,4,6,8,10,12,14,16,18

You can just use () if you have no parameters.
() => 2;

The lmabda is:
() => 2

Related

Return combination of other delegates

I need to return expression of multiplication of two other expression, but this example gives me error
public Func<double> EvaluateOne()
{
return () => EvaluateTwo() * EvaluateTwo();
}
public Func<double> EvaluateTwo()
{
return () => 2;
}
in function EvaluateOne
error:can't applay operand * to operands of type Func<double> and Func<double>
You can't multiply two Func<decimal> objects, but you can multiply the results of evaluating them.
return () => EvaluateTwo()() * EvaluateTwo()();
That is because a call to EvaluateTwo() returns a Func<double>, not the value 2.
You can fix that by:
public Func<double> EvaluateOne()
{
var eval2 = EvaluateTwo();
return () => eval2() * eval2();
}
Note: #Blorgbeard's answer does not have a weakness that the method in this answer has. If a call to EvaluateTwo() would return a different Func<double> instance on each invokation, this answer would lead to an incorrect outcome.
return () => { double two = EvaluateTwo()(); return two * two; }
This way you get both optimization and lazy evaluation.
You can also use expression trees to do this, which allows you to recursively create an expression of increasing size without computing anything:
using NumFunc = System.Func<double>;
using NumExpr = System.Linq.Expressions.Expression<System.Func<double>>;
...
static NumExpr Square(NumExpr operand)
{
return Product(operand, operand);
}
static NumExpr Product(NumExpr left, NumExpr right)
{
return Expression.Lambda<NumFunc>(Expression.Multiply(left.Body, right.Body));
}
Now, when you use this, you get nicely formatted logging of the composite expression as a nice bonus:
var result1 = Product(() => 2, () => 3);
var result2 = Product(result1, () => 5);
var result3 = Square(result2);
// Nothing has been computed so far!
Console.WriteLine("{0}={1}", result3.Body, result3.Compile().Invoke());
// Output: (((2 * 3) * 5) * ((2 * 3) * 5))=900
You can see a demo here: http://ideone.com/forcW3

Func<T> get result of every single call?

I recently discovered that there is little difference between a delegate and an event. In fact you can "hook" multiple functions into a single Func<T>, for example:
Func<int> mFunction;
...
Func<int, int> getValue = value => {
Console.WriteLine("assigning {0}", value);
return value;
};
mFunction += () => getValue(6);
mFunction += () => getValue(5);
...
int x = 0;
Func<int> function = mFunction;
if (function != null)
x = function();
Console.WriteLine(x);
This calls each "hooked" function, and assigns each value to x in sequence, and x ends up with the last value assigned. In other words, the output is:
assigning 6
assigning 5
5
Is there a way to retrieve all of the return values of these function calls?
You can loop through each Func<int> in the GetInvocationList() method of your object:
foreach(Func<int> f in function.GetInvocationList())
{
var y = f();
//y holds the result
}
Per default, you only get the last return value. However, you can fetch all delegates using GetInvocationList() and then call each individually.
See Calling delegates individually?

Inline function definition

For better readability, I want to define inline functions in C#, like this one:
var HasFullAccess = (mask => mask % 2 == 1);
foreach(AccessControlEntry ace in acl)
{
if(HasFullAccess(ace.AccessMask)) ...
The problem is the var. I guess I have to put sth. there that tells C# to expect a lambda expression? I also tried
(int => bool) HasFullAccess = (mask => mask % 2 == 1);
which also does not work. So how can I define an inline function?
You can do like this
Func<int,bool> HasFullAccess = mask => mask % 2 == 1;
You cannot assign a lambda expression to an implicitly-typed local variable (as the compiler should have pointed out). You will have to specify your delegate type (in this case Func<int, bool>) explicitly.
var HasFullAccess = new Func<int, bool>(mask => mask % 2 == 1);
Or, alternatively
Func<int, bool> HasFullAccess = mask => mask % 2 == 1;
like this
var hasFullAccess = new Func<int, bool>(mask => mask % 2 == 1);
or this,
Func<int, bool> hasFullAccess = mask => mask % 2 == 1;
for other types of function you'll need to use a compatible delegate type. You have to give the compiler some help.
Standard way to do this is to define this helper function:
public static Func<A, T> func<A, T>(Func<A, T> f)
{
return f;
}
somewhere in your namespace. Then you can call
var myfunc = func((int mask) => mask % 2 == 1);
and it will happily infer the type for you.

Function variable calling itself [duplicate]

This question already has answers here:
C#: Recursive functions with Lambdas
(3 answers)
Closed 9 years ago.
How can you call a Func function from itself?
For example:
Func<int, int> f = x => {
// do stuff
if (x > 5) { return f(x); }
// do other stuff
};
Simple way to is to create the variable, assign it null, and then use it in your lambda:
Func<int, int> f = null;
f = x => {
// do stuff
if (x > 5) { return f(x); }
// do other stuff
};
By the time it comes to actually invoke the delegate in f, it will have been assigned to a non-null value.
If you prefer, you can also follow the approach shown in this (theory heavy) blog entry.
dlev's answer is fairly straight forward, but you can also do this way:
First declare a delegate type that accepts itself as a parameter:
public delegate TResult RecursiveFunc<TParam, TResult>(
TParam param1,
RecursiveFunc<TParam, TResult> func);
NOTE: of course the delegate doesn't have to be generic.
You can now create your lambda expression like this:
RecursiveFunc<int, int> f = (x, g) => {
// do stuff
if (x > 5) { return g(x, g); }
// do other stuff
};
f(123, f); // Invoke recursively

Executing multicast delegates

I have a Multiple target
Func<int,int,int> funHandler=Max;
funHandler+=square;
When i execute
Console.WriteLine(funHandler(10,10)); it return the square of 10 (i.e) 200.It did not fire Max.
i used something like
foreach(var v in funHandler.GetInvocationList())
{
Console.WriteLine(v(10,20));
}
'V' is a variable,but it is used like a method.How can i fire all methods that is in delegate's
invocation list?
Well, may be Max has no side effects and you can't notice it? When you execute multicast delegate it returns result of only last delegate.
Try this:
Func<int, int, int> funHandler = (x, y) => { Console.WriteLine(x); return x; };
funHandler += (x, y) => { Console.WriteLine(y); return y; };
int res = funHandler(1, 2);
Console.WriteLine(res);
See? it works
To use invocation list do this:
foreach (var v in funHandler.GetInvocationList())
{
((Func<int, int, int>)v)(1, 2);
}
Or:
foreach (Func<int, int, int> v in funHandler.GetInvocationList())
{
v(1, 2);
}
Multicast with a delegate that returns something doesn't make much sense to me. I'd guess it executes all of them but discards all results but one.

Categories

Resources