Skip to main content

Mojo function

map

map[origins: OriginSet, //, func: fn(Int) capturing -> None](size: Int)

Maps a function over the integer range [0, size). This lets you apply an integer index-based operation across data captured by the mapped function (for example, an indexed buffer).

For example:

from algorithm import map

def main():
    # Create list with initial values to act on
    var list = List[Float32](1.0, 2.0, 3.0, 4.0, 5.0)

    # Function applied to the value at each index
    @parameter
    fn exponent_2(idx: Int):
        list[idx] = 2.0 ** list[idx]

    # Apply the mapped function across the index range
    map[exponent_2](len(list))

    # Show results
    for idx in range(len(list)):
        print(list[idx])

Example output:

2.0
4.0
8.0
16.0
32.0

Parameters:

  • โ€‹origins (OriginSet): Capture origins for mapped function.
  • โ€‹func (fn(Int) capturing -> None): Parameterized function applied at each index.

Args:

  • โ€‹size (Int): Number of elements in the index range.

Was this page helpful?