Think of a coffee machine. The automated kind with water, milk, coffee and chocolate inside. That is lazy evaluation.
In such a coffee machine we have a ‘store’ of water, milk, coffee and other ingredients but these are not mixed and processed to produce a specific type of coffee till the request comes in. This is Lazy Evaluation.
What the machine does not do is keep the milk froth ready, keep the water boiling etc. this would be Greedy Evaluation.
So what:
Lazy evaluation can help save time, cost, and resources. We do not need to use up memory to store intermediate results as the whole processing becomes one large task execution graph. This is applicable for any area where there are a set of tasks that need to be combined based on incoming request.
From the coffee shop, to amazon warehouses, to your software program.
Looking at software:
Greedy Evaluation…
Milk_froth = milk_froth_maker(Milk)
Boiled_water = water_boil(Water)
Coffee_powder = grind_beans(CoffeeBeans)
if request = ‘americano’:
Coffee = make_americano(Boiled_water, Coffee_powder)
else if request = ‘cappucino’:
Coffee = make_cappucion(Boiled_water, Coffee_powder, Milk_froth)
# water is boiled, milk is frothed, coffee is powedered
# but wait we were asked for an americano no milk!
Lazy Evaluation…
milk_froth_maker()
water_boil()
grind_beans()
if request = ‘americano’:
Coffee = make_americano(water_boil(Water), grind_beans(CoffeeBeans))
else if request = ‘cappucino’:
Coffee = make_cappucion(water_boil(Water), grind_beans(CoffeeBeans), milk_froth_maker(Milk))
# nothing is actually done till the request comes in
# therefore we save energy and cost