violet0sea / note

can not open gist, so write here
0 stars 0 forks source link

Function Programming #22

Open violet0sea opened 6 years ago

violet0sea commented 6 years ago

为什么要写FP?一直以来都在使用React技术栈,函数式编程贯穿其间。就在现在,React16.7.0-alpha版本发布在即,引入了React Hooks概念,而此概念的核心便是用function逐渐替代class的写法,大势如此。

函数式优点:

Pure functions have no side effects. In Imperative Programming languages such as Javascript, Java, and C#, Side Effects are everywhere. This makes debugging very difficult because a variable can be changed anywhere in your program.

composition 组合函数

将简单的函数组合从而形成一个复杂功能的函数,在数学概念里: f(g(x)) eg: 实现一个数学用算 2 + 3 * 5

const add = (a, b) => a + b;
const mult = (a, b) => a * b;
add(2, mult(3, 5));

key point: 用一个函数的输出作为另一个函数的输入。组合的方式主要使用在数据过滤,通过写几个功能简单的条件过滤函数,通过组合形成功能强大的过滤函数

虽然上述的方式可以实现组合,但是一点也不优雅,可以使用compose高阶函数来实现组合的抽象

// f1(f2(fn(arg))) 关注结合的顺序 right to left *** [pipe is left to right] ***   只有一个参数作为输入而且仅有一个参数作为输出
compose(f1, f2, f2, ...)

const compose = (...fns) => args => fns.reduce((a, b) => a(b(arg)))
or
const compose = (...fns) => arg => fns.reduceRight((a, b) => b(a(arg)))
or
const compose = (...fns) => arg => {
    const fnsArr = [...fns];
    let result = fnsArr.pop()(arg);
    while(fnsArr.length) {
        result = fnsArr.pop()(result);
    }
    return result;
}

待补充

violet0sea commented 5 years ago

a qq 20181126104941 qq 20181126110409 '

violet0sea commented 5 years ago

某独角兽的面试题

若f(a,b,c,d,e) = a + b + c + d + e;
构造一个函数g,使得
g(a,b,c,d,e) | g(a,b,c,d)(e) | g(a,b)(c)(d,e) | ...= f(a,b,c,d,e)
应用FP的partial application解法
function partial(fn, arity = fn.length) {
  return (function nextPartial(prevArgs) {
    return function partialed(...nextArgs) {
      const args = [...prevArgs, ...nextArgs];
      if(args.length >= arity) {
        return fn(...args);
      } else {
        return nextPartial(args);
      }
    }
  })([]);
}

qq 20181204152631