Search code examples
functional-programmingclojureschemecontinuations

Continuations in Clojure


I read somewhere where rich hickey said:

"I think continuations might be neat in theory, but not in practice"

I am not familiar with clojure.
1. Does clojure have continuations?
2. If no, don't you need continuations? I have seen a lot of good examples especially from this guy. What is the alternative?
3. If yes, is there a documentation?


Solution

  • When talking about continuations, you’ll have to distinguish between two different kinds of them:

    • First-class continuations – Continuation-support that is deeply integrated in the language (Scheme or Ruby). Clojure does not support first-class continuations.

    • Continuation-passing-style (CPS) – CPS is just a style of coding and any language supporting anonymous functions will allow this style (which applies to Clojure too).

    Examples:

    -- Standard function
    double :: Int -> Int
    double x = 2 * x
    
    -- CPS-function – We pass the continuation explicitly
    doubleCPS :: Int -> (Int -> res) -> res
    doubleCPS x cont = cont (2 * x)
    
    ; Call
    print (double 2)
    
    ; Call CPS: Continue execution with specified anonymous function
    double 2 (\res -> print res)
    

    Read continuation on Wikipedia.

    I don’t think that continuations are necessary for a good language, but especially first-class continuations and CPS in functional languages like Haskell can be quite useful (intelligent backtracking example).