Skip to content
BANG

8. Swap the handler, keep the program

Teaches: the same program under two different handlers

Because a handler is just a value installed at a with site, the same program runs differently depending only on which handler you swap in. Both programs below perform the identical three log calls; only the handler's log clause differs — one discards, one counts. This is the cartridge-swap moment: a runtime is a value you choose, not a fixed part of the language.

examples/logger-silent/

effect Log { log : Int -> Int }
 
handle
  (logger.log(10)) + (logger.log(20)) + (logger.log(30))
with Log as logger {
  log(msg) => 0
}

Expected output (bang run stdout):

0

examples/logger-counting/

effect Log { log : Int -> Int }
 
handle
  (logger.log(10)) + (logger.log(20)) + (logger.log(30))
with Log as logger {
  log(msg) => 1
}

Expected output (bang run stdout):

3

Run it yourself:

curl -fsSL https://raw.githubusercontent.com/phibkro/bang/main/tools/install.sh | sh
bang run examples/logger-silent/main.bang
bang run examples/logger-counting/main.bang

← 7. Declare your own effect · 9. Identity dispatch (the lexical cap) →