liveBook · Manning

replicateM

As explained in Functional Programming in Scala, Second Edition

replicateM is a monadic combinator that repeats an effectful computation a specified number of times and collects the results in a monadic list.

replicateM repeats an effectful value n times and combines the results into one monadic list. The monad determines how repetition combines: List explores choices, while Option propagates failure. section 11.3 section 11.7

A direct recursive definition handles the empty case with unit(Nil) and prepends each result with map2. A more reusable definition creates n copies and delegates the work to sequence, avoiding duplicated traversal logic. section 11.7 section 11.3

def replicateM[A](n: Int, fa: F[A]): F[List[A]]

The generic signature makes the two roles explicit: n controls repetition, and F controls the effect and combination behavior. section 11.3

Concrete behaviors reveal what the abstraction means:

  • With List(1, 2), replicateM(2, ...) produces four ordered lists: every choice at one repetition combines with every choice at the next. section 11.7
  • With Some(x), it returns Some containing n copies of x; with None, positive repetition returns None, while zero repetition returns Some(Nil). section 11.7
  • With State, repeated actions can thread and update state while collecting each action’s result; with IO, repeated reads become an IO[List[String]]. section 11.7 section 13.2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines the signature, recursive and sequence-based implementations, and concrete List, Option, State, and IO behavior.
Examples
Uses list choices, Option success and failure, repeated State increments, and ten IO console reads as examples.
What it assumes
Assumes familiarity with map2, sequence, traverse, unit, and monadic values while reinforcing their common abstraction.
What you can do after
Apply it via a Monad instance to repeat computations while preserving the effect type and collecting their results.
How it connects
Connects Monad, sequence, traverse, map2, List, Option, State, Parser, Gen, and IO.

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.