Skip to content
BANG

9. Identity dispatch (the lexical cap)

Teaches: why nesting the same effect twice does NOT pick the nearest handler

Nest two handlers for the same effect, and give the program capabilities named after each (inner, outer). A capability dispatches to the handler it was lexically bound to, not to whichever handler is nearest at runtime — inner.fetch always reaches the inner handler even from inside the outer one's scope. This is identity-keyed dispatch: the capability carries which specific handler instance it names, not just an effect label.

effect Net { fetch : Int -> Int }
handle (
  handle
    (inner.fetch(1)) + (outer.fetch(2))
  with Net as inner {
    fetch(n) => n * 10
  }
) with Net as outer {
  fetch(n) => n * 100
}

Expected output (bang run stdout):

210

Run it yourself:

curl -fsSL https://raw.githubusercontent.com/phibkro/bang/main/tools/install.sh | sh
bang run examples/handle-custom-nested/main.bang

← 8. Swap the handler, keep the program · 10. Generation as an effect →