liveBook · Manning

Imperative programming

As explained in Functional Programming in Scala, Second Edition

Imperative programming is a programming paradigm that expresses computation as an ordered sequence of statements that may modify program state.

Imperative programming expresses computation as an ordered sequence of statements that may modify program state. Functional programming is not its opposite: State actions can read and return state without side effects, making the resulting programs referentially transparent and amenable to equational reasoning. section 6.6

State actions preserve imperative sequencing by passing each result into the next computation. Operations such as map and flatMap propagate state explicitly, while a for-comprehension restores a readable imperative mood without changing the underlying program. section 6.6

Sequencing random state

A random computation can obtain x, obtain the next y, generate a list of length x, and return elements reduced modulo y. The for-comprehension exposes those steps as named bindings while retaining a pure State computation. section 6.6

val ns: Rand[List[Int]] =
  for
    x <- int              #1
    y <- int              #2
    xs <- ints(x)         #3
  yield xs.map(_ % y)     #4

Shows imperative-looking sequencing of State actions: retrieve two integers, generate a list, then transform its elements. section 6.6

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines ordered state-modifying statements, explains pure state threading, and demonstrates sequencing while deferring broader equational reasoning.
Examples
Uses random-number sequencing, list generation, modulo transformation, and stateful candy-machine simulation.
What it assumes
Assumes familiarity with State actions, map, and flatMap while defining imperative programming through ordered state-modifying statements.
What you can do after
Apply it via State actions and Scala for-comprehensions to sequence stateful computations without side effects.
How it connects
Connects imperative programming with functional programming, referential transparency, State actions, IO, and ST.

Also explained in

Compare how 14 books explain imperative programming →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in Scala, Second Edition. The section links point to the parts of the book it draws on.