###

Question:

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?

###

Solution:1

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)) `

###

Solution:2

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.

###

Solution:3

you can extract out the polymorphic part as a function

`quux :: Cabbage a => String -> a quux s = quux' undefined where quux' :: Cabbage a => a -> a quux' x = bar (s ++ foo x) `

**Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com**

EmoticonEmoticon