2 First-Class Functions and Applicative Programming

Functions as First-Class Things

  • A number can be stored in a variable and so can a function:
  var fortytwo = function() { return 42 };
  • A number can be stored in an array slot and so can a function:
var fortytwos = [42, function() { return 42 }];
  • A number can be stored in an object field and so can a function:
var fortytwos = {number: 42, fun: function() { return 42 }};
  • A number can be created as needed and so can a function:
42 + (function() { return 42 })();
//=> 84
  • A number can be passed to a function and so can a function:
function weirdAdd(n, f) { return n + f() }
weirdAdd(42, function() { return 42 });
//=> 84
  • A number can be returned from a function and so can a function:
return 42;
return function() { return 42 };
_.each(['whiskey', 'tango', 'foxtrot'], function(word) {
 console.log(word.charAt(0).toUpperCase() + word.substr(1));
});
// (console) Whiskey
// (console) Tango
// (console) Foxtrot

JavaScript's Multiple Paradigms

Imperative programming
Programming based around describing actions in detail
Prototype-based object-oriented programming
Programming based around prototypical objects and instances of them
Metaprogramming
Programming manipulating the basis of JavaScript's execution model

Imperative programming

var lyrics = [];
for (var bottles = 99; bottles > 0; bottles--) {
 lyrics.push(bottles + " bottles of beer on the wall");
 lyrics.push(bottles + " bottles of beer");
 lyrics.push("Take one down, pass it around");
 if (bottles > 1) {
 lyrics.push((bottles - 1) + " bottles of beer on the wall.");
 }
 else {
 lyrics.push("No more bottles of beer on the wall!");
 }
}
function lyricsSegment(n) {
  return _.chain([])
    .push(n + "bottles of beer on the wall")
    .push(n + "bottles of beer")
    .push("Take one down, pass it around")
    .tap(function(lyrics) {
      if(n > 1)
        lyrics.push((n - 1) + "bottles of beer on the wall.");
      else
        lyrics.push("No more bottles of beer on the wall!");
    })
    .value();
}

Prototype-based object-oriented programming

var a = {name: "a", fun: function () { return this; }};
a.fun();
//=> {name: "a", fun: ...};
var bFunc = function () { return this };
var b = {name: "b", fun: bFunc};
b.fun();
//=> some global object, probably Window

Metaprogramming

function Point2D(x, y) {
  this._x = x;
  this._y = y;
}
new Point2D(0, 1);
//=> {_x: 0, _y: 1}
function Point3D(x, y, z) {
  Point2D.call(this, x, y);
  this._z = z;
}
new Point3D(10, -1, 100);
//=> {_x: 10, _y: -1, _z: 100}

Applicative Programming

var nums = [1,2,3,4,5];
function doubleAll(array) {
  return _.map(array, function(n) {return n*2});
}

doubleAll(nums);
//=> [2, 4, 6, 8, 10]

function average(array) {
  var sum = _.reduce(array, function(a, b) {return a+b});
  return sum / _.size(array);
}

average(nums);
//=> 3

/* grab only even numbers in nums */
function onlyEven(array) {
 return _.filter(array, function(n) {
 return (n%2) === 0;
 });
}
onlyEven(nums);
//=> [2, 4]
  • _.map calls a function on every value in a collection in turn, returning a collection of the results
  • _.reduce collects a composite value from the incremental results of a supplied with an accumulation value and each value in a collection
  • _.filter calls a predicate function (one returning a true or false value) and grabs each value where said predicate returned true, returning them in a new collection

Collection-Centric Programming

_.map({a: 1, b: 2}, _.identity);
//=> [1,2]
_.map({a: 1, b: 2}, function(v, k) {
  return [k,v];
});
//=> [['a', 1], ['b', 2]]
_.map({a: 1, b: 2}, function(v,k,coll) {
 return [k, v, _.keys(coll)];
});
//=> [['a', 1, ['a', 'b']], ['b', 2, ['a', 'b']]]

Other Examples of Applicative Programming

reduceRight

var nums = [100,2,25];
function div(x,y) {return x/y};

_.reduce(nums, div);
//=> 2

_.reduceRight(nums, div);
//=> 0.125
function allOf(/* funs */) {
 return _.reduceRight(arguments, function(truth, f) {
 return truth && f();
 }, true);
}
function anyOf(/* funs */) {
 return _.reduceRight(arguments, function(truth, f) {
 return truth || f();
 }, false);
}
function T() { return true }
function F() { return false }
allOf();
//=> true
allOf(T, T);
//=> true
allOf(T, T, T , T , F);
//=> false
anyOf(T, T, F);
//=> true
anyOf(F, F, F, F);
//=> false
anyOf();
//=> false

find

_.find(['a', 'b', '3', 'd'], _.isNumber);
//=> 3

reject

_.reject(['a', 'b', 3, 'd'], _.isNumber);
//=> ['a', 'b', 'd']

all

_.all([1, 2, 3, 4], _.isNumber);
//=> true

any

_.any([1, 2, 'c', 4], _.isString);
//=> true

sortBy, groupBy, and countBy

var people = [{name: "Rick", age: 30}, {name: "Jaka", age: 24}];
_.sortBy(people, function(p) { return p.age });
//=> [{name: "Jaka", age: 24}, {name: "Rick", age: 30}]
var albums = [{title: "Sabbath Bloody Sabbath", genre: "Metal"},
 {title: "Scientist", genre: "Dub"},
 {title: "Undertow", genre: "Metal"}];
_.groupBy(albums, function(a) { return a.genre });
//=> {Metal:[{title:"Sabbath Bloody Sabbath", genre:"Metal"},
// {title:"Undertow", genre:"Metal"}],
// Dub: [{title:"Scientist", genre:"Dub"}]}


_.countBy(albums, function(a) {return a.genre});
//=> {Metal: 2, Dub: 1}

Defining a Few Applicative Functions

function cat() {
 var head = _.first(arguments);
 if (existy(head))
 return head.concat.apply(head, _.rest(arguments));
 else
 return [];
}
cat([1,2,3], [4,5], [6,7,8]);
//=> [1, 2, 3, 4, 5, 6, 7, 8]
function construct(head, tail) {
 return cat([head], _.toArray(tail));
}
construct(42, [1,2,3]);
//=> [42, 1, 2, 3]

Data Thinking

var zombie = {name: "Bub", film: "Day of the Dead"};
_.keys(zombie);
//=> ["name", "film"]
_.values(zombie);
//=> ["Bub", "Day of the Dead"]
_.pluck([{title: "Chthon", author: "Anthony"},
 {title: "Grendel", author: "Gardner"},
 {title: "After Dark"}],
 'author');
//=> ["Anthony", "Gardner", undefined]

Summary

  • They can be stored in a variable.
  • They can be stored in an array slot.
  • They can be stored in an object field.
  • They can be created as needed.
  • They can be passed to other functions.
  • They can be returned from functions.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,362评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,330评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,247评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,560评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,580评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,569评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,929评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,587评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,840评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,596评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,678评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,366评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,945评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,929评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,165评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,271评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,403评论 2 342

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,355评论 0 23
  • 3980元,在我刚刚完成点击支付宝的瞬间,这笔钱流入了北京新东方的口袋。 是的,从决定考gmat到完成报班、订住宿...
    婉琰阅读 204评论 0 0
  • 爱情里最担心的就是 当你们吵架闹矛盾的时候 别人趁虚而入来安慰他来逗他开心 然后让他认为遇见了比你更好的人。
    Hilarious阅读 418评论 0 0
  • 这世间有觉得钱重要的人,可是最终,只是想和一个能好好说话,说得通的人在一起。不然,日日夜夜,抱着金砖玉瓦,如鲠在喉...
    兰卡公子阅读 350评论 0 1
  • Preamble Date: Mon Feb 9 12:59:01 PST 2015 近些時間想要瞭解一些特效L...
    jProvim阅读 616评论 0 5