1️⃣ 什么是 Point-Free 风格?
定义:
Point-Free 风格是一种 函数式编程风格,特点是 不显式提及函数参数,而是通过 函数组合 来定义新的函数。
核心思想:
- 关注函数组合而不是参数本身
- 使用
map、filter、reduce、compose等函数组合操作 - 可读性提高,逻辑更紧凑
常规写法(带参数)
let numbers = [1, 2, 3, 4, 5]
// 普通写法
let doubled = numbers.map { x in x * 2 }
- 明确提及了参数
x
Point-Free 风格
如果有一个函数 multiplyBy2,可以直接传给 map,无需显示写出参数:
func multiplyBy2(_ x: Int) -> Int {
return x * 2
}
let numbers = [1, 2, 3, 4, 5]
// Point-Free 风格
let doubled = numbers.map(multiplyBy2)
- 不需要
{ x in multiplyBy2(x) } - 参数隐含于函数组合中
- 更接近数学式的“函数组合”风格
2️⃣ 组合多个函数的 Point-Free 示例
假设我们要对数组做两步操作:
- 过滤大于 3 的数字
- 翻倍
普通写法
let numbers = [1, 2, 3, 4, 5]
let result = numbers
.filter { $0 > 3 }
.map { $0 * 2 }
print(result) // [8, 10]
Point-Free 风格
func greaterThan3(_ x: Int) -> Bool { x > 3 }
func multiplyBy2(_ x: Int) -> Int { x * 2 }
let numbers = [1, 2, 3, 4, 5]
let result = numbers
.filter(greaterThan3)
.map(multiplyBy2)
print(result) // [8, 10]
- 参数
$0被 隐藏,逻辑通过函数组合描述 - 可读性强,逻辑清晰
- 更容易进行函数复用和组合
3️⃣ 总结
Point-Free 风格特点:
- 不显式写参数
- 强调函数组合而非数据
- 逻辑更简洁,适合函数式流水线
Swift 实践建议:
- 对常用转换、过滤、映射等操作定义小函数
- 使用
map,filter,reduce等组合 - 可以隐藏闭包参数,实现 Point-Free 风格
💡 记忆技巧:
Point-Free = “不显式提及点(参数)”,只组合函数