Hacker News new | ask | show | jobs
by dnautics 2074 days ago
I think also we have learned why map/reduce or functional recursion is better than for loops - because the state of the system is explicitly contained; with a for loop you could literally mutate anything in scope, so the cognitive burden to understanding the process is potentially unbounded; with map, your state between iterations is nothing, and with reduce, it's strictly what you can stash in your accumulator.

I was laughing at myself the other week because I was having so much trouble writing a for loop because I had gotten used to the explicitness of the functional iteration operatiors

3 comments

> with a for loop you could literally mutate anything in scope

That depends on the language. In Elixir for instance, you can't mutate anything. Elixir does have 'for comprehensions', and there are things that you can express very clearly in what is effectively a for loop that would be much harder to read in a chain of iterators.

That's not strictly true. You could use the process dictionary to keep hidden mutable state in the for loop. Don't do this.
Same here. I maintain around 30 small-to-medium size Ruby projects and in all that code I can only remember writing a single for loop. On the plus side, I am highly confident that code works right since I spent so much time thinking about it!
Mutation is the scapegoat here. It's all about expressing intent.

Eg: I would take a count_if(condition) function over filtering and then taking the length.