concept state in category haskell

appears as: state, state
Haskell in Depth

This is an excerpt from Manning's book Haskell in Depth.

State as a Monad is responsible for keeping and mutating the state as requested by the user, this is a job for the >>= method implementation. Consequently, the combination of two computations put 42 and get in this particular order (as in put 42 >> get, remember that >> is normally implemented via >>=) should reveal 42 as a result of the combined computation.

runState :: State s a -> s -> (a, s)
execState :: State s a -> s -> s
evalState :: State s a -> s -> a

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
withState :: (s -> s) -> State s a -> State s a
Get Programming with Haskell

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

This code clearly isn’t Haskell, because both tick and reset violate the rules we established. Neither function takes any arguments nor returns any value. The question is, then, what are these functions doing, and how is this different from functions in Haskell? It’s not a long shot to suppose that tick is incrementing a counter and that reset restores that counter to its starting value. Even if we’re not exactly right, this reasoning gives us insight into our question. If you aren’t passing an argument to a function, you must be accessing a value in your environment, and if you aren’t returning a value, you must also be changing a value in your environment. When you change a value in your programming environment, you’re changing the program’s state. Changing state creates side effects in your code, and these side effects can make code hard to reason about and therefore unsafe.

Listing 10.4. Defining a drink message that updates state
drink aCup ozDrank = cup (flOz - ozDrank) where flOz = getOz aCup

Writing a bubble sort with Haskell has a few large issues. The first is that you’ve relied heavily on lists as your primary data structure, but they’re not nearly as efficient as proper arrays for this type of problem. A much larger issue is the requirement that the sort be in place; You can’t create a copy of your array. Nearly all the code you’ve written in this book relies on changing the state of a data structure the functional way: creating a new version of the structure and discarding the original. For the majority of problems, this is both reasonably efficient and easy to do. Sorting an array is one case where you absolutely need to modify the state of a data structure for reasons of efficiency.

42.2. Mutating state with STUArray

The vast majority of the time, Haskell forcing the programmer to remove statefulness from the code results in safer, more predictable code with roughly the same performance. This isn’t true for most array algorithms. If Haskell had no way to mutate state in these cases, a wide range of essential algorithms would be off-limits in Haskell.