[Haskell-beginners] mempty and "No instance for (Monoid Int)"
David McBride
toad3k at gmail.com
Wed Jun 7 16:53:19 UTC 2017
In ghci there are type defaulting rules. When you go mempty ==
Nothing, it type defaults it to "Maybe ()". But when you type Just 4,
4 is definitely not (), and so it looks at the Monoid instance for the
a default type to use in cases of numeric literals, the first of which
is Int.
Which brings you to the next problem. Maybe Int is only a Monoid if
Int is an instance of Monoid, and Int is definitely not.
That's because is 3 `mappend` 3 == 6 via addition? Or should it be 9
via multiplication? Or something else? What should mempty be, 0? Or
maybe 1? Who is to decide what the only way of combining Ints
together is.
It turns out there are instances for both of those cases, but you have
to wrap the int into a type so that it knows which way you want it to
be interpreted.
import Data.Monoid
mempty == Just (Product 1)
> false
mempty == Just (Sum 1)
> false
There are similar monoidal instances for Bool, such as Any and All.
On Wed, Jun 7, 2017 at 12:33 PM, Baa <aquagnu at gmail.com> wrote:
> Maybe a is the Monoid:
>
> instance Monoid a => Monoid (Maybe a) -- Defined in ‘GHC.Base’
>
> so I can compare its values with empty value:
>
> mempty == Nothing
> => True
>
> But if I try:
>
> mempty == Just 4
>
> I get:
>
> <interactive>:1:1: error:
> • Ambiguous type variable ‘a0’ arising from a use of ‘mempty’
> prevents the constraint ‘(Monoid a0)’ from being solved.
> Probable fix: use a type annotation to specify what ‘a0’ should
> be. These potential instances exist:
> instance Monoid a => Monoid (IO a) -- Defined in ‘GHC.Base’
> instance Monoid Ordering -- Defined in ‘GHC.Base’
> instance Monoid a => Monoid (Maybe a) -- Defined in ‘GHC.Base’
> ...plus 7 others
> (use -fprint-potential-instances to see them all)
> • In the first argument of ‘(==)’, namely ‘mempty’
> In the expression: mempty == Just 4
> In an equation for ‘it’: it = mempty == Just 4
>
> OK, I try:
>
> mempty::Maybe Int
>
> and get:
>
> <interactive>:1:1: error:
> • No instance for (Monoid Int) arising from a use of ‘mempty’
> • In the expression: mempty :: Maybe Int
> In an equation for ‘it’: it = mempty :: Maybe Int
>
> so, how is related Int to Monoid, why does ghc expect from mempty::Maybe
> Int, Int to be Monoid?! As I understand, this means only that I
> mean "mempty" from (Maybe Int) type, which is Monoid and exists sure.
>
> Interesting is, that:
>
> mempty::Maybe [Int]
> => Nothing
>
> but how is related "monoidality" of "Maybe a" with "monoidality of
> "a" ???
>
> Initial idea was to make comparison:
>
> mempty :: Maybe Int == Just 4
> => False
>
>
> /Best regards,
> Paul
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/beginners
More information about the Beginners
mailing list