News for hackers. Stuff that matters.
Re:Adventures of an imperative programmer in the land of fp by silentbicycle on Friday August 27, 2010 @03:48PM (#1639988)
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?
Re:Adventures of an imperative programmer in the land of fp by jacquesm on Friday August 27, 2010 @04:29PM (#1640137)
Stack 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.

Re:Adventures of an imperative programmer in the land of fp by silentbicycle on Friday August 27, 2010 @04:50PM (#1640232)
Indeed. 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.)

Re:Adventures of an imperative programmer in the land of fp by jacquesm on Friday August 27, 2010 @05:46PM (#1640392)
> 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.

Re:Adventures of an imperative programmer in the land of fp by jules on Friday August 27, 2010 @07:18PM (#1640616)
Yep, 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.