Immutability
When you write a definition in your code, like:
flagisn't a keyword, it's just a normal variable name.
or
you cannot later write in the same codebase:
or
This is because all Haskell values (including functions) are immutable. To write a = b is simply to state that a is a name for b, and that wherever you see a in the code, it can be replaced by b.
For example, given the definition swap (a, b) = (b, a), whenever you see swap (a, b) in your code, it can be replaced by (b, a).
Loops and mutation¶
In Python you could write:
This imperative approach isn't usually the natural one in a functional language.
Note
There are fairly simple ways to write code like this, e.g.:
import Control.Monad (forM)
import Control.Monad.State (execState, modify)
loop = flip execState 0 $ forM [0..9] $ \i -> -- (1)!
modify (+i)
- Here,
forMandmodifyare just regular functions, not built-in control-flow operators.
However, there's often a simpler solution that avoids thinking about loops and state altogether.
Instead, you could write:
See this section for how this kind of approach scales to more complex situations.