Haskell logo CIS 552: Advanced Programming

Fall 2019

  • Home
  • Schedule
  • Homework
  • Resources
  • Style guide
  • Syllabus
Note: this is the stubbed version of module DList. You should download the lhs version of this module and replace all parts marked undefined. Eventually, the complete version will be made available.

In class exercise: Difference lists

In this problem, you will use first-class functions to implement an alternative version of lists, called DLists, short for difference lists.

> module DList where
> import Test.HUnit

Motivation

DLists support O(1) append operations on lists, making them very useful for append-heavy uses, such as logging and traversing tree-like data structures in linear time. (An implementation of this data structure is available on hackage but try to complete it on your own. No peeking!)

See the micro-benchmark section below for experiments you can do once you have completed the implementation.

Implementation

The key idea is that we will represent a list using a function from lists to lists. In otherwords, we will tell Haskell that the type [a] -> [a] can be called DList a for any type parameter a.

> type DList a = [a] -> [a]

You can think of a difference list as a data structure where we have "factored out" the end of the list.

For example, we might write a regular list like this:

> list :: [Int]
> list = 1 : 2 : 3 : []  -- end is nil

The analogous "difference list" replaces the nil at the end of the list with a parameter.

> dlist :: DList Int
> dlist =  \x -> 1 : 2 : 3 : x -- end is "x"

This parameterization gives us flexibility. We can always fill in the parameter with [] and get a normal list. However, we can also fill in the parameter with another list, effectively appending [1, 2, 3] to the beginning of that other list.

See if you can figure out how to define the following standard list operations for this new type of DLists.

> empty :: DList a
> empty = undefined
> singleton :: a -> DList a
> singleton x = undefined
> append :: DList a -> DList a -> DList a
> append = undefined
> cons :: a -> DList a -> DList a
> cons = undefined

Now write a function to convert a regular list to a DList using the above definitions and foldr.

> fromList :: [a] -> DList a
> fromList = undefined

Once we have constructed a DList, the only way to observe it is to convert it to a list. This data structure does not support any other form of pattern matching.

> toList :: DList a -> [a]
> toList x = x []

And that's it. You're on your own for testing here. Write some unit tests for the above functions. You should ensure that 'DList's behave like normal lists.

> testDList :: IO ()
> testDList = do
>   _ <- runTestTT $ TestList [
>           toList empty ~?= ([] :: [Char])
> 
>        ]
>   return ()
>            

Micro-benchmarks

If you'd like to see the difference between using (++) with regular lists and append using DLists, in GHCi you can type

*Main> :set +s

That will cause GHCi to give you timing and allocation information for each evaluation that you do. Then, after you complete this file, you can test out these logging micro-benchmarks.

This first example repeatedly appends a single character to its string parameter with each recursive call.

> micro1 :: Char
> micro1 = last (t 10000 "") where
>   t 0 l = l
>   t n l = t (n-1) (l ++ "s")
*Main> micro1
's'
(2.80 secs, 4,300,584,976 bytes)

This version does the same, except that this time it uses the DList operations.

> micro2 :: Char
> micro2 = last (toList (t 10000 empty)) where
>    t 0 l = l
>    t n l = t (n-1) (l `append` singleton 's')
 *Main> micro2
 's'
 (0.02 secs, 10,359,248 bytes)

Notice how the second version is much faster and uses much less memory. Why is this the case? The ++ operator for lists takes time proportional to its first argument. So as the l argument of t grows in length, adding an s to the end of it takes longer and longer. However, the DList append operator doesn't have this behavior. It just remembers that we are going to add an additional character at each step and then constructs the list all at once with toList. Nifty!

We can also see the effect of using difference lists for defining a list reverse function.

For example, consider this version of the list reverse function. This function is easy to understand, but it is O(n^2), not O(n). Can you see why?

> naiveReverse :: [a] -> [a]
> naiveReverse = rev where
>   rev []     = []
>   rev (x:xs) = rev xs ++ [x]

Let's use a list containing 10,001 integers to micro-benchmark this function.

> bigList :: [Int]
> bigList = [0 .. 10000]

Don't skip this next step! Let's look at the last element in this list. This command will force GHCi to evaluate the expression above and allocate the list into memory. (We don't want our first benchmark below to include time for constructing this list---we only want to time the reverse operation.)

*Main> last bigList
10000
(0.01 secs, 882,216 bytes)

Let's try to reverse this list. How long does it take? How many bytes? Give it a try.

> micro3 :: Int
> micro3 = last (naiveReverse bigList) 
*Main> micro3

We can dress up the reverse function a bit using foldr, flip and the singleton section (:[]), but that doesn't really help. It's fundamentally the same algorithm. (I also find this 'point-free' version much harder to understand! Try to convince yourself that this definition really is doing the same thing as naiveReverse!)

> ivoryTowerReverse :: [a] -> [a]
> ivoryTowerReverse = foldr (flip (++) . (:[]))  []

But, the microbenchmark shows that this version is doing about the same amount of work. Try it out.

> micro4 :: Int
> micro4 = last (ivoryTowerReverse bigList)
*Main> micro4

Now watch what happens when we use a DList instead. Compare this definition with the naiveReverse one above. It's still easy to read. All we have done is replace the standard list operations with the DList versions, through a fairly mechanical process.

> dlistReverse :: [a] -> [a]
> dlistReverse = toList . rev where
>   rev []     = empty
>   rev (x:xs) = rev xs `append` singleton x
> micro5 :: Int
> micro5 = last (dlistReverse bigList)
 *Main> micro5

We can also replace the list operations in ivoryTowerReverse with their DList analogues, also a mechanical process.

> dlistIvoryTowerReverse :: [a] -> [a]
> dlistIvoryTowerReverse = toList . (foldr (flip append . singleton) empty)
> micro6 :: Int
> micro6 = last (dlistIvoryTowerReverse bigList)
 *Main> micro6

(Of course, it is often better to use the standard library definition of common operations. How does the built-in operation, which has been optimized for GHC compare?)

> micro7 :: Int
> micro7 = last (reverse bigList)
 *Main> micro7
Design adapted from Minimalistic Design | Powered by Pandoc and Hakyll