Getting a list of all possible data type values in Haskell

前端 未结 4 1992
一整个雨季
一整个雨季 2020-12-06 04:06

If I have a data type say:

data Color = Red | Yellow | Green

Is there a way I can turn this into a list of type [Color] getting all possibl

4条回答
  •  执笔经年
    2020-12-06 04:28

    Surely delnan's answer is better. Since I do not know how to include a piece of code in a comment, I'll give a generalisation as a separate answer here.

    allValues :: (Bounded a, Enum a) => [a]
    allValues = [minBound..]
    

    Now, this works for any type with a Bounded and Enum instance! And allColors is just a special case:

    allColors :: [Color]
    allColors = allValues
    

    In many cases, you won't even need to define allColors separately.

提交回复
热议问题