by fleabitdev · 2y ago · 0 comments
It's ambient state, just like a `catch` block, and so you can make it ambiently available to a whole tree of function calls. The outcome is the same as passing around a context argument by hand, and it can have equally strong type-checking, but the compiler handles all of the boilerplate for you.
To answer your second question: I agree that, in a dynamic language like JavaScript, making all of these language features implicit could be too costly. I'm more optimistic about effect systems in statically-typed languages.
So a "localized global variable" of sorts? Sounds interesting, got any links to examples I could look at?
It isn't a very common language feature, but you could take a look at React's `Context` or Common Lisp's `defparameter`.
I was imagining more along the lines of (on-the-spot pseudo-code)
using [x := foo(...)]
{
bar();
output();
}
func bar()
{
x = x + 1
}
where bar() and output(), or something they call in turn, can reference x and it would be a compile-time error to use bar() or output() in cases where they couldn't resolve x. Or something more along those lines.Anyway, cheers, always fun to ponder these things.
The killer feature is that you can shadow a dynamic variable, changing its value for the duration of a dynamic scope, in the same way that an inner `catch` handler overrides an outer one.
For example, you could have a dynamic variable which tells the `print` function where to send its text output. The variable's value would probably default to stdout. By temporarily assigning a string-stream to that variable, you could collect an arbitrary function's text output into a string instead. Regardless of where the text is going, any function which produces text could still use the convenient global `print` function.