CoffeeKid
CoffeeKid

Reputation: 123

Creating a data type that holds specific values of another data type

I want to create the following data structure, the first is an algebraic data type OneToTen and the second I want to be a list that holds all the values that OneToTen can be for future mappings I do in my program.

data OneToTen = I | II | III | IV | V | VI | VII | VIII | IX | X
???? SetOneToTen = [I, II, III, IV, V, VI, VII, VIII, IX, X]

Is this somehow possible in haskell, or should i just use a function that returns a list like the one above and work with that?

Update: My haskelly way of doing it:

data OneToTen = I | II | III | IV | V | VI | VII | VIII | IX | X
               deriving (Enum, Show)

setOneToTen :: [OneToTen]
setOneToTen = [I .. X]

and then just call this function when you want the list :)

Upvotes: 2

Views: 93

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

just remove the ???? and rename SetOneToTen to setOneToTen:

data OneToTen = I | II | III | IV | V | VI | VII | VIII | IX | X

setOneToTen = [I, II, III, IV, V, VI, VII, VIII, IX, X]

Now setOneToTen is a list of OneToTens.

If the data type contains only data constructors with no parameters, you can easily make these an instance of Bounded and Enum, in that case you can use [minBound ..] to construct the list of possible values:

data OneToTen = I | II | III | IV | V | VI | VII | VIII | IX | X deriving (Bounded, Eq, Enum)

setOneToTen = [minBound ..]

Upvotes: 4

Related Questions