1

I'm trying to write a function that flattens nested Lists.

The code:

data NestedList a = Elem a | List [NestedList a]

flatten :: NestedList a -> [a]
flatten (Elem e) = [e]
flatten (List l) = foldMap flatten l

main = do
    let c0 = List []
    print $ flatten c0

When I try and provide an empty List from main I get a compiler error:

Ambiguous type variable ‘a0’ arising from a use of ‘print’
  prevents the constraint ‘(Show a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.

I am wondering what causes this error and how to fix it.

Any help is much appreciated!

3
  • 6
    It's exactly as the error message says - GHC can't figure out what the a is in NestedList a for the value List []. To fix, again as GHC says, just give a type annotation, eg let c0 = (List [] :: NestedList Int) Commented Sep 12, 2020 at 23:11
  • Does this answer your question? Testing empty list [] with Eq type Commented Sep 12, 2020 at 23:12
  • I found this article, and it really helped me learn about this error and others: obround.blogspot.com/2020/09/… Commented Sep 13, 2020 at 22:47

1 Answer 1

0

When you call print :: (Show a) => a -> IO (), the constraint on Show a needs to be solved somehow. In your case, the type of c0 is inferred to be NestedList a, which is of course not enough information to solve the Show [a] constraint from print $ flatten c0.

You solve this problem by adding a type signature to the binding of c0 to make it monomorphic.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.