Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this type variable ambiguous?

Cabbage.hs:

module Cabbage where 
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))

When I compile (with ghc) I get this error message:

Cabbage.hs:7:19:
    Ambiguous type variable `a' in the constraint:
      `Cabbage a' arising from a use of `foo' at Cabbage.hs:7:19-38
    Probable fix: add a type signature that fixes these type variable(s)

I don't understand why a is ambiguous. Surely the a in line 7 is the same as the a in line 6? How do I fix this?

Alternatively, is there a better way of declaring a per-instance constant?

like image 293
dave4420 Avatar asked Apr 03 '09 08:04

dave4420


2 Answers

Using scoped type variables you can let GHC know that the undefined :: a should be the same (otherwise a is just a shorthand for forall a. a). Scoped type variables must then be explicitly forall-qualified:

{-# LANGUAGE ScopedTypeVariables #-}
module Cabbage where 
class Cabbage a
  where foo :: a -> String      -- the parameter is only present for its type,
                                -- the parameter value will be ignored
        bar :: String -> a
quux :: forall a. Cabbage a => String -> a
quux s = bar (s ++ foo (undefined :: a))
like image 146
nominolo Avatar answered Nov 08 '22 06:11

nominolo


The problem is that Haskell doesn't know which instance of Cabbage that foo corresponds to there. So far as I know, it doesn't match the a in (undefined :: a) with the a in quux :: Cabbage a => String -> a

Assuming that's what you want, you can do this:

quux :: Cabbage a => String -> a
quux s = result
    where result = bar (s ++ foo result)

This ties foo and bar together so that it uses the same instance for both, and since you don't actually need the value of the input for foo, it bottoms out. I don't know of a better way of doing per-instance constants though. Hopefully someone else will come along who does.

like image 20
Peter Burns Avatar answered Nov 08 '22 08:11

Peter Burns