3 ms·
But you'd probably only get hung up on that being "magic" if your mental model of programming assumed stack-based scope for everything. Besides, how about this
by silentbicycle 16y ago
But you'd probably only get hung up on that being "magic" if your mental model of programming assumed stack-based scope for everything.
Besides, how about this pseudocode?
class Foo {
field x;
constructor(x) { this.x = x; }
fun add(y) { return x + y; }
}
bar = Foo(3);
bar.add(5) // returns 8, wait how did the x in the object remember the 3?
- jacquesm 16y agoStack based 'mental' scope is one of the bigger things to 'unlearn'. When I look at a function I build up a mental image of what is going on on the stack as the function executes. Things that I don't see declared within the function or that are explicitly allocated update the heap. To get away from that image is very hard to do at first. I compare it to learning real life languages, like English versus German. If you've never seen a language that has declinations in the endings of words then it can completely overwhelm you. Likewise tonal languages are strange when you've only spoken English or German. Each of those opens up the perspective you had before you learned that language to show you that there is more under the sun than what you thought was 'normal', and that your way is not always the better one. In programming languages it is much the same way.
- silentbicycle 16y agoIndeed. For some reason, closures never tripped me up, but continuations took a while to wrap my head around. (I think because I tried to learn continuation-passing-style first. While also learning OCaml.) Since you know C, it might help to think of continuations in terms of setjmp/longjmp, but with multiple, persistent stacks. (Same with coroutines, but coroutines and continuations have a lot of overlap.)
- jacquesm 16y ago> in terms of setjmp/longjmp, but with multiple, persistent stacks. That's exactly the thing I used to help me visualize it :) Funny you came up with the exact same model. Setjmp and longjmp are by the way probably two of the most abused calls in the C runtime package. But when you need them, you need them badly.
- jules 16y agoYep, that's how closures are implemented. Changing your mental model of programming from stack based to what you could call "lexical scope based" is what's difficult here yes.