Control flow #
Imperative languages #
You should already be familiar with basic control flow in Java, in particular:
- conditional statements (e.g.
if (<condition>) {<instructions>} else {<instructions>}) switchstatements (for multiple cases),- loops (
while,for, etc.), - method calls and
returnstatements, - etc.
Most imperative languages (like C/C++, C#, JavaScript, Python, Rust, etc.) have similar constructions.
Functional programming #
Conditions #
Functional languages often provide conditional and switch-like statements that are similar to imperative ones.
In addition, a traditional feature of functional languages is pattern matching, which we will introduce in this chapter.
Iteration #
Pure functional programming does not admit loops. In particular, this is the case of Haskell.
So iteration in Haskell is primarily implemented via recursive functions.
However, Haskell also provides a convenient syntax for a limited form of iteration, called list comprehensions.
Lazy evaluation #
Functional programs tend to focus on what should be computed (rather than how), leaving more room to the compiler. In particular, an important feature of functional languages (including Haskell) is lazy evaluation, i.e.:
- the evaluation of an expression can be cached and reused,
- computations can be delayed until they are strictly required.
This is possible in the presence of pure functions.
Content #
In this chapter, we will cover:
- pattern matching in Haskell and Java,
- other ways to check conditions in Haskell (guards and conditional statements),
- list comprehensions, in Haskell only (since they do not exist in Java),
- the call stack (language independent).
Recursion will be studied in a dedicated chapter.