Resolving ambiguities for overloaded functions

122 views Asked by At

I want to have an overloaded function in Haskell.

{-# LANGUAGE FlexibleInstances #-}
class Foo a where
   foo :: a

instance Foo (String -> Int) where
   foo = length

instance Foo String where
   foo = "world"

However such overloading deals very poorly with type ambiguities. print $ foo "hello" would result in an error, while print $ length "hello" works fine. However, provided that my list of instances is fixed, there shouldn't be a technical reason why Haskell can't realize that the only instance of foo :: String -> a is foo :: String -> Int. Can I have Haskell make this realization?

2

There are 2 answers

8
Daniel Wagner On BEST ANSWER

It is easy to do in this particular case. Simply:

instance a ~ Int => Foo (String -> a) where foo = length
1
viorior On

In your case GHCI knows, that foo :: String -> ??

We are going to change signature to String -> Int:

print (foo "hello" :: Int)