Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Safe Haskell doesn't enforce global uniqueness of instances

View A.hs
1 2 3 4 5 6 7 8 9
-- Code taken from http://stackoverflow.com/questions/12735274/breaking-data-set-integrity-without-generalizednewtypederiving/12744568#12744568
-- Discussion on haskell-cafe: http://thread.gmane.org/gmane.comp.lang.haskell.cafe/100870
-- http://www.haskell.org/pipermail/haskell-cafe/2012-October/103984.html
--
-- See also: http://blog.ezyang.com/2014/07/type-classes-confluence-coherence-global-uniqueness/
-- https://gist.github.com/rwbarton/dd8e51dce2a262d17a80
 
module A where
data U = X | Y deriving (Eq, Show)
View A.hs
1 2 3 4 5 6 7 8 9 10 11 12
module B where
import Data.Set
import A
 
instance Ord U where
compare X X = EQ
compare X Y = LT
compare Y X = GT
compare Y Y = EQ
 
ins :: U -> Set U -> Set U
ins = insert
View A.hs
1 2 3 4 5 6 7 8 9 10 11 12
module C where
import Data.Set
import A
 
instance Ord U where
compare X X = EQ
compare X Y = GT
compare Y X = LT
compare Y Y = EQ
 
ins' :: U -> Set U -> Set U
ins' = insert
View A.hs
1 2 3 4 5 6 7 8 9 10 11
module Main where
import Data.Set
import A
import B
import C
 
test :: Set U
test = ins' X $ ins X $ ins Y $ empty
 
main :: IO ()
main = print test
View A.hs
1 2 3 4 5 6 7 8 9 10 11 12
$ ghc -Wall -XSafe -fforce-recomp --make D.hs
[1 of 4] Compiling A ( A.hs, A.o )
[2 of 4] Compiling B ( B.hs, B.o )
 
B.hs:5:10: Warning: Orphan instance: instance [safe] Ord U
[3 of 4] Compiling C ( C.hs, C.o )
 
C.hs:5:10: Warning: Orphan instance: instance [safe] Ord U
[4 of 4] Compiling Main ( D.hs, D.o )
Linking D ...
$ ./D
fromList [X,Y,X]
dolio commented

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE IncoherentInstances #-}

module Foo where

class C a where
c :: a -> a

instance C a where
c = id

instance C Int where
c _ = 5

-- Rejected without IncoherentInstances
d :: a -> a
d = c

e :: Int -> Int
e = c

f :: C a => a -> a
f = c

x :: (Int, Int, Int)
x = (d 4, e 4, f 4)
-- x = (4, 5, 5)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.