public
Last active

Functor type class ported to C#

  • Download Gist
FuctorTest.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
// 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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.