The last few days i’ve been hacking on a data encoding library in Haskell. Haskell has long been lacking in this area and receiving a double-encoded email about a week ago alerted me to this (you might have had to actually be in my head to follow that train of thought ). Yesterday I put up a Wiki page and posted an email to the Haskell library list. I also logged into #Haskell and asked for feedback. This was when Saizan came with an interesting suggestion:
What about using phantom types to annotate the encoding and use a typeclass to unify the interfaces?
That’s an excellent idea. One thought has been bugging me since beginning implementing the library, each module exposes the same methods, with the same type signatures, but there is no type-safe polymorphism in the API. I’ve never really understood phantom types so Saizan’s idea was a bit of an eye-opener for me. I think they can help solve the problem. Unfortunately I ran into another problem when playing.
I picked base16 encoding to play a bit with this because the implementation is fairly short and simple. I began with creating a new typeclass:
class DataEncoding d where encode :: [Word8] -> d String decode :: d String -> [Word8] chop :: Int -> d String -> d [String] unchop :: d [String] -> d String liberate :: d [String] -> [String] incarcerate :: [String] -> d [String]
I added the last two functions since it’s no good to have the encoding locked up and inaccessible all the time, at some point we might actually want to do something with the data.
The implementation in Base16 looks like this:
data B16Enc p = B16EncS String | B16EncLS [String] deriving (Eq, Show) instance DataEncoding B16Enc where encode os = B16EncS $ b16Encode os decode (B16EncS s) = b16Decode s chop n (B16EncS s) = B16EncLS $ b16Chop n s unchop (B16EncLS ss) = B16EncS $ b16Unchop ss liberate (B16EncLS ss) = ss incarcerate ss = B16EncLS ss
Then I realised that it might be useful to be able to liberate not only the result of a
chop but also the result of a plain
encode. That is I want something like
liberate :: d a -> a incarcerate :: a -> d a
a can be
[String] and nothing else (I’ll settle for a weaker type if I have to though). What I want to avoid, if possible is the need for two functions for both
liberateS :: d String -> String incarcerateS :: String -> d String liberateSL :: d [String] -> [String] incarcerateSL :: [String] -> d [String]
I’ve tried just introducing the
a like above, but that causes a failure to match types, and declaring the class on
DataEncoding d a (and enabling Glasgow extensions) causes arity problems in the types that confuse me to no end.
So, introducing phantom types and a typeclass is still ongoing. Any tip on solving the immidiate issue is welcome. I’ll be back as soon as I’ve come to any conclusion as to whether it’s worth the trouble or not