首页 > 代码库 > Functional JavaScript 笔记

Functional JavaScript 笔记

Functional JavaScript

目录

  • 1Get Started with FP
  • 2First-class Functions and Applicative Programming
  • 3Variable Scope and Closures
  • 4High-order Functions
  • 5Function-Building Functions
  • 6Recursion
  • 7Purity, Immutability and Policies for Change
  • 8Flow-based Programming
  • 9Programming without Class
  • 10Appendix

Get Started with FP

  1. CSV parse:
    return _.reduce(str.split("\n"), function(table, row){
    table.push(_.map(row.split(","), function(cell){return cell.trim();})); return table;}, []); };
  2. 作者是ClojureScript的作者?

First-class Functions and Applicative Programming

  1. return _.reduceRight(arguments, function(truth,f){ return truth && f(); }, true);
  2. 传递null作为第一个参数给apply:意味着this引用全局对象...
  3. p44 传统的SQL Select实际上对应关系代数里的Project
  4. JS的lambda语法太麻烦,给写FP风格的代码带来了麻烦
    1. restrict( project( as(library, {ed: ‘edition‘}), [‘title‘,‘isbn‘,‘edition‘]),
      function(book){ return book.edition>1; } );

Variable Scope and Closures

High-order Functions

Function-Building Functions

  1. function partial(fun /*, pargs */){
    var pargs = _.rest(arguments);
    return function(/* arguments */){
    var args = cat(pargs, _.toArray(arguments));
    return fun.apply(fun, args);
    } }

Recursion

  1. trampoline(避免mutual-recursive溢出):
    1. function even(n){ if(n==0) return true; else return partial1(odd, n-1); }
      1. ==> odd(20000001)()()...();
    2. function trampoline(fun /*, args */){
      var result = fun.apply(fun, _.rest(arguments)); //又来了
      while(_.isFunction(result)) result = result();
      return result; }
  2. generator(惰性无限序列)
    1. head-tail()抽象,其中,tail封装了“剩余序列的计算”
    2. function genTake(n, gen){
      var doTake = function(x, g, ret){ if(x==0)return ret; else return partial(doTake, x-1, genTail(g), cat(ret, genHead(g)));}
      return trampoline(doTake, n, gen, []);

Purity, Immutability and Policies for Change

  1. Object#freeze => deepFreeze
  2. API:让对象修改方法返回新对象实例

Flow-based Programming

  1. _.chain
  2. LazyChain
    1. thunk:a function waiting to be called
    2. #force()
  3. jQuery $.Deferred()
  4. Pipelining
  5. Action(Monad):flowing in context?
    1. lift
    2. actions

Programming without Class

  1. Mixins
    1. var polyToString = dispatch( function(s){ return _.isString(s)? s : undefined; }, ...
  2. var MyMixin = {
    setValue: function(v){ ... this._value = http://www.mamicode.com/v; this.notify(oldVal, v); }
  3. _.extend(MyClass.prototype, MyMixin);
  4. var CAS = function(val){ MyClass.call(this, val); }
    1. var CASMixin = ...

Appendix

  1. Underscore-contrib
  2. RxJS
  3. Bilby‘s multimethods
  4. allong.es:support for stateful iterators
  5. *Reducers:inspired by Clojure‘s reducer
  6. ClojureScript(作者就是写《The Joy of Clojure》的?)
  7. CoffeeScript
    1. Literate编程
    2. Varargs
    3. 列表理解
    4. 解构赋值
  8. Roy:inspired by ML
  9. Elm(+不用作字符串拼接,需要用++):FRP 

Functional JavaScript 笔记