Last active
December 15, 2015 07:39
-
-
Save btawney/5225499 to your computer and use it in GitHub Desktop.
C# expression of model Toyl program ToylModel20130322
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ToylModel20130322 | |
{ | |
public delegate TReturn ToylFunc<TReturn>(); | |
public delegate TReturn ToylFunc<T1, TReturn>(ISignature<T1> p1); | |
public delegate TReturn ToylFunc<T1, T2, TReturn>(ISignature<T1> p1, ISignature<T2> p2); | |
public interface ISignature<T> { | |
T Value(); | |
} | |
public class Constant<T> : ISignature<T> { | |
private T _value; | |
public Constant(T value) { | |
this._value = value; | |
} | |
public T Value() { | |
return this._value; | |
} | |
} | |
public class CurryFactory<T1, T2, TReturn> { | |
private ISignature<T1> _p1; | |
private ToylFunc<T1, T2, TReturn> _currier; | |
private CurryFactory(ToylFunc<T1, T2, TReturn> currier, ISignature<T1> p1) { | |
this._p1 = p1; | |
this._currier = currier; | |
} | |
public static ToylFunc<T2, TReturn> Curry(ToylFunc<T1, T2, TReturn> currier, ISignature<T1> p1) { | |
CurryFactory<T1, T2, TReturn> factory = new CurryFactory<T1, T2, TReturn> (currier, p1); | |
return factory.CurriedMethod; | |
} | |
public TReturn CurriedMethod(ISignature<T2> p2) { | |
return this._currier (this._p1, p2); | |
} | |
} | |
public class ToylModel20130322 { | |
public int AddAndMultiply(ISignature<int> x, ISignature<int> y) { | |
if (x.Value () < 0) { | |
throw new Exception("x must not be less than zero"); | |
} else { | |
return (y.Value () + x.Value ()) * x.Value (); | |
} | |
} | |
public ISignature<int> C13 = new Constant<int>(13); | |
public ToylFunc<int, int> AddCAndMultiplyByC; | |
public static class HigherOrder<T> { | |
public static T ApplyTwice(ISignature<ToylFunc<T, T>> f, ISignature<T> v) { | |
return f.Value ()(new Constant<T>(f.Value () (v))); | |
} | |
} | |
ToylFunc<ToylFunc<int, int>, int, int> ApplyTwice = HigherOrder<int>.ApplyTwice; | |
public int TestFunction() { | |
// ApplyTwice(AddCAndMultiplyByC, 72) | |
// = AddCAndMultiplyByC(AddCAndMultiplyByC(72)) | |
// = AddCAndMultiplyByC((72 + 13) * 13) | |
// = AddCAndMultiplyByC(1105) | |
// = (1105 + 13) * 13 | |
// = 14534 | |
return ApplyTwice | |
( | |
new Constant<ToylFunc<int, int>>(AddCAndMultiplyByC), | |
new Constant<int>(72) | |
); | |
} | |
public ToylModel20130322() { | |
this.AddCAndMultiplyByC = CurryFactory<int, int, int>.Curry (this.AddAndMultiply, this.C13); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment