博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Compose] 14. Build curried functions
阅读量:4876 次
发布时间:2019-06-11

本文共 1708 字,大约阅读时间需要 5 分钟。

We see what it means to curry a function, then walk through several examples of curried functions and their use cases.

 

For example we have an 'add' function:

const add = (x, y) => x + y;const inc = y => add(1, y); inc(2) //3

 

We want to conver it to using curry function, the way we do it is by function another function inside add function:

const add = x => y =>  x + y;

SO the first time we call add(), it will remember the value we passed in:

const inc = add(1); // now x = 1

But the function won't be run until we pass in second param:

const res = inc(2); // now y = 2console.log(res) // 3

 

----------

Of course, previous example is not that useful, there is another example:

const modulo = dvr => dvd => dvd % dvr;const isOdd = modulo(2); // dvr = 2;const res1 = isOdd(7);  //dvd = 7const res2 = isOdd(4);  //dvd = 4console.log(res1) // 1console.log(res2) // 0

 

Exmaple2:

const modulo = dvr => dvd => dvd % dvr;const isOdd = modulo(2); // dvr = 2;const filter = pred => ary => ary.filter(pred);const getAllOdds = filter(isOdd);const res = getAllOdds([1,2,3,4,5]);console.log(res) //[1, 3, 5]

 

Example3:

const replace = regex => replaceWith => str =>   str.replace(regex, replaceWith);const censor = replace(/[aeiou]/ig)('*'); // [aeiou] --> regex, replaceWith --> *const res = censor('Hello World');console.log(res); //"H*ll* W*rld"

 

Example 4:

const map = fn => ary => ary.map(fn);const replace = regex => replaceWith => str =>   str.replace(regex, replaceWith);const censor = replace(/[aeiou]/ig)('*'); // [aeiou] --> regex, replaceWith --> *const censorAll = map(censor);const res = censorAll(["Hello", "World"]);console.log(res); //["H*ll*", "W*rld"]

 

转载于:https://www.cnblogs.com/Answer1215/p/6204313.html

你可能感兴趣的文章
Pandas截取列部分字符,并据此修改另一列的数据
查看>>
Android性能优化(2)
查看>>
java.lang.IllegalArgumentException
查看>>
pytest
查看>>
python爬取某个网站的图片并保存到本地
查看>>
【Spark】编程实战之模拟SparkRPC原理实现自定义RPC
查看>>
关于Setup Factory 9的一些使用方法
查看>>
接口实现观察者模式
查看>>
网站Session 处理方式
查看>>
记开发个人图书收藏清单小程序开发(九)Web开发——新增图书信息
查看>>
四则运算完结篇
查看>>
poj3401二分图
查看>>
Objective-C中的类目,延展,协议
查看>>
Python标准模块--Iterators和Generators
查看>>
Introduction Sockets to Programming in C using TCP/IP
查看>>
PHP 简单实现webSocket
查看>>
zookeeper部署搭建
查看>>
navigationController pop回之前控制器
查看>>
汇编语言实验一
查看>>
Web.config配置文件详解(新手必看)
查看>>