Generate a list of all constructors

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Generate a list of all constructors

Kees Bleijenberg

In this piece of code

 

data Color = RED | BLUE | YELLOW

 

allColors :: [Color]

allColors = [RED, BLUE, YELLOW]

 

I have to remeber that if I add a Color, I have to add the color in allColors too.  

Is there no better way to  add all possible colors in allColors?

 

Kees


_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Generate a list of all constructors

Francesco Ariis
On Sat, Nov 14, 2015 at 07:56:45PM +0100, Kees Bleijenberg wrote:

> In this piece of code
>
>  
>
> data Color = RED | BLUE | YELLOW
>
>  
>
> allColors :: [Color]
>
> allColors = [RED, BLUE, YELLOW]
>
>  
>
> I have to remeber that if I add a Color, I have to add the color in
> allColors too.  
>
> Is there no better way to  add all possible colors in allColors?

Yes, if you make Color instance of Enum. E.g.:

    data Color = RED | BLUE | YELLOW deriving (Show, Enum)
    allColors = enumFrom RED
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
Reply | Threaded
Open this post in threaded view
|

Re: Generate a list of all constructors

amindfv
The problem there is if you add a new color before "RED". I'd do:

data Color = RED | BLUE | YELLOW
   deriving (Show, Enum, Bounded)

allColors :: [Color]
allColors = [minBound..maxBound]

tom


> El 14 nov 2015, a las 14:12, Francesco Ariis <[hidden email]> escribió:
>
>> On Sat, Nov 14, 2015 at 07:56:45PM +0100, Kees Bleijenberg wrote:
>> In this piece of code
>>
>>
>>
>> data Color = RED | BLUE | YELLOW
>>
>>
>>
>> allColors :: [Color]
>>
>> allColors = [RED, BLUE, YELLOW]
>>
>>
>>
>> I have to remeber that if I add a Color, I have to add the color in
>> allColors too.  
>>
>> Is there no better way to  add all possible colors in allColors?
>
> Yes, if you make Color instance of Enum. E.g.:
>
>    data Color = RED | BLUE | YELLOW deriving (Show, Enum)
>    allColors = enumFrom RED
> _______________________________________________
> Beginners mailing list
> [hidden email]
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
_______________________________________________
Beginners mailing list
[hidden email]
http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners