I\'ve been experimenting with Codensity
lately which is supposed to relate DList
with []
among other things. Anyway, I\'ve never found cod
One view could be that DList
is a way for reordering monoid operations, just as Codensity
is a way for reordering monad operations.
[]
is a free monoid on a
, so let's represent lists using a free writer monad, that is Free ((,) a)
:
module Codensity where
import Control.Monad
import Control.Monad.Free
import Control.Monad.Codensity
import Control.Monad.Trans (lift)
type DList a = Free ((,) a) ()
Now we can define the standard list operations:
nil :: DList a
nil = return ()
singleton :: a -> DList a
singleton x = liftF (x, ())
append :: DList a -> DList a -> DList a
append = (>>)
infixr 5 `snoc`
snoc :: DList a -> a -> DList a
snoc xs x = xs >> singleton x
exec :: Free ((,) a) () -> [a]
exec (Free (x, xs)) = x : exec xs
exec (Pure _) = []
fromList :: [a] -> DList a
fromList = mapM_ singleton
toList :: DList a -> [a]
toList = exec
This representation has the same drawbacks as list when it comes to snoc
. We can verify that
last . toList . foldl snoc nil $ [1..10000]
takes a significant (quadratic) amount of time. However, just as every free monad, it can be improved using Codensity
. We just replace the definition with
type DList a = Codensity (Free ((,) a)) ()
and toList
with
toList = exec . lowerCodensity
Now the same expression is executed instantly, as Codensity
reorders the operations, just like the original difference lists.