What's the practical value of all those newtype wrappers in `Data.Monoid`?

前端 未结 5 463
误落风尘
误落风尘 2020-12-15 21:13

When looking at Data.Monoid, I see there are various newtype wrappers, such as All, Sum, or Product, which e

5条回答
  •  一个人的身影
    2020-12-15 21:35

    Suppose you are working in the Writer monad and you want to store the sum of everything you tell. In that case you would need the newtype wrapper.

    You would also need the newtype to use functions like foldMap that have a Monoid constraint.

    The ala and alaf combinators from Control.Lens.Wrapped in the lens package can make working with these newtypes more pleasant. From the documentation:

    >>> alaf Sum foldMap length ["hello","world"]
    10
    
    >>> ala Sum foldMap [1,2,3,4]
    10
    

提交回复
热议问题