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?

asked Mar 2, 2020 at 5:44
$\endgroup$
1
  • $\begingroup$ Recursively, translate the do x and do y first. $\endgroup$ Commented Mar 3, 2020 at 2:30

1 Answer 1

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.

answered Mar 8, 2020 at 9:00
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.