resource on translating imperative programs to functional programs I'm not asking this question for the purpose of any particular project. Rather, I'm trying to understand how to translate non-trivial programs in imperative style to functional style. By functional program/style I mean one in which all objects are immutable and functions are pure, and so forth.

The only example I've seen so far of translating imperative code to functional code is for highly specific and simple code. In particular, the example that seems to be used a lot is the factorial function, and translating iteration into recursion:

//imperative -- iteration
int factorial (n)
   for i=1;i&lt;n;i++
      x=x*i;
   end for
   return x;

//functional -- recursion
int factorial (n)
    if (n==1) return 1; else return factorial (n-1) * n


However, this is such a specific example of a function (the factorial), that it doesn't make it clear to me how in general to translate core constructs in imperative style to functional style. e.g. can we always translate a for loop into recursion?

I'm looking for a comprehensive textbook or other resource that in generality shows how to translate imperative code to functional code


How do we translate the basic building blocks of imperative code to functional code? Can we even do this in general? 
How do we translate some examples of not-completely-trivial (e.g. not the factorial function) programs?
Especially interesting, are there fully general automated algorithms for doing these translations? Are they actually used? I can imagine that some compilers do something like this.
(perhaps also interesting, the opposite, translating functional code to imperative code.)
There probably are automated ways of doing it, but the result will be a unreadable mess. You have to understand what the imperative program is doing and rethink it as a functional program. Not easy.

The point is that many imperative algorithms have a recursive idea behind them (think binary search, mergesort, quicksort, any tree walking), there it is recognizing that starting point and write it functionally.

First rule I try to impress on my students: Programs aren't for the computer's consumption, they are principally for ḧuman understanding. Humans will have to write it, and modify it if it turns out wrong (be it a bug or a change in requirements). Today the human's time is much more valuable than the computer's (How much does a computer cost? How much does it's time cost, assuming a life of two years? Take any random program, how often will it have to be run to make up for your salary of a week, if that is what it takes to make it twice as fast?).