{"id":13512182,"url":"https://github.com/shfshanyue/fp-jargon-zh","last_synced_at":"2025-05-16T07:03:52.845Z","repository":{"id":41983818,"uuid":"83943764","full_name":"shfshanyue/fp-jargon-zh","owner":"shfshanyue","description":"函数式编程术语及示例。本项目译自 https://github.com/hemanth/functional-programming-jargon","archived":false,"fork":false,"pushed_at":"2023-01-29T02:23:10.000Z","size":126,"stargazers_count":1288,"open_issues_count":2,"forks_count":111,"subscribers_count":24,"default_branch":"master","last_synced_at":"2025-04-08T00:39:35.748Z","etag":null,"topics":["fp","functional-programming"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/shfshanyue.png","metadata":{"files":{"readme":"Readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-03-05T04:08:34.000Z","updated_at":"2025-03-20T15:25:53.000Z","dependencies_parsed_at":"2023-02-15T20:15:19.867Z","dependency_job_id":null,"html_url":"https://github.com/shfshanyue/fp-jargon-zh","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shfshanyue%2Ffp-jargon-zh","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shfshanyue%2Ffp-jargon-zh/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shfshanyue%2Ffp-jargon-zh/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/shfshanyue%2Ffp-jargon-zh/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/shfshanyue","download_url":"https://codeload.github.com/shfshanyue/fp-jargon-zh/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254485053,"owners_count":22078767,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fp","functional-programming"],"created_at":"2024-08-01T03:01:34.260Z","updated_at":"2025-05-16T07:03:52.669Z","avatar_url":"https://github.com/shfshanyue.png","language":null,"funding_links":[],"categories":["Others"],"sub_categories":[],"readme":"# 函数式编程术语\n\n\u003e 译者注：本项目译自 [functional-programing-jargon](https://github.com/hemanth/functional-programming-jargon)，专业术语居多，如有错误，可以提 pr 更正。除了术语翻译，针对每项术语，也有代码示例，位于 /demos 目录下。另外，这里也有几份不错的文章和仓库。\n  + [函数式编程入门教程](http://www.ruanyifeng.com/blog/2017/02/fp-tutorial.html)\n  + [mostly-adequate-guide (10749 stars)](https://github.com/MostlyAdequate/mostly-adequate-guide)\n  + [mostly-adequate-guide-chinese (602 stars)](https://github.com/llh911001/mostly-adequate-guide-chinese)\n  + [fantasy-land](https://github.com/fantasyland/fantasy-land)\n\n函数式编程有许多优势，由此越来越受欢迎。然而每个编程范式 (paradigm) 都有自己唯一的术语，函数式编程也不例外。我们提供一张术语表，希望使你学习函数式编程变得容易些。\n\n示例均为 javascript (ES2015)。[为什么使用JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F)\n\n*尚在 WIP 阶段，欢迎 pr。*\n\n如果适用，本篇文档使用定义在 [Fantasy Land spec](https://github.com/fantasyland/fantasy-land) 中的术语。\n\n**目录**\n\n* [Arity](#arity)\n* [高阶函数 (HOF)](#higher-order-functions-hof)\n* [闭包 (Closure)](#closure)\n* [偏函数应用 (Partial Application)](#partial-application)\n* [柯里化 (Currying)](#currying)\n* [自动柯里化 (Auto Currying)](#auto-currying)\n* [函数组合 (Function Composition)](#function-composition)\n* [后续 (Continuation)](#continuation)\n* [纯函数 (Purity)](#purity)\n* [副作用 (Side effects)](#side-effects)\n* [幂等性 (Idempotent)](#idempotent)\n* [Point-Free 风格 (Point-Free Style)](#point-free-style)\n* [断定 (Predicate)](#predicate)\n* [契约 (Contracts)](#contracts)\n* [范畴 (Category)](#category)\n* [值 (Value)](#value)\n* [常量 (Constant)](#constant)\n* [函子 (Functor)](#functor)\n  * [一致性 (Preserves identity)](#preserves-identity)\n  * [组合性 (Composable)](#composable)\n* [指向函子 (Pointed Functor)](#pointed-functor)\n* [抬升 (Lift)](#lift)\n* [引用透明性 (Referential Transparency)](#referential-transparency)\n* [等式推理 (Equational Reasoning)](#equational-reasoning)\n* [Lambda](#lambda)\n* [Lambda 演算 (Lambda Calculus)](#lambda-calculus)\n* [惰性求值 (Lazy evaluation)](#lazy-evaluation)\n* [幺半群 (Monoid)](#monoid)\n* [单子 (Monad)](#monad)\n* [余单子 (Comonad)](#comonad)\n* [应用函子 (Applicative Functor)](#applicative-functor)\n* [态射 (Morphism)](#morphism)\n  * [Endomorphism (自同态)](#endomorphism)\n  * [Isomorphism (同构)](#isomorphism)\n  * [Homomorphism (同态)](#homomorphism)\n  * [Catamorphism](#catamorphism)\n  * [Anamorphism](#anamorphism)\n  * [Hylomorphism](#hylomorphism)\n  * [Paramorphism](#paramorphism)\n  * [Apomorphism](#apomorphism)\n* [Setoid](#setoid)\n* [半群 (Semigroup)](#semigroup)\n* [可折叠性 (Foldable)](#foldable)\n* [透镜 (Lens)](#lens)\n* [类型签名 (Type Signatures)](#type-signatures)\n* [代数数据类型 (Algebraic data type)](#algebraic-data-type)\n  * [和类型 (Sum type)](#sum-type)\n  * [积类型 (Product type)](#product-type)\n* [可选类型 (Option)](#option)\n* [函数 (Function)](#function)\n* [偏函数 (Partial Function)](#partial-function)\n* [函数式编程库](#functional-programming-libraries-in-javascript)\n\n\u003cdiv id=\"arity\"\u003e\u003c/div\u003e\n\n## Arity\n函数参数的个数。来自于单词 unary(一元), binary(二元), ternary(三元) 等等。这个单词是由 -ary 与 -ity 两个后缀拼接而成。例如，加法函数有两个参数，因此它被定义为二元函数(`binary function`)，或者说它的 `arity` 是2。它也被那些更喜欢希腊词根而非拉丁词根的人称为 `dyadic`。同样地，带有可变数量的参数的函数被称为 `variadic`，而二元函数只能且必须带两个参数，尽管有柯里化(currying)和偏函数应用(partial application)的存在(见下文)。\n\n``` js\nconst sum = (a, b) =\u003e a + b\n\nconst arity = sum.length\nconsole.log(arity)        // 2\n\n// 函数sum的arity为2。\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/arity.js)\n\n\u003cdiv id=\"higher-order-functions-hof\"\u003e\u003c/div\u003e\n\n## 高阶函数 (Higher-Order Function / HOF)\n以函数为参数或/和返回值的函数。\n\n``` js\nconst filter = (predicate, xs) =\u003e xs.filter(predicate)\n\nconst is = (type) =\u003e (x) =\u003e Object(x) instanceof type\n\nfilter(is(Number), [0, '1', 2, null]) // 0, 2\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/hoc.js)\n\n\u003cdiv id=\"closure\"\u003e\u003c/div\u003e\n\n## 闭包 (Closure)\n闭包是访问在其作用域外的变量的一种方式。正式地说，闭包是一种用于实现词法作用域命名绑定的技术。它是存储一个函数和它的环境的一种方法。\n\n闭包是一个作用域，它会捕获函数的局部变量，因此即使执行过程已经移出了定义它的那个代码块，也可以访问它们。也就是说，它们允许在声明变量的代码块已经执行完成之后，还是可以引用这个作用域。\n\n``` js\nconst addTo = x =\u003e y =\u003e x + y;\nvar addToFive = addTo(5);\naddToFive(3); //返回 8\n```\n\n函数`addTo()`返回了一个函数(在内部调用了`add()`)，我们将它保存在了一个叫做`addToFive`的变量中，并且柯里化地用一个参数5来调用它。\n\n理想情况下，当函数`addTo`执行完成后，它的作用域，包括本地变量add(即+)，x，y，都应该无法访问了。但是，`addToFive()`的调用返回了8。这说明，`addTo`函数的状态被保存了，即使在代码块已经完成执行之后。否则，就不会知道`addTo`曾经被`addTo(5)`这样调用过，且x的值被设为了5。\n\n词法作用域(lexical scoping)是它能找到x和add这两个已经完成执行的父级私有变量的原因。这个值就称为闭包。\n\n栈和函数的词法作用域被以父函数的引用的形式存储。这可以防止闭包和底层的变量被垃圾回收(因为至少有一个对它的有效引用)。\n\nLambda Vs 闭包：Lambda本质上是一个内联定义的函数，而不是声明函数的标准方法。Lambda经常可以作为对象被传递。\n\n闭包是通过引用其主体外部的字段来将其周围的状态包裹进来的函数。被包裹的状态在闭包调用期间保持不变。\n\n\u003cdiv id=\"partial-application\"\u003e\u003c/div\u003e\n\n## 偏函数应用 (Partial Application)\n\"部分地\"应用一个函数，即预设原始函数的部分参数来创建一个新的函数。\n\n``` js\n// 创建偏函数，固定一些参数\nconst partial = (f, ...args) =\u003e\n  // 返回一个带有剩余参数的函数\n  (...moreArgs) =\u003e\n    // 调用原始函数\n    f(...args, ...moreArgs)\n\nconst add3 = (a, b, c) =\u003e a + b + c // (c) =\u003e 2 + 3 + c\n\n// 部分地将`2`和`3`应用于`add3`，得到一个只有一个参数的函数\nconst fivePlus = partial(add3, 2, 3)\n\nfivePlus(4)  // 9\n```\n\n也可以使用 `Function.prototype.bind` 实现偏函数。\n\n``` js\nconst add1More = add3.bind(null, 2, 3) // (c) =\u003e 2 + 3 + c\n```\n\n偏函数应用通过对复杂的函数填充一部分数据来构成一个简单的函数。柯里化就是自动实现的偏函数。\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/partial.js)\n\n\u003cdiv id=\"currying\"\u003e\u003c/div\u003e\n\n## 柯里化 (Currying)\n将一个多元函数转变为一元函数的过程。\n每当函数被调用时，它仅仅接收一个参数并且返回带有一个参数的函数，直到传递完所有的参数。\n\n``` js\nconst sum = (a, b) =\u003e a + b\n\nconst curriedSum = (a) =\u003e (b) =\u003e a + b\n\ncurriedSum(3)(4)         // 7\n\nconst add2 = curriedSum(2)\n\nadd2(10)     // 12\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/curry.js)\n\n\u003cdiv id=\"auto-currying\"\u003e\u003c/div\u003e\n\n## 自动柯里化 (Auto Currying)\n将一个包含多个参数的函数转换成另一个函数，这个函数如果被给到的参数少于正确的数量，就会返回一个接受剩余参数的函数。\n\nlodash \u0026 Ramda 有一个`curry`函数可以做到这一点。\n\n``` js\nconst add = (x, y) =\u003e x + y\n\nconst curriedAdd = _.curry(add)\n\ncurriedAdd(1, 2)   // 3\ncurriedAdd(1)(2)   // 3\ncurriedAdd(1)      // (y) =\u003e 1 + y\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/curry2.js)\n\n#### 进一步阅读\n+ [Favoring Curry](http://fr.umio.us/favoring-curry/)\n+ [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA)\n\n\u003cdiv id=\"function-composition\"\u003e\u003c/div\u003e\n\n## 函数组合 (Function Composition) \n把两个函数放在一起形成第三个函数的行为，一个函数的输入为另一个函数的输出。\n\n``` js\nconst compose = (f, g) =\u003e (a) =\u003e f(g(a))    // 定义\nconst floorAndToString = compose((val) =\u003e val.toString(), Math.floor) // 使用\nfloorAndToString(12.12)   // '12'\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/compose.js)\n\n\u003cdiv id=\"continuation\"\u003e\u003c/div\u003e\n\n## Continuation (后续)\n在一个程序执行的任意时刻，尚未执行的代码称为 Continuation。\n\n``` js\nconst printAsString = (num) =\u003e console.log(`Given ${num}`)\n\nconst addOneAndContinue = (num, cc) =\u003e {\n  const result = num + 1\n  cc(result)\n}\n\naddOneAndContinue(2, printAsString) // 'Given 3'\n```\n\nContinuation 在异步编程中很常见，比如当程序需要接收到数据才能够继续执行。请求的响应通常作为代码的剩余执行部分，一旦接收到数据，对数据的处理被作为 Continuation。\n\n``` js\nconst continueProgramWith = (data) =\u003e {\n  // 继续执行程序\n}\n\nreadFileAsync('path/to/file', (err, response) =\u003e {\n  if (err) {\n    // 错误处理\n    return\n  }\n  continueProgramWith(response)\n})\n```\n\n\u003cdiv id=\"purity\"\u003e\u003c/div\u003e\n\n## 纯函数 (Purity)\n输出仅由输入决定，且不产生副作用。\n\n``` js\nconst greet = (name) =\u003e `hello, ${name}`\n\ngreet('world')\n```\n\n以下代码不是纯函数：\n\n``` js\nwindow.name = 'Brianne'\n\nconst greet = () =\u003e `Hi, ${window.name}`\n\ngreet() // \"Hi, Brianne\"\n```\n\n以上示例中，函数输出基于在函数外部存储的数据。\n\n``` js\nlet greeting\n\nconst greet = (name) =\u003e {\n    greeting = `Hi, ${name}`\n}\n\ngreet('Brianne')\ngreeting // \"Hi, Brianne\"\n```\n\n以上示例中，函数修改了外部状态。\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/purity.js)\n\n\u003cdiv id=\"side-effects\"\u003e\u003c/div\u003e\n\n## 副作用 (Side effects)\n如果一个函数或者表达式除了返回一个值之外，还与外部可变状态进行了交互（读取或写入），则它是有副作用的。\n\n``` js\nconst differentEveryTime = new Date()\n```\n\n``` js\nconsole.log('IO就是一种副作用!')\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/sideEffect.js)\n\n\u003cdiv id=\"idempotent\"\u003e\u003c/div\u003e\n\n## 幂等 (Idempotent)\n如果一个函数执行多次皆返回相同的结果，则它是幂等的。\n\n``` js\nf(f(x)) ≍ f(x)\n```\n\n``` js\nMath.abs(Math.abs(10))\n```\n\n``` js\nsort(sort(sort([2, 1])))\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/idempotent.js)\n\n\u003cdiv id=\"point-free-style\"\u003e\u003c/div\u003e\n\n## Point-Free 风格 (Point-Free Style)\n定义函数时，不显式地指出函数所带参数。这种风格通常需要柯里化或者高阶函数。也叫 Tacit programming。\n\n``` js\n// 已知：\nconst map = (fn) =\u003e (list) =\u003e list.map(fn)\nconst add = (a) =\u003e (b) =\u003e a + b\n\n// 所以：\n\n// 非Points-Free —— number 是显式参数\nconst incrementAll = (numbers) =\u003e map(add(1))(numbers)\n\n// Points-Free —— list 是隐式参数\nconst incrementAll2 = map(add(1))\n```\n\n`incrementAll` 识别并且使用了 `numbers` 参数，因此它不是 Point-Free 风格的。\n`incrementAll2` 仅连接函数与值，并不提及它所使用的参数，因为它是 Point-Free 风格的。\n\nPoint-Free 风格的函数就像平常的赋值，不使用 `function` 或者 `=\u003e`。\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/pointFree.js)\n\n\u003cdiv id=\"predicate\"\u003e\u003c/div\u003e\n\n## 断定 (Predicate)\n根据输入返回 true 或 false。通常用在 array filter 的回调函数中。\n\n``` js\nconst predicate = (a) =\u003e a \u003e 2\n\n;[1, 2, 3, 4].filter(predicate)\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/predicate.js)\n\n\u003cdiv id=\"contracts\"\u003e\u003c/div\u003e\n\n## 契约 (Contracts)\n契约规定了函数或表达式在运行时的行为的职责和保障。它表现为一组规则，这些规则是对函数或表达式的输入和输出的期望。当违反契约时，将抛出一个错误。\n\n``` js\n// 定义的contract: int -\u003e boolean\nconst contract = (input) =\u003e {\n  if (typeof input === 'number') return true\n  throw new Error('Contract Violated: expected int -\u003e int')\n}\n\nconst addOne = (num) =\u003e contract(num) \u0026\u0026 num + 1\n\naddOne(2) // 3\naddOne('hello') // 违反了contract: int -\u003e boolean\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/contracts.js)\n\n\u003cdiv id=\"category\"\u003e\u003c/div\u003e\n\n## 范畴 (Category)\n在范畴论中，范畴是指对象集合及它们之间的态射 (morphism)。在编程中，数据类型作为对象，函数作为态射。\n\n一个有效的范畴遵从以下三个原则：\n\n1. 必有一个同一态射（identity morphism）将一个对象映射到它自身。即当 `a` 是范畴里的一个对象时，必有一个函数使 `a -\u003e a`。\n2. 态射必是可组合的。`a`，`b`，`c` 是范畴里的对象，`f` 是态射 `a -\u003e b`，`g` 是 `b -\u003e c` 态射。`g(f(x))` 一定与 `(g • f)(x)` 是等价的。\n3. 组合满足结合律。`f • (g • h)` 与 `(f • g) • h` 是等价的。\n\n由于这些准则是在非常抽象的层面控制着组合方式，因此范畴论对于发现组合的新方法来说是伟大的。\n\n#### 进一步阅读\n+ [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)\n\n\u003cdiv id=\"value\"\u003e\u003c/div\u003e\n\n## 值 (Value)\n任何可以赋给变量的东西叫做值。\n\n``` js\n5\nObject.freeze({name: 'John', age: 30})\n;(a) =\u003e a\n;[1]\nundefined\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/value.js)\n\n\u003cdiv id=\"constant\"\u003e\u003c/div\u003e\n\n## 常量 (Constant)\n一旦被定义之后就不可以被重新赋值。\n\n``` js\nconst five = 5\nconst john = Object.freeze({name: 'John', age: 30})\n```\n\n常量是[引用透明](#referential-transparency)的，也就是说，它们可以被它们所代表的值替代而不影响结果。\n\n对于以上两个常量，以下语句总会返回 true。\n\n``` js\njohn.age + five === ({name: 'John', age: 30}).age + (5)\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/constant.js)\n\n\u003cdiv id=\"functor\"\u003e\u003c/div\u003e\n\n## 函子 (Functor)\n函子是一个实现了 `map` 函数的对象。`map` 函数会遍历对象中的每个值并生成一个新的对象\b，遵守两个准则:\n\n\u003cdiv id=\"preserves-identity\"\u003e\u003c/div\u003e\n\n### 一致性 (Preserves identity)\n\n``` js\nobject.map(x =\u003e x) ≍ object\n```\n\n\u003cdiv id=\"composable\"\u003e\u003c/div\u003e\n\n### 组合性 (Composable)\n\n``` js\nobject.map(compose(f, g)) ≍ object.map(g).map(f)  // f, g 为任意函数\n```\n(`f`, `g` 是任意的函数)\n\n在 javascript 中一个常见的函子是 Array, 因为它遵守因子的两个准则。\n\n``` js\nconst f = x =\u003e x + 1\nconst g = x =\u003e x * 2\n\n;[1, 2, 3].map(x =\u003e f(g(x)))\n;[1, 2, 3].map(g).map(f)\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/functor.js)\n\n\u003cdiv id=\"pointed-functor\"\u003e\u003c/div\u003e\n\n### 指向函子 (Pointed Functor)\n一个对象，拥有一个`of`函数，可以将一个任何值放入它自身。\n\nES2015 添加了 `Array.of`，使 Array 成为了 Pointed Functor。\n\n``` js\nArray.of(1)\n```\n\n\u003cdiv id=\"lift\"\u003e\u003c/div\u003e\n\n## 抬升 (Lift)\n抬升是指将一个值放进一个对象（如[函子](#functor)）中。如果你将一个函数抬升到一个[应用函子](#applicative-functor)中，那么就可以将它作用于该函子中的值。\n\n``` js\nconst liftA2 = (f) =\u003e (a, b) =\u003e a.map(f).ap(b) // 注意这里是 ap 而不是 map.\n\nconst mult = a =\u003e b =\u003e a * b\n\nconst liftedMult = liftA2(mult) // 这个函数现在可以作用于函子，如Array\n\nliftedMult([1, 2], [3]) // [3, 6]\nliftA2(a =\u003e b =\u003e a + b)([1, 2], [3, 4]) // [4, 5, 5, 6]\n```\n\n抬升并应用一个单参数的函数的作用等同于 `map`。\n\n``` js\nconst increment = (x) =\u003e x + 1\n\nlift(increment)([2]) // [3]\n;[2].map(increment) // [3]\n```\n\n\u003cdiv id=\"referential-transparency\"\u003e\u003c/div\u003e\n\n## 引用透明性 (Referential Transparency)\n如果一个表达式能够被它的值替代而不改变程序的行为，则它是引用透明的。\n\n例如我们有 greet 函数：\n\n``` js\nconst greet = () =\u003e 'hello, world.'\n```\n\n任何对 `greet()` 的调用都可以被替换为 `Hello World!`, 因此 greet 是引用透明的。\n\n\u003cdiv id=\"equational-reasoning\"\u003e\u003c/div\u003e\n\n## 等式推理 (Equational Reasoning)\n当一个应用程序由表达式组成并且没有副作用时，我们可以从这些组成部分中得知系统的真相。\n\n\u003cdiv id=\"lambda\"\u003e\u003c/div\u003e\n\n## Lambda\n一种可以被视作一个值的匿名函数。\n\n``` js\n;(function (a) {\n    return a + 1\n})\n\n;(a) =\u003e a + 1\n```\n\nLambda 通常作为参数被传递给高阶函数。\n\n``` js\n[1, 2].map((a) =\u003e a + 1)\n```\n\n可以把 Lambda 赋值给一个变量。\n\n``` js\nconst add1 = (a) =\u003e a + 1\n```\n\n\u003cdiv id=\"lambda-calculus\"\u003e\u003c/div\u003e\n\n## Lambda演算 (Lambda Calculus)\n数学的一个分支，使用函数创造 [通用计算模型](https://en.wikipedia.org/wiki/Lambda_calculus)\n\n\u003cdiv id=\"lazy-evaluation\"\u003e\u003c/div\u003e\n\n## 惰性求值 (Lazy evaluation)\n惰性求值是一种按需调用的求值机制，它将表达式的求值延迟到需要它的值为止，在函数式语言中，允许类似无限列表这样的结构存在，而这在非常重视命令顺序的命令式语言中通常是不可用的。\n\n``` js\nconst rand = function* () {\n  while (true) {\n    yield Math.random()  \n  } \n}\n\nconst randIter = rand()\nrandIter.next() // 每次执行产生一个随机值，表达式会在需要时求值。\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/functor.js)\n\n\u003cdiv id=\"monoid\"\u003e\u003c/div\u003e\n\n## 幺半群 (Monoid)\n一个对象，它拥有一个函数，这个函数用来与另一个相同类型的对象\"结合\"。对象的类型（[半群](#semigroup)）必须具有一个\"identity\"值。\n\n数值加法是一个简单的幺半群:\n\n``` js\n1 + 1   // 2\n```\n\n以上示例中，数是对象而 `+` 是函数。\n\n当任何一个值与\"identity\"值结合时，结果一定是原始的值。\"identity\"也是可换位的（即排列次序不影响结果）。\n\n加法的特征值是 0。\n\n``` js\n1 + 0   // 1\n```\n\n操作的组合不会影响结果（必须满足结合律）:\n\n``` js\n1 + (2 + 3) === (1 + 2) + 3 // true\n```\n\n数组的结合也是幺半群:\n\n``` js\n;[1, 2].concat([3, 4]) // [1, 2, 3, 4]\n```\n\n`identity` 值为空数组\n\n``` js\n;[1, 2].concat([])\n```\n\n减法作为一个反例，不形成幺半群，因为不存在可以换位的\"identity\"值。\n\n``` js\n0 - 4 === 4 - 0 // false\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/monoid.js)\n\n\u003cdiv id=\"monad\"\u003e\u003c/div\u003e\n\n## 单子 (Monad)\n拥有 `of` 和 `chain` 函数的对象即为单子。`chain` 很像 `map`， 不同的是它可以展平嵌套数据。\n\n``` js\nArray.prototype.chain = function (f) {\n  return this.reduce((acc, it) =\u003e acc.concat(f(it)), [])  \n}\n\n// 使用\n;Array.of('cat,dog', 'fish,bird').chain(s =\u003e s.split(',')) // ['cat', 'dog', 'fish', 'bird']\n\n// 和 map 相比\n;Array.of('cat,dog', 'fish,bird').map(s =\u003e s.split(',')) // [['cat', 'dog'], ['fish', 'bird']]\n```\n\n在有些函数式语言中，`of` 也称为 `return`，`chain` 也称为 `flatmap` 与 `bind`。\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/monad.js)\n\n\u003cdiv id=\"comonad\"\u003e\u003c/div\u003e\n\n## 余单子 (Comonad)\n拥有 `extract` 与 `extend` 函数的对象。\n\n``` js\nconst CoIdentity = (v) =\u003e ({\n  val: v,\n  extract () {\n    return this.val  \n  },\n  extend (f) {\n    return CoIdentity(f(this))  \n  }\n})\n```\n\nExtract 将值从余单子中取出。\n\n``` js\nCoIdentity(1).extract() // 1\n```\n\nExtends 在余单子上运行一个函数。这个函数会返回和余单子相同的类型。\n\n``` js\nCoIdentity(1).extend(x =\u003e x.extract() + 1) // CoIdentity(2)\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/comonad.js)\n\n\u003cdiv id=\"applicative-functor\"\u003e\u003c/div\u003e\n\n## 应用函子 (Applicative Functor)\n一个拥有 `ap` 函数的对象称为应用函子。`ap` 将对象中的函数应用于另一个同样类型的对象中的值。\n\n``` js\n// 实现\nArray.prototype.ap = function (xs) {\n    return this.reduce((acc, f) =\u003e acc.concat(xs.map(f)), [])\n}\n\n// 示例\n;[(a) =\u003e a + 1].ap([1]) // [2]\n```\n\n如果你有两个对象，并需要对他们的元素执行一个二元函数，这将会很有用。\n\n``` js\n// 你想要组合的两个数组\nconst arg1 = [1, 3]\nconst arg2 = [4, 5]\n\n// 组合函数 - 必须要柯里化\nconst add = (x) =\u003e (y) =\u003e x + y\n\nconst partiallyAppliedAdds = [add].ap(arg1) // [(y) =\u003e 1 + y, (y) =\u003e 3 + y]\n```\n\n由此得到了一个函数数组，并且可以调用 `ap` 函数得到结果。\n\n``` js\npartiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8]\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/applicativeFunctor.js)\n\n\u003cdiv id=\"morphism\"\u003e\u003c/div\u003e\n\n## 态射 (Morphism)\n一个变形函数。\n\n\u003cdiv id=\"endomorphism\"\u003e\u003c/div\u003e\n\n### Endomorphism (自同态)\n输入输出是相同类型的函数。\n\n``` js\n// uppercase :: String -\u003e String\nconst uppercase = (str) =\u003e str.toUpperCase()\n\n// decrement :: Number -\u003e Number\nconst decrement = (x) =\u003e x - 1\n```\n\n\u003cdiv id=\"isomorphism\"\u003e\u003c/div\u003e\n\n### Isomorphism (同构)\n两个不用类型的对象之间的变换，保持结构并且不丢失数据。\n\n例如，一个二维坐标既可以表示为数组 `[2, 3]`，也可以表示为对象 `{x: 2, y: 3}`。\n\n``` js\n// 提供函数在两种类型间互相转换\nconst pairToCoords = (pair) =\u003e ({x: pair[0], y: pair[1]})\n\nconst coordsToPair = (coords) =\u003e [coords.x, coords.y]\n\ncoordsToPair(pairToCoords([1, 2])) // [1, 2]\n\npairToCoords(coordsToPair({x: 1, y: 2})) // {x: 1, y: 2}\n```\n\n\u003cdiv id=\"homomorphism\"\u003e\u003c/div\u003e\n\n### Homomorphism (同态)\n同态只是一个保持结构的映射，实际上，函子只是[范畴](#category)之间的同态，因为它在映射下保持了原范畴的结构。\n\n``` js\nA.of(f).ap(A.of(x)) == A.of(f(x))\n\nEither.of(_.toUpper).ap(Either.of(\"oreos\")) == Either.of(_.toUpper(\"oreos\"))\n```\n\n\u003cdiv id=\"catamorphism\"\u003e\u003c/div\u003e\n\n### Catamorphism\n\n一个 `reduceRight` 函数，它应用于累加器(accumulator)和数组中的每个值（从右到左），来将其缩减为一个单一的值。\n\n\u003cdiv id=\"anamorphism\"\u003e\u003c/div\u003e\n\n### Anamorphism\n一个 `unfold` 函数。`unfold` 是 `fold`（`ruduce`）的反面。它从一个值生成一个列表。\n\n``` js\nconst unfold = (f, seed) =\u003e {\n  function go(f, seed, acc) {\n    const res = f(seed);\n    return res ? go(f, res[1], acc.concat([res[0]])) : acc;\n  }\n  return go(f, seed, [])\n}\n```\n\n``` js\nconst countDown = n =\u003e unfold((n) =\u003e {\n  return n \u003c= 0 ? undefined : [n, n - 1]\n}, n)\n\ncountDown(5) // [5, 4, 3, 2, 1]\n```\n\n\u003cdiv id=\"hylomorphism\"\u003e\u003c/div\u003e\n\n### Hylomorphism\nAnamorphism 和 catamorphism 的结合。\n\n\u003cdiv id=\"paramorphism\"\u003e\u003c/div\u003e\n\n### Paramorphism\n一类类似于 `reduceRight` 的函数，不过还是有区别的：\n\n在Paramorphism中，reducer的参数是当前的值、所有先前的值的缩减(reduction，即reduce的结果)、以及形成该缩减的值的列表。\n\n``` js\n// 包含 undefined 对于列表来说显然是不安全的，\n// 但是足以说明问题。\nconst para = (reducer, accumulator, elements) =\u003e {\n  if (elements.length === 0)\n    return accumulator\n\n  const head = elements[0]\n  const tail = elements.slice(1)\n\n  return reducer(head, tail, para(reducer, accumulator, tail))\n}\n\nconst suffixes = list =\u003e para(\n  (x, xs, suffxs) =\u003e [xs, ... suffxs],\n  [],\n  list\n)\n\nsuffixes([1, 2, 3, 4, 5]) // [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []]\n```\n\n上面的例子中的 reducer（`[x, ... xs]`）的第三个参数有点像一个\"如何达到你当前的 acc 值\"的历史记录。\n\n\u003cdiv id=\"apomorphism\"\u003e\u003c/div\u003e\n\n### Apomorphism\nparamorphism 的反面。就像 anamorphism 是 catamorphism 的反面一样。对于 paramorphism，我们结合了对累加器的访问和已经累加的东西，而apomorphism让我们可以 unfold（展开）并且具有提早return的可能性。\n\n\u003cdiv id=\"setoid\"\u003e\u003c/div\u003e\n\n## Setoid\n拥有 `equals` 函数的对象。`equals` 可以用来和其它相同类型的对象比较。\n\n``` js\nArray.prototype.equals = function (arr) {\n  const len = this.length\n  if (len !== arr.length) {\n    return false\n  }\n  for (let i = 0; i \u003c len; i++) {\n    if (this[i] !== arr[i]) {\n      return false\n    }\n  }\n  return true\n}\n\n;[1, 2].equals([1, 2])   // true\n;[1, 2].equals([3, 4])   // false\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/setoid.js)\n\n\u003cdiv id=\"semigroup\"\u003e\u003c/div\u003e\n\n## 半群 (Semigroup)\n一个拥有 `concat` 函数的对象。`concat` 可以连接相同类型的两个对象。\n\n``` js\n;[1].concat([2]) // [1, 2]\n```\n\n[示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/semigroup.js)\n\n\u003cdiv id=\"foldable\"\u003e\u003c/div\u003e\n\n## 可折叠性 (Foldable)\n一个拥有 `reduce` 函数的对象具有可折叠性。`reduce` 可以把一种类型的对象转化为另一种类型。\n\n``` js\nconst sum = (list) =\u003e list.reduce((acc, val) =\u003e acc + val, 0)\nsum([1, 2, 3])        // 6\n```\n\n\u003cdiv id=\"lens\"\u003e\u003c/div\u003e\n\n## 透镜 (Lens)\nLens是一种结构（通常是一个对象或者函数），他为其他数据结构对 getter 和非可变的 setter 进行配对。\n\n``` js\n// 使用 [Ramda's lens](http://ramdajs.com/docs/#lens)\nconst nameLens = R.lens(\n  // 一个对象的 name 属性的 getter\n  (obj) =\u003e obj.name,\n  // name 属性的 setter\n  (val, obj) =\u003e Object.assign({}, obj, {name: val})\n)\n```\n\n为给定的数据结构设置 `get` 和 `set` 可以实现一些关键特性。\n\n``` js\nconst person = {name: 'Gertrude Blanch'}\n\n// 调用 getter\nR.view(nameLens, person) // 'Gertrude Blanch'\n\n// 调用 setter\nR.set(nameLens, 'Shafi Goldwasser', person) // {name: 'Shafi Goldwasser'}\n\n// 将函数应用于结构中的值\nR.over(nameLens, uppercase, person) // {name: 'GERTRUDE BLANCH'}\n```\n\nlens 也是可以组合的。这让我们可以对深度嵌套的数据进行简单的不可变更新。\n\n``` js\n// 这个 lens 关注一个非空数组中的第一个元素\nconst firstLens = R.lens(\n  // 获取数组的第一个元素\n  xs =\u003e xs[0],\n  // 数组的第一个元素的非可变 setter\n  (val, [__, ...xs]) =\u003e [val, ...xs]\n)\n\nconst people = [{name: 'Gertrude Blanch'}, {name: 'Shafi Goldwasser'}]\n\n// 无论你怎么想，lens 是从左到右合成的\nR.over(compose(firstLens, nameLens), uppercase, people) // [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]\n```\n\n其他实现:\n\n[partial.lenses](https://github.com/calmm-js/partial.lenses) - \"好吃\"的语法糖和很多强大功能\n\n[nanoscope](http://www.kovach.me/nanoscope/) - 流畅接口\n\n\u003cdiv id=\"type-signatures\"\u003e\u003c/div\u003e\n\n## 类型签名 (Type Signatures)\n通常 js 中的函数会在注释中指出参数与返回值的类型。\n\n在整个社区内存在很大的差异，但通常遵循以下模式：\n\n``` js\n// functionName :: firstArgType -\u003e secondArgType -\u003e returnType\n\n// add :: Number -\u003e Number -\u003e Number\nconst add = (x) =\u003e (y) =\u003e x + y\n\n// increment :: Number -\u003e Number\nconst increment = (x) =\u003e x + 1\n```\n\n如果函数接受其他函数作为参数，那么这个函数需要用括号括起来。\n\n``` js\n// call :: (a -\u003e b) -\u003e a -\u003e b\nconst call = (f) =\u003e (x) =\u003e f(x)\n```\n\n字符 `a`, `b`, `c`, `d` 表明参数可以是任意类型。以下版本的 `map` 的函数类型的参数 `f`，把一种类型 `a` 的数组转化为另一种类型 `b` 的数组。\n\n``` js\n// map :: (a -\u003e b) -\u003e [a] -\u003e [b]\nconst map = (f) =\u003e (list) =\u003e list.map(f)\n```\n\n进一步阅读：\n\n- [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures)\n- [What is Hindley-Milner?](https://stackoverflow.com/questions/399312/what-is-hindley-milner/399392#399392) on Stack Overflow\n\n\u003cdiv id=\"algebraic-data-type\"\u003e\u003c/div\u003e\n\n## 代数数据类型 (Algebraic data type)\n一种由其他类型组合而成的复合类型。两种常见的代数类型是[sum](#sum-type)和[product](#product-type)。\n\n\u003cdiv id=\"sum-type\"\u003e\u003c/div\u003e\n\n### 和类型 (Sum type)\n和类型是将两种类型组合成另一种类型。之所以称为和，是因为结果类型的可能的值的数目是两种输入类型的值的数目的和。\n\njs 中没有这种类型，但是我们可以用 set 来假装：\n\n``` js\n// 想象这些不是 set，而是仅包含这些值的某种类型。\nconst bools = new Set([true, false])\nconst halfTrue = new Set(['half-true'])\n\n// 这个 weakLogic 类型包含 bools 类型和 halfTrue 类型的和。\nconst weakLogicValues = new Set([...bools, ...halfTrue])\n```\n\n和类型有时也称作联合类型（union type）、区分联合（discriminated union）或标记联合（tagged unions）。\n\nJS中有一些库可以帮助定义和使用联合类型。\n\n流（flow）包括联合类型，而TypeScript具有提供相同能力的枚举（enum）。\n\n\u003cdiv id=\"product-type\"\u003e\u003c/div\u003e\n\n### Product type\n用一种你可能更熟悉的方式把数据类型联合起来:\n\n``` js\n// point :: (Number, Number) -\u003e {x: Number, y: Number}\nconst point = (x, y) =\u003e ({x: x, y: y})\n```\n\n之所以称之为积，是因为数据结构的总的可能值是不同值的乘积。许多语言都有 tuple 类型，这是积类型的最简单形式。\n\n另见 [Set theory](https://en.wikipedia.org/wiki/Set_theory)\n\n\u003cdiv id=\"option\"\u003e\u003c/div\u003e\n\n## 可选类型 (Option)\nOption 是一种联合类型，它有两种情况，`Some` 或者 `None`。\n\nOption对于一些可能不会返回值的组合函数非常有用。\n\n``` js\n// 简单的定义\nconst Some = (v) =\u003e ({\n  val: v,\n  map (f) {\n    return Some(f(this.val))\n  },\n  chain (f) {\n    return f(this.val)\n  }\n})\n\nconst None = () =\u003e ({\n  map (f) {\n    return this\n  },\n  chain (f) {\n    return this\n  }\n})\n\n// maybeProp :: (String, {a}) -\u003e Option a\nconst maybeProp = (key, obj) =\u003e typeof obj[key] === 'undefined' ? None() : Some(obj[key])\n```\n\n使用 `chain` 可以序列化返回 `Option` 的函数。\n\n``` js\n// getItem :: Cart -\u003e Option CartItem\nconst getItem = (cart) =\u003e maybeProp('item', cart)\n\n// getPrice :: Item -\u003e Option Number\nconst getPrice = (item) =\u003e maybeProp('price', item)\n\n// getNestedPrice :: cart -\u003e Option a\nconst getNestedPrice = (cart) =\u003e getItem(obj).chain(getPrice)\n\ngetNestedPrice({}) // None()\ngetNestedPrice({item: {foo: 1}}) // None()\ngetNestedPrice({item: {price: 9.99}}) // Some(9.99)\n```\n\n在其它的一些地方，`Option` 也称为 `Maybe`，`Some` 也称为 `Just`，`None` 也称为 `Nothing`。\n\n[示例 option.js](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/option.js)\n[示例 maybe.js](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/maybe.js)\n\n\u003cdiv id=\"function\"\u003e\u003c/div\u003e\n\n## Function\n一个函数 `f :: A =\u003e B` 是一个表达式，通常称为 arrow 或者 lambda 表达式——只能有**一个**（这点是不可变的）的 `A` 类型参数和**一个** `B` 类型返回值。该返回值完全取决于参数，使函数独立于上下文，或者说[引用透明](#referential-transparency)。这里暗示的是一个函数不能产生任何隐藏的[副作用](#side-effects)——根据定义，函数总是[纯](#purity)的。这些属性使函数易于使用：它们是完全确定的，因此也是可以预测的。函数可以将代码作为数据进行处理，对行为进行抽象：\n\n``` js\n// times2 :: Number -\u003e Number\nconst times2 = n =\u003e n * 2\n\n[1, 2, 3].map(times2) // [2, 4, 6]\n```\n\n\u003cdiv id=\"partial-function\"\u003e\u003c/div\u003e\n\n## 偏函数 (Partial function)\n偏函数是没有为全部参数定义的函数——它可能返回意料之外的结果或者永远不会终止。偏函数增加了认知开销，它们更难推理，并可能导致运行时错误。一些例子：\n\n``` js\n// 例1: 列表的和\n// sum :: [Number] -\u003e Number\nconst sum = arr =\u003e arr.reduce((a, b) =\u003e a + b)\nsum([1, 2, 3]) // 6\nsum([]) // TypeError: Reduce of empty array with no initial value\n\n// 例2: 获取列表的第一个值\n// first :: [A] -\u003e A\nconst first = a =\u003e a[0]\nfirst([42]) // 42\nfirst([]) // undefined\n// 甚至更糟: \nfirst([[42]])[0] // 42\nfirst([])[0] // Uncaught TypeError: Cannot read property '0' of undefined\n\n// 例3: 将函数重复 N 次\n// times :: Number -\u003e (Number -\u003e Number) -\u003e Number\nconst times = n =\u003e fn =\u003e n \u0026\u0026 (fn(n), times(n - 1)(fn))\ntimes(3)(console.log)\n// 3\n// 2\n// 1\ntimes(-1)(console.log)\n// RangeError: Maximum call stack size exceeded\n```\n\n### 处理偏函数\n偏函数是危险的，它们需要被非常谨慎地对待。你可能会得到意料之外的（错误的）结果或遇到运行时错误。有时偏函数可能根本不会返回。意识到并相应地处理所有这些边缘情况可能会变得非常乏味。幸运的是，部分函数可以转换为常规函数。我们可以提供默认值或使用 guard 来处理偏函数未定义的输入。利用 option 类型，我们可以在可能会出现意外行为的地方使用 yield `Some(value)` 或 `None`: \n\n``` js\n// 例1: 列表的和\n// 我们可以提供默认值，使它总会返回结果\n// sum :: [Number] -\u003e Number\nconst sum = arr =\u003e arr.reduce((a, b) =\u003e a + b, 0)\nsum([1, 2, 3]) // 6\nsum([]) // 0\n\n// 例2: 获取列表的第一个值\n// 将结果改为 Option\n// first :: [A] -\u003e A\nconst first = a =\u003e a.length ? Some(a[0]) : None()\nfirst([42]).map(a =\u003e console.log(a)) // 42\nfirst([]).map(a =\u003e console.log(a)) // console.log 不会执行\n//我们之前的糟糕情况\nfirst([[42]]).map(a =\u003e console.log(a[0])) // 42\nfirst([]).map(a =\u003e console.log(a[0])) // 不会执行，所以不会有 error\n// 更重要的是，通过返回类型 (Option) ，我们会知道：\n// 我们应该使用 .map 方法来访问数据，所以我们不会忘记检查输入，\n// 因为这样的检查会被内建在函数中。\n\n// 例3: 将函数重复 N 次\n// 我们需要通过改变条件来确保函数总会终止: \n// times :: Number -\u003e (Number -\u003e Number) -\u003e Number\nconst times = n =\u003e fn =\u003e n \u003e 0 \u0026\u0026 (fn(n), times(n - 1)(fn))\ntimes(3)(console.log)\n// 3\n// 2\n// 1\ntimes(-1)(console.log)\n// 不会再执行\n```\n\n将偏函数改成全函数可以防止此类运行时错误。总是返回一个\"值\"也会使得代码更容易维护和推理。\n\n\u003cdiv id=\"functional-programing-libraries-in-javascript\"\u003e\u003c/div\u003e\n\n## 在 js 中的函数式编程库\n\n+ [mori](https://github.com/swannodette/mori)\n+ [Immutable](https://github.com/facebook/immutable-js/)\n+ [Immer](https://github.com/immerjs/immer)\n+ [Ramda](https://github.com/ramda/ramda)\n+ [ramda-adjunct](https://github.com/char0n/ramda-adjunct)\n+ [Folktale](http://folktalejs.org)\n+ [monet.js](https://cwmyers.github.io/monet.js/)\n+ [lodash](https://github.com/lodash/lodash)\n+ [Underscore.js](https://github.com/jashkenas/underscore)\n+ [Lazy.js](https://github.com/dtao/lazy.js)\n+ [maryamyriameliamurphies.js](https://github.com/sjsyrek/maryamyriameliamurphies.js)\n+ [Haskell in ES6](https://github.com/casualjavascript/haskell-in-es6)\n+ [Sanctuary](https://github.com/sanctuary-js/sanctuary)\n+ [Crocks](https://github.com/evilsoft/crocks)\n+ [Fluture](https://github.com/fluture-js/Fluture)\n+ [fp-ts](https://github.com/gcanti/fp-ts)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshfshanyue%2Ffp-jargon-zh","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fshfshanyue%2Ffp-jargon-zh","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fshfshanyue%2Ffp-jargon-zh/lists"}