Re: the standard function enumFrom
Daniel Fischer <[email protected]> Mon, 25 Oct 2010 17:30:27 +0200
| Newsgroups | gmane.comp.lang.haskell.hugs.user |
|---|---|
| Message-ID | <[email protected]> |
On Monday 25 October 2010 17:12:45, Paqui Lucio wrote: > Hi, > Given the following enumerated type (as an example) > > data P =3D A | B | C | D | E > deriving (Show,Enum) > > and the Prelude definition: > enumFrom x =3D map toEnum [ fromEnum x ..] That's not a definition to be used for all cases, it's a default definition= =20 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=20 the derived Enum instance calls error for arguments of toEnum outside the=20 range [0 .. number of constructors - 1]. > =C2=BFWhy the expression 2) doesn't not produce the same error? The derived Enum instance is cleverer, it uses the number of constructors=20 in the datatype to determine upper bounds for enumFrom and enumFromTo, so=20 that [x .. ] and [x, y .. ] don't try to call toEnum on an invalid=20 argument. > =C2=BFDoes 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=20 rarely be the right thing to do). > There should be something that I'm missing in this computation. > Some hints? > > Thanks in advance, > Paqui