0

I'm working through Artyom's Aeson tutorial, and have coded myself this snippet:

parseFoo (Object obj) = do
    a <- case HM.lookup "a" obj of
        Just x  -> parseJSON x
        Nothing -> fail "no field 'a'"

    return a

I've noticed that if I return True, I get an "ambiguous reference" error:

No instance for (FromJSON t0) arising from a use of ‘parseJSON’
The type variable ‘t0’ is ambiguous
Note: there are several potential instances:
...

The type of the non-ambiguous case is

parseFoo :: FromJSON b => Value -> Parser b

My question is, why (how) does a need the return statement to infer its type?

Ben
  • 54,723
  • 49
  • 178
  • 224

1 Answers1

2

The type of parseJSON is FromJSON a => Value -> Parser a, so if you never use the result, GHC can’t possibly figure out what a is supposed to be: it could be anything at all with a FromJSON instance. When you use it as the return value, then the caller of the parseFoo function will pick a concrete type for b, which will be used to pick the instance for the parseFoo call.

As an aside, your return is totally redundant in this case. You could omit the do, the a <-, and the return, since a >>= return is just a by the monad laws.

Alexis King
  • 43,109
  • 15
  • 131
  • 205