4

Let's say I create an enumerable data set (or two) in Haskell.

data Note = C | CsDb | D | DsEb | E | F | FsGb | G | GsAb | A | AsBb | B deriving (Read, Show, Eq, Ord)
data Diatonic = Unison | Min2 | Maj2 | Min3 | Maj3 | Per4 | Tritone | Per5 | Min6 | Maj6 | Min7 | Maj7 | Octave deriving (Read, Show, Eq, Ord)

I'd like to have access to a list of these values, and this is the only way I know how:

notes :: [Note]
notes = [C, CsDb, D, DsEb, E, F, FsGb, G, GsAb, A, AsBb, B]

diatonics :: [Diatonic]
diatonics = [Unison, Min2, Maj2, Min3, Maj3, Per4, Tritone, Per5, Min6, Maj6, Min7, Maj7, Octave]

This seems like redundant boilerplate. Is this the only way to create such a list, or can Haskell do it for me somehow?

1
  • 2
    note that this is not a list of data-types - it's still a list of values - maybe you should change the title Commented Nov 24, 2015 at 9:02

1 Answer 1

12

if you add automatic deriving for Enum and Bounded it's as easy as:

data Note = C | CsDb | D | DsEb | E | F | FsGb | G | GsAb | A | AsBb | B
          deriving (Read, Show, Eq, Ord, Enum, Bounded)

notes :: [Note]
notes = [minBound .. maxBound]

example:

λ> notes
[C,CsDb,D,DsEb,E,F,FsGb,G,GsAb,A,AsBb,B]

I'll guess you will know how to do the other ;)


you need the Enum for the [ .. ] syntax and Bounded for minBound and maxBound - so you don't have to use Bounded if you don't want but in this case you have to add the bounds yourself:

data Note = C | CsDb | D | DsEb | E | F | FsGb | G | GsAb | A | AsBb | B
          deriving (Read, Show, Eq, Ord, Enum)

notes :: [Note]
notes = [C .. B]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.