All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonMain.effekt.state.kt Maven / Gradle / Ivy

Go to download

Provides fully-fledged multishot delimitied continuations in Kotlin with Coroutines

The newest version!
package effekt

import State
import get
import pushState
import set

public interface StateScope {
  public suspend fun  field(init: T): Field
  public interface Field {
    public suspend fun get(): T
    public suspend fun set(value: T)
  }
}

public suspend inline fun  StateScope.Field.update(f: (T) -> T) {
  set(f(get()))
}

public suspend fun  region(body: suspend StateScope.() -> R): R = handle {
  body(StateScopeImpl(this))
}

// TODO use map implementation
private class StateScopeImpl(prompt: HandlerPrompt) : StateScope, Handler by prompt {
  override suspend fun  field(init: T): StateScope.Field = FieldImpl(State()).apply {
    use {
      state.pushState(init) {
        it(Unit)
      }
    }
  }

  private data class FieldImpl(val state: State) : StateScope.Field {
    override suspend fun get(): T = state.get()
    override suspend fun set(value: T) = state.set(value)
  }
}

public interface Stateful> {
  public fun fork(): S
}

public suspend fun , S : Stateful> handleStateful(
  handler: ((() -> StatefulPrompt) -> H), value: S,
  body: suspend H.() -> E
): E = handleStateful(handler, value, Stateful::fork, body)

public suspend fun > handleStateful(
  value: S, body: suspend StatefulPrompt.() -> E
): E = handleStateful(value, Stateful::fork, body)

public suspend fun > StatefulHandler.handleStateful(
  value: S, body: suspend () -> E
): E = handleStateful(value, Stateful::fork, body)