2
votes

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?

2

2 Answers

4
votes

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.

3
votes

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