2

I wrote a generic type to type converter in Haskell using classes as follows:

{-# LANGUAGE FlexibleInstances #-}

class Convertable a where
    convert::a

instance Convertable (Int -> String) where
    convert = show

instance Convertable (String -> Int) where
    convert = read

main = do
    let result = ((+1) . convert :: String -> Int) "1"
    print result

But I need the explicit type String -> Int in order to get it to work (which kind of negates the purpose of having a generic type converter....)

Why would this type declaration be needed at all, there is just one possibility that satisfies the types?

recursion.ninja
  • 5,377
  • 7
  • 46
  • 78
jamshidh
  • 12,002
  • 17
  • 31

2 Answers2

4

convert is not the problem here, numbers by default are of type Num a => a, so the problem here is +1 you have there. You have to give it a concrete type.

Arjan
  • 19,957
  • 2
  • 55
  • 48
  • Shouldn't Haskell still recognize that the only "a" that is type consistent is "a=Int"?Is there a reason that this doesn't happen other than it just isn't implemented yet (which is cool, I don't mean to complain), or is there something more fundamental that makes this impossible. – jamshidh Nov 06 '13 at 00:30
  • 2
    Haskell's type classes are "open". You can add new instances at all times. As a consequence, the presence (or absence) of instances never influences type checking. You have to provide a context that's unambiguous and thereby makes it clear which instance to choose. – kosmikus Nov 06 '13 at 00:33
  • 1
    OK, I get it.... If this worked as I indicated it should, it might compile today, then a few months down the road when another Convertable is added (perhaps deep inside some updated library), suddenly things would mysteriously break. Makes sense. Thanks. – jamshidh Nov 06 '13 at 00:43
3

You can also just specify the type of result and ghc will infer the type of convert and of the Num instance for (+1):

main = do
    let result :: Int
        result = ((+1) . convert) "1"
    print result
ErikR
  • 51,541
  • 9
  • 73
  • 124