HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Difference list

Categories: Idioms

1 Difference lists as functions

A difference list of the second sort represents lists as a function f, which when given a list x, returns the list that f represents, prepended to x. 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 show and shows of Prelude, where the first one implements the naive approach and the second one uses difference lists. Consider showing a binary tree.

L-T-R gives

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

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

3 See also

Retrieved from "http://www.haskell.org/haskellwiki/Difference_list"

This page has been accessed 394 times. This page was last modified 10:05, 4 January 2008. Recent content is available under a simple permissive license.