Skip to content

Instantly share code, notes, and snippets.

@softmechanics
Created December 1, 2010 20:37
Show Gist options
  • Save softmechanics/724175 to your computer and use it in GitHub Desktop.
Save softmechanics/724175 to your computer and use it in GitHub Desktop.
Directing type inference with equality constraints and multi parameter type classes
{-# LANGUAGE MultiParamTypeClasses
, FlexibleInstances
, TypeFamilies
#-}
class Add a b where
add :: a -> b -> a
instance Num a => Add a a where
add = (+)
{--
two = add (1::Int) 1
-- two would give an error:
-- No instance for (Add Int t)
-- arising from a use of `add' at coercions.hs:12:6-19
--}
{--
nonsense = add (1::Int) 'c'
-- No instance for (Add Int Char)
-- arising from a use of `add' at coercions.hs:23:11-26
--}
class Add' a b where
add' :: a -> b -> a
instance (Num a, a ~ b) => Add' a b where
add' = (+)
two' = add' (1::Int) 1
{--
nonsense' = add' (1::Int) '1'
-- nonsense' would give an error:
-- Couldn't match expected type `Char' against inferred type `Int'
-- When generalising the type(s) for `nonsense'
--}
main = return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment