Getting a list of all possible data type values in Haskell

前端 未结 4 1995
一整个雨季
一整个雨季 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:40

    Here is an example of using this technique to parse enums with Parsec

    data FavoriteColor = Maroon | Black | Green  | Red | 
                         Blue   | Pink  | Yellow | Orange
                                 deriving (Show, Read, Enum, Bounded)
    

    And the parsec parser

    parseColor :: Parser FavoriteColor           
    parseColor = fmap read . foldr1 (<|>) $ map (try . string . show) 
      [ minBound :: FavoriteColor ..] 
    

    of course the try could could be applied by better by pattern matching and a few other things could make it nicer but this is just an example of some usage of the technique.

提交回复
热议问题