call/cc in Lua - Possible?

前端 未结 6 530
小鲜肉
小鲜肉 2020-12-13 19:46

The Wikipedia article on Continuation says:
\"In any language which supports closures, it is possible to write programs in continuation passing style an

6条回答
  •  难免孤独
    2020-12-13 20:34

    There are two prerequisites to manually implement call/cc per the Wikipedia quote:

    1. the language must support closures
    2. you must write your program in continuation passing style (CPS)

    I suspect you will not like #2.

    To write your program in continuation passing style:

    1. Every function must take a continuation argument
    2. Functions must return by calling their continuation

    So, using k as the name of the continuation argument, a function would look like:

    function multiplyadd(k, x, y, z) return k(x * y + z) end
    

    The toplevel might use print as its continuation, so invoking multiplyadd at top level would look like:

    multiplyadd(print, 2, 4, 1)
    

    With that scaffolding we could define call/cc as

    function callcc(k,f) return f(k,k) end
    

    Note that the above multiplyadd actually cheats since * and + are not in CPS. It is very tedious to add all the operators in CPS form, replace all the Lua library functions with CPS equivalents, and translate/generate all your code to CPS; see details here.

提交回复
热议问题