Created
February 23, 2010 18:14
-
-
Save tomlokhorst/312509 to your computer and use it in GitHub Desktop.
Read 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
// Read type class ported to C# | |
// Only tested with: Mono C# compiler version 2.4.2.3 | |
// | |
// 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()); | |
Console.WriteLine(x); | |
// Explictly pass bool dictionary | |
bool b = andStrings(new BoolDictionary()); | |
Console.WriteLine(b); | |
// Polymorphic usage | |
int y = readSomething(new IntDictionary()); | |
Console.WriteLine(y); | |
} | |
static int mulStrings(IReadDictionary<int> dict) | |
{ | |
int x = dict.read("4"); | |
int y = dict.read("16"); | |
return x * y; | |
} | |
static bool andStrings(IReadDictionary<bool> dict) | |
{ | |
bool b1 = dict.read("false"); | |
bool b2 = dict.read("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) | |
{ | |
return dict.read("815"); | |
} | |
} | |
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