liveBook · Manning

Mutating function

As explained in Julia as a Second Language

A mutating function is a function that can modify one or more of its input objects rather than producing all results in new objects.

A mutating function can modify an input object instead of returning every result in a new object. Julia marks many such functions with !, as in push! and map!. section 4.7

Use mutating functions when:

  • map! writes transformed values directly into a preallocated destination array, reducing repeated allocations. section 4.7
  • push! adds an element to an existing array and potentially alters the array passed as its input. section 4.7
  • Prefer a single combined transformation when readability and data-flow analysis matter more than in-place updates. section 4.7

Transform values in place

Preallocate storage, then reuse it for successive mappings: result = zeros(Float64, length(0:15:90)); map!(deg2rad, result, 0:15:90); map!(sin, result, result). The final call uses the same array as input and output. section 4.7

result = zeros(Float64, length(0:15:90))    #1
map!(deg2rad, result, 0:15:90)              #2
 map!(sin, result, result)                  #2

Shows the compact Julia pattern for allocating a destination and applying map! transformations in place. section 4.7

How Julia as a Second Language covers it

How deep it goes
Explains ! naming, input modification, map! destinations, and readability trade-offs, but stops short of deeper mutation internals.
Examples
Demonstrates sine-table transformations with map!, array construction with push!, and a custom transform function.
What it assumes
Assumes functions, arrays, iterable collections, and function arguments; demonstrates these ideas through compact examples.
What you can do after
Apply map! and push! deliberately while recognizing their effects on input arrays and readability.
How it connects
Connects mutation with arrays, map, map!, push!, higher-order functions, memory allocation, and data-flow analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.