Open In App

Apply operations on a collection in Julia – map() and map!() Methods

Last Updated : 26 Mar, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The map() is an inbuilt function in julia which is used to transform the specified collection by using specified operation to each element.

Syntax: map(f, c…)

Parameters:

  • f: Specified operation.
  • c: Specified collection.

Returns: It returns the transformed elements.

Example:




# Julia program to illustrate 
# the use of map() method
  
# Getting the transformed elements.
println(map(x -> x * 2, [5, 10, 15]))
println(map(+, [1, 2, 3], [10, 20, 30]))
println(map(x -> x / 5, [5, 10, 15]))
println(map(-, [10, 20, 30], [1, 2, 3]))


Output:

[10, 20, 30]
[11, 22, 33]
[1.0, 2.0, 3.0]
[9, 18, 27]

map!()

The map!() is an inbuilt function in julia. This function is same as map() function but stores the result in destination rather than a new collection. The destination must be at least as large as the first collection.

Syntax:
map!(function, destination, collection…)

Parameters:

  • function: Specified operation.
  • destination: The destination where the result get stored.
  • collection: Specified collection.

Returns: It returns the transformed elements.

Example:




# Julia program to illustrate 
# the use of map !() method
  
# Getting the transformed elements.
a = zeros(3);
map !(x -> x * 3, a, [1, 2, 3]);
println(a)
  
b = ones(3);
map !(x -> x / 3, b, [3, 6, 9]);
println(b)


Output:

[3.0, 6.0, 9.0]
[1.0, 2.0, 3.0]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads