DEV Community

Discussion on: Stop Telling People For Loops Are Bad

Collapse
 
jbristow profile image
Jon Bristow • Edited

In lazily evaluated languages,

[1,2,3,4].map(add2).filter(isDivBy(3)).reduce(+) doesn’t do anything until you ask for it.

Another example:
x := [a,b,c].map(g).map(f) does nothing, but calling x[2] will return f(g(2)) (doing the calculation and caching it when called)

This allows you to work with things like infinite (or practically infinite) without the cost of running your calculations on infinite things.

It also allows the compiler/interpreter to optimize the f(g(x)) into a new function f•g(x). Example: f(x)=x+2; g(x)=x / 4; h(x) = (x/4)+2 Then f(g(x))==h(x) (coincidentally, this is why encrypting something multiple times is technically equal to doing it once with a different function)

Now that’s not to say if you know h ahead of time that you shouldn’t just write h. BUT, if you have a bunch of functions that do f, it’s often easier to reason about if you extract the logic that’s different and define g, g’, g'', g''', etc and just pass them in.