Reversing a list - Recursive worker function pattern
In the previous recipe, we saw implementation using a simple recursive definition. In this recipe, we will use a commonly found recursive function implementation pattern called worker pattern.
The list does not have random access. We have to access elements of a list sequentially to be able to do something with it. When reversing a list, we need to remember this fact.
Getting ready
Create a new project, reverse, using Stack and the simple template. Also, build the project:
stack new reverse simple stack build
How to do it...
- Change directory to
reverse, and opensrc/Main.hs. This file defines theMainmodule. - Conditionally import
Prelude, hiding thereversefunction:
import Prelude hiding (reverse)
Note
Note that Prelude is imported automatically unless it is explicitly imported. Since we will write our own reverse function, we need to hide the reverse function while importing Prelude.
- Write the signature of a
reversefunction...