Back to Projections

Functions · Projections · Practice Question

When to Use a Projection vs a Lambda

Sign in to track your progress

Question

For each of the following tasks, decide whether a projection or a lambda is the cleaner solution, implement both, and explain your choice.

  1. A function that adds 5% to any number
  2. A function that pads a string to 12 characters, and one that formats a number as a string padded to 12 characters
  3. A function that filters a list of prices to those within a given range, where the range is set at definition time to 50.0–150.0

Solution

/ 1. Add 5% — projection wins (simple scaling, one fixed arg)
add5pct:  1.05*              / projection
add5pctL: {x * 1.05}        / lambda — more verbose for no gain

add5pct 200.0    / 210f

/ 2. Pad a string to 12 chars — projection wins
pad12:  12$                 / projection
pad12L: {12$x}              / lambda

pad12 "hello"   / "hello       "

/ ... but formatting a *number* needs two steps (string, then pad) — lambda wins
fmt12: {12$string x}
fmt12 3.14      / "3.14        "

/ 3. Range filter — lambda wins (logic is non-trivial to read as projection)
inRange:  {x where (x >= 50.0) and x <= 150.0}
inRangeP: {x where between[50.0; 150.0;] each x}   / uses projection internally

inRange 30.0 75.0 110.0 200.0   / 75 110f

Explanation

Projection wins when fixing one argument to a constant transforms a general function into something with an obvious, self-documenting meaning:

1.05*        / "multiply by 1.05" — reads as a description
12$          / "pad to 12" — equally clear

A lambda adds noise here without adding clarity.

Lambda wins when the logic involves multiple operations that would be unclear if written point-free, or when the function combines its arguments in a non-trivial way. A reader scanning {x where (x >= 50.0) and x <= 150.0} can follow the logic step by step; a projection-only version would be significantly harder to read.

Rule of thumb:

  • If you can describe the projected function in a handful of words that match the code exactly (double, above500, pad to 12), a projection is appropriate. Once a second step is needed (as in fmt12), a lambda is usually clearer.
  • If describing it requires explaining the relationship between inputs and outputs, a lambda is clearer.