I've got a general question about functional programming vs imperative programming. I am a hobby programmer implementing some engineering problems with C#. You always here a lot concerning the benefits of functional programming. Maybe I get it totally wrong, but I can't understand why functional programming does not result in waste of computation time compared to a carefully designed imperative program:
Suppose I have the following scenario, where two class properties are based on a heavy computation and a lightweight computation,respectively. Furthermore, suppose the lightweight result is dependent on the result of the heavy calculation, but is only necessary from time to time. A pseudo-C# implementation might look like this:
public class Class
{
public double? HeavyComputationVariable { get; set; }
public double LightComputationVariable { get; set; }
void CalcHeavyComputation(double input)
{
//Some heavy time consuming computation here
HeavyComputationVariable = resultOfHeavyComputation;
}
void CalcLightComputation()
{
if(HeavyComputationVariable == null) CalcHeavyComputation();
//Some light computation
LightComputationVariable = HeavyComputationVariable*resultOfLightComputation;
}
}
So in this example when calling the lightweight computation, the heavy computation is only done, if not performed before. So the lightweight computation does not result in a recalculation of the complicated variable per se, but only if necessary.
As I understand functional programming I would implement a function for the complicated calcualtion and one for the simple one:
fHeavy (someInput) return complicated;
fSimple (fHeavy(someInput)) return simple*fHeavy;
Maybe, the example is not to well defined. But I hope one can understand the general question. How do I avoid intensive and unneccessary recalculation if not providing some imperative control to check, if the recalculation is really necessary.