[Haskell-beginners] mapping over newtypes

Tim Baumgartner baumgartner.tim at googlemail.com
Wed Dec 15 23:15:51 CET 2010


I'll provide more details. Banana is actually a (shopping) cart:

newtype Cart = Cart (Map.Map Product Amount)

mapCart f (Cart m) = Cart (f m)

I was too lazy to write down the signature of mapCart, since the type
of the cart content might evolve.

Now I have some state:
type Shopping a = State Cart a

and I update it:
buy :: Amount -> Product -> Shopping ()
buy amount product =
  modify . mapCart $ Map.insertWith (+) product amount

and the last line is the place where I use mapCart.
This works as expected but I wanted to be sure that I do it "the right way".


2010/12/15 Stephen Tetley <stephen.tetley at gmail.com>:
> Doesn't mapBanana work if you give it this signature:
>
> mapBanana :: (Something -> Something) -> Banana -> Banana
> mapBanana f (Banana b) = Banana (f b)
>
>
> Possibly you are wanting a polymorphic Banana?
>
> newtype Banana a = Banana a
>
> mapBanana :: (a -> b) -> Banana a -> Banana b
> mapBanana f (Banana x) = Banana (f x)
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>



More information about the Beginners mailing list