Return combination of other delegates - c#

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

Related

How to parse a list quickly using a C# Method that only takes an item?

I am learning C# myself and I wonder if C# method can quickly parse a list of values just like Python does as below:
def myMethod(somevalue):
return somevalue * 2
x = [1,2,3,4,5]
a = [myMethod(i) for i in x]
Currently I am trying to make a class that has a method that takes in a double.
But what if x is a list?
class myClass
{
public double somevalue;
public myClass(double someValue)
{
somevalue = someValue;
}
public double myMethod()
{
return somevalue * 2;
}
}
myClass output = new myClass(x);
A = output.myMethod();
My question is, can C# create very concise codes that makes the Method takes in the list, loop through the list and gives out a list of results?
Not a python expert but this:
def myMethod(somevalue):
return somevalue * 2
x = [1,2,3,4,5]
a = [myMethod(i) for i in x]
Looks like it would be this in C#:
//either:
double TimesTwo(double d) => d * 2; //a method declaration that is "expression bodied" style
//or:
double TimesTwo(double d) { return d * 2; } //a method declaration that is "normal" style
void SomeOtherMethod(){ //these statements can't just be floating around in a namespace like the method declarations above, they have to be inside some other method
var x = new[] {1d,2,3,4,5}; //the first element is a double (1d), the others will be promoted from int to double without needing an explicit cast, the whole array x is a double[]
var a = x.Select(TimesTwo).ToArray();
}
You can skip creating a separate method for the * 2 operation (the method above is called TimesTwo) and just put the logic of what you want inline:
var x = new[] { 1d,2,3,4,5 };
var a = x.Select(p => p * 2).ToArray();
The p => p * 2 is something like an "inline method" - we refer to them as lambdas; the input argument is called p and its type is inferred from the type of the collection that .Select is called on. In this case a double is inferred, because x is a double array
The return keyword is not specified in a single line lambda (which we refer to as an expression bodied something); the single line of code after the => (in both p => ... and TimesTwo(int i) => ...) is a statement that resolves to a value, and that value is implicitly returned. In this case the statement p => p * 2 multiplies input p by 2 and the result is returned automatically.
The result of the .Select method is an enumerable (specifically of type IEnumerable<double>, and the ToArray() method will enumerate it and turn it into an array. It is the calling of ToArray that causes p*2 to be invoked on every member, and ToArray collects all the results and outputs an array
All this code comes from extension methods in the System.Linq namespace, so your code needs using System.Linq; at the top
One important point, that may well bite at some time in the future; the code in the lambda within the Select is not performed if the enumerable output by the Select is not actually enumerated. If you had:
var enumerableThing = oneThousandThings.Select(p => SomeOperationThatTakesOneSecond(p));
It would execute near instantly; nothing in that line of code enumerates the resulting enumerable, no memory is allocated for a new array, no looping over collections of anything occurs, the operation that takes 1 second is not even called once let alone a thousand times.
If you later did something that actually enumerated the result, then the operation would take a thousand seconds:
var arr = enumerableThing.ToArray() //takes 1000s
foreach(var x in enumerableThing) //would take 1000s to finish looping
...
int i = 500;
foreach(var x in enumerableThing){ //would take 500s, the enumeration quitting early after being half done
i--;
if(i == 0) break;
}
This enumerating could be done hours or days later; it's called deferred execution and is worth looking into further if you're not familiar with it
You would use System.Linq.Enumerable.Where() to filter the List
var filtered = x.Where(y => myMethod(y)).ToList();
or Select to convert the list
var converted = x.Select(y => myMethod(y)).ToList();

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?

LINQ List.AsParallel with boolean return

I've got a static List<long> primes of all known primes up to a certain point, and a function like this:
static bool isPrime(long p)
{
double rootP = Math.Sqrt(p);
foreach (long q in primes)
{
if (p % q == 0)
return false;
if (q >= rootP)
return true;
}
return true;
}
which could be parallelised like this:
static bool isPrime(long p)
{
double rootP = Math.Sqrt(p);
primes.AsParallel().ForAll(q =>
{
if (p % q == 0)
return false;
if (q > rootP)
break;
});
return true;
}
However, this gives a compile-time error saying some return types in my block aren't implicitly convertible to the delegate return type.
I'm somewhat new to LINQ, especially PLINQ. This, to me, seems like a good candidate for parallelism, since the checking of each known prime against the candidate prime is an independent process.
Is there an easy way to fix my block so that it works, or do I need to attack this problem in a completely different way?
Syntax-wise, you're making two mistakes in your code:
A return in a lambda doesn't return from the enclosing method, just from the lambda, so your return false; wouldn't work correctly.
You can't break out of lambda. Even if that lambda is executed in a loop, that loop is basically invisible to you, you certainly can't control it directly.
I think the best way to fix your code is to use a LINQ method made exactly for this purpose: Any(), along with TakeWhile() to filter out the primes that are too large:
static bool IsPrime(long p)
{
double rootP = Math.Sqrt(p);
return !primes.AsParallel().TakeWhile(q => q > rootP).Any(q => p % q == 0);
}
But there is also a flaw in your reasoning:
This, to me, seems like a good candidate for parallelism, since the checking of each known prime against the candidate prime is an independent process.
It's not as simple as that. Checking each prime is also an extremely simple process. This means that the overhead of simple parallelization (like the one I suggested above) is likely to be bigger than the performance gains. A more complicated solution (like the one suggested by Matthew Watson in a comment) could help with that.
This is a solution to your problem:
static List<long> primes = new List<long>() {
2,3,5,7,11,13,17,19,23
};
static bool isPrime(long p) {
var sqrt = (long)Math.Sqrt(p);
if (sqrt * sqrt == p)
return (false);
return (primes.AsParallel().All(n => n > sqrt || p % n != 0));
}
It even tries to reduce parallelism for quadratic numbers and will stop checking more candidates as soon as the first is found which is
The error occurs because if your condition
p % q == 0
is true the closure will return false and when
q > rootP
it breaks and returns nothing. This will work in PHP but not in .NET :P
A lambda is a full anonymous function and return types allways have to be consistent.
You have to redesign your code here. You have done it right in your non-parallelised example... Just replace break with return true (it won't be prettier then, but it should work).
It maybe easier to use Parallel.For instead
static volatile bool result = true;
static bool isPrime(long p)
{
double rootP = Math.Sqrt(p);
Parallel.For(0, primes.Count, (q, state) =>
{
if (p % q == 0)
{
result = false;
state.Break();
}
if (q > rootP)
state.Break();
});
return result;
}

Why my Generic Extension Method says cannot convert from T to ..... or .... to T

Further to my questions
https://stackoverflow.com/questions/10241345/any-percentage-function-in-net
https://stackoverflow.com/questions/9942202/percentage-of-each-element-in-linq
i want to create a generic extension method in .Net 4.0 which will generate percentage of the list items to the sum of the list. This list will be of Numeric types only.
My code is
public static T Percentage<T>(this T array) where T: ? // What should come in place of ?
{
double[] darray = (double[])T; // Error convert type 'T' to 'double[]'
darray = darray.Select(x=> x * 100 / darray.Sum()).ToArray();
return darray; // Error convert type 'double[]' to 'T'
}
I want to call it like
double[] MD = {8.0,21.0,25.0,13.0,26.0,37.0,37.0,33.0,71.0,9.0};
MD = MD.Percentage().ToArray();
What am i doing wrong;
You cannot constrain types by "numeric" values. It is somewhat of a limitation of the framework.
Your best best is to do this:
public static IEnumerable<double> Percentage(this IEnumerable<int> values)
{
var sum = values.Sum();
return values.Select(v => (double)v / (double)sum).ToArray();
}
public static IEnumerable<double> Percentage(this IEnumerable<long> values)
{
var sum = values.Sum();
return values.Select(v => (double)v / (double)sum).ToArray();
}
public static IEnumerable<double> Percentage(this IEnumerable<double> values)
{
var sum = values.Sum();
return values.Select(v => v / sum).ToArray();
}
Essentially you need to produce an overload for each type you want to support.
It is not possible to have constrain of type you want. Check out Constraining a generic type argument to numeric types for details.
Since there are not too many numeric types (int/float/double/decimal) it may be easier to simply provide concrete implementations.
More options
require IConvertable and use IConvertible.ToDouble to perform all math in doubles
use https://jonskeet.uk/csharp/miscutil/usage/genericoperators.html mentioned here C#: Generic Interface for Numbers.
There is an alternative that works, which is to pass in the selector function that allows you to convert to doubles when you call Percentage. This is the extension method:
public static double[] Percentage<T>(this T[] array, Func<T,double> selector)
{
var doubles = array.Select(selector);
var sum = doubles.Sum();
var result = doubles.Select(x => x * 100 / sum).ToArray();
return result;
}
Usage:
double[] MD = {8.0,21.0,25.0,13.0,26.0,37.0,37.0,33.0,71.0,9.0};
var MDPercent = MD.Percentage(x => x).ToArray();
And then you can have a simple double version:
public static double[] Percentage(this double[] array)
{
return Percentage(array, x => x);
}
Or an int version:
public static double[] Percentage(this int[] array)
{
return array.Percentage(x => (double)x);
}
Which are simpler to use:
var MDPercent = MD.Percentage().ToArray();

Lambda expression with a void input

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

Categories

Resources