How to initialize generic local variable? - c#

The objective is to create a simple program that calculates the sum of pre-processed set. The Sum must be generic to allow it accepts both integer and floating point set.
The following code does not compile. Could you tell me how to fix it?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
static class Program
{
delegate T del<T>(T x);
static T Sum<T>(del<T> df, IEnumerable<T> data)
{
T s = 0;
foreach (var x in data) s += df(x);
return s;
}
static void Main(string[] args)
{
var data = Enumerable.Range(1, 4);
int sum = Sum<int>(x => x * x, data);
Console.WriteLine(sum);
}
}
}
Error Messages (roughly speaking):
cannot convert int to T.
+= is not available for T.

Ignoring the other issues with your code, you can't do what you're trying to do. C# does not support arithmetic operators on generic types.
Therefore, one option will be to Sum(del<int>, ..), Sum(del<float>, ...).. etc.
Or, use dynamic:
delegate T del<T>(T x);
static T Sum<T>(del<T> df, IEnumerable<T> data)
{
dynamic s = default(T);
foreach (var x in data) s += df(x);
return s;
}
This results is 30 for your provided example.

You can use the generic Add() method defined here.
The trick is to pass the initial value of s as the type T into the Sum() method instead of initializing it inside the function.
public class Program
{
public static T Add<T>(T a, T b)
{
var paramA = Expression.Parameter(typeof (T), "a");
var paramB = Expression.Parameter(typeof (T), "b");
var body = Expression.Add(paramA, paramB);
var add = Expression.Lambda<Func<T, T, T>>(body, paramA, paramB).Compile();
return add(a, b);
}
public delegate T del<T>(T x);
//pass the variable s into the function instead of initializing it inside the function.
public static T Sum<T>(T s, del<T> df, IEnumerable<T> data)
{
return data.Aggregate(s, (current, x) => Add(current, df(x)));
}
public static void Main(string[] args)
{
var data = Enumerable.Range(1, 4);
int sum = Sum(0, x => x * x, data);
Console.WriteLine(sum);
}
}

VERY similar to Simon Whitehead answer
static T Sum<T>(del<T> df, dynamic data)
{
T s = default(T);
foreach (var x in data) s += df(x);
return s;
}
this return also 30

You need to use the default keyword, specifically:
// was: T s = 0;
T s = default(T);
I replied in haste to the question in the title, on the secondary issue of performing add operations between generics, this has been covered in another StackOverflow question, so I wont double post. It involves using dynamic, which means you no longer have compile-time safety. Read the other question for more details.

Related

How can i access the value of a local variable from within an expression tree

By examining an expression tree i can get the value of a constant, instance field and property but not a local variable defined in a method.
Executing the following will output 1, 2, 3 (from the constant, instance field and property) then an exception as i don't know how to get the instance on which the FieldInfo is declared in order to call GetValue() for the local variable.
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Example
{
class Program
{
private int _intField = 2;
static void Main()
{
new Program().Run();
Console.ReadLine();
}
private void Run()
{
IntProp = 3;
var intVariable = 4;
Test(() => 1);
Test(() => _intField);
Test(() => IntProp);
Test(() => intVariable);
}
public int IntProp { get; set; }
void Test<T>(Expression<Func<T>> func)
{
var body = func.Body;
if (body.NodeType == ExpressionType.Constant)
{
Console.WriteLine(((ConstantExpression)body).Value);
}
else
{
var memberExpression = body as MemberExpression;
var #object = memberExpression.Member.DeclaringType == GetType()
? this
: null; //Can I do anything here? Instance of the method the variable is defined in?
if (memberExpression.Member.MemberType == MemberTypes.Field)
{
Console.WriteLine(((FieldInfo)memberExpression.Member).GetValue(#object));
}
else if (memberExpression.Member.MemberType == MemberTypes.Property)
{
Console.WriteLine(((PropertyInfo)memberExpression.Member).GetValue(#object));
}
}
}
}
}
The local variable which has been captured by the lambda and included in the expression tree, will at that time really be a field on some compiler-generated class. This works on my version of .NET:
void Test<T>(Expression<Func<T>> func)
{
var body = func.Body;
if (body.NodeType == ExpressionType.Constant)
{
Console.WriteLine(((ConstantExpression)body).Value);
}
else
{
var memberExpression = (MemberExpression)body;
var #object =
((ConstantExpression)(memberExpression.Expression)).Value; //HERE!
if (memberExpression.Member.MemberType == MemberTypes.Field)
{
Console.WriteLine(((FieldInfo)memberExpression.Member).GetValue(#object));
}
else if (memberExpression.Member.MemberType == MemberTypes.Property)
{
Console.WriteLine(((PropertyInfo)memberExpression.Member).GetValue(#object));
}
}
}
Of course, you can also "cheat":
void Test<T>(Expression<Func<T>> func)
{
Console.WriteLine(func.Compile()());
}
No, you cannot.
Reflection does not extend to reading the values of method variable.
It only handles the declaration metadata of variables. And even then, the compiler may have removed the variable you thought you declared. You allready can access to properties, fields.
No, you cannot because those variables are simply not available outside the method their scope.
No you can't with reflection. But there are other methods to do so. As an example, I show you how to export a variable out of the functions' lexical scope.
Say you have a method like this:
private void f(int x)
{
// your code here
}
You also have a piece of code like this:
int x_in_f;
f(3);
x_in_f = /* I want to have the value here */;
To get the value out of f() you must export a getter function. As f() returns void, you just could return the getter. In a general case (when f() has a non-void return type) you can leverage an out parameter. Here are both variants:
private Func<int> f(int x)
{
// your code here
return () => { return x; };
}
or through the out parameter:
private void f(int x, out Func<int> g)
{
// your code here
g = () => { return x; };
}
The code would then be:
int x_in_f;
Func<int> g;
g = f(3);
x_in_f = g(); // this will return the value of x as it was passed to f()
or through the out parameter invoke f() as follows:
f(3, out g);
At that point you can pass g() around to other functions:
private void h(Func<int> getx)
{
// your code here
int x = getx();
// now you have the value of x inside the h() function
}
and the invocation with h():
Func<int> g = f(3);
// ...
h(g);
I hope this helps or at least shows how to use closures to circumvent lexical scoping.
For the designers out there, this is the Object Capability Model. This is a video by Douglas Crockford on how to use it for security purposes in Javascript. It translates to C# and other purposes easily, as I've shown above.

Reflection GetMethod issue in Class Library (Portable)

I have a class library in which I have defined a few functions f1, f2 that I would like to put them in a dictionary to later call by name. However, the reflection Type.GetMethod does not seem to be defined in the class library portable even I am using System.Reflection. Can you suggest a work around?
This is my simple piece of code for illustration
public class Class1
{
public delegate int myFunction(object o);
private Dictionary<string, myFunction> list = new Dictionary<string, myFunction>();
public Class1()
{
string[] n = { "f1", "f2" };
MethodInfo mInfo;
foreach (var i in n)
{
mInfo = typeof(Class1).GetMethod(i);
}
list.Add("f1", f1);
list.Add("f2", f2);
}
public int f1(object o)
{
System.Diagnostics.Debug.WriteLine("f1: parameter is {0} " ,o);
return 0;
}
public int f2(object o)
{
System.Diagnostics.Debug.WriteLine("f2: parameter is {0} ", o);
return 0;
}
}
my original intention was putting all my functions in my dictionary list. I can manually add:
list.Add("f1", f1);
list.Add("f2", f2);
But when I declare an array of string with the name of the function, use GetMethod to pick up the function, compiler was generating an error "Type does not contain definition for GetMethod...
Please advise.
Thanks!
Update: Compiling Error
Update with Singleton:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
namespace ClassLibrary1
{
public sealed class Class1
{
public delegate int myFunction(object o);
public Dictionary<string, myFunction> list = new Dictionary<string, myFunction>();
private static readonly Class1 _instance = new Class1();
static Class1()
{
}
public Class1()
{
string[] n = { "f1", "f2" };
MethodInfo mInfo;
foreach (var i in n)
{
mInfo = typeof(Class1).GetTypeInfo().GetDeclaredMethod(i);
//NewExpression constrExpr = Expression.New(typeof(Class1).GetTypeInfo().DeclaredConstructors.Single(ci => ci.GetParameters().Length == 0));
ParameterExpression objExpr = Expression.Parameter(typeof(object));
Expression<myFunction> expr = Expression.Lambda<myFunction>(Expression.Call(null, mInfo, objExpr), objExpr);
//Expression<myFunction> expr = Expression.Lambda<myFunction>(Expression.Call(constrExpr, mInfo, objExpr), objExpr);
list.Add(i, expr.Compile());
}
list.Add("f11", f1);
list.Add("f21", f2);
}
public static Class1 Instance
{
get
{
return _instance;
}
}
public int f1(object o)
{
System.Diagnostics.Debug.WriteLine("f1: parameter is {0} ", o);
return 0;
}
public int f2(object o)
{
System.Diagnostics.Debug.WriteLine("f2: parameter is {0} ", o);
return 0;
}
}
}
First of all, most PCL profiles are using TypeInfo for type information, see e.g. here and here. TypeInfo also comes with a slightly different set of methods.
So, instead of writing
typeof(Class1).GetMethod(i)
you should thus write:
typeof(Class1).GetTypeInfo().GetDeclaredMethod(i)
But even if you use the above expression to obtain MethodInfo, you cannot (to my knowledge) immediately convert this object into a myFunction delegate.
One way of solving this problem would be to use expression trees. You would then need to formulate an Expression<myFunction> object which you would compile into a myFunction delegate.
I think you can do something like this:
Expression<myFunction> expr =
Expression.Lambda<myFunction>(
Expression.Call(
constrExpr,
typeof(Class1).GetTypeInfo().GetDeclaredMethod(i),
objExpr),
objExpr);
list.Add(i, expr.Compile());
where constrExpr is an expression for creating an instance of Class1 using the default constructor
NewExpression constrExpr =
Expression.New(
typeof(Class1).GetTypeInfo().DeclaredConstructors
.Single(ci => ci.GetParameters().Length == 0));
and objExpr is a representation of the object o parameter
ParameterExpression objExpr = Expression.Parameter(typeof(object));
With these changes, you should be able to invoke an arbitrary method in your dictionary, like this:
int i = list["f1"]("hello");
int j = list["f2"](20.0);

Can anonymous delegate have return value as non void type?

Can anonymous delegate have return value as non void type?
Yes. Both the delegate { return xyz; } and lambda x => x+1 syntax can return values.
I also had this question, and wrote a test program. The answer is yes.
using System;
public delegate int ReturnedDelegate(string s);
class AnonymousDelegate
{
static void Main()
{
ReturnedDelegate len = delegate(string s)
{
return s.Length;
};
Console.WriteLine(len("hello world"));
}
}

How can I get this example using "param" in C# to work?

I am trying to understand the meaning and use of the param parameter in this line taken from a RelayCommand example:
return new RelayCommand(param => MessageBox.Show("It worked."));
First, I understand that the "param" parameter has nothing to do with the "params" keyword, is this correct?
public int Add(params int[] list)
{
int sum = 0;
foreach (int i in list)
sum += i;
return sum;
}
Second, what kind of delegate code do I have to add to get the following example to work?
using System;
using System.Collections.Generic;
namespace TestParam222
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The total is {0}.", Tools.GetTest(param => 23));
Console.ReadLine();
}
}
class Tools
{
public static string GetTest(List<int> integers)
{
return "ok";
}
}
}
param isn't a keyword. It's the parameter for a lambda expression in your sample. You'd need to make your method take a delegate or an expression tree, e.g.
using System;
using System.Collections.Generic;
namespace TestParam222
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("The total is {0}.", Tools.GetTest(param => 23));
Console.ReadLine();
}
}
class Tools
{
public static string GetTest(Func<int, int> integers)
{
return "ok";
}
}
}
The Func<int,int> could actually be any Func<T,int> (or Func<T,long> etc) because your lambda expression doesn't use param anywhere. Alternatively it could be an Expression<Func<int,int>> etc.
I suggest you read up on lambda expressions for more details, for instance in any of these SO questions:
Can you explain lambda expressions
What is a lambda
C# lambda expression, why should I use this

Mathematical function differentiation with C#?

I see that I can declare a function with (say)
public double Function(double parameter)
but what if I do want to take the derivative of that function?
You can't calculate the exact derivative of a function using a computer program (unless you're doing symbolic math... but that's another, way more complicated, topic).
There are several approaches to computing a numerical derivative of a function. The simplest is the centered three-point method:
Take a small number h
Evaluate [f(x+h) - f(x-h)] / 2h
VoilĂ , an approximation of f'(x), with only two function evaluations
Another approach is the centered five-point method:
Take a small number h
Evaluate [f(x-2h) - 8f(x-h) + 8f(x+h) - f(x+2h)] / 12h
VoilĂ , a better approximation of f'(x), but it requires more function evaluations
Another topic is how to implement this using C#. First, you need a delegate that represents a function that maps a subset of the real numbers onto a another subset of the real numbers:
delegate double RealFunction(double arg);
Then, you need a routing that evaluates the derivative:
public double h = 10e-6; // I'm not sure if this is valid C#, I'm used to C++
static double Derivative(RealFunction f, double arg)
{
double h2 = h*2;
return (f(x-h2) - 8*f(x-h) + 8*f(x+h) - f(x+h2)) / (h2*6);
}
If you want an object-oriented implementation, you should create the following classes:
interface IFunction
{
// Since operator () can't be overloaded, we'll use this trick.
double this[double arg] { get; }
}
class Function : IFunction
{
RealFunction func;
public Function(RealFunction func)
{ this.func = func; }
public double this[double arg]
{ get { return func(arg); } }
}
class Derivative : IFunction
{
IFunction func;
public static double h = 10e-6;
public Derivative(IFunction func)
{ this.func = func; }
public double this[double arg]
{
get
{
double h2 = h*2;
return (
func[arg - h2] - func[arg + h2] +
( func[arg + h] - func[arg - h] ) * 8
) / (h2 * 6);
}
}
}
If you're thinking of symbolic manipulation of formulae then you're better off doing your derivations in languages like Maple or Mathematica. They're designed for symbolic computation.
EDIT: If Maple and Mathematica are too expensive for you then there are other options. Wikipedia has a fairly complete listing of computer algebra packages. http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems
Are you thinking of Lambda Expressions?
Basically you can pass a function into a function.
So think of a Sort on an object.
Depending on the nature of the object would help determine how the objects are sorted.
But you can still create a generic sort function then pass in how to compare objects.
Another approach can be to leverage the extensions methods using the well-known definition of the derivative number and compute its approximation accordingly.
As it has already been mentioned, this is pretty easy for a numeric approach not a symbolic one:
public partial static class IEnumerableExtensions
{
public static IEnumerable<Double> Derivate1<TSource>(this IEnumerable<TSource> source, Func<TSource, Double> selectorX, Func<TSource, Double> selectorY)
{
var enumerator = source.GetEnumerator();
enumerator.Reset();
enumerator.MoveNext();
var itemPrevious = enumerator.Current;
var itemNext = default(TSource);
while (enumerator.MoveNext())
{
itemNext = enumerator.Current;
var itemPreviousX = selectorX(itemPrevious);
var itemPreviousY = selectorY(itemPrevious);
var itemNextX = selectorX(itemNext);
var itemNextY = selectorY(itemNext);
var derivative = (itemNextY - itemPreviousY) / (itemNextX - itemPreviousX);
yield return derivative;
itemPrevious = itemNext;
}
}
}
or if you are more into a foreach fashion
public partial static class IEnumerableExtensions
{
public static IEnumerable<Double> Derivate2<TSource>(IEnumerable<TSource> source, Func<TSource, Double> selectorX, Func<TSource, Double> selectorY)
{
var itemPrevious = source.First();
source = source.Skip(1);
foreach (var itemNext in source)
{
var itemPreviousX = selectorX(itemPrevious);
var itemPreviousY = selectorY(itemPrevious);
var itemNextX = selectorX(itemNext);
var itemNextY = selectorY(itemNext);
var derivative = (itemNextY - itemPreviousY) / (itemNextX - itemPreviousX);
yield return derivative;
itemPrevious = itemNext;
}
}
}
You can refactor everything as below:
public static partial class MathHelpers
{
public static Double Derivate(Double xPrevious, Double xNext, Double yPrevious, Double yNext)
{
var derivative = (yNext - yPrevious)/(xNext - xPrevious);
return derivative;
}
}
public static class IEnumerableExtensions
{
public static IEnumerable<Double> Derivate<TSource>(IEnumerable<TSource> source, Func<TSource, Double> selectorX, Func<TSource, Double> selectorY)
{
var itemPrevious = source.First();
source = source.Skip(1);
foreach (var itemNext in source)
{
var derivative = MathHelpers.Derivate(selectorX(itemPrevious), selectorX(itemNext), selectorY(itemPrevious), selectorY(itemNext));
yield return derivative;
itemPrevious = itemNext;
}
}
}
If you have written the function, it's already been derived.
And given that it's an int function, I'll assume you don't mean the calculus definition of "derive".

Categories

Resources