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"]
Comments
Post a Comment