Ambiguity elimination for overloaded functions

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 an overload is very poorly related to type ambiguity. print $ foo "hello"will lead to an error, but it print $ length "hello"works fine. However, provided that my list of instances is corrected, there should be no technical reason why Haskell cannot understand that the only instance foo :: String -> ais foo :: String -> Int. Can I make Haskell for this implementation?

+4
source share
2 answers

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

instance a ~ Int => Foo (String -> a) where foo = length
+4
source

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

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

print (foo "hello" :: Int)
0
source

All Articles