liveBook · Manning

Map!

As explained in Julia as a Second Language

map! is a Julia mutating mapping function that writes transformed elements into a destination array.

Julia’s `map!` applies a function to each value in an input collection and writes the results into an existing destination array. Call it as `map!(f, destination, input)`: the destination is the second argument, not the third. Unlike `map`, it lets you reuse an array instead of creating a new one for each transformation. section 4.7

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

A sine-table calculation first allocates a `Float64` result array. One `map!` call fills it with radians; the next uses that same array as both input and destination to replace radians with sine values. section 4.7

When input and destination are separate, `map!` leaves the input unchanged. Reusing one array for both requires it to have the type and length needed for the output. For simpler code, consider combining transformations into one function and calling `map` once; mutation can make code harder to analyze. section 4.7

How Julia as a Second Language covers it

How deep it goes
Explains argument order and demonstrates two successive mappings, but does not develop a broader procedure for managing mutation.
Examples
Uses a sine table that converts degree values to radians, then replaces them with sine values in one array.
What it assumes
Assumes basic arrays and functions while introducing higher-order mapping through concrete collection transformations.
What you can do after
Apply it via Julia’s map! to write transformations into a destination array and, when suitable, reuse that array as input.
How it connects
Connects map! to map, higher-order functions, array allocation, and function composition.

Also explained in

Compare how 2 books explain map! →

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.