Skip to content

Instantly share code, notes, and snippets.

@23Skidoo
Last active October 11, 2015 11:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 23Skidoo/3854294 to your computer and use it in GitHub Desktop.
Save 23Skidoo/3854294 to your computer and use it in GitHub Desktop.
Safe Haskell doesn't enforce global uniqueness of instances
-- 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)
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
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
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
$ 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
Copy link

dolio commented Jul 10, 2014

{-# 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