[Haskell-cafe] do-notation for building monoid values
olf at aatal-apotheke.de
Thu Mar 8 13:02:16 UTC 2018
prompted by a discussion with the author of blaze-markup  I realized a pattern and would like to know whether other haskellers have exploited this/find this useful:
For every monoid m, the types Writer m () and m are isomorphic as types via tell and execWriter. Moreover, Writer m is a monad if and only if m is a monoid. For every monad t, the type t () is a monoid with
mempty = return ()
mappend = (>>).
In the particular case of Writer m () and m, the isomorphism of Haskell types is in fact an isomorphism of monoids, that is, the functions tell and execWriter preserve the monoid operations.
This enables us to use do-notation in building complicated values of any monoid type, e.g. Text or any other syntax. Instead of writing
complicatedValue = component1 <>
modifier (component3 <> component4)
one can write
complicatedValue = execWriter $ do
modifier $ do
Should such an idiom be encouraged/discouraged? How do you handle the construction of monoid values (especially text-like) with interspersed function applications (e.g. show, prettyprint)?
More information about the Haskell-Cafe