[ prog / sol / mona ]

prog


Inverse Recursion?

5 2020-05-14 01:56

>>2,3

Try doing the transformation yourself before looking at the next code snippet! This is what I got:

This is actually kinda crazy. I was really struggling to rewrite this function so I ended up thinking I might be able to cheat a little. I ended up rewriting this function iteratively, reversing the iteration of the helper function, and then inlining that function with some partial evaluation. I knew this process wouldn't work in the general case because reversing the iteration of the helper function while preserving meaning is not always trivial/possible:

(define (fib-cps n c)
  (cond ((zero? n) 0)
        ((= n 1) ((c 1) 0))
        (else (fib-cps (- n 1) (lambda (x) (lambda (y) ((c (+ x y)) x)))))))

(fib-cps 20 (lambda (x) (lambda (y) x)))
=> 6765

I then read the remainder of your posts to discover you mention all of these things! I was completely unaware of defunctionalisation, which seems to be a very powerful explanatory device; it's like making a little mini-interpreter as needed for higher order functions. So if I understand correctly CPS functions are higher-order iterative function, which are isomorphic with normal iterative functions through (de)functionalisaton, and all recursive functions are in turn isomorphic with CPS functions because they can be rewritten (right?). CPS and iterative functions both make the stack explicit, and in this way iterative functions are just a special case of CPS functions where the continuation is not higher order, this is why iterative functions through TCO don't expand the stack. Anyway I appreciate the effort you've expended in these posts, they've really helped me out.

9


VIP:

do not edit these