[Hugs-users] the standard function enumFrom

Daniel Fischer daniel.is.fischer at web.de
Mon Oct 25 11:30:27 EDT 2010


On Monday 25 October 2010 17:12:45, Paqui Lucio wrote:
> Hi,
> Given the following enumerated type (as an example)
>
> data P = A | B | C | D | E
>          deriving (Show,Enum)
>
> and the Prelude definition:
>  	    enumFrom x  = map toEnum [ fromEnum x ..]

That's not a definition to be used for all cases, it's a default definition 
to be used if nothing better is provided.

>
> I guess that  the two expressions
> 	1) (map toEnum [ fromEnum A ..]) :: [P]
> 	2)  enumFrom A
> should produces the same result, say
> 	[A,B,C,D,E] :: [P]
>
> However, the expression 1)  produces an error as a consequence of trying
> to apply toEnum to the number 5.

Because [fromEnum A .. ] is [0 .. ], which is [0 .. maxBound :: Int] and 
the derived Enum instance calls error for arguments of toEnum outside the 
range [0 .. number of constructors - 1].

> ¿Why the expression 2) doesn't not produce the same error?

The derived Enum instance is cleverer, it uses the number of constructors 
in the datatype to determine upper bounds for enumFrom and enumFromTo, so 
that [x .. ] and [x, y .. ] don't try to call toEnum on an invalid 
argument.

> ¿Does Hugs not apply the definition in the Prelude for evaluating the
> expression 2)?

No, the derived Enum instances don't use the default method (which would 
rarely be the right thing to do).

> There should be something that I'm missing in this computation.
> Some hints?
>
> Thanks in advance,
> Paqui



More information about the Hugs-Users mailing list