[Haskell-cafe] Circular enums

Henning Thielemann lemming at henning-thielemann.de
Mon Feb 4 08:56:51 EST 2008


On Sat, 2 Feb 2008, Ben Butler-Cole wrote:

> [Resend with formatting maybe fixed.]
>
> Hello
>
> I'm trying to define functions that allow you to traverse a bounded enumeration, "wrapping" at the start and the end.
>
> My implementation looks like this:
>
>     next, prev :: (Enum a, Bounded a) => a -> a
>     next = turn 1
>     prev = turn (-1)
>
>     turn :: (Enum a, Bounded a) => Int -> a -> a
>     turn n e = toEnum (add (fromEnum (maxBound::a) + 1) (fromEnum e) n)
>         where
>           add mod x y = (x + y + mod) `rem` mod
                ^^^

This should give warnings about a name clash with Prelude's 'mod'
function. Actually, I think you want to use 'mod' here instead of 'rem':
  http://www.haskell.org/haskellwiki/Things_to_avoid#Forget_about_quot_and_rem

To fix the type of 'maxBound' a GHC extension is certainly overkill.
Better use `asTypeOf` instead.


More information about the Haskell-Cafe mailing list