在Swift中,函數(shù)式編程可以通過(guò)將多個(gè)函數(shù)組合在一起來(lái)創(chuàng)建更復(fù)雜的功能。有多種方法可以實(shí)現(xiàn)函數(shù)組合,這里列舉了一些常見(jiàn)的方法:
compose(_:)
:func compose<A, B, C>(_ f: (B) -> C, _ g: (A) -> B) -> (A) -> C {
return { a in f(g(a)) }
}
// 示例
func addOne(_ x: Int) -> Int {
return x + 1
}
func multiplyByTwo(_ x: Int) -> Int {
return x * 2
}
let composedFunction = compose(multiplyByTwo, addOne) // 組合后的函數(shù)
print(composedFunction(3)) // 輸出 8 (3 * 2 + 1)
let addOne = { x in x + 1 }
let multiplyByTwo = { x in x * 2 }
let composedFunction = { x in multiplyByTwo(addOne(x)) }
print(composedFunction(3)) // 輸出 8 (3 * 2 + 1)
struct FunctionWrapper<T, U> {
let function: (T) -> U
}
extension FunctionWrapper {
func andThen<V>(other: @escaping (U) -> V) -> (T) -> V {
return { x in other(self.function(x)) }
}
}
// 示例
let addOne = FunctionWrapper(function: { x in x + 1 })
let multiplyByTwo = FunctionWrapper(function: { x in x * 2 })
let composedFunction = addOne.andThen(other: multiplyByTwo.function)
print(composedFunction(3)) // 輸出 8 (3 * 2 + 1)
這些方法可以幫助你根據(jù)需要靈活地組合函數(shù)式編程中的函數(shù)。