Maps and filters are typical for functional languages. A map is a function of the form map(func, coll)
, where func
is a (often anonymous) function that is successively applied to every element of the coll
collection, so map returns a new collection. Some examples are as follows:
map(x -> x * 10, [1, 2, 3])
returns[10, 20, 30]
cubes = map(x-> x^3, [1:5])
returns[1, 8, 27, 64, 125]
Map can also be used with functions that take more than one argument. In this case, it requires a collection for each argument, for example, map(*, [1, 2, 3], [4, 5, 6])
works per element and returns [4, 10, 18]
.
When the function passed to map requires several lines, it can be a bit unwieldy to write this as an anonymous function. For instance, consider using the following function:
map( x-> begin if x == 0 return 0 elseif iseven(x) return 2 elseif isodd(x) return 1 end end,[-3:3])
This function returns [1,2,1,0...