Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using FunctionalProgramming;
namespace FunctionalProgramming
{
public interface IOperation<I, O>
{
O Apply(I arg);
}
public class Operator<A, B, O>
{
private Func<A, B, O> func;
public Operator(Func<A, B, O> func)
{
this.func = func;
}
public static OperatorLeftArg<A, B, O> operator |(A arg, Operator<A, B, O> op)
{
return new OperatorLeftArg<A, B, O>(op.func, arg);
}
public static OperatorRightArg<A, B, O> operator |(Operator<A, B, O> op, B arg)
{
return new OperatorRightArg<A, B, O>(op.func, arg);
}
}
public class OperatorLeftArg<A, B, O> : IOperation<B, O>
{
private Func<A, B, O> func;
private A arg;
public OperatorLeftArg(Func<A, B, O> func, A arg)
{
this.func = func;
this.arg = arg;
}
public static O operator |(OperatorLeftArg<A, B, O> op, B arg)
{
return op.func(op.arg, arg);
}
public O Apply(B arg)
{
return this | arg;
}
}
public class OperatorRightArg<A, B, O> : IOperation<A, O>
{
private Func<A, B, O> func;
private B arg;
public OperatorRightArg(Func<A, B, O> func, B arg)
{
this.func = func;
this.arg = arg;
}
public O Apply(A arg)
{
return this.func(arg, this.arg);
}
}
}
namespace FPinCSh
{
class Program
{
static void Main(string[] args)
{
var plus = new Operator<int, int, int>((a, b) => a + b);
var times = new Operator<int, int, int>((a, b) => a * b);
var pow = new Operator<double, double, double>(Math.Pow);
var square = pow | 2;
var twopower = 2 | pow;
Console.WriteLine("4 `plus` (3 `times` 2) = {0}", 4 | plus | (3 | times | 2));
Console.WriteLine("square 3 = {0}", square.Apply(3.0));
Console.WriteLine("twopower 3 = {0}", twopower.Apply(3.0));
Console.ReadKey(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.