[Haskell-beginners] Type polymorphism with size

Brent Yorgey byorgey at seas.upenn.edu
Wed Nov 19 07:52:20 EST 2008


On Tue, Nov 18, 2008 at 07:58:24PM -0800, David Frey wrote:
> On 11/18/2008, "Michael Snoyman" <michael at snoyman.com> wrote:
> 
> >I am trying to write some code to read flat files from a mainframe system.
> >This includes some character fields. This is a fixed width file, so each
> >field will have a consistent length between records, but there are fields of
> >different length within a record. For example, I might have a "name" field
> >length 20 and an eye color field length 5.
> >
> >I am trying to use the binary library to read in this file. I've written a
> >binary type, MFChar2, for reading in a 2-length character field. It is
> >defined as such (you can safely ignore the ebcdicToAscii piece, it is just
> >doing character conversion):
> >
> >data MFChar2 = MFChar2 [Word8]
> >instance Binary MFChar2 where
> >    put = undefined
> >    get = do ebcdic <- replicateM 2 getWord8
> >             return $ MFChar2 $ map ebcdicToAscii ebcdic
> >
> >What I would like to do is have some kind of generic "MFChar" data type
> >which could take any character length, but I can't figure out how to do it.
> >Any help would be appreciated.
> >
> >Thanks,
> >Michael
> 
> 
> Is this something that could be accomplished using template Haskell? I
> don't know anything about template Haskell, but maybe someone else on
> the list can comment on this suggestion.

Yes, in the sense that you could use Template Haskell to generate all
the repetitive boilerplate code that you'd rather not write yourself,
e.g. one instance of Binary for each number of Words.  In this
particular case it seems sort of overkill, in the sense that it
probably wouldn't be worth the pain of learning how to use it.  (For
those who don't know, Template Haskell [1] is a GHC feature + library
that lets you do compile-time metaprogramming/code generation.)

-Brent

[1] http://www.haskell.org/haskellwiki/Template_Haskell


More information about the Beginners mailing list