Review of Pointers in Haskell
In this document we review the important ideas behind
- Pointers in Haskell
- Using pointers to build linked structures with mutable links.
Pointers in Haskell
- Pointers are references to memory locations.
- A pointer never changes, but the memory location it points to
can be observed and changed using commands.
- The pointer commands include:
-
newPtr :: a -> IO (Ptr a)
-
readPtr :: Ptr a -> IO a
-
writePtr:: Ptr a -> a -> IO ()
-
samePtr:: Ptr a -> Ptr a -> Bool
- All of the operations have constant time costs.
We can envision a pointer as an arrow pointing to a blue box.
The blue box represents the contents of the memory location. The data
inside the blue box can be observed or altered.
To observe the contents
use the readPtr command
To change the contents
of the blue box, use the writePtr command.
We can embed pointers in algebraic data structures, thus creating
mutable structures. For example a mutable list, where both the
elements in the list and the links in the list are mutable can be defined as follows:
data MutList a = Nil | Cons (Ptr a) (Ptr (MutList a))
One might picture a mutable list as follows.
One can create Queue structure by combining
a mutable list and a pair of pointers, one to the front,
and one to the rear of the Queue.
To enqueue an element requires changing a few pointers
Back to the Daily Record.
Back to the class web-page.