[Haskell-cafe] [Haskell Cafe] Data construction: how to avoid boilerplate code?

minh thu noteed at gmail.com
Thu Jul 30 03:06:50 EDT 2009


2009/7/29 Luke Palmer <lrpalmer at gmail.com>:
> On Wed, Jul 29, 2009 at 10:15 AM, Paul Sujkov<psujkov at gmail.com> wrote:
>> Hi Luke,
>>
>> I'm not pretty sure. The thing I don't like is the need to copy-and-paste
>> all the code with enumeration constructors. So, now I have two types to make
>> Type data from, but they could be many, so I'll have many almost identical
>> makeTypeFromFoo-functions. The thing I need is something like (*):
>>
>> makeType :: ? -> Type
>> makeType c = case c of
>>                ("-$-" or 240)       -> Status
>>                ("-M-" or 64)       -> Message
>>                ("-W-" or 32)       -> Warning
>
> Well, you could write a helper like this:
>
> matchType :: (Eq a) => (a,a,a) -> a -> Type
> matchType (status,message,warning) x
>    | x == status = Status
>    | x == message = Message
>    | x == warning = Warning
>
> To reduce the size of your specifications:
>
> makeTypeStr = matchType ("-$-", "-M-", "-W-")
> makeTypeInt = matchType (240, 64, 32)
>
> There are trade-offs to doing something like this.  It's smaller, but
> harder to read as specification.  But, because it uses a tuple, it
> will catch you if you add a new case but forget to add it to one of
> the makeType*s (providing you remember to change matchType).
>
> What you're asking for puts all the conversions in the same place,
> which forbids them from being split out, decoupled, and modularlized.
> What if, instead of simple values, you had a more involved parser for
> these things?
>
> Even though it's kind of verbose, I think what you already have is
> fine.  You do have to repeat the names, but it is still content code,
> and the relationship of the content to the names is explicit.  You
> might find tables like this in a user's manual for your software...

Hi,

Maybe two simple association lists would be acceptable ?

Cheers,
Thu


More information about the Haskell-Cafe mailing list