fork download
  1. {-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FunctionalDependencies, FlexibleContexts, UndecidableInstances, OverlappingInstances, IncoherentInstances #-}
  2.  
  3. class SubtypeOf a b | a -> b where
  4. upcast :: a -> b
  5. downcastSafe :: b -> Maybe a
  6. downcast :: b -> a
  7. downcast b = case downcastSafe b of
  8. Nothing -> error $ "can not downcast the value"
  9. Just a -> a
  10.  
  11. class (Ord a) => Rangable t a | t -> a where
  12. lowLim :: t -> a
  13. highLim :: t -> a
  14.  
  15. class Packable t a | t -> a where
  16. pack :: a -> t
  17. unpack :: t -> a
  18.  
  19. class MultipleTo t a | t -> a where
  20. multiple :: t -> a
  21.  
  22. instance (Num a, Ord a, Rangable range a, Packable range a) => SubtypeOf range a where
  23. upcast = unpack
  24. downcastSafe b | b >= (lowLim $ pb) && b <= (highLim $ pb) = Just $ pb
  25. | otherwise = Nothing
  26. where
  27. pb = pack b
  28.  
  29. instance (Integral a, Packable range a, MultipleTo range a) => SubtypeOf range a where
  30. upcast = unpack
  31. downcastSafe b | b `mod` (multiple pb) == 0 = Just pb
  32. | otherwise = Nothing
  33. where
  34. pb = pack b
  35.  
  36. newtype Range1 a = Range1 {unRange1 :: a}
  37. deriving Show
  38.  
  39. instance (Num a, Ord a) => Rangable (Range1 a) a where
  40. lowLim _ = 0
  41. highLim _ = 10
  42.  
  43. instance (Num a, Ord a) => Packable (Range1 a) a where
  44. pack = Range1
  45. unpack = unRange1
  46.  
  47. newtype Range2 a = Range2 {unRange2 :: a}
  48. deriving Show
  49.  
  50. instance (Num a, Ord a) => Rangable (Range2 a) a where
  51. lowLim _ = -10
  52. highLim _ = 200
  53.  
  54. instance (Num a, Ord a) => Packable (Range2 a) a where
  55. pack = Range2
  56. unpack = unRange2
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
[1 of 1] Compiling Main             ( prog.hs, prog.o )

prog.hs:22:0:
    Duplicate instance declarations:
      instance [incoherent] (Num a,
                             Ord a,
                             Rangable range a,
                             Packable range a) =>
                            SubtypeOf range a
        -- Defined at prog.hs:(22,0)-(27,16)
      instance [incoherent] (Integral a,
                             Packable range a,
                             MultipleTo range a) =>
                            SubtypeOf range a
        -- Defined at prog.hs:(29,0)-(34,16)
stdout
Standard output is empty