m0meni
m0meni

Reputation: 16435

Show list of unknown type in Haskell

I was given an assignment in which I should have the type signature

Group g => Int -> Int -> [[g]]

However if g is ambiguous how can I print it? I get this error:

No instance for (Show g0) arising from a use of ‘print’
The type variable ‘g0’ is ambiguous
Note: there are several potential instances:
  instance Show Double -- Defined in ‘GHC.Float’
  instance Show Float -- Defined in ‘GHC.Float’
  instance (Integral a, Show a) => Show (GHC.Real.Ratio a)
    -- Defined in ‘GHC.Real’
  ...plus 24 others
In the expression: print
In the expression: print $ myTest 10 0
In an equation for ‘main’: main = print $ myTest 10 0

Which makes sense to me. Is there an error in the assignment? Or is there a way to print an ambiguous type?

Upvotes: 2

Views: 373

Answers (1)

bheklilr
bheklilr

Reputation: 54058

Try running

> :info Group

This should print out the Group typeclass and its members, followed by a list of instances. Pick one of these instances, then execute

> myTest 1 2 :: [[TheTypeYouPicked]]

If you wanted to use it inside main you'll have to give it a type signature there too:

main :: IO ()
main = print (myTest 10 0 :: [[TheTypeYouPicked]])

The reason why the compiler is showing you this error is because there could be many instances of Group to choose from, not all of them necessarily implement Show as well. In order to print something in the console, either by just executing it (there's an implicit print when you just run a normal function in GHCi) or with an explicit print it needs to implement Show.

Upvotes: 3

Related Questions