學習三 函式組合

2021-10-09 15:19:18 字數 2268 閱讀 6276

純函式和柯里化很容易寫出洋蔥**,函式組合就可以把細粒度的函式重新組合成乙個新的函式。

函式組合案例:

function compose (fn1, fn2)

}function reverse (array)

function first (array)

const last = compose(first,reverse);

let arr = [1,2,3,4,5,6];

console.log(last(arr));

lodash中的函式組合flow,flowright:

const _ = require('lodash');

const reverse = arr => arr.reverse();

const first = arr => arr[0];

const toupper = arr => arr.touppercase();

const fn =_.flowright(toupper,first,reverse);

console.log(fn(['one','two','three']));

手寫lodash中的flowright:

const reverse = arr => arr.reverse();

const first = arr => arr[0];

const toupper = arr => arr.touppercase();

// const fn =_.flowright(toupper,first,reverse);

// 模擬 lodash 中的 flowright

// function compose (...args) , value)

// }

// }

const compose = (...args) => value => args.reverse().reduce((acc, fn) => fn(acc), value)

const f = compose(toupper, first, reverse)

console.log(f(['one', 'two', 'three']))

函式組合要滿足結合律 

如果我們組合的函式,跟我們預期的結果不一致,要怎麼除錯呢

const _ = require('lodash');

let target = 'never say die';

const log = _.curry((tag ,v) =>)

const split = _.curry((sep , str) => _.split(str, sep));

const join = _.curry((sep ,arr) => _.join(arr, sep));

const f = _.flowright(_.tolower,log('join:'),join('-'),log('split:'),split(' '));

console.log(f(target));

lodash中的fp模組,也就是function programming模組,是ladash針對函式式程式設計的模組。

lodash中的fp模組,函式優先,引數滯後。

二、pointfree

我們可以把資料處理的過程定義成與資料無關的合成運算,不需要用到代表資料的那個引數,

只要把簡單的運算步驟合成到一起,在使用這個模式之前我們需要定義一些輔助的基本運算函式。

1、我們不要指明處理的資料

2、我們只需要合成運算過程

3、需要定義一些輔助的基本運算函式

案例:

const fp = require('lodash/fp')

// hello world => hello_world

const f = fp.flowright(fp.replace(/\s+/g, '_'), fp.tolower)

console.log(f('hello world'))

// world wild web ==> w. w. w

const firstlettertoupper = fp.flowright(fp.join('. '), fp.map(fp.flowright(fp.first, fp.toupper)), fp.split(' '))

console.log(firstlettertoupper('world wild web'))

函式組合應用

函式通道就是自左向右。function compose f,g function touppercase str function add str function split str function reverse str function compose return result var f...

python 函式組合

額,是看 中看到的.首先我們定義個函式類如下.class function object def init self,f self.f f def call self,x return self.f x 嗯,很簡單,就是把乙個函式拖進來而已.呼叫也簡單.如下 但是如果把上面的函式稍稍擴充套件下就很好...

柯里化函式組合的學習

2020 09 19 柯里化函式組合的學習 說明 思路 never say die never say die const require lodash join函式改寫 柯里化的join 在組合中 可以事先傳入使用哪種方式組合 const join curry sep,arr arr.join s...