[Haskell-beginners] 'Iterating a data type'
mail at paulvisschers.net
Tue Dec 30 05:30:17 EST 2008
You actually have two different questions. The first about iteration can
be done by the function map in the following way:
Instead of [func Square, func Circle, func Triangle] you use:
map func [Square, Circle, Triangle].
The list comprehensions should also work:
[func x | x <- [Square, Circle, Triangle]]
Now as for obtaining/generating all values of Shape, the easiest way is
to make Shape an instance of Enum, like this:
data Shape = Square | Circle | Triangle deriving Enum
You can then generate a list of all the values by:
You use Square here because it is the first constructor of Shape, and
you want to enumerate them all.
I hope this helps,
raeck at msn.com wrote:
> Are there anyway to express the "iterating" of a user-defined data type
> in Haskell?
> For example, in
>> data Shape = Square | Circle | Triangle
> how can I 'iterate' them and apply them all to the same function without
> indicating them explicitly?
> such as [func Square, func Circle, func Triangle].
> Can I use a form similar to the following case in a list instead:
>> Numbers = [1,2,3,4,5]
>> [func x | x <- Numbers ]
> Actually what I want is to obtain all the possible values of a data type
> Thank you very much!
> Best wishes,
> Beginners mailing list
> Beginners at haskell.org
More information about the Beginners