[Haskell-beginners] question on typeclasses and applicatives

Alec Benzer alecbenzer at gmail.com
Thu Sep 2 15:02:33 EDT 2010

I came up with some code when trying to understand applicatives:

import Control.Applicative
import qualified Data.Map as M

instance Applicative (M.Map String) where
  pure x = M.fromList [("",x)]
  fs <*> xs = M.fromList [(k1 ++ " " ++ k2,v1 v2) | k1 <- M.keys fs, k2 <-
M.keys xs, v1 <- M.elems fs, v2 <- M.elems xs]

1. When I :load this in ghci it gives me some error about using (M.Map
String) here, and tells me it'll work if I use the -XFlexibleInstances flag.
Why is this type of behavior disabled by default? Is it potentially
dangerous in some way?

2. When running the following:

       fromList [("double",(*2))] <*> fromList[("two",2),("seven",7)]

I get:

        fromList [("double seven",4),("double two",4)]

instead of what I'd expect:

        fromList [("double seven",14),("double two",4)]

Although this:

        (*2) <$> fromList[("two",2),("seven",7)]

gives what I'd expect:

        fromList [("seven",14),("two",4)]

Why is this happening? I can't seem to figure it out.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100902/f0974c8f/attachment.html

More information about the Beginners mailing list