Solution (source code)

= Solution

Capturing a <continuation> retains the destination, while the <computer memory> is supplied when that destination is eventually invoked. The required <Haskell> definitions are:

``
callcc :: (Cont a -> M a) -> M a
callcc f k s = f k k s

withc :: Cont a -> M a -> M a
withc saved p _current s = p saved s

callccPrim :: [Value] -> M Value
callccPrim [Function f] =
  callcc (\k -> f [Continuation k])

withcPrim :: [Value] -> M Value
withcPrim [Continuation k,v] = withc k (result v)
``

In `callcc`, the handler `f k` initially runs with the same current <continuation> `k`. If it returns normally, its result goes there. If it invokes `withc` with a saved <continuation>, the current destination is discarded. In particular,
$$
\boxed{\operatorname{callcc}(f)\,k\,s=f(k)\,k\,s,\qquad
\operatorname{withc}(k',p)\,k\,s=p\,k'\,s.}
$$
The primitive interface receives values, because the surrounding <call-by-value> <interpreter> has already evaluated its arguments. Thus the expression supplied as the second argument of `withc` is evaluated once, before `withcPrim` transfers its value. Wrapping that value with `result` implements precisely the remaining transfer; the primitive must not try to evaluate it a second time. Neither operation restores a saved snapshot of <computer memory>.