Let's say we want to write a most simple implementation 'avg' function:

const avg = list => {
let sum = 0;
for(let i = 0; i < list.length; i++) {
sum += list[i]
}
return sum / list.length
}

Basiclly, the 'avg' function doing two things:

  • Calculate sum
  • Divide sum / length

It works fine for tiny / small application, but for the large application, we need to think about reuseablitiy. We want to breakdown one function and think about any reuseable partten, which later can be reused.

In the following examples, We want to bring in two libarays which are commonly used in FP. One is Ramda, another one is Crocks.

Currying:

First, we want to write 'sum' and 'devide' functions by ourselves:

const { curry, reduce, compose } = require("crocks");
const R = require("ramda"); const sum = reduce(R.add, 0);
// divideByLen :: [Number] -> Number -> Number
const divideByLen = curry(
compose(
R.flip(R.divide),
R.length
)
);

'sum' is simple, using 'reduce' from Crocks, you can also write JS reduce, doesn't matter.

What we need to explain is 'divideByLen' function.

  • Why 'curry'?

Basic we want to call divideByLen in two ways:

divideByLen([1,2,3], sum([1,2,3]))
divideByLen([1,2,3])(sum([1,2,3]))

[Notice] You need to bring in 'curry' from Crocks, it is more flexable.

  • Why 'flip'?

Because R.divide(sum, length), we need to feed the divide function with sum as first argement, then length as second arguement. But when we write code, length will be feeded frist, sum will be partially applied, it will come second, therefore we need to call 'flip'.

Bring all together:

const avg = list =>
compose(
divideByLen(list),
sum
)(list);

We notice that, we have to pass 'list' to both Sum(list) and divideByLen(list). The code looks not so good. Whenever you are facing the situation, you need to pass the same arguement to two functions in parallel. You can consider to using 'Partial Application'.

Partial Application:

// Ramda

const avg = R.converge(R.divide, [R.sum, R.length]);

We are using 'Ramda's converge' function, bascilly you have pass in a data, the data will be passed to R.sum(data) & R.length(data), the return results of those two functions, will be passed to R.divide(resOfSum, resOfLength).

//Crocks:

const { curry, fanout, merge, compose } = require("crocks");

const avg = compose(
merge(R.divide),
fanout(R.sum, R.length)
);

We are using the Pair ADT, the data will be passed to R.sum(data) & R.length(data) thought 'fanout' function, it returns Pair(resOfSum, resOfLength).

Then we use 'merge', it works with Pair ADT, we merge two results by R.divide(resOfSum, resOfLength).

[Functional Programming] From simple implementation to Currying to Partial Application的更多相关文章

  1. Currying vs Partial Application

    柯里化相当于函数重构: 偏函数相当于函数适配. So, what is the difference between currying and partial application? As we s ...

  2. [Functional Programming] Write simple Semigroups type

    An introduction to concatting items via the formal Semi-group interface. Semi-groups are simply a ty ...

  3. [Functional Programming] Compose Simple State ADT Transitions into One Complex Transaction

    State is a lazy datatype and as such we can combine many simple transitions into one very complex on ...

  4. Functional Programming without Lambda - Part 1 Functional Composition

    Functions in Java Prior to the introduction of Lambda Expressions feature in version 8, Java had lon ...

  5. Functional Programming without Lambda - Part 2 Lifting, Functor, Monad

    Lifting Now, let's review map from another perspective. map :: (T -> R) -> [T] -> [R] accep ...

  6. Beginning Scala study note(4) Functional Programming in Scala

    1. Functional programming treats computation as the evaluation of mathematical and avoids state and ...

  7. a primary example for Functional programming in javascript

    background In pursuit of a real-world application, let’s say we need an e-commerce web applicationfo ...

  8. Functional programming

    In computer science, functional programming is a programming paradigm, a style of building the struc ...

  9. BETTER SUPPORT FOR FUNCTIONAL PROGRAMMING IN ANGULAR 2

    In this blog post I will talk about the changes coming in Angular 2 that will improve its support fo ...

随机推荐

  1. C++ code:prime decision

    1 判断一个数是否为素数 对于判断一个数m是否为素数,最朴素的方式是按照素数的定义,试除以从2开始到m-1的整数,倘若无一例外地不能整除,则该数必为素数. #include<iostream&g ...

  2. Redis的优势和特点

    Redis的特点: 内存数据库,速度快,也支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用. Redis不仅仅支持简单的key-value类型的数据,同时还提供list ...

  3. Ubuntu 16.04 LTS 搭建ftp服务器

    其实我之前搭建好了,但是最近我上来看好像跟没搭建一样呢,于是我从新搭建一遍? 我的ubuntu版本: cat /etc/issue Ubuntu 16.04 LTS \n \l 1.安装vsftpd( ...

  4. 【BZOJ3307】雨天的尾巴

    题解: win下的10mb和linux下的好像不是很一样 明天再看看 求lca用的离线求,注意bz数组开2*n 这道题的线段树合并还是很好想的 我们只要把操作差分一下就好了 时间复杂度nlogn的 写 ...

  5. [转]一个研究生毕业以后的人生规划[ZZ]

    只有选择去国内的大公司或外企才是出路 文章转载如下: 我今年39岁了, 25岁研究生毕业,工作14年,回头看看,应该说走了不少的弯路,有一些经验和教训.现在开一个小公司,赚的钱刚够养家糊口的.看看这些 ...

  6. 【AtCoder】ARC081

    C - Make a Rectangle 每次取两个相同的且最大的边,取两次即可 #include <bits/stdc++.h> #define fi first #define se ...

  7. 【AtCoder】CODE FESTIVAL 2017 qual A

    A - Snuke's favorite YAKINIKU -- #include <bits/stdc++.h> #define fi first #define se second # ...

  8. Strom的集群停止以及启动

    一:停止 1.概述 关于strom没有停止命令 2.第一种方式(kill) jps之后 使用bin/strom -kill wordcount 3.第二种方式(书写脚本) 4.先新建superviso ...

  9. C++ 冒泡排序、选择排序、快速排序

    #include<stdio.h> #define N 10 void swap(int *p1, int *p2); void BubbleSort(int *a); void Sele ...

  10. 小程序使用 rpx 单位 转 px的方法(用于动画、canvas画图)

    1.需要借助的API:wx.getSystemInfoSync(); 通过API可获取的值: // 在 iPhone6 下运行: var systemInfo = wx.getSystemInfoSy ...