Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


Functional languages support this type of operation in a few different ways.

One is through constructs like Clojure's `take-while`. Instead of setting a vairable when you want to exit the loop, you define a predicate that is false when the loop should exit.

Another is through `any` and `all` (aka `some` and `every`), which work in a similar way to `take-while`, except they reduce OR or AND across the returned values from the predicate as they go.

EDIT: grammar and clarity




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: