This sounds really interesting, but I'm getting a bit confused trying to apply it to a simpler problem. Say I start with this recursive function to filter a list:<p><pre><code> def my_filter_recursive(l, f):
if l:
x, *xs = l
if f(x):
return [x] + my_filter_recursive(xs, f)
else:
return my_filter_recursive(xs, f)
else:
return []
</code></pre>
In Continuation Passing Style it becomes:<p><pre><code> def my_filter_cps(l, f, kont):
if l:
x, *xs = l
if f(x):
my_filter_cps(xs, f, lambda y: kont([x] + y))
else:
my_filter_cps(xs, f, lambda y: kont(y))
else:
kont([])
</code></pre>
Then I think with defunctionalisation it becomes:<p><pre><code> def my_filter_defun(l, f, kont):
if l:
x, *xs = l
if f(x):
my_filter_defun(xs, f, KontAdd(x, kont))
else:
my_filter_defun(xs, f, KontSkip(kont))
else:
kont.apply([])
class KontAdd:
def __init__(self, var, kont):
self.var = var
self.kont = kont
def apply(self, acc):
self.kont.apply([self.var] + acc)
class KontSkip:
def __init__(self, kont):
self.kont = kont
def apply(self, acc):
self.kont.apply(acc)
class KontPrint:
def apply(self, acc):
print(acc)
</code></pre>
Is that right? It seems that we've basically just moved the recursion from one place to another.