Translating imperative to functional code

There is a number of ways to do such a translation efficiently. First, it worth doing an SSA transform with a consequent CPS transform: this way you'd get a bunch of trivial mutually recursive functions out of an imperative code with variables and branches. Function calls (and even virtual calls) can also be CPS-ed easily, by passing a continuation parameter instead of relying on an implicit stack semantics.

Arrays can be handled the same way as variables, prior to an SSA transform all the array access should be replaced with get and update function calls, which should have an implicit copy semantics (but beware of an aliasing in this case). Same for structures.

And only for those cases where it is impossible to maintain a copying semantics you need to have this TheWorld object which should keep all the allocated objects and should be copyied entierly each time you're modifying one of them.


As SK-logic points out, you can represent you imperative program in SSA form.

However, rather than applying the CPS transform, you can directly transform the imperative SSA representation into an equivalent purely functional program in "Administrative Normal Form" -- a restricted functional language, based on the algorithm published by Zadarnowski et al.

The two languages are given by:

enter image description here

See: "A Functional Perspective on SSA Optimisation Algorithms", which gives algorithms for automatically translating programs in SSA form to ANF.