[Haskell-cafe] Cannot update a field in a record with a polymorphic type.

Henning Thielemann lemming at henning-thielemann.de
Sun Sep 6 10:33:23 UTC 2020


On Sun, 6 Sep 2020, Ignat Insarov wrote:

> I have a problem trying to do something very simple.
>
> Consider this conversation with GHC:
>
>    λ data Y α = Y {y ∷ α}
>    λ defaultY = Y {y = mempty}
>    λ :type defaultY
>    defaultY :: Monoid α => Y α
>    λ :type defaultY {y = "c"} ∷ Y String
>
>    <interactive>:1:1: error:
>        • Ambiguous type variable ‘α0’ arising from a use of ‘defaultY’
>          prevents the constraint ‘(Monoid α0)’ from being solved.
>          Probable fix: use a type annotation to specify what ‘α0’ should be.
>          These potential instances exist:
>            instance Monoid a => Monoid (IO a) -- Defined in ‘GHC.Base’
>            instance Monoid Ordering -- Defined in ‘GHC.Base’
>            instance Semigroup a => Monoid (Maybe a) -- Defined in ‘GHC.Base’
>            ...plus 7 others
>            (use -fprint-potential-instances to see them all)
>        • In the expression: defaultY
>          In the expression: defaultY {y = "c"} :: Y String
>
> Why does this not work?

I think it should work:

:type (defaultY::Y [()]) {y = "c"}

The problem is, that GHCi cannot infer the type of defaultY, because the 
update changes the type. By adding the type annotation Y String at the 
end, you only tell GHCi what it already knows, namely, that the result of 
the update has type Y String. But there is no way to infer what the type 
of 'mempty' must have been before the update.


More information about the Haskell-Cafe mailing list