天天看點

Functional JavaScript 筆記Functional JavaScript

Functional JavaScript

目錄

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

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 ){

    var pargs = _.rest(arguments);

    return function(){

    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 ){

      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 = 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 

繼續閱讀