Skip to content

Instantly share code, notes, and snippets.

@mausch
Created March 28, 2014 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mausch/9840670 to your computer and use it in GitHub Desktop.
Save mausch/9840670 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
static class Extensions {
public static Func<A, IEnumerable<C>> Kleisli<A,B,C>(this Func<A, IEnumerable<B>> f, Func<B, IEnumerable<C>> g) {
return a => from b in f(a) from c in g(b) select c;
}
}
class Program {
static void Main(string[] args) {
Func<int, IEnumerable<string>> f = i => Enumerable.Range(0, i).Select(x => x.ToString());
Func<string, IEnumerable<string>> g = s => s.Split(',');
Func<string, IEnumerable<int>> digits = s => new[] { s.IndexOf("0") };
// verbose kleisli composition with LINQ:
{
var r =
from a in f(20)
from b in g(a)
from c in digits(b)
select c;
}
// point-free kleisli composition
{
var r = f.Kleisli(g).Kleisli(digits)(20);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment