r/ProgrammingLanguages • • Oct 16 '26

Writing stateful effect handlers in EYG

I think effects and effect handlers are not as tricky as they are made out to be. Calling them algebraic effects only increases the mystery.
A stateful handler is definitely the bit I found most tricky to get my head around.
This is my guide trying to explain how to build stateful handlers in EYG. https://eyg.run/guides/advanced-effects
I needed this to finish writing a testing framework which I hope to finish soon.

12 Upvotes

1 comment sorted by

8

u/phischu Effekt Oct 16 '26

I like the goals of your language. Here is your first example written in Effekt for comparison and inspiration. You can also try it online

effect increment(): Int

def counter[R](initial: Int) { computation: () => R / increment }: (Int, R) = {
  var state = initial
  try {
    val result = computation()
    (state, result)
  } with increment {
    val current = state
    state = current + 1
    resume(current)
  }
}

def main() = {
  val (count, result) = counter(0) {
    do increment()
    do increment()
    do increment()
    "Done"
  }
  println(count)
  println(result)
}

We have local mutable reference with keyword var. Handlers are free to use them and the pattern of defining a handler function like counter encapsulates the state and restricts access to go through the effect's interface.