[Haskell-beginners] mapping over newtypes

Daniel Fischer daniel.is.fischer at googlemail.com
Wed Dec 15 23:24:36 CET 2010


On Wednesday 15 December 2010 23:15:51, Tim Baumgartner wrote:
> 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".

Yes, it's the right way.

You should keep an eye on modify though, it may be too lazy and build large 
thunks in the state if you do it a lot.



More information about the Beginners mailing list