Live data from Hacker News

Ask HN: Why do functional programmers hate loops (for, while, etc.)?

news.ycombinator.com

51–60 of 73 posts

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#51
Loops have an implicit ordering, and thus are inherently non parallelizable at face value. map can enable easy parallelization, wether with SIMD or threads or GPU warps or Spark nodes. It's just a construct that specifies less about execution, and thus leaves more room for the compiler/runtime.

This construct is natural with functional programming's abstraction: the function. You encapsulate basic behavior in functions, and then shape the data flow with map(fn)/reduce()/flatmap(). If you really need an index, you can still have them with number ranges, zipWithIndex, etc. If you do use them, you are explicitly reintroducing ordering into your program and lose the parallelism.

This is just a finer level of detail wrt accidental vs essential complexity. IMHO it is always better to specify less about your program, and stick to what you must encode and only that.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#52
post #6

Well, how to calculate sum from 1 to 5000 ? Instead of looping from 1 to 5000, you define the relationship instead: sum(1,n) = 1 + n + sum(2, n-1). Isn't this clearer to understand problem first, instead of just looping ?

If i ask you to add from 1 to 10 , is that how you add ? 1 + 10 + let_me_add_from2_9 ? So yeah, not at all natural.

You easily see it's (1+10)*10/2, so you'll get to 55 way faster this way. Way more natural.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#53
There are many reasons. Here's one.

FP is built on theory. The language constructs follow the theory. Part of the theory is algebraic data types which allow for structural recursion. Fancy words that basically come to mean the structure of the code that manipulates data follows the structure of the data it manipulates.

Take a loop typical loop

    var someResult = 0;
    for(i = 0; i 
This uses the natural numbers (integers 0, 1, 2, ...) [Some people define the naturals to start at 1. This isn't important.]

The natural numbers are an algebraic data type and therefore allows for structural recursion. For the natural numbers the structure is, a natural number N is either:

* 0; or

* 1 + M, where M is a natural number

So you write out your structural recursion skeleton

    def loop(n) =
      n match {
        case 0 => 
        case n => loop(n - 1)
      }
This exactly follows the structure of the data, including the recursion.

Then you fill in the missing pieces

    def loop(n) =
      n match {
        case 0 => 0
        case n => updateResult(n, loop(n - 1))
      }
Job done. The theory guides us to the solution. No loop needed.

A lot more here: https://www.creativescala.org/creative-scala/recursion/

The main other reason is equational reasoning aka reasoning using substitution. Described here: https://www.creativescala.org/creative-scala/substitution/

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#54

It's kind of silly IMHO. Recursion has plenty of "state", it's added on the stack before each function call. So under the hood it's all stateful. But instead of e.g. a nice simple counter variable, you've got an ever growing pile of stack frames - with hopefully some compiler shenanigans to eliminate them and convert it to a counter internally.

Just as stateful language can perform tail call optimization, so can functional languages.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#55
post #4

To some extent for while loops are a matter of taste. But the issue is that unless you have mutable variables, you cannot use typical imperative control variables . So something like: bool done = false; while (!done) { ... } makes no sense unless you have some way of setting `done = true`; which is not possible in purely functional languages like Haskell.

This construct is totally possible in Haskell, one common way of achieving it is to store the 'done' boolean in a State monad.

The really funny thing is that the while loop itself is not built-in to Haskell but you can write it yourself as a function. In other languages (non-lazy) this sort of thing is not possible without resorting to macros or other tricks, because laziness is required in order to define the correct semantics for conditionals.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#56
In JS, functions like filter/map/reduce can help when you try to write immutable code because you only work with the arguments, and return an output value. You don't have to define an empty/temporary array first, and fill it up in your regular for-loop for example.

I don't 'hate' loops, I still use them sometimes. Personally I just try to avoid them (in JS) because I feel like I can solve my problem without any side-effects. It's something less to think about. It's nice when the logic/variables for a function are encapsulated entirely inside that function. It also makes it easy to extract functions so you can re-use them elsewhere.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#57
Writing what could be a loop in functional style instead allows you to say what you want done without saying how to do it. The results is faster to write, easier to read, and leaves the compiler free to find a good way to do it (e.g. maybe in parallel).

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#58

Fpers, lispers, tdders, clean coders, etc There are many religions in programming world Just get familiar with them, take what is sane and avoid the rest Extremas are rarely the best

>Extremas are rarely the best

Well, they are either the best or the worst (≧▽≦)

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#59
post #48

It's the fundamental difference between declarative and imperative programming. Loops conflate two different questions: "what do you want?" and "how do you want it done?" If I write (Haskell): map (+1) list_of_numbers I have expressed only that I want one added to every number in a list. Whereas if I write (C): for (size_t i = 0; i I have expressed both that I want one added to every number in the array and I have al…

You are too the point. With the nitpicky addition, that Functional Programming prefers things like looping as functions to generate a homogenous construct which you can play with. There is no reason why loop cannot be expressed with some keywords and focus on the WHAT and hiding the HOW.

Re: Ask HN: Why do functional programmers hate loops (for, while, etc.)?

#60
In functional programming, we value immutability and the notion of pure functions, meaning their outputs depend solely on their inputs without any side-effects. This is one of the reasons why we often lean away from traditional loop constructs of imperative languages, which are typically stateful and can produce side effects.

Instead of using loops, we often use higher-level functions like map, filter, and reduce. These functions allow us to focus more on the "what" (the operation being performed) rather than the "how" (the control flow). It's like saying, "transform each item in this list," as opposed to, "start here, do this to each item until you get to the end."

And when we do need to perform repetitive operations, we tend to use recursion rather than loops. Recursive solutions don't require mutable state and are easier to reason about, especially when the logic gets complex.

Lastly, mutable state, which is common in loops, can lead to issues such as race conditions in multithreading or distributed computation environments. The minimized state changes in functional programming makes it often more suitable for these scenarios.

So, it's not really about "hating" loops, but more about choosing the constructs that align better with the philosophy and goals of the functional paradigm.

To conclude, In order to use imperative looping constructs, you have to violate referential transparency and immutability, which are the hallmarks of functional programming.

https://en.wikipedia.org/wiki/Referential_transparency?usesk...

https://en.wikipedia.org/w/index.php?title=Immutable_object&...

Post reply on HN