Home > Net >  How can I define an infinite / looped algebraic datatype in haskell?
How can I define an infinite / looped algebraic datatype in haskell?

Time:01-10

I have a music note datatype defined like so:

data Note = Ab | A | Bb | B | C | Db | D | Eb | E | F | Gb | G deriving (Eq, Ord)

How can i make it an instace of Enum so that succ G returns Ab ?

CodePudding user response:

You have to define the Enum instance yourself:

instance Enum Note where
    fromEnum note = case note of
        Ab -> 0
        A  -> 1
        ...
    toEnum n = case n `mod` 12 of
        0 -> Ab
        1 -> A
        ...

The "modulo 12" part in toEnum will cycle your notes.

  •  Tags:  
  • Related