Visualize Callcc

Posted on September 2, 2022
Tags: typetheory

1 visualize continuations

   plusk
   / \   \
  2   5   k
 +----+   |
   |      |
plus(2,5) | 
   |      |
   o------o
    plus(2,5) is piped into k
def plusk(a,b,k):
  k(a+b)
def mulk(a,b,k):
  k(a*b)

plusk(2,5, λT.mulk(T,7,print))
# 2+5=7 is placed into λT 

In typical cps, the continuations are nested into the 3rd argument
Notice similarity to js except instead of nested, we can move it out into a thennable

plus(2,5).then(T => mult(T,7)).then(o => console.log(o))

      plusk
     / \   \
    2   5   λT.mulk
   +--&--+   /  \   \
      |     T    7  print
      |     |    |      |
plus(2,5)   |    |      |
      |     |    |      |
      o--#--o    |      |
         |       |      |
         |       |      |
  T:=plus(2,5)   |      |
         +----&--+      |
              |         |
      mul(plus(2,5),7)  |
              |         |
              o----#----o   

+--&--+ stands for unwrap, ex: unwrap plusk to plus
o--#--o stands for pipe, ex: pipe plus(2,5) into λK
  1. plusk is unwrapped to plus and @ to (2,5) RESULT: plus(2,5)
  2. continuation of plusk, λK.mulk(a,7,print) is @ to plus(2,5) RESULT: mulk(7,7,print)
  3. mulk is unwrapped to mul and @ to (7,7) RESULT: mul(7,7)
  4. continuation of mulk, print is @ to mul(7,7)

The continuation k is applied @ to (2,5)

1.1 Example 2

  • Notice all the action is being done in the argument of the function.
def Negk(a,k):
  k(-a)

Negk(3,λa.Negk(a,λb.Negk(b,return)))

#same as above but formatted differently
Negk(3,
      λa.Negk(a,
                λb.Negk(b,return)
              )
    )

2 Investigating callcc

   +
  / \
 2   @
    /  \
callcc  lambda cont.
         |
         @
        / \
      cont 3
(+2 (callcc (lambda (cont) 3 )))
> 5
(+ 2 (callcc (lambda cont (cont 3) 6 )))
(+ 2 3)

3 Continuation return beta

4 The only type that really matters it the first a

5 Eventhandlers and Callback functions

event :: A
callback :: A -> B
Eventhandler :: (A -> B) -> A -> K

def Eventhandler(callback,event)
{..callback(event)... }