Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading