Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I automatically generate a list of data values in Haskell?

Tags:

types

haskell

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?

like image 327
Mark Karavan Avatar asked Dec 14 '22 10:12

Mark Karavan


1 Answers

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]
like image 182
Random Dev Avatar answered Jan 25 '23 23:01

Random Dev