Skip to content

deprecated map function

apaj edited this page Jan 1, 2024 · 1 revision

Q: In the following code; what does the 2nd term(beyond .map operator) on the left side of equation really do?

val misa = BigInt(0) | isa_string.map(x => 1 << (x - 'A')).reduce(_|_)

A: The map applies the same operation to every element. The reduce then applies an operator to all pairs of outputs from the map. So, this statement does the following:

The ".map(x ==> " is syntax of the map function. It indicates that 'x' is the variable that represents the character taken from the string.

For example, take the string "IMAFDC"

In this case, isa_string has the value "IMAFDC". Now, the map operator applies to each individual position of the string.

I - 'A' followed by left shift

M - 'A' followed by left shift

and so on. So there is a separate value generated for each position in the string. The subtraction turns the character in the string into a number that represents the character's position in the alphabet. The shift sets a bit in that numeric position.

Then, the .reduce(_|_) is applied. The underscores are place holders, and the vertical bar in the middle is the operation. So, this means apply the vertical bar to each neighboring pair of values generated by the map. Vertical bar is bitwise OR operator.

Here is the result:

1 << ('I' - 'A') | 1 << ('M' - 'A') | 1 << ('A' - 'A') | 1 << ('F' - 'A') | 1 << ('D' - 'A') | 1 << ('C' - 'A') | 1 << ('I' - 'A') | 1 << ('M' - 'A') | 1 << ('A' - 'A') | 1 << ('F' - 'A') | 1 << ('D' - 'A') | 1 << ('C' - 'A')

So, it subtracts the ASCII values, which generates a numerical distance between the characters. Then it shifts a "1" to that value's bit position. The result is an int that has a bit set for each character present in the string.

Clone this wiki locally