0
$\begingroup$

In this question, I asked about a reference for translating imperative code to functional code. I want to ask a more specific question here.

How, in general, do we translate into functional style, a statement of the form:

if (cond) then
    do x;
else
    do y;

I know that functional languages have if-then-else statements but the expressions are only allowed to be pure. Is there a general way of doing this translation?

$\endgroup$
1
  • $\begingroup$ Recursively, translate the do x and do y first. $\endgroup$
    – vonbrand
    Mar 3 '20 at 2:30
2
$\begingroup$

As was mentioned in comments to the other question, any imperative program with side-effects can be trivially transformed into a pure program by simply lifting it into the IO monad, for example.

Or, by implementing an interpreter for an imperative language in a pure language.

That is, however, not good functional design. (Although, embedding a Domain Specific Language for side-effects into a program to provide limited and isolated side-effects in clearly demarcated sections of the code could certainly be considered good design.)

There is no general way of doing this translation. You need to understand what the original problem is that the program is solving, then solve that problem in a functional manner.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.