Skip to content

Instantly share code, notes, and snippets.

@nbogie
Created November 2, 2011 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nbogie/1335141 to your computer and use it in GitHub Desktop.
Save nbogie/1335141 to your computer and use it in GitHub Desktop.
Question on typeclasses: Can we make all instances of Enum and Bool instances of Generator?
class Generator a where
generate :: [a]
data Media = Book | Video deriving (Enum, Bounded, Show)
data Category = Fiction | NonFiction deriving (Enum, Bounded, Show)
data Item = Item Media Category deriving (Show)
instance Generator Media where
generate = [minBound..maxBound]
instance Generator Category where
generate = [minBound..maxBound] -- yuck, repetition!
instance Generator Bool where
generate = [minBound..maxBound] -- same
-- ....
-- QUESTION: Can we make all instances of Enum and Bool instances of Generator?
--
-- instance (Enum a, Bounded a) => Generator a where
-- generate = [minBound..maxBound]
-- Note that not all instances of our Generator typeclass are instances
-- of Enum and Bounded, and need a different implementation. E.g. this one:
instance Generator Item where
generate = [Item m c | m<-generate, c<-generate]
main = do
print (generate :: [Item])
print (generate :: [Bool])
-- alternative: don't use a typeclass. Ok, but we'd like to refer to
-- all instances of generator sometimes.
gen2 :: (Enum a, Bounded a) => [a]
gen2 = [minBound..maxBound]
main2 = print $ (gen2::[Bool])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment