m (The previous worker wrapper transformation link went to a spam website - I changed it to a pdf paper about the topic.)
|(2 intermediate revisions by one user not shown)|
Latest revision as of 19:43, 19 July 2013
It is sometimes easier or more efficient to write functions which have particular "start arguments" or that pass state. When this is the case write wrappers rather than trying to code within the original signature.
 1 Accumulator examples
e.g. the function reverse
reverse :: [a] -> [a]
could be written
reverse  =  reverse (x:xs) = reverse xs ++ [x]
however this will be more efficient if it were written
reverse xs = revWorker  xs revWorker s  = s revWorker s (x:xs) = revWorker (x:s) xs
note often a worker will also return some state along with a result which can be stripped away.
 2 Other examples
Wrappers are often used to play the role of loop initialisation in imperative languages. For example:
fib n = fibWorker n 0 1 fibWorker n f1 f2 | n == 0 = f1 | otherwise = fibWorker (n-1) f2 (f1+f2)
 3 Hiding the worker
Also, often one hides the worker(s) with a where (or let). E.g. :
fib = fibWorker 0 1 where fibWorker f0 f1 n | n == 0 = f0 | True = fibWorker f1 (f0 + f1) (n-1)
Of course, one then has to de-hide the worker if one want to test it with different initial arguments.
In some cases, though, the worker can be a generally useful function on its own merits, in that case one obviously shouldn't hide it.
One common case is where you want to subject the worker function to Unit testing. In such a situation, the test suite has to be able to get to the worker function. Another is where the worker might be a candidate for further abstraction. (See Higher order function for examples.)