CS 214: Programming Languages
Spring 2009

Home|Syllabus|Schedule
<<|>>|Haskell templates

Functions as First Class Objects
Haskell, Iteration 3

Do all of your work in languages/haskell/factorial.

Repeated Code

Take a look at FactorialTest.hs.

This is an artificial situation. Normally you don't test four functions which all calculate the same value, so it's a little strange to have this in a test case, but you have a lot of repeated code in there. Why specify the same assertions for each of the four functions you defined in the previous iterations? You need to make the same assertions, but do you have to explicitly write them?

Answer: no!

Write a function in FactorialTest.hs named listOfTests. It should take a single argument, f, which will be a function. It should return a TestList of (ultimately) assertions for the factorial function.

Just copy one of the TestLists you already have, and make that the result of listOfTests. Replace the call to a specific factorial function with the f argument.

This is a refactoring, so nothing should break.

Compile, and green bar.

Now start using the function:

  1. Replace factorialTests with
    factorialTests = listOfTests factorial
    
  2. Compile, and green bar.

It it's good for one, it's good for the rest.

Do the same for all of the other ...Tests variables, one by one, making sure the tests always green bar.

This works because Haskell allows (encourages!) you to pass around functions as values. This is just a small case of the power this ability gives you.