haskellst-monad

syntax of ST monad declaration


I recently began looking at core libraries on Hackage, and there's a recurring idiom I don't understand. Here's an example from the ST module:

instance Monad (ST s) where
    {-# INLINE (>>=)  #-}
    (>>) = (*>)
    (ST m) >>= k
      = ST (\ s ->
        case (m s) of { (# new_s, r #) ->
        case (k r) of { ST k2 ->
        (k2 new_s) }})

In particular, I don't understand (# new_s, r #). I assume the second hash refers to an unboxed value, but the rest is a mystery to me (something to do with "new state", presumably).


Solution

  • (# x, y, z #) is an unboxed tuple with three elements. See "8.2.2. Unboxed Tuples" at https://downloads.haskell.org/~ghc/6.8.3/docs/html/users_guide/primitives.html.

    The rest is basically just an implementation of State.