ScopedValue

lib/ScopedValue.gob

Scoped values: a value bound for the extent of a call, which every call inside it can read without being passed it.

let depth : ScopedValue Int = ScopedValue.new()

fun indent() -> String =
    String.repeat("  ", Option.unwrapOr(ScopedValue.get(depth), 0))

fun nested(f : fun() -> a) -> a =
    ScopedValue.with(depth, Option.unwrapOr(ScopedValue.get(depth), 0) + 1, f)

with(key, value, f) binds key to value while f() runs, and get returns the innermost binding of key, or None outside every one. When with returns, the binding it made is gone and any it shadowed is back. Nothing assigns a binding; a value that has to change is a mutable object, bound once.

Bindings belong to the running coroutine, not to the thread: a task that suspends inside a with and resumes on another worker still sees them. A task starts with the bindings in force where its coroutine is made, and later withs on either side do not reach the other. For System.Task, that is where runScope runs the spawn action, the same place the task takes its scope from, and not where spawn was called. So runScope(with(k, v, fun() = spawn(f))) starts a task without k: the with returns the action, and it runs outside.

A key is made once, usually as a top-level let. Each new() makes a distinct key, even for the same type.

Costs. A coroutine's bindings are an immutable list, innermost first, because there are a handful of them at most: with allocates one node and does no copying, a new task shares its creator's list, and get walks the list to its key. A key bound deep under many others, or shadowed by many rebindings, costs a step per binding in front of it.

type ScopedValue a

A key for scoped values of type a: its number, unique among keys.

The constructor is not exported, and get's cast relies on that. Only new makes a key, each with a fresh number, and a call is never generalized, so a number belongs to one key at one type. A key built from a constructor would be a value, and a polymorphic one could bind a String and be read as an Int.

fun new : fun() -> ScopedValue a

Returns a new key, distinct from every other.

fun with : fun(ScopedValue a, a, fun() -> b) -> b

Returns f(), run with key bound to value.

fun get : fun(ScopedValue a) -> Option a

Returns the value of the innermost binding of key, or None if no with around the running code binds it.