Skip to content

Instantly share code, notes, and snippets.

@leftaroundabout
Forked from depp/Enum.hs
Created April 1, 2012 23:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leftaroundabout/2279399 to your computer and use it in GitHub Desktop.
Save leftaroundabout/2279399 to your computer and use it in GitHub Desktop.
Demonstration of how incorrect (Enum x, Enum y) => Enum (x, y) instance can be used for Enum a => Enum (a,a)
{-# LANGUAGE FlexibleInstances #-}
-- See http://stackoverflow.com/questions/9967790/instance-in-haskell
instance (Enum a) => Enum (a, a) where
fromEnum (x,y) =
k^2 + 2*j + if permuted then 1 else 0
where
k = max (fromEnum x) (fromEnum y)
j = min (fromEnum x) (fromEnum y)
permuted = (fromEnum y) > (fromEnum x)
toEnum n =
let k = floor . sqrt $ fromIntegral n
(j, permdAdd) = (n-k^2) `divMod` 2
permute (x,y) | permdAdd>0 = (toEnum y, toEnum x)
| otherwise = (toEnum x, toEnum y)
in permute (k, j)
data A = A1 | A2 deriving (Show, Enum)
data B = B1 | B2 | B3 deriving (Show, Enum)
main = do
print [(A1,A1)..(A2,A2)]
print [(B1,B1)..(B3,B3)]
-- $ runhaskell tupleenum.hs
-- [(A1,A1),(A2,A1),(A1,A2),(A2,A2)]
-- [(B1,B1),(B2,B1),(B1,B2),(B2,B2),(B3,B1),(B1,B3),(B3,B2),(B2,B3),(B3,B3)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment