Suppose I have the following functions:
function f(x) { return x + 1; }
function g(x) { return x * 2; }
function h() { return 5; }
How could I convert the expression f(g(h()))
into continuation passing style? I know that h
is transformed to:
function h(ret) { ret(5); }
However, I don't know how to convert the expression f(g(h()))
into CPS.
In addition, what if f
takes 2 arguments instead of 1? How would that look in CPS?
Furthermore, what if f
and g
don't take any arguments at all? How does that look in CPS?
Continuation passing style is really simple. For example, suppose you have the following functions which you want to convert to CPS:
Written in CPS:
When
f
takes two arguments:In the case
f
andg
don't take any arguments, they are not functions (in the mathematical sense of a function). Hence, they are just constants:There is no way to compose constants using CPS. Think about it:
f(g(h()))
doesn't really make any sense whenf
andg
don't take any arguments. It's better to just writeh(), g(), f()
.Continuation passing style is especially nice when used in conjunction with currying:
Hope that helps.