- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 320字
- 2021-07-02 23:54:33
A composed function with custom operator
Let's define a new custom operator to use instead of our composed function:
precedencegroup AssociativityLeft {
associativity: left
}
infix operator |> : AssociativityLeft
func |> <T, V>(f: @escaping (T) -> V, g: @escaping (V) -> V ) -> (T) -> V {
return { x in g(f(x)) }
}
let composedWithCustomOperator = extractElements |> formatWithCurrency
composedWithCustomOperator("10,20,40,30,80,60")
// The result will be: ["10$", "20$", "40$", "30$", "80$", "60$"]
In this example, we have defined a new operator, |>, that takes two generic functions and combines them, returning a function that has the first function's input as the parameter and the second function's return as the return type.
As this new operator is going to combine two functions and is binary, we defined it as infix. Then we need to use the operator keyword. The next step will be to choose the notation for our new custom operator. As we will group functions to the left, we need to specify it as associativity left.
To be able to use this operator, we need to define a corresponding function. Our function takes two functions as follows:
- f: This function takes a generic type of T and returns a generic type of V
- g: This function takes a generic type of V and returns a generic type of V
In our previous example, we had the following functions:
- extractElements - String -> [String]
- formatWithCurrency - [String] -> [String]
So T becomes String and V becomes [String].
Our |> function returns a function that takes a generic type of T and returns a generic type of V. We need to receive the String -> [String] from the composed function so, again, T becomes String and V becomes [String].
Using our|> custom operator makes our code more readable and less verbose. Do not worry about @escaping for now, we will talk about it in the Closures--Capturing values section of this chapter.
- 大數(shù)據(jù)時(shí)代下的智能轉(zhuǎn)型進(jìn)程精選(套裝共10冊(cè))
- 數(shù)據(jù)驅(qū)動(dòng)設(shè)計(jì):A/B測(cè)試提升用戶體驗(yàn)
- LabVIEW 完全自學(xué)手冊(cè)
- 圖數(shù)據(jù)實(shí)戰(zhàn):用圖思維和圖技術(shù)解決復(fù)雜問(wèn)題
- 云數(shù)據(jù)中心網(wǎng)絡(luò)與SDN:技術(shù)架構(gòu)與實(shí)現(xiàn)
- IPython Interactive Computing and Visualization Cookbook(Second Edition)
- 探索新型智庫(kù)發(fā)展之路:藍(lán)迪國(guó)際智庫(kù)報(bào)告·2015(上冊(cè))
- Kubernetes快速進(jìn)階與實(shí)戰(zhàn)
- 數(shù)據(jù)挖掘算法實(shí)踐與案例詳解
- MySQL性能調(diào)優(yōu)與架構(gòu)設(shè)計(jì)
- 成功之路:ORACLE 11g學(xué)習(xí)筆記
- Practical Convolutional Neural Networks
- 代碼的未來(lái)
- 數(shù)據(jù)分析方法及應(yīng)用:基于SPSS和EXCEL環(huán)境
- Machine Learning for Mobile