[Haskell-cafe] Basic question....

Brent Yorgey byorgey at gmail.com
Fri Aug 17 11:14:15 EDT 2007


On 8/17/07, rodrigo.bonifacio <rodrigo.bonifacio at uol.com.br> wrote:
>
> Hi all.
>
> I want to create the following polymorphic type (EnvItem) that we can
> apply two functions (envKey and envValue). I tried the following:
>
> > type Key = String
>
> > data EnvItem a = EnvItem (Key, a)
>
> > envKey :: EnvItem (Key, a) -> String
> > envKey EnvItem (key, value) = key
>
> > envValue :: EnvValue(Key, a) -> a
> > envValue EnvItem (key, value) = value
>
> But this is resulting in the error: [Constructor "EnvItem" must have
> exactly 1 argument in pattern]
>
> I think this is a very basic problem, but I don't know what is wrong.
>
> Regards,
>
> Rodrigo.


By the way, I would suggest giving the data type and constructor different
names:

data EnvItem a = EI (Key, a)

You do often see people use the same name for both, but that can be
confusing since they are really two different things.  The envKey function
(for example) would now be written like this:

envKey :: EnvItem a -> Key
envKey (EI (key, _)) = key

The difference between the parameter type (EnvItem a) and a pattern to match
the shape of such a value (EI (key, _)) is now much clearer: whatever is on
the left side of the data declaration is the type, and goes in type
signatures; whatever is on the right side describes the shape of values of
that type, and is used to construct or deconstruct (through
pattern-matching) such values.  This way it is much harder to make mistakes
like (for example) putting EnvItem (Key, a) in the type signature instead of
EnvItem a.

-Brent
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070817/ddc03646/attachment.htm


More information about the Haskell-Cafe mailing list