liveBook · Manning

lazyUnit

As explained in Functional Programming in Scala, Second Edition

lazyUnit is a book-defined Par operation that accepts a by-name value and constructs a parallel computation for evaluating it asynchronously.

lazyUnit turns an unevaluated value into a Par computation marked for concurrent evaluation. It keeps two choices distinct: how computations are combined, and whether a particular computation is started asynchronously. section 7.1.3 section 7.2

def unit[A](a: A): Par[A]
def lazyUnit[A](a: => A): Par[A] = fork(unit(a))

Its definition is deliberately small: fork supplies the concurrent boundary, while unit lifts the eventual value into Par. section 7.1.3

The by-name argument matters: evaluating lazyUnit(f(a)) does not evaluate f(a) immediately. When the resulting Par is run, the computation is submitted to the executor and evaluates f(a) on an OS thread. section 7.9

Lifting an ordinary function

asyncF converts A => B into A => Par[B] with a => lazyUnit(f(a)). This provides a reusable asynchronous wrapper without exposing Future or calling run in application code. section 7.9 section 7.2.1

lazyUnit is a derived combinator rather than a primitive: it depends only on unit and fork, not on Par's representation. That separation preserves a composable, pure interface even when run ultimately uses ExecutorService and Future. section 7.1.3 section 7.2.1

How Functional Programming in Scala, Second Edition covers it

How deep it goes
Defines lazyUnit through fork and unit, then traces asyncF substitution down to executor job submission.
Examples
Uses asyncF(a => lazyUnit(f(a))) and contrasts lazyUnit(as.filter(f)) with per-element parallel filtering.
What you can do after
Build it from scratch as a derived combinator and apply it to lift A => B into asynchronous Par-producing functions.
How it connects
Connects Par, unit, fork, run, asyncF, ExecutorService, Future, parMap, and parFilter.

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.