Daniil Iaitskov
Daniil Iaitskov

Reputation: 6079

Haskell interpreter cannot infer return type

I was trying to implement polymorphic tuple mapping and eventually wrote following snipped in GHCi:

data MaxS = MaxS
class Strategy action input result | input -> result where  
    work :: action -> input -> result
instance (Ord a) => Strategy MaxS (a, a, a) a where work _ (a, b, c) = max a (max b c)
f :: (Strategy action input result) => action -> input -> result ; f a i = work a i
f MaxS (1, 2, 3)   

<interactive>:91:1: error:
    * No instance for (Ghci13.Strategy
                         MaxS (Integer, Integer, Integer) ())
        arising from a use of `it'
    * In the first argument of `print', namely `it'
      In a stmt of an interactive GHCi command: print it

f MaxS (1, 2, 3) :: Integer
3

So my question is why Unit type is picked if nothing specified and how to avoid obvious return type definition.

Upvotes: 0

Views: 44

Answers (1)

chi
chi

Reputation: 116174

TL;DR Don't use GHCi to enter non trivial code. Write your code in a file and load it in GHCi.

Your error message mentions Ghci13.Strategy, which is a different class from Strategy. GHCi prints references to module GhciXXX when your have some code around which refers to a class which was redefined during the GHCi session. You probably have half of the code referring to an old class, and the other half referring to a new class, and that results in chaos.

To reproduce, try this in GHCi:

> class C a where foo :: a -> Bool 
> bar = foo                        
> class C a where foo :: a -> Int  
> :t foo                           
foo :: C a => a -> Int                    
> :t bar                           
bar :: Ghci1.C a => a -> Bool             

Note the last Ghci1.C which refers to the old class.

Upvotes: 5

Related Questions