Latest revision as of 11:24, 22 April 2012
 1 Difference lists as functionsA difference list of the second sort represents lists as a function
Whether this kind of difference list is more efficient than another list representations depends on usage patterns. If an algorithm builds a list by concatenating smaller lists, which are themselves built by concatenating still smaller lists, then use of difference lists can improve performance by effectively "flattening" the list building computations.This can best be exemplified by
Consider showing a binary tree.
- (show L) ++ (show T ++ (show R))
- ((show LL) ++ (show LT ++ (show LR))) ++ (show T ++ (show R))
- (((show LLL) ++ (show LLT ++ (show LLR))) ++ (show LT ++ (show LR))) ++ (show T ++ (show R))
If the tree is large, you end up with a pretty large left association for the left subtree. True, there's lot of right association, too, but bad enough.
With difference lists you write
- shows L . (shows T . shows R)
- (shows LL . (shows LT . shows LR)) . (shows T . shows R)
- ((shows LLL . (shows LLT . shows LLR)) . (shows LT . shows LR)) . (shows T . shows R)
You still need to resolve three (.) until you get to the first character of the result string, but for the subsequent characters you do not need to resolve those dots. In the end, resolution of all (.) may need some time but then concatenation is performed entirely right-associative.
 2 Examples
- ShowS type in the Prelude of Haskell
- The Endo monoid from allows a simple difference list implementation. E.g.Data.Monoidrepresents the listEndo ("bla"++),"bla"represents the empty list,memptyis list concatenation andmappendconverts the difference listappEndo dlist to a regular list.dlist
- Donald Bruce Stewart's difference list library
- Bas van Dijk's difference strings library (which is just a newtype wrapper around a DList Char)