Created
November 2, 2011 22:30
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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