MAP
Description
MAP
is used to perform the same action on each individual value in a list.
That way, it lets you transform a list of values into another list, which comes in especially handy when working with user-provided values like nationalities
or sources_of_income
.
Map comes in two versions:
A functional version
MAP(<list>, <expression with CURRENT>)
where the keywordCURRENT
inside the expression will be replaced with the current element of the list.A method version that you call on the list as
<list>.map(<var> => <expression with var>)
that can be called directly on the list
For readability, we recommend using the method version whenever you can.
Example: Double some numbers
We call map on a list, here the list of numbers
[1, 2, 3]
.The argument within map is the function we use on each element, here
number * 2
. It takes each number from that array and multiplies it by 2. With each calculation, the variablenumber
is replaced by the next value from the list, until the last value has been dealt with. We chose the name to benumber
as the variable before=>
. We could have also chosenn
orx
if we would have wanted to.Since a SUM operator encloses the MAP function, the final output will be the added total of all doubled values - in this case: 12.
The calculations step-by-step:
1 * 2 = 2
2 * 2 = 4
3 * 2 = 6
The intermediate result of MAP is the new list [2, 4, 6]
SUM adds these new values: 2 + 4 + 6 = 12.
Example: Get total income
Here we use the functional version:
we assume a user selects the relevant sources of income out of
salary
,capital_gain
, andgifts
the user then fills out the information with predictable keys, like
income_salary
,income_capital_gain
, andincome_gifts
.with
get_attr
, these values are accessed and added up. If a value has no entry from the user, its default will be 0.
The calculations step-by-step:
the first argument of
MAP
isself.sources_of_income
.let's say the user has filled out 10,000 under
income_salary
, 5000 underincome_capital_gain
, and nothing underincome_gifts
.the values of the first argument, which
MAP
will run over in succession, are salary, capital gain, and gifts.in the first iteration, the first argument of
MAP
,self.sources_of_income
, gets the valuesalary
.Next,
CURRENT
in the second argument takes that valuesalary
from the first argument.CONCAT
attaches it to the string "income_".This means the first run of the
MAP
function looks like this:MAP(self.salary, get_attr(income_salary)
Using the values the user has provided, the
MAP
function will store 10,000 as the first value of its output.MAP
then starts its work over on the second value in the list capital gain.Once
MAP
has run over all values in the list, it’s intermediate output will be[10000, 5000, 0]
Since
MAP
is wrapped in aSUM
function, the final output yields 15000.
Last updated