Skip to content

Instantly share code, notes, and snippets.

@ijp
Created January 21, 2012 15:56
Show Gist options
  • Save ijp/1653137 to your computer and use it in GitHub Desktop.
Save ijp/1653137 to your computer and use it in GitHub Desktop.
yin yang problem explanation

The Yin Yang Problem

08/06/2011

(let* ((yin
         ((lambda (cc) (display #\@) cc) (call-with-current-continuation (lambda (c) c))))
       (yang
         ((lambda (cc) (display #\*) cc) (call-with-current-continuation (lambda (c) c)))) )
    (yin yang))

While I figured out this before, I never bothered to write down my explanation, so I’m doing so now.

First, yin is bound to a continuation k1( which prints @, then proceeds to bind yang, and then call yin with yang). Next, yang is bound to a continuation k2( which prints *, then calls yin with yang). Next, we call yin (k1), with the argument yang(k2). Having done so, yin is now bound to k2 and yang is bound to a continuation k3 (which prints *, then calls yin with yang). Then, we call k2, with k3. Having done so, yin is bound to k1 (which it was when k2 was bound), and yang is bound to k3. Now we call k1 with k3. Now, yin is bound to k3, and yang gets bound to a new continuation, k4, (which prints *, then calls yin with yang). Then, yin is called with yang (that is k3 is called with k4). Now, yin is bound to k2 (which it was when k3 was created), and yang is bound to k4. We then call k2 with k4. Now, yin is bound to k1 (which it was when k2 was crated), and yang is bound to k4, and we call k1 with k4. Now, yin is bound to k4, and we bind yang to a new continuation, k5, then we call k4 with k5. … and so on.

As we can see above, the yin yang problem creates an ever increasing chain of continuations. When we create a fresh continuation in yang, it is passed to the top of the chain, which will be in yin. Having invoked that continuation, we will have our new continuation in yang, and the value of yin will be the top of the chain when our current top was created. We call the old top with our fresh continuation, passing it further down the chain until we reach the bottom, and our value is stored in yin (meaning that continuation is now top of the chain), and we create a new continuation to pass to it, thus starting the whole thing over again, but with an extra link in the chain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment