Swift: map() can be taxing


I've been told that Haskell, a strict functional programming language, where functions like map(), flatMap(), and so on, are prominent, is largely used in finance and the stock market. It makes sense, therefore, that financial analogies (and allusions to spreadsheets) prove useful in understanding functions inherited from functional programming by Swift.

The map() function is no exception here, and we might consider a column of net prices that need a parallel column of gross prices (once tax has been added).
let netPrices = [10.67,45.50,32,16,5]
let taxRate = 1.2
let grossPrices = netPrices.map{netPrice in netPrice * taxRate}
grossPrices // [12.804, 54.6, 38.4, 19.2, 6]
And this extends yesterday's analogy of a bank statement, which was used to consider the reduce function.

Beyond the Financial

But working with numbers needn't restrict us to sums. The map() function can also be used to make quick work of manipulating byte arrays:
let byteArray:[UInt8] = [10,45,32,16,255]
let arrayNOT = byteArray.map(~)
arrayNOT // [245, 210, 223, 239, 0]
Not to mention working with words:
let singularWords = ["car","van","park","flower"]
let pluralWords = singularWords.map(){$0 + "s"}
pluralWords // ["cars", "vans", "parks", "flowers"]

Conclusion

As has been written and said in many ways before, the map() function and other functions like it cut down on the number of loops that are required and the need to initialise an array before loading it with values. (Therefore making for less mutability.) While the spreadsheet analogies help to illustrate the expectation that we have a column of one set of values that we might need to be uniformly duplicated with some consistent alteration, such as the adding of tax. And that in order to create this second column we shouldn't need to alter the first (because we still need that information), and neither should we enter into some convoluted method that opens the path for error.


Endorse on Coderwall

Comments