在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)
这些方法可以帮助你根据需要灵活地组合函数式编程中的函数。