Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translating imperative to functional code

I need to write a program that will translate imperative code to pure functional style. I'm not worried about I/O - I have some solutions in mind for that - but I do need to deal with heap objects as well as local variables.

I suppose it could be done by passing a TheWorld object with every function call and return, and then optimizing from there, trying to remove that parameter from functions where it's not used etc. But is there a known better way of doing it?

like image 552
rwallace Avatar asked Jul 07 '11 05:07

rwallace


People also ask

Is functional programming imperative or declarative?

Functional programming is a form of declarative programming that expresses a computation directly as pure functional transformation of data. A functional program can be viewed as a declarative program where computations are specified as pure functions.

What are the differences between functional and imperative programming styles?

Functional vs Imperative ProgrammingFunctional Programming is a programming paradigm that considers computation as the evaluation of mathematical functions and avoids changing state and mutable data. Imperative Programming is a programming paradigm that uses statements, that change a program's state.


1 Answers

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.

like image 148
Don Stewart Avatar answered Oct 15 '22 07:10

Don Stewart