public
Last active

Read type class ported to C#

  • Download Gist
ReadTest.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
// 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);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.