<p>I'm trying to grasp the concept of continuations and I found several small teaching examples like this one from the <a href="http://en.wikipedia.org/wiki/Continuation" rel="noreferrer">Wikipedia article</a>:</p>

<pre><code>(define the-continuation #f)

(define (test)
  (let ((i 0))
    ; call/cc calls its first function argument, passing 
    ; a continuation variable representing this point in
    ; the program as the argument to that function. 
    ;
    ; In this case, the function argument assigns that
    ; continuation to the variable the-continuation. 
    ;
    (call/cc (lambda (k) (set! the-continuation k)))
    ;
    ; The next time the-continuation is called, we start here.
    (set! i (+ i 1))
    i))
</code></pre>

<p>I understand what this little function does, but I can't see any obvious application of it. While I don't expect to use continuations all over my code anytime soon, I wish I knew a few cases where they can be appropriate. </p>

<p>So I'm looking for more explicitely usefull code samples of what continuations can offer me as a programmer.</p>

<p>Cheers!</p>

[{'answer_id': 34173, 'author': 'A. Rex', 'author_id': 3508, 'author_profile': 'https://Stackoverflow.com/users/3508', 'pm_score': 2, 'selected': False, 'text': '<p>Continuations can be used in "real-life" examples whenever the program flow is not linear, or not even pre-determined.  A familiar situation is <a href="http://www.ibm.com/developerworks/library/j-contin.html" rel="nofollow noreferrer">web applications</a>.</p>\n'}, {'answer_id': 34175, 'author': 'David Webb', 'author_id': 3171, 'author_profile': 'https://Stackoverflow.com/users/3171', 'pm_score': 3, 'selected': False, 'text': '<p>Continuations are used by some web servers and web frameworks to store session information.  A continuation object is created for each session and then used by each request within the session.</p>\n\n<p><a href="http://www.ibm.com/developerworks/library/os-lightweight9/index.html" rel="noreferrer">There\'s an article about this approach here.</a></p>\n'}, {'answer_id': 34273, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 3, 'selected': False, 'text': '<p>Seaside: </p>\n\n<ul>\n<li><a href="http://www.seaside.st/" rel="nofollow noreferrer">homepage</a> </li>\n<li><a href="http://en.wikipedia.org/wiki/Seaside_%28software%29" rel="nofollow noreferrer">wikipedia page</a></li>\n</ul>\n'}, {'answer_id': 34327, 'author': 'Sébastien RoccaSerra', 'author_id': 2797, 'author_profile': 'https://Stackoverflow.com/users/2797', 'pm_score': 3, 'selected': False, 'text': '<p>@Pat</p>\n\n<blockquote>\n  <p>Seaside</p>\n</blockquote>\n\n<p>Yes, <a href="http://www.seaside.st" rel="nofollow noreferrer">Seaside</a> is a great example. I browsed its code quickly and found this message  illustrating passing control between components in a seemingly statefull way accross the Web.</p>\n\n<pre><code>WAComponent &gt;&gt; call: aComponent\n    "Pass control from the receiver to aComponent. The receiver will be\n    temporarily replaced with aComponent. Code can return from here later\n    on by sending #answer: to aComponent."\n\n    ^ AnswerContinuation currentDo: [ :cc |\n        self show: aComponent onAnswer: cc.\n        WARenderNotification raiseSignal ]\n</code></pre>\n\n<p>So nice!</p>\n'}, {'answer_id': 34387, 'author': 'sven', 'author_id': 46, 'author_profile': 'https://Stackoverflow.com/users/46', 'pm_score': 5, 'selected': True, 'text': '<p>In Algo &amp; Data II we used these all the times to "exit" or "return" from a (long) function</p>\n\n<p>for example the BFS algorthm to traverse trees with was implemented like this:</p>\n\n<pre><code>(define (BFS graph root-discovered node-discovered edge-discovered edge-bumped . nodes)\n  (define visited (make-vector (graph.order graph) #f))\n  (define q (queue.new))\n  (define exit ())\n  (define (BFS-tree node)\n    (if (node-discovered node)\n      (exit node))\n    (graph.map-edges\n     graph\n     node\n     (lambda (node2)\n       (cond ((not (vector-ref visited node2))\n              (when (edge-discovered node node2)\n                (vector-set! visited node2 #t)\n                (queue.enqueue! q node2)))\n             (else\n              (edge-bumped node node2)))))\n    (if (not (queue.empty? q))\n      (BFS-tree (queue.serve! q))))\n\n  (call-with-current-continuation\n   (lambda (my-future)\n     (set! exit my-future)\n     (cond ((null? nodes)\n            (graph.map-nodes\n             graph\n             (lambda (node)\n               (when (not (vector-ref visited node))\n                 (vector-set! visited node #t)\n                 (root-discovered node)\n                 (BFS-tree node)))))\n           (else\n            (let loop-nodes\n              ((node-list (car nodes)))\n              (vector-set! visited (car node-list) #t)\n              (root-discovered (car node-list))\n              (BFS-tree (car node-list))\n              (if (not (null? (cdr node-list)))\n                (loop-nodes (cdr node-list)))))))))\n</code></pre>\n\n<p>As you can see the algorithm will exit when the node-discovered function returns true:</p>\n\n<pre><code>    (if (node-discovered node)\n      (exit node))\n</code></pre>\n\n<p>the function will also give a "return value": \'node\'</p>\n\n<p>why the function exits, is because of this statement:</p>\n\n<pre><code>(call-with-current-continuation\n       (lambda (my-future)\n         (set! exit my-future)\n</code></pre>\n\n<p>when we use exit, it will go back to the state before the execution, emptying the call-stack and return the value you gave it.</p>\n\n<p>So basically, call-cc is used (here) to jump out of a recursive function, instead of waiting for the entire recursion to end by itself (which can be quite expensive when doing lots of computational work)</p>\n\n<p>another smaller example doing the same with call-cc:</p>\n\n<pre><code>(define (connected? g node1 node2)\n  (define visited (make-vector (graph.order g) #f))\n  (define return ())\n  (define (connected-rec x y)\n    (if (eq? x y)\n      (return #t))\n    (vector-set! visited x #t)\n    (graph.map-edges g\n                     x\n                     (lambda (t)\n                       (if (not (vector-ref visited t))\n                         (connected-rec t y)))))\n  (call-with-current-continuation\n   (lambda (future)\n     (set! return future)\n     (connected-rec node1 node2)\n     (return #f))))\n</code></pre>\n'}, {'answer_id': 53674, 'author': 'Sébastien RoccaSerra', 'author_id': 2797, 'author_profile': 'https://Stackoverflow.com/users/2797', 'pm_score': 3, 'selected': False, 'text': '<p>I came accross an implementation of the <code>amb</code> operator in <a href="http://www.randomhacks.net/articles/2005/10/11/amb-operator" rel="noreferrer">this post</a> from <a href="http://www.randomhacks.net" rel="noreferrer">http://www.randomhacks.net</a>, using continuations.</p>\n\n<p>Here\'s what the <code>amb</code> opeerator does:</p>\n\n<pre><code># amb will (appear to) choose values\n# for x and y that prevent future\n# trouble.\nx = amb 1, 2, 3\ny = amb 4, 5, 6\n\n# Ooops! If x*y isn\'t 8, amb would\n# get angry.  You wouldn\'t like\n# amb when it\'s angry.\namb if x*y != 8\n\n# Sure enough, x is 2 and y is 4.\nputs x, y \n</code></pre>\n\n<p>And here\'s the post\'s implementation:</p>\n\n<pre><code># A list of places we can "rewind" to\n# if we encounter amb with no\n# arguments.\n$backtrack_points = []\n\n# Rewind to our most recent backtrack\n# point.\ndef backtrack\n  if $backtrack_points.empty?\n    raise "Can\'t backtrack"\n  else\n    $backtrack_points.pop.call\n  end\nend\n\n# Recursive implementation of the\n# amb operator.\ndef amb *choices\n  # Fail if we have no arguments.\n  backtrack if choices.empty?\n  callcc {|cc|\n    # cc contains the "current\n    # continuation".  When called,\n    # it will make the program\n    # rewind to the end of this block.\n    $backtrack_points.push cc\n\n    # Return our first argument.\n    return choices[0]\n  }\n\n  # We only get here if we backtrack\n  # using the stored value of cc,\n  # above.  We call amb recursively\n  # with the arguments we didn\'t use.\n  amb *choices[1...choices.length]\nend\n\n# Backtracking beyond a call to cut\n# is strictly forbidden.\ndef cut\n  $backtrack_points = []\nend\n</code></pre>\n\n<p>I like <code>amb</code>!</p>\n'}, {'answer_id': 69874, 'author': 'Jonathan Arkell', 'author_id': 11052, 'author_profile': 'https://Stackoverflow.com/users/11052', 'pm_score': 3, 'selected': False, 'text': '<p>I built my own unit testing software.  Before executing the test, I store the continuation before executing the test, and then on failure, I (optionally) tell the scheme interpreter to drop into debug mode, and re-invoke the continuation.  This way I can step through the problematic code really easily.</p>\n\n<p>If your continuations are serializable, you can also store then on application failure, and then re-invoke them to get detailed information about variable values, stack traces, etc.</p>\n'}, {'answer_id': 69906, 'author': 'Greg', 'author_id': 4123, 'author_profile': 'https://Stackoverflow.com/users/4123', 'pm_score': 2, 'selected': False, 'text': "<p>Continuations are a good alternative to thread-per-request in server programming (including web application frontends.</p>\n\n<p>In this model, instead of launching a new (heavy) thread every time a request comes in, you just start some work in a function. Then, when you are ready to block on I/O (i.e. reading from the database), you pass a continuation into the networking response handler. When the response comes back, you execute the continuation. With this scheme, you can process lots of requests with just a few threads.</p>\n\n<p>This makes the control flow more complex than using blocking threads, but under heavy load, it is more efficient (at least on today's hardware).</p>\n"}, {'answer_id': 499490, 'author': 'Tom Dunham', 'author_id': 6402, 'author_profile': 'https://Stackoverflow.com/users/6402', 'pm_score': 1, 'selected': False, 'text': '<p>How about the <a href="http://code.google.com/apis/maps/documentation/mapplets/guide.html" rel="nofollow noreferrer">Google Mapplets API</a>? There are a bunch of functions (all ending in <code>Async</code>) to which you pass a callback. The API function does an async request, gets it\'s result, then passes that result to your callback (as the "next thing to do"). Sounds a lot like <a href="http://en.wikipedia.org/wiki/Continuation-passing_style" rel="nofollow noreferrer">continuation passing style</a> to me.</p>\n\n<p>This <a href="http://code.google.com/apis/maps/documentation/mapplets/guide.html#Asynchronous" rel="nofollow noreferrer">example</a> shows a very simple case.</p>\n\n<pre><code>map.getZoomAsync(function(zoom) {\n    alert("Current zoom level is " + zoom); // this is the continuation\n});  \nalert("This might happen before or after you see the zoom level message");\n</code></pre>\n\n<p>As this is Javascript there\'s no <a href="http://en.wikipedia.org/wiki/Tail_call_optimization" rel="nofollow noreferrer">tail call optimization</a>, so the stack will grow with every call into a continuation, and you\'ll eventually return the thread of control to the browser. All the same, I think it\'s a nice abstraction. </p>\n'}, {'answer_id': 615158, 'author': 'jfs', 'author_id': 4279, 'author_profile': 'https://Stackoverflow.com/users/4279', 'pm_score': 0, 'selected': False, 'text': '<p>Continuations can be used to implement exceptions, a debugger.</p>\n'}, {'answer_id': 2769791, 'author': 'Justin Smith', 'author_id': 252401, 'author_profile': 'https://Stackoverflow.com/users/252401', 'pm_score': 1, 'selected': False, 'text': '<p>If you have to invoke an asynchronous action, and suspend execution until you get the result, you would normally either poll for the result or put the rest of your code in a callback to be executed by the asynchronous action upon completion. With continuations you don\'t need to do the inefficient option of polling, and you don\'t need to wrap up all your code to be run after the asynch event in a callback - you just pass the current state of the code as your callback - and the code is effectively "woken up" as soon as the asynch action completes.</p>\n'}, {'answer_id': 2855037, 'author': 'Zorf', 'author_id': 2281094, 'author_profile': 'https://Stackoverflow.com/users/2281094', 'pm_score': 2, 'selected': False, 'text': "<p>The amb operator is a good example that allows prolog-like declarative programming.</p>\n\n<p>As we speak I'm coding a piece of music composition software in Scheme (I'm a musician with next to no knowledge of the theory behind music and I'm just analysing my own pieces to see how the maths behind it works.)</p>\n\n<p>Using the amb operator I can just fill in constraints which a melody must satisfy and let Scheme figure out the result.</p>\n\n<p>Continuations are probably put into Scheme because of the language philosophy, Scheme is a framework enabling you to realize about any programming paradigm found in other language by defining libraries in Scheme itself. Continuations are for making up your own abstract control structures like 'return', 'break' or to enable declarative programming. Scheme is more 'generalizing' and begs that such constructs should be able to be specified by the programmer too.</p>\n"}]
['https://Stackoverflow.com/questions/34155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2797/']