[Haskell-beginners] question on typeclasses and applicatives
byorgey at seas.upenn.edu
Thu Sep 2 17:48:04 EDT 2010
On Thu, Sep 02, 2010 at 05:10:29PM -0400, Alec Benzer wrote:
> Ah, ok, so the reason what I trying didn't work is because I used an
> actual type instead of a type variable? I got confused because of the
> emphasis you put on * distinct *.
I think the emphasis is from the error message that GHC spits out, not
from Daniel. This is a particularly confusing error message though.
> And so, if I want to make Maps applicative functors without dealing
> with FlexibleInstances, I'd have to do something like this?
> import Control.Applicative
> import qualified Data.Map as M
> import Data.Monoid
> instance (Monoid k, Ord k) => Applicative (M.Map k) where
> pure x = M.fromList [(mempty,x)]
> fs <*> xs = M.fromList [(k1 `mappend` k2,v1 v2) | (k1,v1) <-
> M.assocs fs, (k2,v2) <- M.assocs xs]
Sure. Although there's really no reason to avoid FlexibleInstances.
> (sacrificing some functionality, since spaces won't get intercalated
> between keys if i use strings)
Technically, the version with the intercalated spaces didn't satisfy
the Applicative laws anyway. For example, if <*> inserts a space it
is not the case that
pure f <*> x = f <$> x
since there would be an extra space introduced on the left-hand side.
I like your more general Monoid-based version much better (and I think
it's not too hard to show it satisfies the Applicative laws, although
I haven't thought about it too hard).
More information about the Beginners