Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I'm trying to create a memoization interface for functions with arbitrary number of arguments, but I'm failing miserably I feel like my solution is not very flexible. I tried to define an interface for a function which gets memoized automatically upon execution and each function will have to implement this interface. Here is an example with a two parameter Exponential Moving Average function:
class EMAFunction:IFunction
{
Dictionary<List<object>, List<object>> map;
class EMAComparer : IEqualityComparer<List<object>>
{
private int _multiplier = 97;
public bool Equals(List<object> a, List<object> b)
{
List<object> aVals = (List<object>)a[0];
int aPeriod = (int)a[1];
List<object> bVals = (List<object>)b[0];
int bPeriod = (int)b[1];
return (aVals.Count == bVals.Count) && (aPeriod == bPeriod);
}
public int GetHashCode(List<object> obj)
{
// Don't compute hash code on null object.
if (obj == null)
{
return 0;
}
List<object> vals = (List<object>) obj[0];
int period = (int) obj[1];
return (_multiplier * period.GetHashCode()) + vals.Count;
}
}
public EMAFunction()
{
NumParams = 2;
Name = "EMA";
map = new Dictionary<List<object>, List<object>>(new EMAComparer());
}
#region IFunction Members
public int NumParams
{
get;
set;
}
public string Name
{
get;
set;
}
public object Execute(List<object> parameters)
{
if (parameters.Count != NumParams)
throw new ArgumentException("The num params doesn't match!");
if (!map.ContainsKey(parameters))
{
//map.Add(parameters,
List<double> values = new List<double>();
List<object> asObj = (List<object>)parameters[0];
foreach (object val in asObj)
{
values.Add((double)val);
}
int period = (int)parameters[1];
asObj.Clear();
List<double> ema = TechFunctions.ExponentialMovingAverage(values, period);
foreach (double val in ema)
{
asObj.Add(val);
}
map.Add(parameters, asObj);
}
return map[parameters];
}
public void ClearMap()
{
map.Clear();
}
#endregion
}
Here are my tests of the function:
private void MemoizeTest()
{
DataSet dataSet = DataLoader.LoadData(DataLoader.DataSource.FROM_WEB, 1024);
List<String> labels = dataSet.DataLabels;
Stopwatch sw = new Stopwatch();
IFunction emaFunc = new EMAFunction();
List<object> parameters = new List<object>();
int numRuns = 1000;
long sumTicks = 0;
parameters.Add(dataSet.GetValues("open"));
parameters.Add(12);
// First call
for(int i = 0; i < numRuns; ++i)
{
emaFunc.ClearMap();// remove any memoization mappings
sw.Start();
emaFunc.Execute(parameters);
sw.Stop();
sumTicks += sw.ElapsedTicks;
sw.Reset();
}
Console.WriteLine("Average ticks not-memoized " + (sumTicks/numRuns));
sumTicks = 0;
// Repeat call
for (int i = 0; i < numRuns; ++i)
{
sw.Start();
emaFunc.Execute(parameters);
sw.Stop();
sumTicks += sw.ElapsedTicks;
sw.Reset();
}
Console.WriteLine("Average ticks memoized " + (sumTicks/numRuns));
}
Update:
Thanks for pointing out my n00bish error... I always forget to call Reset on the stopwatch!
I've seen another approach to memoization as well... it doesn't offer n-argument memoization, but my approach with the Interface is not much more advantageous since I have to write a class for each function. Is there a reasonable way that I can merge these ideas into something more robust? I want to make it easier to memoize a function without making the user write a class for each function that they intend to use.
How about this? First write a one-argument memoizer:
static Func<A, R> Memoize<A, R>(this Func<A, R> f)
{
var d = new Dictionary<A, R>();
return a=>
{
R r;
if (!d.TryGetValue(a, out r))
{
r = f(a);
d.Add(a, r);
}
return r;
};
}
Straightforward. Now write a function tuplifier:
static Func<Tuple<A, B>, R> Tuplify<A, B, R>(this Func<A, B, R> f)
{
return t => f(t.Item1, t.Item2);
}
And a detuplifier:
static Func<A, B, R> Detuplify<A, B, R>(this Func<Tuple<A, B>, R> f)
{
return (a, b) => f(Tuple.Create(a, b));
}
and now a two-argument memoizer is easy:
static Func<A, B, R> Memoize<A, B, R>(this Func<A, B, R> f)
{
return f.Tuplify().Memoize().Detuplify();
}
To write a three-argument memoizer just keep following this pattern: make a 3-tuplifier, a 3-untuplifier, and a 3-memoizer.
Of course, if you don't need them, there's no need to make the tuplifiers nominal methods:
static Func<A, B, R> Memoize<A, B, R>(this Func<A, B, R> f)
{
Func<Tuple<A, B>, R> tuplified = t => f(t.Item1, t.Item2);
Func<Tuple<A, B>, R> memoized = tuplified.Memoize();
return (a, b) => memoized(Tuple.Create(a, b));
}
UPDATE: You ask what to do if there is no tuple type. You could write your own; it's not hard. Or you could use anonymous types:
static Func<T, R> CastByExample<T, R>(Func<T, R> f, T t) { return f; }
static Func<A, B, R> Memoize<A, B, R>(this Func<A, B, R> f)
{
var example = new { A=default(A), B=default(B) };
var tuplified = CastByExample(t => f(t.A, t.B), example);
var memoized = tuplified.Memoize();
return (a, b) => memoized(new {A=a, B=b});
}
Slick, eh?
UPDATE: C# 7 now has value tuples built in to the language; use them rather than rolling your own or using anonymous types.
First, you need to call sw.Reset() between your tests. Otherwise your results for the second test will be in addition to the time from the first.
Second, you probably shouldn't use vals.GetHashCode() in your GetHashCode() override on the comparer, as this will lead you to getting different hash codes for objects that would evaluate to true for your Equals override. For now, I would worry about making sure that equivalent objects always get the same hash code rather than trying to get an even distribution of the codes. If the hash codes don't match, Equals will never be called, so you'll end up processing the same parameters multiple times.
StopWatch.Stop does not reset the stopwatch so you are accumulating time on each start/stop.
For example
Stopwatch sw = new Stopwatch();
sw.Start();
System.Threading.Thread.Sleep(100);
sw.Stop();
Debug.WriteLine(sw.ElapsedTicks);
sw.Start();
System.Threading.Thread.Sleep(100);
sw.Stop();
Debug.WriteLine(sw.ElapsedTicks);
Gives the following results
228221
454626
You can use StopWatch.Restart (Framework 4.0) to restart the stopwatch each time, or if not Framework 4.0, you can use StopWatch.Reset to reset the stopwatch.
Alternative (to tuples & anonymous types) approach might be as follows:
static void Main(string[] args)
{
var func = Memoize<int, int, int>(Func);
Console.WriteLine(func(3)(4));
Console.WriteLine(func(3)(5));
Console.WriteLine(func(2)(5));
Console.WriteLine(func(3)(4));
}
//lets pretend this is very-expensive-to-compute function
private static int Func(int i, int j)
{
return i + j;
}
private static Func<TArg1, Func<TArg2, TRes>> Memoize<TArg1, TArg2, TRes>(Func<TArg1, TArg2, TRes> func)
{
Func<TArg1, Func<TArg2, TRes>> func1 =
Memoize((TArg1 arg1) => Memoize((TArg2 arg2) => func(arg1, arg2)));
return func1;
}
private static Func<TArg, TRes> Memoize<TArg, TRes>(Func<TArg, TRes> func)
{
var cache = new Dictionary<TArg, TRes>();
return arg =>
{
TRes res;
if( !cache.TryGetValue(arg, out res) )
{
Console.WriteLine("Calculating " + arg.ToString());
res = func(arg);
cache.Add(arg, res);
}
else
{
Console.WriteLine("Getting from cache " + arg.ToString());
}
return res;
};
}
Based on these two Memoize funcs you can easily build extensions for as many args as you wish.
I initially came here just looking for an abstract memoization method for a no-parameter function. This isn't exactly an answer to the question but wanted to share my solution in case someone else came looking for the simple case.
public static class MemoizationExtensions
{
public static Func<R> Memoize<R>(this Func<R> f)
{
bool hasBeenCalled = false; // Used to determine if we called the function and the result was the same as default(R)
R returnVal = default(R);
return () =>
{
// Should be faster than doing null checks and if we got a null the first time,
// we really want to memoize that result and not inadvertently call the function again.
if (!hasBeenCalled)
{
hasBeenCalled = true;
returnVal = f();
}
return returnVal;
};
}
}
If you use LinqPad you can use the following code to easily test out the functionality through the use of LinqPad's super cool Dump method.
new List<Func<object>>(new Func<object>[] {
() => { "Entered func A1".Dump(); return 1; },
() => { "Entered func A2".Dump(); return default(int); },
() => { "Entered func B1".Dump(); return String.Empty; },
() => { "Entered func B2".Dump(); return default(string); },
() => { "Entered func C1".Dump(); return new {Name = String.Empty}; },
() => { "Entered func C2".Dump(); return null; },
})
.ForEach(f => {
var f1 = MemoizationExtensions.Memoize(f);
Enumerable
.Range(1,3)
.Select(i=>new {Run=i, Value=f1()})
.Dump();
});
P.S. You will need to include the MemoizationExtensions class in the code of the LinqPad script otherwise it won't work!
Related
I'm using some functional stuff in C# and keep getting stuck on the fact that List.Add doesn't return the updated list.
In general, I'd like to call a function on an object and then return the updated object.
For example it would be great if C# had a comma operator:
((accum, data) => accum.Add(data), accum)
I could write my own "comma operator" like this:
static T comma(Action a, Func<T> result) {
a();
return result();
}
It looks like it would work but the call site would ugly. My first example would be something like:
((accum, data) => comma(accum.Add(data), ()=>accum))
Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?
I know this as Fluent.
A Fluent example of a List.Add using Extension Methods
static List<T> MyAdd<T>(this List<T> list, T element)
{
list.Add(element);
return list;
}
I know that this thread is very old, but I want to append the following information for future users:
There isn't currently such an operator. During the C# 6 development cycle a semicolon operator was added, as:
int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);
which can be translated as follows:
int square = compiler_generated_Function();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x - 2);
return x * x;
}
However, this feature was dropped before the final C# release.
You can do almost exactly the first example naturally using code blocks in C# 3.0.
((accum, data) => { accum.Add(data); return accum; })
This is what Concat http://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx is for. Just wrap a single item in an array. Functional code should not mutate the original data. If performance is a concern, and this isn't good enough, then you'll no longer be using the functional paradigm.
((accum, data) => accum.Concat(new[]{data}))
Another technique, straight from functional programming, is as follows. Define an IO struct like this:
/// <summary>TODO</summary>
public struct IO<TSource> : IEquatable<IO<TSource>> {
/// <summary>Create a new instance of the class.</summary>
public IO(Func<TSource> functor) : this() { _functor = functor; }
/// <summary>Invokes the internal functor, returning the result.</summary>
public TSource Invoke() => (_functor | Default)();
/// <summary>Returns true exactly when the contained functor is not null.</summary>
public bool HasValue => _functor != null;
X<Func<TSource>> _functor { get; }
static Func<TSource> Default => null;
}
and make it a LINQ-able monad with these extension methods:
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class IO {
public static IO<TSource> ToIO<TSource>( this Func<TSource> source) {
source.ContractedNotNull(nameof(source));
return new IO<TSource>(source);
}
public static IO<TResult> Select<TSource,TResult>(this IO<TSource> #this,
Func<TSource,TResult> projector
) =>
#this.HasValue && projector!=null
? New(() => projector(#this.Invoke()))
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,TResult>(this IO<TSource> #this,
Func<TSource,IO<TResult>> selector
) =>
#this.HasValue && selector!=null
? New(() => selector(#this.Invoke()).Invoke())
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,T,TResult>(this IO<TSource> #this,
Func<TSource, IO<T>> selector,
Func<TSource,T,TResult> projector
) =>
#this.HasValue && selector!=null && projector!=null
? New(() => { var s = #this.Invoke(); return projector(s, selector(s).Invoke()); } )
: Null<TResult>();
public static IO<TResult> New<TResult> (Func<TResult> functor) => new IO<TResult>(functor);
private static IO<TResult> Null<TResult>() => new IO<TResult>(null);
}
and now you can use the LINQ comprehensive syntax thus:
using Xunit;
[Fact]
public static void IOTest() {
bool isExecuted1 = false;
bool isExecuted2 = false;
bool isExecuted3 = false;
bool isExecuted4 = false;
IO<int> one = new IO<int>( () => { isExecuted1 = true; return 1; });
IO<int> two = new IO<int>( () => { isExecuted2 = true; return 2; });
Func<int, IO<int>> addOne = x => { isExecuted3 = true; return (x + 1).ToIO(); };
Func<int, Func<int, IO<int>>> add = x => y => { isExecuted4 = true; return (x + y).ToIO(); };
var query1 = ( from x in one
from y in two
from z in addOne(y)
from _ in "abc".ToIO()
let addOne2 = add(x)
select addOne2(z)
);
Assert.False(isExecuted1); // Laziness.
Assert.False(isExecuted2); // Laziness.
Assert.False(isExecuted3); // Laziness.
Assert.False(isExecuted4); // Laziness.
int lhs = 1 + 2 + 1;
int rhs = query1.Invoke().Invoke();
Assert.Equal(lhs, rhs); // Execution.
Assert.True(isExecuted1);
Assert.True(isExecuted2);
Assert.True(isExecuted3);
Assert.True(isExecuted4);
}
When one desires an IO monad that composes but returns only void, define this struct and dependent methods:
public struct Unit : IEquatable<Unit>, IComparable<Unit> {
[CLSCompliant(false)]
public static Unit _ { get { return _this; } } static Unit _this = new Unit();
}
public static IO<Unit> ConsoleWrite(object arg) =>
ReturnIOUnit(() => Write(arg));
public static IO<Unit> ConsoleWriteLine(string value) =>
ReturnIOUnit(() => WriteLine(value));
public static IO<ConsoleKeyInfo> ConsoleReadKey() => new IO<ConsoleKeyInfo>(() => ReadKey());
which readily allow the writing of code fragments like this:
from pass in Enumerable.Range(0, int.MaxValue)
let counter = Readers.Counter(0)
select ( from state in gcdStartStates
where _predicate(pass, counter())
select state )
into enumerable
where ( from _ in Gcd.Run(enumerable.ToList()).ToIO()
from __ in ConsoleWrite(Prompt(mode))
from c in ConsoleReadKey()
from ___ in ConsoleWriteLine()
select c.KeyChar.ToUpper() == 'Q'
).Invoke()
select 0;
where the old C comma operator is readily recognized for what it is: a monadic compose operation.
The true merit of the comprehension syntax is apparent when one attempts to write that fragment in the flunt style:
( Enumerable.Range(0,int.MaxValue)
.Select(pass => new {pass, counter = Readers.Counter(0)})
.Select(_ => gcdStartStates.Where(state => _predicate(_.pass,_.counter()))
.Select(state => state)
)
).Where(enumerable =>
( (Gcd.Run(enumerable.ToList()) ).ToIO()
.SelectMany(_ => ConsoleWrite(Prompt(mode)),(_,__) => new {})
.SelectMany(_ => ConsoleReadKey(), (_, c) => new {c})
.SelectMany(_ => ConsoleWriteLine(), (_,__) => _.c.KeyChar.ToUpper() == 'Q')
).Invoke()
).Select(list => 0);
The extension method is arguably the best solution, but for completeness' sake, don't forget the obvious alternative: a wrapper class.
public class FList<T> : List<T>
{
public new FList<T> Add(T item)
{
base.Add(item);
return this;
}
public new FList<T> RemoveAt(int index)
{
base.RemoveAt(index);
return this;
}
// etc...
}
{
var list = new FList<string>();
list.Add("foo").Add("remove me").Add("bar").RemoveAt(1);
}
I thought it would be interesting to make a version of my wrapper class answer that doesn't require you write the wrapper methods.
public class FList<T> : List<T>
{
public FList<T> Do(string method, params object[] args)
{
var methodInfo = GetType().GetMethod(method);
if (methodInfo == null)
throw new InvalidOperationException("I have no " + method + " method.");
if (methodInfo.ReturnType != typeof(void))
throw new InvalidOperationException("I'm only meant for void methods.");
methodInfo.Invoke(this, args);
return this;
}
}
{
var list = new FList<string>();
list.Do("Add", "foo")
.Do("Add", "remove me")
.Do("Add", "bar")
.Do("RemoveAt", 1)
.Do("Insert", 1, "replacement");
foreach (var item in list)
Console.WriteLine(item);
}
Output:
foo
replacement
bar
EDIT
You can slim down the syntax by exploiting C# indexed properties.
Simply add this method:
public FList<T> this[string method, params object[] args]
{
get { return Do(method, args); }
}
And the call now looks like:
list = list["Add", "foo"]
["Add", "remove me"]
["Add", "bar"]
["RemoveAt", 1]
["Insert", 1, "replacement"];
With the linebreaks being optional, of course.
Just a bit of fun hacking the syntax.
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.
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.
I'm using some functional stuff in C# and keep getting stuck on the fact that List.Add doesn't return the updated list.
In general, I'd like to call a function on an object and then return the updated object.
For example it would be great if C# had a comma operator:
((accum, data) => accum.Add(data), accum)
I could write my own "comma operator" like this:
static T comma(Action a, Func<T> result) {
a();
return result();
}
It looks like it would work but the call site would ugly. My first example would be something like:
((accum, data) => comma(accum.Add(data), ()=>accum))
Enough examples! What's the cleanest way to do this without another developer coming along later and wrinkling his or her nose at the code smell?
I know this as Fluent.
A Fluent example of a List.Add using Extension Methods
static List<T> MyAdd<T>(this List<T> list, T element)
{
list.Add(element);
return list;
}
I know that this thread is very old, but I want to append the following information for future users:
There isn't currently such an operator. During the C# 6 development cycle a semicolon operator was added, as:
int square = (int x = int.Parse(Console.ReadLine()); Console.WriteLine(x - 2); x * x);
which can be translated as follows:
int square = compiler_generated_Function();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private int compiler_generated_Function()
{
int x = int.Parse(Console.ReadLine());
Console.WriteLine(x - 2);
return x * x;
}
However, this feature was dropped before the final C# release.
You can do almost exactly the first example naturally using code blocks in C# 3.0.
((accum, data) => { accum.Add(data); return accum; })
This is what Concat http://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx is for. Just wrap a single item in an array. Functional code should not mutate the original data. If performance is a concern, and this isn't good enough, then you'll no longer be using the functional paradigm.
((accum, data) => accum.Concat(new[]{data}))
Another technique, straight from functional programming, is as follows. Define an IO struct like this:
/// <summary>TODO</summary>
public struct IO<TSource> : IEquatable<IO<TSource>> {
/// <summary>Create a new instance of the class.</summary>
public IO(Func<TSource> functor) : this() { _functor = functor; }
/// <summary>Invokes the internal functor, returning the result.</summary>
public TSource Invoke() => (_functor | Default)();
/// <summary>Returns true exactly when the contained functor is not null.</summary>
public bool HasValue => _functor != null;
X<Func<TSource>> _functor { get; }
static Func<TSource> Default => null;
}
and make it a LINQ-able monad with these extension methods:
[SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces")]
public static class IO {
public static IO<TSource> ToIO<TSource>( this Func<TSource> source) {
source.ContractedNotNull(nameof(source));
return new IO<TSource>(source);
}
public static IO<TResult> Select<TSource,TResult>(this IO<TSource> #this,
Func<TSource,TResult> projector
) =>
#this.HasValue && projector!=null
? New(() => projector(#this.Invoke()))
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,TResult>(this IO<TSource> #this,
Func<TSource,IO<TResult>> selector
) =>
#this.HasValue && selector!=null
? New(() => selector(#this.Invoke()).Invoke())
: Null<TResult>();
public static IO<TResult> SelectMany<TSource,T,TResult>(this IO<TSource> #this,
Func<TSource, IO<T>> selector,
Func<TSource,T,TResult> projector
) =>
#this.HasValue && selector!=null && projector!=null
? New(() => { var s = #this.Invoke(); return projector(s, selector(s).Invoke()); } )
: Null<TResult>();
public static IO<TResult> New<TResult> (Func<TResult> functor) => new IO<TResult>(functor);
private static IO<TResult> Null<TResult>() => new IO<TResult>(null);
}
and now you can use the LINQ comprehensive syntax thus:
using Xunit;
[Fact]
public static void IOTest() {
bool isExecuted1 = false;
bool isExecuted2 = false;
bool isExecuted3 = false;
bool isExecuted4 = false;
IO<int> one = new IO<int>( () => { isExecuted1 = true; return 1; });
IO<int> two = new IO<int>( () => { isExecuted2 = true; return 2; });
Func<int, IO<int>> addOne = x => { isExecuted3 = true; return (x + 1).ToIO(); };
Func<int, Func<int, IO<int>>> add = x => y => { isExecuted4 = true; return (x + y).ToIO(); };
var query1 = ( from x in one
from y in two
from z in addOne(y)
from _ in "abc".ToIO()
let addOne2 = add(x)
select addOne2(z)
);
Assert.False(isExecuted1); // Laziness.
Assert.False(isExecuted2); // Laziness.
Assert.False(isExecuted3); // Laziness.
Assert.False(isExecuted4); // Laziness.
int lhs = 1 + 2 + 1;
int rhs = query1.Invoke().Invoke();
Assert.Equal(lhs, rhs); // Execution.
Assert.True(isExecuted1);
Assert.True(isExecuted2);
Assert.True(isExecuted3);
Assert.True(isExecuted4);
}
When one desires an IO monad that composes but returns only void, define this struct and dependent methods:
public struct Unit : IEquatable<Unit>, IComparable<Unit> {
[CLSCompliant(false)]
public static Unit _ { get { return _this; } } static Unit _this = new Unit();
}
public static IO<Unit> ConsoleWrite(object arg) =>
ReturnIOUnit(() => Write(arg));
public static IO<Unit> ConsoleWriteLine(string value) =>
ReturnIOUnit(() => WriteLine(value));
public static IO<ConsoleKeyInfo> ConsoleReadKey() => new IO<ConsoleKeyInfo>(() => ReadKey());
which readily allow the writing of code fragments like this:
from pass in Enumerable.Range(0, int.MaxValue)
let counter = Readers.Counter(0)
select ( from state in gcdStartStates
where _predicate(pass, counter())
select state )
into enumerable
where ( from _ in Gcd.Run(enumerable.ToList()).ToIO()
from __ in ConsoleWrite(Prompt(mode))
from c in ConsoleReadKey()
from ___ in ConsoleWriteLine()
select c.KeyChar.ToUpper() == 'Q'
).Invoke()
select 0;
where the old C comma operator is readily recognized for what it is: a monadic compose operation.
The true merit of the comprehension syntax is apparent when one attempts to write that fragment in the flunt style:
( Enumerable.Range(0,int.MaxValue)
.Select(pass => new {pass, counter = Readers.Counter(0)})
.Select(_ => gcdStartStates.Where(state => _predicate(_.pass,_.counter()))
.Select(state => state)
)
).Where(enumerable =>
( (Gcd.Run(enumerable.ToList()) ).ToIO()
.SelectMany(_ => ConsoleWrite(Prompt(mode)),(_,__) => new {})
.SelectMany(_ => ConsoleReadKey(), (_, c) => new {c})
.SelectMany(_ => ConsoleWriteLine(), (_,__) => _.c.KeyChar.ToUpper() == 'Q')
).Invoke()
).Select(list => 0);
The extension method is arguably the best solution, but for completeness' sake, don't forget the obvious alternative: a wrapper class.
public class FList<T> : List<T>
{
public new FList<T> Add(T item)
{
base.Add(item);
return this;
}
public new FList<T> RemoveAt(int index)
{
base.RemoveAt(index);
return this;
}
// etc...
}
{
var list = new FList<string>();
list.Add("foo").Add("remove me").Add("bar").RemoveAt(1);
}
I thought it would be interesting to make a version of my wrapper class answer that doesn't require you write the wrapper methods.
public class FList<T> : List<T>
{
public FList<T> Do(string method, params object[] args)
{
var methodInfo = GetType().GetMethod(method);
if (methodInfo == null)
throw new InvalidOperationException("I have no " + method + " method.");
if (methodInfo.ReturnType != typeof(void))
throw new InvalidOperationException("I'm only meant for void methods.");
methodInfo.Invoke(this, args);
return this;
}
}
{
var list = new FList<string>();
list.Do("Add", "foo")
.Do("Add", "remove me")
.Do("Add", "bar")
.Do("RemoveAt", 1)
.Do("Insert", 1, "replacement");
foreach (var item in list)
Console.WriteLine(item);
}
Output:
foo
replacement
bar
EDIT
You can slim down the syntax by exploiting C# indexed properties.
Simply add this method:
public FList<T> this[string method, params object[] args]
{
get { return Do(method, args); }
}
And the call now looks like:
list = list["Add", "foo"]
["Add", "remove me"]
["Add", "bar"]
["RemoveAt", 1]
["Insert", 1, "replacement"];
With the linebreaks being optional, of course.
Just a bit of fun hacking the syntax.
I was thinking about writing generic functions for basic Math operations such as Min, Max etc.
But i i dont know how to compare two generic types :
public T Max<T>(T v1, T v2) where T: struct
{
return (v1 > v2 ? v1 : v2);
}
How about that?
Thank you.
You probably want to constrain the generic types to implement IComparable:
public T Max<T>(T v1, T v2) where T: struct, IComparable<T>
and then use the CompareTo method:
{
return (v1.CompareTo(v2) > 0 ? v1 : v2);
}
If you only want to create comparison functions then you could use the default comparer for the type T. For example:
public static T Max<T>(T x, T y)
{
return (Comparer<T>.Default.Compare(x, y) > 0) ? x : y;
}
If T implements IComparable<T> then that comparer will be used; if T doesn't implement IComparable<T> but does implement IComparable then that comparer will be used; if T doesn't implement either IComparable<T> or IComparable then a runtime exception will be thrown.
If you want/need to do more than just compare the items then you could have a look at the generic operators implementation in MiscUtil and the related article.
Let me disagree.
The #LukeH's implementation is not Generic.
I will explain why it is not Generic:
Comparer<T>.Default involves inspecting T at run-time to determine if it implements IComparable<T>, IComparable or neither.
Although this behavior is not well documented in http://msdn.microsoft.com/en-us/library/azhsac5f.aspx, we can deduct it because Comparer<T>.Default throws an exception when T does not implement neither. If the inspection was done at compilation-time there would be no need for an exception (runtime), with an compile-time error would suffice.
Then, as Comparer<T>.Default uses Reflection, this means a high cost on Run-Time, then...., It is NOT Generic... Why?
Because Generic Programming means: A single algorithm (Generic) can cover many implementations (for many types) maintaining efficiency of hand-written versions.
Take an example. The handwritten version for integers would be:
public static int Max( int x, int y)
{
return (x.CompareTo(y) > 0) ? x : y;
}
It is very simple, involving only a comparison (or maybe more, depending on how Int32.CompareTo() is implemented).
If we use the #LukeH's implementation, we are adding Reflection to something that is very simple.
In short:
Always prefer Compilation-time errors to Run-Time Exceptions ( this is not Javascript, Ruby,... :-) )
This implementation is less efficient compared to the handwritten version (for any type)
On the other hand.
What do you think Max should return when x and y are equivalents?
I'm starting to analyze Real-Generic implementations....
The ideal implementation would be something like...
public static T Max<T>(T x, T y, Func<T, T, int> cmp)
{
return (cmp(x, y) > 0) ? x : y;
}
//Pseudo-code ( note the 'or' next to 'where' )
public static T Max<T>(T x, T y) where T: IComparable<T> or IComparable
{
return Max(x, y, (a, b) => { return a.CompareTo(b); });
}
This is not possible in C#, the next try is could be...
//pseudo-code
public static T Max<T>(T x, T y, Func<T, T, int> cmp)
{
return (cmp(x, y) > 0) ? x : y;
}
public static T Max<T>(T x, T y) where T: IComparable<T>
{
return Max(x, y, (a, b) => { return a.CompareTo(b); });
}
public static T Max<T>(T x, T y) where T: IComparable
{
return Max(x, y, (a, b) => { return a.CompareTo(b); });
}
But, this is neither possible, because overload resolution doesn't takes into account Generics Constraints....
Then, I'll leave out IComparable consciously. I'm just going to worry about IComparable<T>
public static T Max<T>(T x, T y, Func<T, T, int> cmp)
{
return (cmp(x, y) > 0) ? x : y;
}
public static T Max<T>(T x, T y) where T: IComparable<T>
{
return Max(x, y, (a, b) => { return a.CompareTo(b); });
}
This is a little too late, but why not use dynamic types and delegates as an alternative to IComparable? This way you get compile-type safety in most cases and will only get a runtime error when the types supplied both do not support the operator < and you fail to provide the default comparer as an argument.
public static T Max<T>(T first, T second, Func<T,T,bool> f = null)
{
Func<dynamic,dynamic,bool> is_left_smaller = (x, y) => x < y ? true : false;
var compare = f ?? new Func<T, T, bool>((x, y) => is_left_smaller(x, y));
return compare(first, second) ? second : first;
}
The solution I present on this answer would have worked (I actually did something like this) at the time the question was asked. I'm surprised no answer presents this alternative, thus I'll present it.
You can (and could have used back then) Linq.Expressions (Which was added in .NET 3.5, in 2007, making it a valid answer at the time of the question).
For starters:
using System.Linq.Expressions;
// ...
public T Max<T>(T v1, T v2)
{
var expression = Expression.GreaterThan
(
Expression.Constant(v1),
Expression.Constant(v2)
);
return Expression.Lambda<Func<bool>>(expression).Compile()() ? v1 : v2);
}
That has no need of dynamic, or Comparison<T>/IComparer<T>.
I believe that having a way to specify a custom comparison is better, but that is not what we are doing here. And of course, any type for which the presented solution works, Comparer<T>.Default would work. However, using Linq.Expressions would allow you implement any arithmetic operations. Take this as illustration of that approach.
There is, of course, overhead. Let us have a version that does compile to a function with parameters, we can think later about how to cache it:
using System.Linq.Expressions;
// ...
public T Max<T>(T v1, T v2)
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var lambda = Expression.Lambda<Func<T, T, bool>>
(
Expression.GreaterThan(a, b),
new[]{a, b}
);
return ((Func<T, T, bool>)lambda.Compile())(v1, v2) ? v1 : v2;
}
Alright, to cache it, let us start with the generic class approach, which is easier to write:
using System.Linq.Expressions;
class GenericMath<T>
{
private static Func<T, T, bool>? _greaterThan;
public static Func<T, T, bool> GetGreaterThan()
{
if (_greaterThan == null)
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var lambda = Expression.Lambda<Func<T, T, bool>>
(
Expression.GreaterThan(a, b),
new[]{a, b}
);
_greaterThan = (Func<T, T, bool>)lambda.Compile();
}
return _greaterThan;
}
public static T Max(T v1, T v2)
{
return GetGreaterThan()(v1, v2) ? v1 : v2;
}
}
Of course, statics on generics has drawbacks (there is a performance cost, plus the memory is never released). We can start our way to a better solution by using a dictionary cache instead:
using System.Linq.Expressions;
class GenericMath
{
private readonly static Dictionary<Type, Delegate> _gtCache = new Dictionary<Type, Delegate>();
public static Func<T, T, bool> GetGreaterThan<T>()
{
if (!_gtCache.TryGetValue(typeof(T), out var #delegate) || #delegate == null)
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var lambda = Expression.Lambda<Func<T, T, bool>>
(
Expression.GreaterThan(a, b),
new[]{a, b}
);
#delegate = lambda.Compile();
_addCache[typeof(T)] = #delegate;
}
return (Func<T, T, bool>)#delegate;
}
public static T Max<T>(T v1, T v2)
{
return GetGreaterThan<T>()(v1, v2) ? v1 : v2;
}
}
Ok, I hear you, I have introduced a new problem: that solution is not thread-safe.
We could use ConcurrentDictionary (added in .NET 4.0, which -if I'm not mistaken- was on beta at the time of the question), but we would not be releasing memory anyway. Instead, we can make a custom class for this use:
public sealed class TypeCacheDict<TValue>
{
private const int Capacity = 256;
private readonly Entry[] _entries;
public TypeCacheDict()
{
_entries = new Entry[Capacity];
}
public TValue this[Type key]
{
get
{
if (TryGetValue(key, out var value))
{
return value;
}
throw new KeyNotFoundException();
}
set => Add(key, value);
}
public void Add(Type key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var hash = key.GetHashCode();
var index = hash & (_entries.Length - 1);
var entry = _entries[index];
Thread.MemoryBarrier();
if (entry?.Hash != hash || !entry.Key.Equals(key))
{
Interlocked.Exchange(ref _entries[index], new Entry(hash, key, value));
}
}
public bool TryGetValue(Type key, out TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
var hash = key.GetHashCode();
var index = hash & (_entries.Length - 1);
var entry = _entries[index];
Thread.MemoryBarrier();
if (entry?.Hash == hash && entry.Key.Equals(key))
{
value = entry.Value;
return value != null;
}
value = default;
return false;
}
private sealed class Entry
{
internal readonly int Hash;
internal readonly Type Key;
internal readonly TValue Value;
internal Entry(int hash, Type key, TValue value)
{
Hash = hash;
Key = key;
Value = value;
}
}
}
This TypeCacheDict is thread-safe. First of all Entry is immutable. We don't need to worry about shared access to it. Plus, it a reference type, so replacing it is an atomic operation. We are using Thread.MemoryBarrier and Interlocked.Exchange o mimic Volatile.Read and Volatile.Write because Volatile was not available (and Thread.Volatile* lacks generic overload, and I would rather not instroduce extra casts).
With this new type we can now write:
private readonly static TypeCacheDict<Delegate> _gtCache = new TypeCacheDict<Delegate>();
The rest of the code could be left unchanged. Although there is room for improvement: TryGetOrAdd:
public TValue TryGetOrAdd(Type key, Func<TValue> valueFactory)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (valueFactory == null)
{
throw new ArgumentNullException(nameof(valueFactory));
}
var hash = key.GetHashCode();
var index = hash & (_entries.Length - 1);
var entry = _entries[index];
Thread.MemoryBarrier();
if (entry?.Hash == hash && entry.Key.Equals(key))
{
return entry.Value;
}
var value = valueFactory();
Interlocked.Exchange(ref _entries[index], new Entry(hash, key, value));
return value;
}
Which allows us to write:
public static Func<T, T, bool> GetGreaterThan<T>()
{
return (Func<T, T, bool>)_gtCache.TryGetOrAdd
(
typeof(T),
()=>
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var lambda = Expression.Lambda<Func<T, T, bool>>(Expression.GreaterThan(a, b), new[]{a, b});
return lambda.Compile();
}
);
}
Of course, this is how you use it:
Console.WriteLine(GenericMath.Max<int>(90, 100)); // 100
To demostrate, the power of this approach, this is Add:
private readonly static TypeCacheDict<Delegate> _addCache = new TypeCacheDict<Delegate>();
public static Func<T, T, T> GetAdd<T>()
{
return (Func<T, T, T>)_addCache.TryGetOrAdd
(
typeof(T),
()=>
{
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var lambda = Expression.Lambda<Func<T, T, T>>(Expression.Add(a,b), new[]{a, b});
return lambda.Compile();
}
);
}
public static T Add<T>(T v1, T v2)
{
return GetAdd<T>()(v1, v2);
}
And this is how you use it:
Console.WriteLine(GenericMath.Add<int>(90, 100)); // 190
.NET 7 introduces a new feature - generic math (read more here and here) which is based on addition of static abstract interface methods. This feature introduces a lot of interfaces which allow to generically abstract over number types and/or math operations, which allows to rewrite the function in question as:
public T Max<T>(T v1, T v2) where T: IComparisonOperators<T, T, bool> => v1 > v2 ? v1 : v2;
Note that for build-in number types usually you don't need to define your own Max because it is already defined on the INumber<T> interface:
public interface INumber<TSelf> :
// ... other interfaces,
System.Numerics.IComparisonOperators<TSelf,TSelf,bool>
// ... other interfaces
where TSelf : INumber<TSelf>
From memory, T also needs to be IComparable (add that to the where), and then you use v1.CompareTo(v2) > 0 etc.
Necromancing.
You can have a Max/Min function on an arbitrary number of parameters:
public static T Min<T>(params T[] source)
where T: struct, IComparable<T>
{
if (source == null)
throw new System.ArgumentNullException("source");
T value = default(T);
bool hasValue = false;
foreach (T x in source)
{
if (hasValue)
{
// if (x < value) // https://learn.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netcore-3.1
// Less than zero This object precedes the object specified by the CompareTo method in the sort order.
// Zero This current instance occurs in the same position in the sort order as the object specified by the CompareTo method argument.
// Greater than zero
if (x.CompareTo(value) < 0)
value = x;
}
else
{
value = x;
hasValue = true;
}
}
if (hasValue)
return value;
throw new System.InvalidOperationException("Sequence contains no elements");
}
public static T Max<T>(params T[] source)
where T : struct, IComparable<T>
{
if (source == null)
throw new System.ArgumentNullException("source");
T value = default(T);
bool hasValue = false;
foreach (T x in source)
{
if (hasValue)
{
// if (x > value) // https://learn.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netcore-3.1
// Less than zero This object precedes the object specified by the CompareTo method in the sort order.
// Zero This current instance occurs in the same position in the sort order as the object specified by the CompareTo method argument.
// Greater than zero
if (x.CompareTo(value) > 0)
value = x;
}
else
{
value = x;
hasValue = true;
}
}
if (hasValue)
return value;
throw new System.InvalidOperationException("Sequence contains no elements");
}