在Swift中,函數式編程可以通過將多個函數組合在一起來創建更復雜的功能。有多種方法可以實現函數組合,這里列舉了一些常見的方法:
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) // 組合后的函數
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)
這些方法可以幫助你根據需要靈活地組合函數式編程中的函數。