Skip to content

Instantly share code, notes, and snippets.

@JamesTryand
Created February 24, 2015 11:22
Show Gist options
  • Save JamesTryand/7ae4c820115578809354 to your computer and use it in GitHub Desktop.
Save JamesTryand/7ae4c820115578809354 to your computer and use it in GitHub Desktop.
Simple Pipelines in C#

Pipelines in C#

This does a pipeline wrapper class, and as an extension method for implementations of a type. This is useful for arranging pipelines and whatnot; it does this using a state for that instance, so it's nothing like an indexed monad, but it does allow enumerations of funcs to be applied.

the next step to this would be to make sure that it's monadic: if i could do it as monadic extension methods then that would be ideal, but in the meantime here's this little thing.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication13
{
class Program
{
static void Main(string[] args)
{
var n = new X<int>(5);
n.Pipeline(
x => x + 3,
x => x * x,
x => x + 9,
x => x / 3);
n.Then(Console.WriteLine);
Console.ReadLine();
}
}
public class X<T>
{
T state;
public X(T seed)
{
state = seed;
}
public T Pipeline(params Expression<Func<T, T>>[] process)
{
// T state = null;
foreach (var func in process)
{
state = func.Compile()(state);
}
return state;
}
public T Operation<U>(KeyValuePair<Func<T, U, T>, U> statechange)
{
return statechange.Key(state, statechange.Value);
}
public T Operations<U>(IEnumerable<KeyValuePair<Func<T, U, T>, U>> statechanges)
{
foreach (var statechange in statechanges)
{
state = statechange.Key(state, statechange.Value);
}
return state;
}
public T Operation<U>(U value, Func<T, U, T> action)
{
return action(state, value);
}
public void Then(Action<T> operation)
{
operation(state);
}
public T So()
{
return state;
}
}
public interface Q { }
public static class Y
{
public static T Pipeline<T>(this T state, params Expression<Func<T, T>>[] process) where T : Q
{
foreach (var func in process)
{
state = func.Compile()(state);
}
return state;
}
public static T Operations<T, U>(this T state, params KeyValuePair<Func<T, U, T>, U>[] statechanges) where T : Q
{
foreach (var statechange in statechanges)
{
state = statechange.Key(state, statechange.Value);
}
return state;
}
public static void Then<T>(this T state, Action<T> operation) where T : Q
{
operation(state);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment