简体   繁体   中英

Resolving ambiguities 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 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?

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

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

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

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

print (foo "hello" :: Int)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM