We all love monoidal combinator libraries. What I mean by this is a library that offers a monoid that can e.g. accumulate some settings. Most famous example is probably optparse-applicative
where we can have each of the options or flags enriched with some information by appending to some monoid.
We also all know that whenever you do many appends to a monoid, it is often nicer, to instead use a list and use mconcat
. But this often is a tradeoff! you now have replaced <>
with ,
but instead you have this annoying mconcat
.
You don’t need this tradeof though! Define this simple IsList
instance and all your worries will be a thing of the past!
import Data.List qualified
data SomeMonoid = ..
instance IsList SomeMonoid where
type Item SomeMonoid = SomeMonoid
fromList = mconcat
toList = Data.List.singleton
Now you can always just hand the elements you want to add to your monoid as a list! (of course you need to enable -XOverloadedLists
)
This makes working with these libraries even nicer in practice
PS: yes, the lawful good amongst you may have noticed that IsList
has a rule ( fromList . toList = id
) attached to it and rest assured, these instances follow it. (keep in mind, the opposite would not be true, but gladly, it doesn’t need to!)
PPS: A trivial example of this in use can be found here.