syntax of ST monad declaration
Asked Answered
W

1

8

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).

Wheelsman answered 7/4, 2017 at 22:38 Comment(0)
S
7

(# 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.

Sailesh answered 7/4, 2017 at 22:55 Comment(1)
In general, # in Haskell means it is doing some sort of low level and/or primitive stuff. You must enable the MagicHash language extension to even use # in names.Dickson

© 2022 - 2024 — McMap. All rights reserved.