Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Read type class ported to C#
// Read type class ported to C#
// Only tested with: Mono C# compiler version
// Because there are no static interface members, new instances of the
// Dictionary classes have to be created (although they contain no state).
// The functions using the read method (like mulStrings) explicitly mention
// `int` in IReadDictionary<int>, but that's just like `x = read "4" :: Int` in
// Haskell.
// Also, since .NET doesn't allow for existing (sealed) classes to be extended,
// the Dictionary classes are separate from the types they work on (can't make
// `class System.Int32 : IReadDictionary<Int32>`).
using System;
// class Read a where
// read :: String -> a
interface IReadDictionary<A>
A read(string s);
class ReadTest
public static void Main()
// Explictly pass int dictionary
int x = mulStrings(new IntDictionary());
// Explictly pass bool dictionary
bool b = andStrings(new BoolDictionary());
// Polymorphic usage
int y = readSomething(new IntDictionary());
static int mulStrings(IReadDictionary<int> dict)
int x ="4");
int y ="16");
return x * y;
static bool andStrings(IReadDictionary<bool> dict)
bool b1 ="false");
bool b2 ="true");
return b1 && b2;
// This function is polymorphic in A
// Here the IReadDictionary<A> interface shows its benefit over manually
// calling Int32.Parse or Boolean.Parse.
static A readSomething<A>(IReadDictionary<A> dict)
class IntDictionary : IReadDictionary<int>
public int read(string s)
return Int32.Parse(s);
class BoolDictionary : IReadDictionary<bool>
public bool read(string s)
return Boolean.Parse(s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.