Created
February 22, 2010 13:07
-
-
Save tomlokhorst/311058 to your computer and use it in GitHub Desktop.
Functor type class ported to C#
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
// Functor type class ported to C# | |
// Only tested with: Mono C# compiler version 2.4.2.3 | |
// | |
// Because .NET doesn't support higher kinded generics, we can't exactly port | |
// the Functor type class. | |
// However, if we're willing to give up a bit of type safety, we can get the | |
// IFuctor interface to work. | |
// | |
// We only have to add a single type cast, directly after using fmap. E.g: | |
// var xs = new List<int>(); | |
// var ys = (List<int>) myList.fmap(x => x + 1); | |
using System; | |
using GC = System.Collections.Generic; | |
// class Functor f where | |
// fmap :: (a -> b) -> f a -> f b | |
interface IFunctor<A> | |
{ | |
IFunctor<B> fmap<B>(Func<A, B> f); | |
} | |
class FunctorTest | |
{ | |
public static void Main() | |
{ | |
// List test | |
var xs = new List<int>{3, 5, 1, 9}; | |
var ys = (List<int>) xs.fmap(x => x * x); | |
ys.Reverse(); // The cast on previous line is really needed here | |
Console.WriteLine(ys); | |
// Maybe test 1 | |
var m1 = new Maybe<string>(); | |
var m2 = (Maybe<string>) m1.fmap(s => s.ToUpper()); | |
Console.WriteLine(m2); | |
// Maybe test 2 | |
var m3 = new Maybe<string>("4815162342"); | |
var m4 = (Maybe<long>) m3.fmap(s => Int64.Parse(s)); | |
Console.WriteLine(m4); | |
} | |
} | |
class List<A> : GC.List<A>, IFunctor<A> | |
{ | |
public IFunctor<B> fmap<B>(Func<A, B> f) | |
{ | |
List<B> ys = new List<B>(); | |
foreach (var x in this) | |
ys.Add(f(x)); | |
return ys; | |
} | |
// "Pretty" printer for lists | |
public override string ToString() | |
{ | |
string s = base.ToString() + ": "; | |
foreach (var x in this) | |
s += x.ToString() + ", "; | |
return s; | |
} | |
} | |
class Maybe<A> : IFunctor<A> | |
{ | |
public IFunctor<B> fmap<B>(Func<A, B> f) | |
{ | |
if (value == null) | |
return new Maybe<B>(); | |
else | |
return new Maybe<B>(f(value)); | |
} | |
public Maybe() {} | |
public Maybe(A x) | |
{ | |
value = x; | |
} | |
public override string ToString() | |
{ | |
return value == null ? "Nothing" : "Just " + value.ToString(); | |
} | |
A value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment