Writing generic arithmetic in C# - c#

I have a list of numbers, and I wrote a method that performs some calculations on these numbers; all in all, it's about a page of code. The method performs some arithmetic and comparisons on these numbers.
My problem is that, in one case, the list is an IList<byte>, and in another case, it's an IList<float>. The algorithm in both cases is exactly the same (yes, I'm aware of things like overflow errors and loss of precision, but in my case it works). How can I write a method that will handle both lists ? I can't write something like void DoStuff<T>(IList<T> numbers), because there are no arithmetic operators (+ - * /) that are generic.
One solution is to simply store everything as float, but I'd like to avoid it. The lists are quite long, and thus storing floats instead of bytes would cost too much memory. I could also do something like DoStuffFloat(byteList.Select(b => (float)b)), but I don't want to pay the performance penalty, either, if I can avoid it.
Short of copy-pasting the entire method and replacing "float" with "byte" (or vice versa), is there some decent solution ?
EDIT: I should've mentioned that I'm restricted to using .NET 3.5 for this project.

What you could do is create a generic interface that includes the operations that you want to support, create a generic factory to create instances for the supported types to perform the operations, and use it.
e.g.,
public interface IOperations<T>
{
T Add(T a, T b);
T Subtract(T a, T b);
T Multiply(T a, T b);
T Divide(T a, T b);
}
public static class Operations<T>
{
public static IOperations<T> Default { get { return Create(); } }
static IOperations<T> Create()
{
var type = typeof(T);
switch (Type.GetTypeCode(type))
{
case TypeCode.Byte:
return (IOperations<T>)new ByteOperations();
case TypeCode.Single:
return (IOperations<T>)new SingleOperations();
default:
var message = String.Format("Operations for type {0} is not supported.", type.Name);
throw new NotSupportedException(message);
}
}
class ByteOperations : IOperations<byte>
{
public byte Add(byte a, byte b) { return unchecked ((byte)(a + b)); }
public byte Subtract(byte a, byte b) { return unchecked ((byte)(a - b)); }
public byte Multiply(byte a, byte b) { return unchecked ((byte)(a * b)); }
public byte Divide(byte a, byte b) { return unchecked ((byte)(a / b)); }
}
class SingleOperations : IOperations<float>
{
public float Add(float a, float b) { return a + b; }
public float Subtract(float a, float b) { return a - b; }
public float Multiply(float a, float b) { return a * b; }
public float Divide(float a, float b) { return a / b; }
}
}
T Mean<T>(IList<T> numbers)
{
var operations = Operations<T>.Default;
var sum = numbers.Aggregate(operations.Add);
var count = (T)Convert.ChangeType(numbers.Count, typeof(T));
return operations.Divide(sum, count);
}
var resultByte = Mean(new byte[] { 1, 2, 3, 4 }); // 2
var resultSingle = Mean(new float[] { 1.1F, 2.1F, 3.1F, 4.1F }); // 2.6F
var resultInt = Mean(new int[] { 1, 2, 3, 4 }); // not supported
If you don't mind a small performance hit, you could dynamically create the operations needed.
class GenericOperations<T> : IOperations<T>
{
public GenericOperations()
{
add = CreateLambda(Expression.Add);
subtract = CreateLambda(Expression.Subtract);
multiply = CreateLambda(Expression.Multiply);
divide = CreateLambda(Expression.Divide);
}
private Func<T, T, T> add, subtract, multiply, divide;
private static Func<T, T, T> CreateLambda(Func<Expression, Expression, BinaryExpression> op)
{
var a = Expression.Parameter(typeof(T), "a");
var b = Expression.Parameter(typeof(T), "b");
var body = op(a, b);
var expr = Expression.Lambda<Func<T, T, T>>(body, a, b);
return expr.Compile();
}
public T Add(T a, T b) { return add(a, b); }
public T Subtract(T a, T b) { return subtract(a, b); }
public T Multiply(T a, T b) { return multiply(a, b); }
public T Divide(T a, T b) { return divide(a, b); }
}

I don't know if this is the best method for your case but it is useful for similar cases too.
This can be done by using the dynamic keyword. What dynamic will do is it will not do the compile time checks until runtime.
Here is a small sample program to show how it works.
class Program
{
static void Main()
{
List<byte> bytes = new List<byte>();
bytes.Add(2);
bytes.Add(1);
List<float> floats = new List<float>();
floats.Add(2.5F);
floats.Add(1F);
Console.WriteLine(DoStuff(bytes));
Console.WriteLine(DoStuff(floats));
Console.ReadLine();
}
static dynamic DoStuff(IList items)
{
dynamic item0 = items[0];
dynamic item1 = items[1];
return item0 - item1;
}
}
Unfortunately in my quick testing I could not make IList<dynamic> work however using the non generic IList then accessing the members as a dynamic works fine.

Create classes to wrap the underlying values, and have them each implement an interface with the operations you need. Then, use ILists of that interface instead of the raw values.

Related

How to convert record to tuple in c# 9

Suppose there is such a record
public record ExampleRecord(int a, int b);
and a method
public int ExampleMethod((int a, int b) t)
{
return t.a + t.b;
}
Is it possible to do something like this to work with record as tuple parameter?
var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t);
You can add an implicit conversion to your record type:
public record ExampleRecord(int a, int b)
{
public static implicit operator ValueTuple<int, int> (ExampleRecord record)
{
return (record.a, record.b);
}
}
Use like this:
var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t);
You can make extension methods. For example:
public static class ExampleRecordExtensions
{
public static (int, int) ToTuple(this ExampleRecord record)
{
return (record.a, record.b);
}
}
Use like this:
var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod(t.ToTuple());
Alternatively you can use deconstruction. Use like this:
var t = new ExampleRecord(a: 1, b: 2);
ExampleMethod((_, _) = t);
I remind you that record types are classes. These tuples are value types (ValueTuple). Which also means that the tuple you create form the record type will always be a copy of the data.

Compile-time method call validation for multiple parameters of the same type

Here is demonstration of the problem:
class Program
{
static double Func(double a, double b) { return a * 1000 + b * b; }
static void Main(string[] args)
{
var a = 1.1d;
var b = 2.2d;
Console.WriteLine(Func(a, b));
// this is the problem, function doesn't recognize when a and b
// "accidentally" exchanged, target is to make this row a compile-time error
Console.WriteLine(Func(b, a));
}
}
This become an issue if there are methods with many parameters (e.g. ten of double type):
double Func(double parameter1, double parameter2, ..., double parameter10);
Question: is there a way to validate parameters when calling method, so that programmer is less prone to do a mistake?
This is not an issue if parameter types are different. I thought what maybe wrapping into new types will help:
class A
{
private double _value;
public static implicit operator A(double value) { return new A() { _value = value }; }
public static implicit operator double(A value) { return value._value; }
}
class B
{
private double _value;
public static implicit operator B(double value) { return new B() { _value = value }; }
public static implicit operator double(B value) { return value._value; }
}
class Program
{
static double Func(A a, B b) { return a * 1000 + b * b; }
static void Main(string[] args)
{
A a = 1.1d;
B b = 2.2d;
Console.WriteLine(Func(a, b));
Console.WriteLine(Func(b, a)); // compile-time error! yay!
Console.WriteLine(Func(a, b) + 123.123d - a * 2); // implicit conversion power
Console.ReadKey();
}
}
And it does, but I am quite unsure if this method is efficient. I have doubts if this is a good idea at all. Is it? Or is there better one?
I know what I can be absolutely safe if I always call method like this (using named arguments method call)
Func(a:a, b:b);
This shouldn't bring any overhead in code, but a lot of typing. Wrapping is better because it is done once (creating new type is easy), but it probably has overhead.
If two arguments are of the same type, it's not possible to detect at compile-time, run-time or otherwise that the name of the argument variable corresponds to the name of the parameter. This is kind of an open question, but I will offer you a couple ideas.
As Mehrzad suggested, consider grouping parameters by some type. For example, instead of double Distance(double x1, double y1, double x2, double y2), consider double Distance(Point p1, Point p2)
In general, if your method has more than 4-5 parameters, consider refactoring. Maybe your method is trying to do too many things and the logic can be divided?
If what you actually want to do is to perform some check such as ensuring that a < b, consider looking into Code contracts. You could also use Debug.Assert(), but this only works at run-time.
I wouldn't recommend the kind of implicit conversion you propose. For me, it feels hacky and unintuitive that A a = 1.1 should have no semantic purpose other than compile-time checking parameters. Your ultimate goal is to make code more maintainable overall.
You should never have 10 parameters for a method.
Once you have around 4 parameters, begin to consider the use of a new class to contain those parameters... As an example, consider the preferences of a user navigating on a website...
void Main()
{
UserPreferences preference = new UserPreferences
{
BackgroundColor = "#fff",
ForegroundColor = "#000",
Language = "en-GB",
UtcOffSetTimeZone = 0
};
User aydin = new User(preference);
}
public class User
{
public User(UserPreferences preferences)
{
this.Preferences = preferences;
}
public UserPreferences Preferences { get; set; }
}
public class UserPreferences
{
public string BackgroundColor { get; set; }
public string ForegroundColor { get; set; }
public int UtcOffSetTimeZone { get; set; }
public string Language { get; set; }
}
Use an inherited class something like this
class Program
{
static double Func(List<Parent> l) { return l[0]._value * 1000 + l[1]._value * l[1]._value; }
static void Main(string[] args)
{
A a = 1.1d;
B b = 2.2d;
Console.WriteLine(Func(new List<Parent>() {a,b}));
Console.WriteLine(Func(new List<Parent>() { a, b })); // compile-time error! yay!
Console.WriteLine(Func(new List<Parent>() { a, b }) + 123.123d - a * 2); // implicit conversion power
Console.ReadKey();
}
}
class Parent
{
public double _value { get; set; }
}
class A : Parent
{
public static implicit operator A(double value) { return new A() { _value = value }; }
public static implicit operator double(A value) { return value._value; }
}
class B : Parent
{
public static implicit operator B(double value) { return new B() { _value = value }; }
public static implicit operator double(B value) { return value._value; }
}

Writing an interpreter in C#: Best way to implement instructions?

I'm writting a PLC language interpreter using C#. That PLC language contains over 20 data types and 25 instructions or so. As soon as I started to generate code I balance two differents ways to write instructions:
1) Every kind of instruction is represented in one class which contains a big switch in order to chose the data type. Example:
public class ADD : Instruction
{
private string type;
public ADD(string type)
{
this.type = type;
}
public bool Exec(Context c)
{
switch (type)
{
case "INT":
short valor2 = c.PopINT();
short valor = c.PopINT();
short result = (short)(valor + valor2);
c.PushINT(result);
break;
case "DINT":
int valor4 = c.PopDINT();
int valor3 = c.PopDINT();
int result2 = (int)(valor4 + valor3);
c.PushDINT(result2);
break;
case "BOOL":
// Implement BOOL
break;
// Implement other types...
default:
break;
}
c.IP++;
return false; ;
}
}
2) Each class represent a single instruction with a single data type. This way avoid the big switch. Example:
public class ADDi : Instruction
{
public bool Exec(Context c)
{
short valor = c.PopINT();
short valor2 = c.PopINT();
short result = (short)(valor + valor2);
c.PushINT(result);
c.IP++;
return false;
}
}
I'm using COMMAND desing pattern (Exec()) to write instructions. I think second choice is better because avoids the big switch, but that choice involves to write over 400 instructions.
Always keep in mind that in this case execution performance is more important than performance in translation.
So, my precise question is as follows: Is there any other way to factorize instructions and data types? I'm looking for writing the lesser amount of instructions without penalizing performance.
EDIT:
This picture shows my type hierarchy:
This is INT class implementation:
public class INT : ANY_INT
{
public override string DefaultInitValue()
{
return "0";
}
public override int GetBytes()
{
return 2;
}
public override string GetLastType()
{
return this.ToString();
}
public override string ToString()
{
return "INT";
}
}
Some classes are more complex (structs, arrays,...).
Operations Push and Pop are defined as follows:
public void PushINT(short value)
{
//SP -> Stack Pointer
resMem.WriteINT(SP, value);
SP += 2;
}
public short PopINT()
{
SP -= 2;
short value = resMem.ReadINT(SP);
return value;
}
And, finally, operations to read and write in memory.
public void WriteINT(int index, short entero)
{
SetCapacity(index + 2); // Memory grows up dinamically
memory[index] = (sbyte)((ushort)entero >> 8 & 0x00FF);
memory[index + 1] = (sbyte)((ushort)entero >> 0 & 0x00FF);
}
public short ReadINT(int index)
{
return (short)(((short)(memory[index]) << 8 & 0xFF00) |
((short)(memory[index + 1]) & 0x00FF));
}
I hope this info helps. Thank you.
If you can change the implementation of Context to support generic types (e.g., Pop<int> instead of PopINT()) you can use delegates to make the implementation simpler.
Addition:
var addInt = new MathInstruction<int>((a, b) => a + b));
var addDouble = new MathInstruction<double>((a, b) => a + b));
var addDecimal = new MathInstruction<decimal>((a, b) => a + b));
Subtraction:
var subtractInt = new MathInstruction<int>((a, b) => a - b));
var subtractDouble = new MathInstruction<double>((a, b) => a - b));
var subtractDecimal = new MathInstruction<decimal>((a, b) => a - b));
Division:
var divideIntAsDouble = new MathInstruction<int, double>((a, b) => a / b));
var divideDouble = new MathInstruction<double>((a, b) => a / b));
var divideDecimal = new MathInstruction<decimal>((a, b) => a / b));
And conversion between types:
var addIntAndDouble = new MathInstruction<int, double, double>((a, b) => a + b));
It would be implemented like this:
class MathInstruction<TA, TB, TResult> : Instruction
{
private Func<TA, TB, TResult> callback;
public MathInstruction(Func<TA, TB, TResult> callback)
{
this.callback = callback;
}
public bool Exec(Context c)
{
var a = c.Pop<TA>();
var b = c.Pop<TB>();
var result = callback(a, b);
c.Push<TResult>(result);
return false;
}
}
// Convenience
class MathInstruction<T, TResult> : MathInstruction<T, T, TResult>
class MathInstruction<T> : MathInstruction<T, T, T>
I'm imagining that your context simply has a Stack<object> and PopINT, PopBOOL etc. just pop the argument and cast. In that case you can probably just use:
public T Pop<T>()
{
var o = stack.Pop();
return Convert.ChangeType(o, typeof(T));
}
public void Push<T>(T item)
{
stack.Push(item);
}
Note this could also handle your logical operators - for example:
var logicalAnd = new MathInstruction<bool>((a, b) => a && b);
var logicalOr = new MathInstruction<bool>((a, b) => a || b);
Could you use inheritance ? I would see a clever combination of inheritance concerning the datatypes, and then a strategy pattern to delegate the execution to the appropriate objects.
But then we really would need to see a class diagramm to help you out.
Just remember to program to an interface, not a type, and also, composition is more powerful than inheritance. I hope this can help you out.

Specialize implementation of GenericType<A,B> for case A == B?

I have a generic class which takes two type parameters, Generic<A, B>. This class has methods with signatures that are distinct so long and A and B are distinct. However, if A == B the signatures match exactly and overload resolution cannot be performed. Is it possible to somehow specify a specialisation of the method for this case? Or force the compiler to arbitrarily choose one of the matching overloads?
using System;
namespace Test
{
class Generic<A, B>
{
public string Method(A a, B b)
{
return a.ToString() + b.ToString();
}
public string Method(B b, A a)
{
return b.ToString() + a.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Generic<int, double> t1 = new Generic<int, double>();
Console.WriteLine(t1.Method(1.23, 1));
Generic<int, int> t2 = new Generic<int, int>();
// Following line gives:
// The call is ambiguous between the following methods
// or properties: 'Test.Generic<A,B>.Method(A, B)' and
// 'Test.Generic<A,B>.Method(B, A)'
Console.WriteLine(t2.Method(1, 2));
}
}
}
Given the purely generic definition there is no way to force the compiler to choose an overload. It has no way to distinguish a winner between the two methods.
It may seem a good idea to just pick one or the other but the decision needs to be deterministic. Even something as simple as the first one in the file is not really doable because you must consider partial classes. How would the compiler choose the first method if each were in a different file?
What you can do though is add a non-generic version of the method which accepts int. The compiler will choose the non-generic version over the generic version and it will produce a win in this very limited scenario. You would have to repeat that for every type which may have a conflict though.
For example. Adding this method will solve your compilation error, but only for int.
public string Method(int b, int a)
{
return b.ToString() + a.ToString();
}
Thanks for the good answers, they prompted me into this solution:
using System;
namespace Test
{
class Generic<A, B>
{
public string Method(A a, B b)
{
return this.DefaultMethod(a, b);
}
protected string DefaultMethod(A a, B b)
{
return a.ToString() + b.ToString();
}
public string Method(B b, A a)
{
return b.ToString() + a.ToString();
}
}
class Generic<A> : Generic<A, A>
{
public new string Method(A a, A b)
{
return base.DefaultMethod(a, b);
}
}
class Program
{
static void Main(string[] args)
{
Generic<int, double> t1 = new Generic<int, double>();
Console.WriteLine(t1.Method(1.23, 1));
Generic<int> t2 = new Generic<int>();
Console.WriteLine(t2.Method(1, 2));
}
}
}
I know it kind of defeats the purpose of the generic, but what about defining the method once, taking two parameters of type object?
Inside the method, you can examine the types and work out which one of your two options to call.
namespace Test
{
class Generic<A, B>
{
public string Method(object a, object b)
{
if (a is A && b is B)
return MethodOneTwo;
else if (a is B && b is A)
return MethodTwoOne;
else
throw new ArgumentException("Invalid Types");
}
private string MethodOneTwo(A a, B b)
{
return a.ToString() + b.ToString();
}
private string MethodTwoOne(B b, A a)
{
return b.ToString() + a.ToString();
}
}
}
This will use reflection to get the Methods and arbitrarily call one. You could make this more robust by filtering on the parameter and return types that are expected whenever you are getting the methods.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
using System;
using System.Reflection;
namespace Test
{
class Generic<A, B>
{
public string Method(A a, B b)
{
return a.ToString() + b.ToString();
}
public string Method(B b, A a)
{
return b.ToString() + a.ToString();
}
}
class Program
{
static void Main(string[] args)
{
Generic<int, double> t1 = new Generic<int, double>();
Console.WriteLine(t1.Method(1.23, 1));
Generic<int, int> t2 = new Generic<int, int>();
// Following line gives:
// The call is ambiguous between the following methods
// or properties: 'Test.Generic<A,B>.Method(A, B)' and
// 'Test.Generic<A,B>.Method(B, A)'
MethodInfo [] methods = t2.GetType().GetMethods();
foreach(MethodInfo method in methods)
{
if (method.Name == "Method")
{
method.Invoke(t2,new Object[2] {1,2});
break;
}
}
}
}
}
}
Edit: Here is a blog about the problem you face, with a solution similar to Jared's.
http://shiman.wordpress.com/2008/07/07/generic-method-overload-a-trap-for-c-net-library-developers/
What we really need are templates that generate concrete signatures at precompile or compile time.
No.
If you want the compiler to decide things arbitrarily, what is the purpose of you calling the method?

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