[Haskell-cafe] Type inference for lambda function

David Feuer david.feuer at gmail.com
Thu Oct 21 18:48:05 UTC 2021


This is the dreaded monomorphism restriction, which is turned on by default
in modules but turned off by default in GHCi. Because your function is not
"syntactically" a function (i.e., there are no arguments to the left of the
= sign), and has no type signature, the type checker insists on it having a
monomorphic type. Unless there's a use of it in the module forcing it to a
particular type, the defaulting rules come into play, and a variable with a
`Num` constraint defaults, by default, to `Integer`.

On Thu, Oct 21, 2021, 2:41 PM Matthias Güdemann <matthias.gudemann at gmail.com>
wrote:

> Hi cafe,
>
> today while explaining lambda functions I came across this case which
> I don't really understand.
>
> This is what I get using ghci
>
> λ> :t (\a b -> a + b)
> (\a b -> a + b) :: Num a => a -> a -> a
>
> but when loading a .hs file with just this function (without signature)
>
> add = \a b -> a + b
>
> I get
>
> λ> :t add
> add :: Integer -> Integer -> Integer
>
> but I can explicitly define add to have this type:
>
> add :: Num a => a -> a -> a
> add = \a b -> a + b
>
> Also ghc infers this polymorphic type for example for
>
> add0 a = \b -> a + b
>
> Why is the type of add without a signature inferred to Integer and not Num
> a?
>
> Best regards
> Matthias
> _______________________________________________
> Haskell-Cafe mailing list
> To (un)subscribe, modify options or view archives go to:
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe
> Only members subscribed via the mailman list are allowed to post.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/haskell-cafe/attachments/20211021/05f99be6/attachment.html>


More information about the Haskell-Cafe mailing list