concept STUArray in category haskell

appears as: STUArray, The STUArray, n STUArray, STUArray
Get Programming with Haskell

This is an excerpt from Manning's book Get Programming with Haskell.

Haskell does have a solution to this problem. You’ll be using a special type of UArray called an STUArray. The STUArray uses a more general type called ST. ST allows for stateful, nonlazy programming. In this lesson, you’ll focus only on STUArray, but it’s important to recognize that the solutions you present here for working with arrays can be extended to a larger class of stateful programs.

To use STUArray, you’ll add the following imports:

import Data.Array.ST
import Control.Monad
import Control.Monad.ST

STUArray is an instance of Monad. In unit 5, you spent a lot of time looking at the family of type classes that include Functor, Applicative, and Monad. The aim of all of these type classes is to allow you to perform arbitrary computation within a context. You’ve seen a variety of examples of this throughout the book:

Like IO, STUArray allows you to perform computation normally forbidden in Haskell in a safe context. Just like IO actions, when working with STUArrays, you’ll use do-notation to treat types in the STUArray context, just as if they were regular data.

The key power STUArray offers is the ability to change values in a UArray (see figure 42.1 for a visual explanation). This is the final efficiency gain you need in order to achieve efficiency on par with programming languages that allow state. By being able to change values in place, you can save tremendously on memory usage, and by not having to re-create a new copy of your data structure with each change, you can also save on time. This is the key to writing a bubble sort that’s as efficient as you’d find in an algorithms text book.

Figure 42.1. The STUArray is a context that allows for stateful mutations.

One important thing to understand about STUArrays and the ST type in general is that they aren’t a hack that allows you to disregard all the functional purity you’ve worked so hard for. STUArray exists to allow you to perform stateful programming only when that statefulness is indistinguishable from pure code for the users of your functions. The vast majority of changes in data structures can be done with both reasonable efficiency and great safety, using the functional data structures you’ve used throughout the book.

You’ll learn how to use STUArray by writing a function, called listToSTUArray, that takes a list of Ints and transforms that into an STUArray. In your first draft of listToSTUArray, you’ll create an empty STUArray the size of your list. This is similar to initializing an empty array of a fixed size, only you’ll do it in a monad. The STUArray type uses the newArray function, which takes a pair representing the bounds of the array as well as a value for initializing the array.