marp | theme | paginate | header |
---|---|---|---|
true |
uncover |
true |
函数式编程指南 第4章:柯里化(curry) |
第 4 章
《函数式编程指南》
柯里的概念:传递一部分的参数来调用函数,它返回一个接受剩余参数的函数
- curry 用处非常广泛
- 只需传给函数一些参数,得到一个新函数
map把参数是单个元素的函数包裹,
转换成参数为数组的函数
const getChildren = (x) => x.childNodes;
map包裹:
const allTheChildren = map(getChildren);
只传给函数一部分参数,也叫做局部调用(partial application)
import * as _ from 'lodash';
const allTheChildren = (elements) => _.map(elements, getChildren);
vs
// curry化
const allTheChildren = map(getChildren);
对比下,下面的局部调用减少样板代码(boilerplate code)
- curry是函数式编程必备工具
- 通过简单地传递几个参数,就能动态创建实用的新函数
- 保留了数学的函数定义,尽管参数不止一个