├── .gitignore ├── Readme.md └── demos ├── adequate.js ├── applicativeFunctor.js ├── arity.js ├── comonad.js ├── compose.js ├── constant.js ├── contracts.js ├── curry.js ├── curry2.js ├── endomor.js ├── functor.js ├── hoc.js ├── idempotent.js ├── lazy.js ├── lift.js ├── maybe.js ├── monad.js ├── monoid.js ├── option.js ├── package.json ├── partial.js ├── pointFree.js ├── pointedFunctor.js ├── predicate.js ├── purity.js ├── semigroup.js ├── setoid.js ├── sideEffects.js ├── typeSignature.js └── value.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # 函数式编程术语 2 | 3 | > 译者注:本项目译自 [functional-programing-jargon](https://github.com/hemanth/functional-programming-jargon),专业术语居多,如有错误,可以提 pr 更正。除了术语翻译,针对每项术语,也有代码示例,位于 /demos 目录下。另外,这里也有几份不错的文章和仓库。 4 | + [函数式编程入门教程](http://www.ruanyifeng.com/blog/2017/02/fp-tutorial.html) 5 | + [mostly-adequate-guide (10749 stars)](https://github.com/MostlyAdequate/mostly-adequate-guide) 6 | + [mostly-adequate-guide-chinese (602 stars)](https://github.com/llh911001/mostly-adequate-guide-chinese) 7 | + [fantasy-land](https://github.com/fantasyland/fantasy-land) 8 | 9 | 函数式编程有许多优势,由此越来越受欢迎。然而每个编程范式 (paradigm) 都有自己唯一的术语,函数式编程也不例外。我们提供一张术语表,希望使你学习函数式编程变得容易些。 10 | 11 | 示例均为 javascript (ES2015)。[为什么使用JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F) 12 | 13 | *尚在 WIP 阶段,欢迎 pr。* 14 | 15 | 如果适用,本篇文档使用定义在 [Fantasy Land spec](https://github.com/fantasyland/fantasy-land) 中的术语。 16 | 17 | **目录** 18 | 19 | * [Arity](#arity) 20 | * [高阶函数 (HOF)](#higher-order-functions-hof) 21 | * [闭包 (Closure)](#closure) 22 | * [偏函数应用 (Partial Application)](#partial-application) 23 | * [柯里化 (Currying)](#currying) 24 | * [自动柯里化 (Auto Currying)](#auto-currying) 25 | * [函数组合 (Function Composition)](#function-composition) 26 | * [后续 (Continuation)](#continuation) 27 | * [纯函数 (Purity)](#purity) 28 | * [副作用 (Side effects)](#side-effects) 29 | * [幂等性 (Idempotent)](#idempotent) 30 | * [Point-Free 风格 (Point-Free Style)](#point-free-style) 31 | * [断定 (Predicate)](#predicate) 32 | * [契约 (Contracts)](#contracts) 33 | * [范畴 (Category)](#category) 34 | * [值 (Value)](#value) 35 | * [常量 (Constant)](#constant) 36 | * [函子 (Functor)](#functor) 37 | * [一致性 (Preserves identity)](#preserves-identity) 38 | * [组合性 (Composable)](#composable) 39 | * [指向函子 (Pointed Functor)](#pointed-functor) 40 | * [抬升 (Lift)](#lift) 41 | * [引用透明性 (Referential Transparency)](#referential-transparency) 42 | * [等式推理 (Equational Reasoning)](#equational-reasoning) 43 | * [Lambda](#lambda) 44 | * [Lambda 演算 (Lambda Calculus)](#lambda-calculus) 45 | * [惰性求值 (Lazy evaluation)](#lazy-evaluation) 46 | * [幺半群 (Monoid)](#monoid) 47 | * [单子 (Monad)](#monad) 48 | * [余单子 (Comonad)](#comonad) 49 | * [应用函子 (Applicative Functor)](#applicative-functor) 50 | * [态射 (Morphism)](#morphism) 51 | * [Endomorphism (自同态)](#endomorphism) 52 | * [Isomorphism (同构)](#isomorphism) 53 | * [Homomorphism (同态)](#homomorphism) 54 | * [Catamorphism](#catamorphism) 55 | * [Anamorphism](#anamorphism) 56 | * [Hylomorphism](#hylomorphism) 57 | * [Paramorphism](#paramorphism) 58 | * [Apomorphism](#apomorphism) 59 | * [Setoid](#setoid) 60 | * [半群 (Semigroup)](#semigroup) 61 | * [可折叠性 (Foldable)](#foldable) 62 | * [透镜 (Lens)](#lens) 63 | * [类型签名 (Type Signatures)](#type-signatures) 64 | * [代数数据类型 (Algebraic data type)](#algebraic-data-type) 65 | * [和类型 (Sum type)](#sum-type) 66 | * [积类型 (Product type)](#product-type) 67 | * [可选类型 (Option)](#option) 68 | * [函数 (Function)](#function) 69 | * [偏函数 (Partial Function)](#partial-function) 70 | * [函数式编程库](#functional-programming-libraries-in-javascript) 71 | 72 |
73 | 74 | ## Arity 75 | 函数参数的个数。来自于单词 unary(一元), binary(二元), ternary(三元) 等等。这个单词是由 -ary 与 -ity 两个后缀拼接而成。例如,加法函数有两个参数,因此它被定义为二元函数(`binary function`),或者说它的 `arity` 是2。它也被那些更喜欢希腊词根而非拉丁词根的人称为 `dyadic`。同样地,带有可变数量的参数的函数被称为 `variadic`,而二元函数只能且必须带两个参数,尽管有柯里化(currying)和偏函数应用(partial application)的存在(见下文)。 76 | 77 | ``` js 78 | const sum = (a, b) => a + b 79 | 80 | const arity = sum.length 81 | console.log(arity) // 2 82 | 83 | // 函数sum的arity为2。 84 | ``` 85 | 86 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/arity.js) 87 | 88 |
89 | 90 | ## 高阶函数 (Higher-Order Function / HOF) 91 | 以函数为参数或/和返回值的函数。 92 | 93 | ``` js 94 | const filter = (predicate, xs) => xs.filter(predicate) 95 | 96 | const is = (type) => (x) => Object(x) instanceof type 97 | 98 | filter(is(Number), [0, '1', 2, null]) // 0, 2 99 | ``` 100 | 101 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/hoc.js) 102 | 103 |
104 | 105 | ## 闭包 (Closure) 106 | 闭包是访问在其作用域外的变量的一种方式。正式地说,闭包是一种用于实现词法作用域命名绑定的技术。它是存储一个函数和它的环境的一种方法。 107 | 108 | 闭包是一个作用域,它会捕获函数的局部变量,因此即使执行过程已经移出了定义它的那个代码块,也可以访问它们。也就是说,它们允许在声明变量的代码块已经执行完成之后,还是可以引用这个作用域。 109 | 110 | ``` js 111 | const addTo = x => y => x + y; 112 | var addToFive = addTo(5); 113 | addToFive(3); //返回 8 114 | ``` 115 | 116 | 函数`addTo()`返回了一个函数(在内部调用了`add()`),我们将它保存在了一个叫做`addToFive`的变量中,并且柯里化地用一个参数5来调用它。 117 | 118 | 理想情况下,当函数`addTo`执行完成后,它的作用域,包括本地变量add(即+),x,y,都应该无法访问了。但是,`addToFive()`的调用返回了8。这说明,`addTo`函数的状态被保存了,即使在代码块已经完成执行之后。否则,就不会知道`addTo`曾经被`addTo(5)`这样调用过,且x的值被设为了5。 119 | 120 | 词法作用域(lexical scoping)是它能找到x和add这两个已经完成执行的父级私有变量的原因。这个值就称为闭包。 121 | 122 | 栈和函数的词法作用域被以父函数的引用的形式存储。这可以防止闭包和底层的变量被垃圾回收(因为至少有一个对它的有效引用)。 123 | 124 | Lambda Vs 闭包:Lambda本质上是一个内联定义的函数,而不是声明函数的标准方法。Lambda经常可以作为对象被传递。 125 | 126 | 闭包是通过引用其主体外部的字段来将其周围的状态包裹进来的函数。被包裹的状态在闭包调用期间保持不变。 127 | 128 |
129 | 130 | ## 偏函数应用 (Partial Application) 131 | "部分地"应用一个函数,即预设原始函数的部分参数来创建一个新的函数。 132 | 133 | ``` js 134 | // 创建偏函数,固定一些参数 135 | const partial = (f, ...args) => 136 | // 返回一个带有剩余参数的函数 137 | (...moreArgs) => 138 | // 调用原始函数 139 | f(...args, ...moreArgs) 140 | 141 | const add3 = (a, b, c) => a + b + c // (c) => 2 + 3 + c 142 | 143 | // 部分地将`2`和`3`应用于`add3`,得到一个只有一个参数的函数 144 | const fivePlus = partial(add3, 2, 3) 145 | 146 | fivePlus(4) // 9 147 | ``` 148 | 149 | 也可以使用 `Function.prototype.bind` 实现偏函数。 150 | 151 | ``` js 152 | const add1More = add3.bind(null, 2, 3) // (c) => 2 + 3 + c 153 | ``` 154 | 155 | 偏函数应用通过对复杂的函数填充一部分数据来构成一个简单的函数。柯里化就是自动实现的偏函数。 156 | 157 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/partial.js) 158 | 159 |
160 | 161 | ## 柯里化 (Currying) 162 | 将一个多元函数转变为一元函数的过程。 163 | 每当函数被调用时,它仅仅接收一个参数并且返回带有一个参数的函数,直到传递完所有的参数。 164 | 165 | ``` js 166 | const sum = (a, b) => a + b 167 | 168 | const curriedSum = (a) => (b) => a + b 169 | 170 | curriedSum(3)(4) // 7 171 | 172 | const add2 = curriedSum(2) 173 | 174 | add2(10) // 12 175 | ``` 176 | 177 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/curry.js) 178 | 179 |
180 | 181 | ## 自动柯里化 (Auto Currying) 182 | 将一个包含多个参数的函数转换成另一个函数,这个函数如果被给到的参数少于正确的数量,就会返回一个接受剩余参数的函数。 183 | 184 | lodash & Ramda 有一个`curry`函数可以做到这一点。 185 | 186 | ``` js 187 | const add = (x, y) => x + y 188 | 189 | const curriedAdd = _.curry(add) 190 | 191 | curriedAdd(1, 2) // 3 192 | curriedAdd(1)(2) // 3 193 | curriedAdd(1) // (y) => 1 + y 194 | ``` 195 | 196 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/curry2.js) 197 | 198 | #### 进一步阅读 199 | + [Favoring Curry](http://fr.umio.us/favoring-curry/) 200 | + [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA) 201 | 202 |
203 | 204 | ## 函数组合 (Function Composition) 205 | 把两个函数放在一起形成第三个函数的行为,一个函数的输入为另一个函数的输出。 206 | 207 | ``` js 208 | const compose = (f, g) => (a) => f(g(a)) // 定义 209 | const floorAndToString = compose((val) => val.toString(), Math.floor) // 使用 210 | floorAndToString(12.12) // '12' 211 | ``` 212 | 213 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/compose.js) 214 | 215 |
216 | 217 | ## Continuation (后续) 218 | 在一个程序执行的任意时刻,尚未执行的代码称为 Continuation。 219 | 220 | ``` js 221 | const printAsString = (num) => console.log(`Given ${num}`) 222 | 223 | const addOneAndContinue = (num, cc) => { 224 | const result = num + 1 225 | cc(result) 226 | } 227 | 228 | addOneAndContinue(2, printAsString) // 'Given 3' 229 | ``` 230 | 231 | Continuation 在异步编程中很常见,比如当程序需要接收到数据才能够继续执行。请求的响应通常作为代码的剩余执行部分,一旦接收到数据,对数据的处理被作为 Continuation。 232 | 233 | ``` js 234 | const continueProgramWith = (data) => { 235 | // 继续执行程序 236 | } 237 | 238 | readFileAsync('path/to/file', (err, response) => { 239 | if (err) { 240 | // 错误处理 241 | return 242 | } 243 | continueProgramWith(response) 244 | }) 245 | ``` 246 | 247 |
248 | 249 | ## 纯函数 (Purity) 250 | 输出仅由输入决定,且不产生副作用。 251 | 252 | ``` js 253 | const greet = (name) => `hello, ${name}` 254 | 255 | greet('world') 256 | ``` 257 | 258 | 以下代码不是纯函数: 259 | 260 | ``` js 261 | window.name = 'Brianne' 262 | 263 | const greet = () => `Hi, ${window.name}` 264 | 265 | greet() // "Hi, Brianne" 266 | ``` 267 | 268 | 以上示例中,函数输出基于在函数外部存储的数据。 269 | 270 | ``` js 271 | let greeting 272 | 273 | const greet = (name) => { 274 | greeting = `Hi, ${name}` 275 | } 276 | 277 | greet('Brianne') 278 | greeting // "Hi, Brianne" 279 | ``` 280 | 281 | 以上示例中,函数修改了外部状态。 282 | 283 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/purity.js) 284 | 285 |
286 | 287 | ## 副作用 (Side effects) 288 | 如果一个函数或者表达式除了返回一个值之外,还与外部可变状态进行了交互(读取或写入),则它是有副作用的。 289 | 290 | ``` js 291 | const differentEveryTime = new Date() 292 | ``` 293 | 294 | ``` js 295 | console.log('IO就是一种副作用!') 296 | ``` 297 | 298 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/sideEffect.js) 299 | 300 |
301 | 302 | ## 幂等 (Idempotent) 303 | 如果一个函数执行多次皆返回相同的结果,则它是幂等的。 304 | 305 | ``` js 306 | f(f(x)) ≍ f(x) 307 | ``` 308 | 309 | ``` js 310 | Math.abs(Math.abs(10)) 311 | ``` 312 | 313 | ``` js 314 | sort(sort(sort([2, 1]))) 315 | ``` 316 | 317 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/idempotent.js) 318 | 319 |
320 | 321 | ## Point-Free 风格 (Point-Free Style) 322 | 定义函数时,不显式地指出函数所带参数。这种风格通常需要柯里化或者高阶函数。也叫 Tacit programming。 323 | 324 | ``` js 325 | // 已知: 326 | const map = (fn) => (list) => list.map(fn) 327 | const add = (a) => (b) => a + b 328 | 329 | // 所以: 330 | 331 | // 非Points-Free —— number 是显式参数 332 | const incrementAll = (numbers) => map(add(1))(numbers) 333 | 334 | // Points-Free —— list 是隐式参数 335 | const incrementAll2 = map(add(1)) 336 | ``` 337 | 338 | `incrementAll` 识别并且使用了 `numbers` 参数,因此它不是 Point-Free 风格的。 339 | `incrementAll2` 仅连接函数与值,并不提及它所使用的参数,因为它是 Point-Free 风格的。 340 | 341 | Point-Free 风格的函数就像平常的赋值,不使用 `function` 或者 `=>`。 342 | 343 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/pointFree.js) 344 | 345 |
346 | 347 | ## 断定 (Predicate) 348 | 根据输入返回 true 或 false。通常用在 array filter 的回调函数中。 349 | 350 | ``` js 351 | const predicate = (a) => a > 2 352 | 353 | ;[1, 2, 3, 4].filter(predicate) 354 | ``` 355 | 356 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/predicate.js) 357 | 358 |
359 | 360 | ## 契约 (Contracts) 361 | 契约规定了函数或表达式在运行时的行为的职责和保障。它表现为一组规则,这些规则是对函数或表达式的输入和输出的期望。当违反契约时,将抛出一个错误。 362 | 363 | ``` js 364 | // 定义的contract: int -> boolean 365 | const contract = (input) => { 366 | if (typeof input === 'number') return true 367 | throw new Error('Contract Violated: expected int -> int') 368 | } 369 | 370 | const addOne = (num) => contract(num) && num + 1 371 | 372 | addOne(2) // 3 373 | addOne('hello') // 违反了contract: int -> boolean 374 | ``` 375 | 376 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/contracts.js) 377 | 378 |
379 | 380 | ## 范畴 (Category) 381 | 在范畴论中,范畴是指对象集合及它们之间的态射 (morphism)。在编程中,数据类型作为对象,函数作为态射。 382 | 383 | 一个有效的范畴遵从以下三个原则: 384 | 385 | 1. 必有一个同一态射(identity morphism)将一个对象映射到它自身。即当 `a` 是范畴里的一个对象时,必有一个函数使 `a -> a`。 386 | 2. 态射必是可组合的。`a`,`b`,`c` 是范畴里的对象,`f` 是态射 `a -> b`,`g` 是 `b -> c` 态射。`g(f(x))` 一定与 `(g • f)(x)` 是等价的。 387 | 3. 组合满足结合律。`f • (g • h)` 与 `(f • g) • h` 是等价的。 388 | 389 | 由于这些准则是在非常抽象的层面控制着组合方式,因此范畴论对于发现组合的新方法来说是伟大的。 390 | 391 | #### 进一步阅读 392 | + [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/) 393 | 394 |
395 | 396 | ## 值 (Value) 397 | 任何可以赋给变量的东西叫做值。 398 | 399 | ``` js 400 | 5 401 | Object.freeze({name: 'John', age: 30}) 402 | ;(a) => a 403 | ;[1] 404 | undefined 405 | ``` 406 | 407 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/value.js) 408 | 409 |
410 | 411 | ## 常量 (Constant) 412 | 一旦被定义之后就不可以被重新赋值。 413 | 414 | ``` js 415 | const five = 5 416 | const john = Object.freeze({name: 'John', age: 30}) 417 | ``` 418 | 419 | 常量是[引用透明](#referential-transparency)的,也就是说,它们可以被它们所代表的值替代而不影响结果。 420 | 421 | 对于以上两个常量,以下语句总会返回 true。 422 | 423 | ``` js 424 | john.age + five === ({name: 'John', age: 30}).age + (5) 425 | ``` 426 | 427 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/constant.js) 428 | 429 |
430 | 431 | ## 函子 (Functor) 432 | 函子是一个实现了 `map` 函数的对象。`map` 函数会遍历对象中的每个值并生成一个新的对象,遵守两个准则: 433 | 434 |
435 | 436 | ### 一致性 (Preserves identity) 437 | 438 | ``` js 439 | object.map(x => x) ≍ object 440 | ``` 441 | 442 |
443 | 444 | ### 组合性 (Composable) 445 | 446 | ``` js 447 | object.map(compose(f, g)) ≍ object.map(g).map(f) // f, g 为任意函数 448 | ``` 449 | (`f`, `g` 是任意的函数) 450 | 451 | 在 javascript 中一个常见的函子是 Array, 因为它遵守因子的两个准则。 452 | 453 | ``` js 454 | const f = x => x + 1 455 | const g = x => x * 2 456 | 457 | ;[1, 2, 3].map(x => f(g(x))) 458 | ;[1, 2, 3].map(g).map(f) 459 | ``` 460 | 461 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/functor.js) 462 | 463 |
464 | 465 | ### 指向函子 (Pointed Functor) 466 | 一个对象,拥有一个`of`函数,可以将一个任何值放入它自身。 467 | 468 | ES2015 添加了 `Array.of`,使 Array 成为了 Pointed Functor。 469 | 470 | ``` js 471 | Array.of(1) 472 | ``` 473 | 474 |
475 | 476 | ## 抬升 (Lift) 477 | 抬升是指将一个值放进一个对象(如[函子](#functor))中。如果你将一个函数抬升到一个[应用函子](#applicative-functor)中,那么就可以将它作用于该函子中的值。 478 | 479 | ``` js 480 | const liftA2 = (f) => (a, b) => a.map(f).ap(b) // 注意这里是 ap 而不是 map. 481 | 482 | const mult = a => b => a * b 483 | 484 | const liftedMult = liftA2(mult) // 这个函数现在可以作用于函子,如Array 485 | 486 | liftedMult([1, 2], [3]) // [3, 6] 487 | liftA2(a => b => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] 488 | ``` 489 | 490 | 抬升并应用一个单参数的函数的作用等同于 `map`。 491 | 492 | ``` js 493 | const increment = (x) => x + 1 494 | 495 | lift(increment)([2]) // [3] 496 | ;[2].map(increment) // [3] 497 | ``` 498 | 499 |
500 | 501 | ## 引用透明性 (Referential Transparency) 502 | 如果一个表达式能够被它的值替代而不改变程序的行为,则它是引用透明的。 503 | 504 | 例如我们有 greet 函数: 505 | 506 | ``` js 507 | const greet = () => 'hello, world.' 508 | ``` 509 | 510 | 任何对 `greet()` 的调用都可以被替换为 `Hello World!`, 因此 greet 是引用透明的。 511 | 512 |
513 | 514 | ## 等式推理 (Equational Reasoning) 515 | 当一个应用程序由表达式组成并且没有副作用时,我们可以从这些组成部分中得知系统的真相。 516 | 517 |
518 | 519 | ## Lambda 520 | 一种可以被视作一个值的匿名函数。 521 | 522 | ``` js 523 | ;(function (a) { 524 | return a + 1 525 | }) 526 | 527 | ;(a) => a + 1 528 | ``` 529 | 530 | Lambda 通常作为参数被传递给高阶函数。 531 | 532 | ``` js 533 | [1, 2].map((a) => a + 1) 534 | ``` 535 | 536 | 可以把 Lambda 赋值给一个变量。 537 | 538 | ``` js 539 | const add1 = (a) => a + 1 540 | ``` 541 | 542 |
543 | 544 | ## Lambda演算 (Lambda Calculus) 545 | 数学的一个分支,使用函数创造 [通用计算模型](https://en.wikipedia.org/wiki/Lambda_calculus) 546 | 547 |
548 | 549 | ## 惰性求值 (Lazy evaluation) 550 | 惰性求值是一种按需调用的求值机制,它将表达式的求值延迟到需要它的值为止,在函数式语言中,允许类似无限列表这样的结构存在,而这在非常重视命令顺序的命令式语言中通常是不可用的。 551 | 552 | ``` js 553 | const rand = function* () { 554 | while (true) { 555 | yield Math.random() 556 | } 557 | } 558 | 559 | const randIter = rand() 560 | randIter.next() // 每次执行产生一个随机值,表达式会在需要时求值。 561 | ``` 562 | 563 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/functor.js) 564 | 565 |
566 | 567 | ## 幺半群 (Monoid) 568 | 一个对象,它拥有一个函数,这个函数用来与另一个相同类型的对象"结合"。对象的类型([半群](#semigroup))必须具有一个"identity"值。 569 | 570 | 数值加法是一个简单的幺半群: 571 | 572 | ``` js 573 | 1 + 1 // 2 574 | ``` 575 | 576 | 以上示例中,数是对象而 `+` 是函数。 577 | 578 | 当任何一个值与"identity"值结合时,结果一定是原始的值。"identity"也是可换位的(即排列次序不影响结果)。 579 | 580 | 加法的特征值是 0。 581 | 582 | ``` js 583 | 1 + 0 // 1 584 | ``` 585 | 586 | 操作的组合不会影响结果(必须满足结合律): 587 | 588 | ``` js 589 | 1 + (2 + 3) === (1 + 2) + 3 // true 590 | ``` 591 | 592 | 数组的结合也是幺半群: 593 | 594 | ``` js 595 | ;[1, 2].concat([3, 4]) // [1, 2, 3, 4] 596 | ``` 597 | 598 | `identity` 值为空数组 599 | 600 | ``` js 601 | ;[1, 2].concat([]) 602 | ``` 603 | 604 | 减法作为一个反例,不形成幺半群,因为不存在可以换位的"identity"值。 605 | 606 | ``` js 607 | 0 - 4 === 4 - 0 // false 608 | ``` 609 | 610 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/monoid.js) 611 | 612 |
613 | 614 | ## 单子 (Monad) 615 | 拥有 `of` 和 `chain` 函数的对象即为单子。`chain` 很像 `map`, 不同的是它可以展平嵌套数据。 616 | 617 | ``` js 618 | Array.prototype.chain = function (f) { 619 | return this.reduce((acc, it) => acc.concat(f(it)), []) 620 | } 621 | 622 | // 使用 623 | ;Array.of('cat,dog', 'fish,bird').chain(s => s.split(',')) // ['cat', 'dog', 'fish', 'bird'] 624 | 625 | // 和 map 相比 626 | ;Array.of('cat,dog', 'fish,bird').map(s => s.split(',')) // [['cat', 'dog'], ['fish', 'bird']] 627 | ``` 628 | 629 | 在有些函数式语言中,`of` 也称为 `return`,`chain` 也称为 `flatmap` 与 `bind`。 630 | 631 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/monad.js) 632 | 633 |
634 | 635 | ## 余单子 (Comonad) 636 | 拥有 `extract` 与 `extend` 函数的对象。 637 | 638 | ``` js 639 | const CoIdentity = (v) => ({ 640 | val: v, 641 | extract () { 642 | return this.val 643 | }, 644 | extend (f) { 645 | return CoIdentity(f(this)) 646 | } 647 | }) 648 | ``` 649 | 650 | Extract 将值从余单子中取出。 651 | 652 | ``` js 653 | CoIdentity(1).extract() // 1 654 | ``` 655 | 656 | Extends 在余单子上运行一个函数。这个函数会返回和余单子相同的类型。 657 | 658 | ``` js 659 | CoIdentity(1).extend(x => x.extract() + 1) // CoIdentity(2) 660 | ``` 661 | 662 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/comonad.js) 663 | 664 |
665 | 666 | ## 应用函子 (Applicative Functor) 667 | 一个拥有 `ap` 函数的对象称为应用函子。`ap` 将对象中的函数应用于另一个同样类型的对象中的值。 668 | 669 | ``` js 670 | // 实现 671 | Array.prototype.ap = function (xs) { 672 | return this.reduce((acc, f) => acc.concat(xs.map(f)), []) 673 | } 674 | 675 | // 示例 676 | ;[(a) => a + 1].ap([1]) // [2] 677 | ``` 678 | 679 | 如果你有两个对象,并需要对他们的元素执行一个二元函数,这将会很有用。 680 | 681 | ``` js 682 | // 你想要组合的两个数组 683 | const arg1 = [1, 3] 684 | const arg2 = [4, 5] 685 | 686 | // 组合函数 - 必须要柯里化 687 | const add = (x) => (y) => x + y 688 | 689 | const partiallyAppliedAdds = [add].ap(arg1) // [(y) => 1 + y, (y) => 3 + y] 690 | ``` 691 | 692 | 由此得到了一个函数数组,并且可以调用 `ap` 函数得到结果。 693 | 694 | ``` js 695 | partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8] 696 | ``` 697 | 698 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/applicativeFunctor.js) 699 | 700 |
701 | 702 | ## 态射 (Morphism) 703 | 一个变形函数。 704 | 705 |
706 | 707 | ### Endomorphism (自同态) 708 | 输入输出是相同类型的函数。 709 | 710 | ``` js 711 | // uppercase :: String -> String 712 | const uppercase = (str) => str.toUpperCase() 713 | 714 | // decrement :: Number -> Number 715 | const decrement = (x) => x - 1 716 | ``` 717 | 718 |
719 | 720 | ### Isomorphism (同构) 721 | 两个不用类型的对象之间的变换,保持结构并且不丢失数据。 722 | 723 | 例如,一个二维坐标既可以表示为数组 `[2, 3]`,也可以表示为对象 `{x: 2, y: 3}`。 724 | 725 | ``` js 726 | // 提供函数在两种类型间互相转换 727 | const pairToCoords = (pair) => ({x: pair[0], y: pair[1]}) 728 | 729 | const coordsToPair = (coords) => [coords.x, coords.y] 730 | 731 | coordsToPair(pairToCoords([1, 2])) // [1, 2] 732 | 733 | pairToCoords(coordsToPair({x: 1, y: 2})) // {x: 1, y: 2} 734 | ``` 735 | 736 |
737 | 738 | ### Homomorphism (同态) 739 | 同态只是一个保持结构的映射,实际上,函子只是[范畴](#category)之间的同态,因为它在映射下保持了原范畴的结构。 740 | 741 | ``` js 742 | A.of(f).ap(A.of(x)) == A.of(f(x)) 743 | 744 | Either.of(_.toUpper).ap(Either.of("oreos")) == Either.of(_.toUpper("oreos")) 745 | ``` 746 | 747 |
748 | 749 | ### Catamorphism 750 | 751 | 一个 `reduceRight` 函数,它应用于累加器(accumulator)和数组中的每个值(从右到左),来将其缩减为一个单一的值。 752 | 753 |
754 | 755 | ### Anamorphism 756 | 一个 `unfold` 函数。`unfold` 是 `fold`(`ruduce`)的反面。它从一个值生成一个列表。 757 | 758 | ``` js 759 | const unfold = (f, seed) => { 760 | function go(f, seed, acc) { 761 | const res = f(seed); 762 | return res ? go(f, res[1], acc.concat([res[0]])) : acc; 763 | } 764 | return go(f, seed, []) 765 | } 766 | ``` 767 | 768 | ``` js 769 | const countDown = n => unfold((n) => { 770 | return n <= 0 ? undefined : [n, n - 1] 771 | }, n) 772 | 773 | countDown(5) // [5, 4, 3, 2, 1] 774 | ``` 775 | 776 |
777 | 778 | ### Hylomorphism 779 | Anamorphism 和 catamorphism 的结合。 780 | 781 |
782 | 783 | ### Paramorphism 784 | 一类类似于 `reduceRight` 的函数,不过还是有区别的: 785 | 786 | 在Paramorphism中,reducer的参数是当前的值、所有先前的值的缩减(reduction,即reduce的结果)、以及形成该缩减的值的列表。 787 | 788 | ``` js 789 | // 包含 undefined 对于列表来说显然是不安全的, 790 | // 但是足以说明问题。 791 | const para = (reducer, accumulator, elements) => { 792 | if (elements.length === 0) 793 | return accumulator 794 | 795 | const head = elements[0] 796 | const tail = elements.slice(1) 797 | 798 | return reducer(head, tail, para(reducer, accumulator, tail)) 799 | } 800 | 801 | const suffixes = list => para( 802 | (x, xs, suffxs) => [xs, ... suffxs], 803 | [], 804 | list 805 | ) 806 | 807 | suffixes([1, 2, 3, 4, 5]) // [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []] 808 | ``` 809 | 810 | 上面的例子中的 reducer(`[x, ... xs]`)的第三个参数有点像一个"如何达到你当前的 acc 值"的历史记录。 811 | 812 |
813 | 814 | ### Apomorphism 815 | paramorphism 的反面。就像 anamorphism 是 catamorphism 的反面一样。对于 paramorphism,我们结合了对累加器的访问和已经累加的东西,而apomorphism让我们可以 unfold(展开)并且具有提早return的可能性。 816 | 817 |
818 | 819 | ## Setoid 820 | 拥有 `equals` 函数的对象。`equals` 可以用来和其它相同类型的对象比较。 821 | 822 | ``` js 823 | Array.prototype.equals = function (arr) { 824 | const len = this.length 825 | if (len !== arr.length) { 826 | return false 827 | } 828 | for (let i = 0; i < len; i++) { 829 | if (this[i] !== arr[i]) { 830 | return false 831 | } 832 | } 833 | return true 834 | } 835 | 836 | ;[1, 2].equals([1, 2]) // true 837 | ;[1, 2].equals([3, 4]) // false 838 | ``` 839 | 840 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/setoid.js) 841 | 842 |
843 | 844 | ## 半群 (Semigroup) 845 | 一个拥有 `concat` 函数的对象。`concat` 可以连接相同类型的两个对象。 846 | 847 | ``` js 848 | ;[1].concat([2]) // [1, 2] 849 | ``` 850 | 851 | [示例](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/semigroup.js) 852 | 853 |
854 | 855 | ## 可折叠性 (Foldable) 856 | 一个拥有 `reduce` 函数的对象具有可折叠性。`reduce` 可以把一种类型的对象转化为另一种类型。 857 | 858 | ``` js 859 | const sum = (list) => list.reduce((acc, val) => acc + val, 0) 860 | sum([1, 2, 3]) // 6 861 | ``` 862 | 863 |
864 | 865 | ## 透镜 (Lens) 866 | Lens是一种结构(通常是一个对象或者函数),他为其他数据结构对 getter 和非可变的 setter 进行配对。 867 | 868 | ``` js 869 | // 使用 [Ramda's lens](http://ramdajs.com/docs/#lens) 870 | const nameLens = R.lens( 871 | // 一个对象的 name 属性的 getter 872 | (obj) => obj.name, 873 | // name 属性的 setter 874 | (val, obj) => Object.assign({}, obj, {name: val}) 875 | ) 876 | ``` 877 | 878 | 为给定的数据结构设置 `get` 和 `set` 可以实现一些关键特性。 879 | 880 | ``` js 881 | const person = {name: 'Gertrude Blanch'} 882 | 883 | // 调用 getter 884 | R.view(nameLens, person) // 'Gertrude Blanch' 885 | 886 | // 调用 setter 887 | R.set(nameLens, 'Shafi Goldwasser', person) // {name: 'Shafi Goldwasser'} 888 | 889 | // 将函数应用于结构中的值 890 | R.over(nameLens, uppercase, person) // {name: 'GERTRUDE BLANCH'} 891 | ``` 892 | 893 | lens 也是可以组合的。这让我们可以对深度嵌套的数据进行简单的不可变更新。 894 | 895 | ``` js 896 | // 这个 lens 关注一个非空数组中的第一个元素 897 | const firstLens = R.lens( 898 | // 获取数组的第一个元素 899 | xs => xs[0], 900 | // 数组的第一个元素的非可变 setter 901 | (val, [__, ...xs]) => [val, ...xs] 902 | ) 903 | 904 | const people = [{name: 'Gertrude Blanch'}, {name: 'Shafi Goldwasser'}] 905 | 906 | // 无论你怎么想,lens 是从左到右合成的 907 | R.over(compose(firstLens, nameLens), uppercase, people) // [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}] 908 | ``` 909 | 910 | 其他实现: 911 | 912 | [partial.lenses](https://github.com/calmm-js/partial.lenses) - "好吃"的语法糖和很多强大功能 913 | 914 | [nanoscope](http://www.kovach.me/nanoscope/) - 流畅接口 915 | 916 |
917 | 918 | ## 类型签名 (Type Signatures) 919 | 通常 js 中的函数会在注释中指出参数与返回值的类型。 920 | 921 | 在整个社区内存在很大的差异,但通常遵循以下模式: 922 | 923 | ``` js 924 | // functionName :: firstArgType -> secondArgType -> returnType 925 | 926 | // add :: Number -> Number -> Number 927 | const add = (x) => (y) => x + y 928 | 929 | // increment :: Number -> Number 930 | const increment = (x) => x + 1 931 | ``` 932 | 933 | 如果函数接受其他函数作为参数,那么这个函数需要用括号括起来。 934 | 935 | ``` js 936 | // call :: (a -> b) -> a -> b 937 | const call = (f) => (x) => f(x) 938 | ``` 939 | 940 | 字符 `a`, `b`, `c`, `d` 表明参数可以是任意类型。以下版本的 `map` 的函数类型的参数 `f`,把一种类型 `a` 的数组转化为另一种类型 `b` 的数组。 941 | 942 | ``` js 943 | // map :: (a -> b) -> [a] -> [b] 944 | const map = (f) => (list) => list.map(f) 945 | ``` 946 | 947 | 进一步阅读: 948 | 949 | - [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures) 950 | - [What is Hindley-Milner?](https://stackoverflow.com/questions/399312/what-is-hindley-milner/399392#399392) on Stack Overflow 951 | 952 |
953 | 954 | ## 代数数据类型 (Algebraic data type) 955 | 一种由其他类型组合而成的复合类型。两种常见的代数类型是[sum](#sum-type)和[product](#product-type)。 956 | 957 |
958 | 959 | ### 和类型 (Sum type) 960 | 和类型是将两种类型组合成另一种类型。之所以称为和,是因为结果类型的可能的值的数目是两种输入类型的值的数目的和。 961 | 962 | js 中没有这种类型,但是我们可以用 set 来假装: 963 | 964 | ``` js 965 | // 想象这些不是 set,而是仅包含这些值的某种类型。 966 | const bools = new Set([true, false]) 967 | const halfTrue = new Set(['half-true']) 968 | 969 | // 这个 weakLogic 类型包含 bools 类型和 halfTrue 类型的和。 970 | const weakLogicValues = new Set([...bools, ...halfTrue]) 971 | ``` 972 | 973 | 和类型有时也称作联合类型(union type)、区分联合(discriminated union)或标记联合(tagged unions)。 974 | 975 | JS中有一些库可以帮助定义和使用联合类型。 976 | 977 | 流(flow)包括联合类型,而TypeScript具有提供相同能力的枚举(enum)。 978 | 979 |
980 | 981 | ### Product type 982 | 用一种你可能更熟悉的方式把数据类型联合起来: 983 | 984 | ``` js 985 | // point :: (Number, Number) -> {x: Number, y: Number} 986 | const point = (x, y) => ({x: x, y: y}) 987 | ``` 988 | 989 | 之所以称之为积,是因为数据结构的总的可能值是不同值的乘积。许多语言都有 tuple 类型,这是积类型的最简单形式。 990 | 991 | 另见 [Set theory](https://en.wikipedia.org/wiki/Set_theory) 992 | 993 |
994 | 995 | ## 可选类型 (Option) 996 | Option 是一种联合类型,它有两种情况,`Some` 或者 `None`。 997 | 998 | Option对于一些可能不会返回值的组合函数非常有用。 999 | 1000 | ``` js 1001 | // 简单的定义 1002 | const Some = (v) => ({ 1003 | val: v, 1004 | map (f) { 1005 | return Some(f(this.val)) 1006 | }, 1007 | chain (f) { 1008 | return f(this.val) 1009 | } 1010 | }) 1011 | 1012 | const None = () => ({ 1013 | map (f) { 1014 | return this 1015 | }, 1016 | chain (f) { 1017 | return this 1018 | } 1019 | }) 1020 | 1021 | // maybeProp :: (String, {a}) -> Option a 1022 | const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]) 1023 | ``` 1024 | 1025 | 使用 `chain` 可以序列化返回 `Option` 的函数。 1026 | 1027 | ``` js 1028 | // getItem :: Cart -> Option CartItem 1029 | const getItem = (cart) => maybeProp('item', cart) 1030 | 1031 | // getPrice :: Item -> Option Number 1032 | const getPrice = (item) => maybeProp('price', item) 1033 | 1034 | // getNestedPrice :: cart -> Option a 1035 | const getNestedPrice = (cart) => getItem(obj).chain(getPrice) 1036 | 1037 | getNestedPrice({}) // None() 1038 | getNestedPrice({item: {foo: 1}}) // None() 1039 | getNestedPrice({item: {price: 9.99}}) // Some(9.99) 1040 | ``` 1041 | 1042 | 在其它的一些地方,`Option` 也称为 `Maybe`,`Some` 也称为 `Just`,`None` 也称为 `Nothing`。 1043 | 1044 | [示例 option.js](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/option.js) 1045 | [示例 maybe.js](https://github.com/shfshanyue/fp-jargon-zh/blob/master/demos/maybe.js) 1046 | 1047 |
1048 | 1049 | ## Function 1050 | 一个函数 `f :: A => B` 是一个表达式,通常称为 arrow 或者 lambda 表达式——只能有**一个**(这点是不可变的)的 `A` 类型参数和**一个** `B` 类型返回值。该返回值完全取决于参数,使函数独立于上下文,或者说[引用透明](#referential-transparency)。这里暗示的是一个函数不能产生任何隐藏的[副作用](#side-effects)——根据定义,函数总是[纯](#purity)的。这些属性使函数易于使用:它们是完全确定的,因此也是可以预测的。函数可以将代码作为数据进行处理,对行为进行抽象: 1051 | 1052 | ``` js 1053 | // times2 :: Number -> Number 1054 | const times2 = n => n * 2 1055 | 1056 | [1, 2, 3].map(times2) // [2, 4, 6] 1057 | ``` 1058 | 1059 |
1060 | 1061 | ## 偏函数 (Partial function) 1062 | 偏函数是没有为全部参数定义的函数——它可能返回意料之外的结果或者永远不会终止。偏函数增加了认知开销,它们更难推理,并可能导致运行时错误。一些例子: 1063 | 1064 | ``` js 1065 | // 例1: 列表的和 1066 | // sum :: [Number] -> Number 1067 | const sum = arr => arr.reduce((a, b) => a + b) 1068 | sum([1, 2, 3]) // 6 1069 | sum([]) // TypeError: Reduce of empty array with no initial value 1070 | 1071 | // 例2: 获取列表的第一个值 1072 | // first :: [A] -> A 1073 | const first = a => a[0] 1074 | first([42]) // 42 1075 | first([]) // undefined 1076 | // 甚至更糟: 1077 | first([[42]])[0] // 42 1078 | first([])[0] // Uncaught TypeError: Cannot read property '0' of undefined 1079 | 1080 | // 例3: 将函数重复 N 次 1081 | // times :: Number -> (Number -> Number) -> Number 1082 | const times = n => fn => n && (fn(n), times(n - 1)(fn)) 1083 | times(3)(console.log) 1084 | // 3 1085 | // 2 1086 | // 1 1087 | times(-1)(console.log) 1088 | // RangeError: Maximum call stack size exceeded 1089 | ``` 1090 | 1091 | ### 处理偏函数 1092 | 偏函数是危险的,它们需要被非常谨慎地对待。你可能会得到意料之外的(错误的)结果或遇到运行时错误。有时偏函数可能根本不会返回。意识到并相应地处理所有这些边缘情况可能会变得非常乏味。幸运的是,部分函数可以转换为常规函数。我们可以提供默认值或使用 guard 来处理偏函数未定义的输入。利用 option 类型,我们可以在可能会出现意外行为的地方使用 yield `Some(value)` 或 `None`: 1093 | 1094 | ``` js 1095 | // 例1: 列表的和 1096 | // 我们可以提供默认值,使它总会返回结果 1097 | // sum :: [Number] -> Number 1098 | const sum = arr => arr.reduce((a, b) => a + b, 0) 1099 | sum([1, 2, 3]) // 6 1100 | sum([]) // 0 1101 | 1102 | // 例2: 获取列表的第一个值 1103 | // 将结果改为 Option 1104 | // first :: [A] -> A 1105 | const first = a => a.length ? Some(a[0]) : None() 1106 | first([42]).map(a => console.log(a)) // 42 1107 | first([]).map(a => console.log(a)) // console.log 不会执行 1108 | //我们之前的糟糕情况 1109 | first([[42]]).map(a => console.log(a[0])) // 42 1110 | first([]).map(a => console.log(a[0])) // 不会执行,所以不会有 error 1111 | // 更重要的是,通过返回类型 (Option) ,我们会知道: 1112 | // 我们应该使用 .map 方法来访问数据,所以我们不会忘记检查输入, 1113 | // 因为这样的检查会被内建在函数中。 1114 | 1115 | // 例3: 将函数重复 N 次 1116 | // 我们需要通过改变条件来确保函数总会终止: 1117 | // times :: Number -> (Number -> Number) -> Number 1118 | const times = n => fn => n > 0 && (fn(n), times(n - 1)(fn)) 1119 | times(3)(console.log) 1120 | // 3 1121 | // 2 1122 | // 1 1123 | times(-1)(console.log) 1124 | // 不会再执行 1125 | ``` 1126 | 1127 | 将偏函数改成全函数可以防止此类运行时错误。总是返回一个"值"也会使得代码更容易维护和推理。 1128 | 1129 |
1130 | 1131 | ## 在 js 中的函数式编程库 1132 | 1133 | + [mori](https://github.com/swannodette/mori) 1134 | + [Immutable](https://github.com/facebook/immutable-js/) 1135 | + [Immer](https://github.com/immerjs/immer) 1136 | + [Ramda](https://github.com/ramda/ramda) 1137 | + [ramda-adjunct](https://github.com/char0n/ramda-adjunct) 1138 | + [Folktale](http://folktalejs.org) 1139 | + [monet.js](https://cwmyers.github.io/monet.js/) 1140 | + [lodash](https://github.com/lodash/lodash) 1141 | + [Underscore.js](https://github.com/jashkenas/underscore) 1142 | + [Lazy.js](https://github.com/dtao/lazy.js) 1143 | + [maryamyriameliamurphies.js](https://github.com/sjsyrek/maryamyriameliamurphies.js) 1144 | + [Haskell in ES6](https://github.com/casualjavascript/haskell-in-es6) 1145 | + [Sanctuary](https://github.com/sanctuary-js/sanctuary) 1146 | + [Crocks](https://github.com/evilsoft/crocks) 1147 | + [Fluture](https://github.com/fluture-js/Fluture) 1148 | + [fp-ts](https://github.com/gcanti/fp-ts) 1149 | -------------------------------------------------------------------------------- /demos/adequate.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash') 2 | 3 | const Container = function (x) { 4 | this.__value = x 5 | } 6 | 7 | Container.of = (x) => new Container(x) 8 | 9 | // console.log(Container.of(3)) 10 | // console.log(Container.of('hello, world')) 11 | // console.log(Container.of(Container.of(3))) 12 | 13 | Container.prototype.map = function (f) { 14 | return Container.of(f(this.__value)) 15 | } 16 | 17 | // console.log(Container.of(3).map(x => x + 2)) 18 | // console.log(Container.of('hello, world.').map(s => s.toUpperCase())) 19 | // console.log(Container.of("bombs").map(_.concat(' away')).map(_.prop('length'))) 20 | 21 | const Maybe = function (x) { 22 | this.__value = x 23 | } 24 | 25 | Maybe.of = (x) => new Maybe(x) 26 | 27 | Maybe.prototype.isNothing = function () { 28 | return this.__value === null || this.__value === undefined 29 | } 30 | 31 | Maybe.prototype.map = function (f) { 32 | return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this)) 33 | } 34 | -------------------------------------------------------------------------------- /demos/applicativeFunctor.js: -------------------------------------------------------------------------------- 1 | Array.prototype.ap = function (xs) { 2 | return this.reduce((acc, f) => acc.concat(xs.map(f)), []) 3 | } 4 | 5 | const r1 = [(a) => a + 1].ap([1]) 6 | 7 | console.log(r1) 8 | 9 | const arg1 = [1, 3, 5] 10 | const arg2 = [4, 5] 11 | 12 | const add = x => y => x + y 13 | const mult = x => x * 3 14 | 15 | const r2 = [add].ap(arg1) 16 | const r3 = r2.ap(arg2) 17 | 18 | const r4 = [add].ap(arg1).ap(arg2) 19 | const r5 = arg1.map(add).ap(arg2) 20 | const r6 = arg2.map(add).ap(arg1) 21 | 22 | console.log(r3, r4, r5, r6) 23 | 24 | // derived from chain 25 | Array.prototype.chain = function (f) { 26 | return this.reduce((acc, it) => acc.concat(f(it)), []) 27 | } 28 | 29 | const adds = [x => x + 1, x => x * 2] 30 | const r7 = adds.ap(arg2) 31 | const r8 = adds.chain(f => arg2.chain(f)) 32 | 33 | console.log(r7, r8) 34 | -------------------------------------------------------------------------------- /demos/arity.js: -------------------------------------------------------------------------------- 1 | const sum = (a, b) => a + b 2 | 3 | const arity = sum.length 4 | console.log(arity) // 2 5 | -------------------------------------------------------------------------------- /demos/comonad.js: -------------------------------------------------------------------------------- 1 | const CoIdentity = (v) => ({ 2 | val: v, 3 | extract () { 4 | return this.val 5 | }, 6 | extend (f) { 7 | return CoIdentity(f(this)) 8 | } 9 | }) 10 | 11 | const a = CoIdentity(1).extract() 12 | const b = CoIdentity(1).extend(x => x.extract() + 1) 13 | 14 | console.log(a, b) 15 | -------------------------------------------------------------------------------- /demos/compose.js: -------------------------------------------------------------------------------- 1 | const compose = (...f) => (a) => { 2 | const len = f.length 3 | let r = a 4 | for (let i = len - 1; i >= 0; i--) { 5 | r = f[i](r) 6 | } 7 | return r 8 | } 9 | 10 | const r1 = compose(x => 3 * x, Number, val => val.toString(), Math.floor) 11 | console.log(r1(12.22)) // '12' 12 | -------------------------------------------------------------------------------- /demos/constant.js: -------------------------------------------------------------------------------- 1 | const five = 5 2 | const john = Object.freeze({name: 'John', age: 30}) 3 | 4 | john.name = 'xiange' 5 | console.log(john) 6 | 7 | john.age + five === ({name: 'John', age: 30}).age + (5) 8 | -------------------------------------------------------------------------------- /demos/contracts.js: -------------------------------------------------------------------------------- 1 | const contract = (input) => { 2 | if (typeof input === 'number') return true 3 | throw new Error('Contract Violated: expected int -> int') 4 | } 5 | 6 | const addOne = (num) => contract(num) && num + 1 7 | 8 | addOne(2) 9 | addOne('hello') 10 | -------------------------------------------------------------------------------- /demos/curry.js: -------------------------------------------------------------------------------- 1 | const sum = (a, b) => a + b 2 | 3 | const curriedSum = (a) => (b) => a + b 4 | 5 | console.log(curriedSum(3)(4)) // 7 6 | 7 | const add2 = curriedSum(2) 8 | 9 | console.log(add2(10)) // 12 10 | -------------------------------------------------------------------------------- /demos/curry2.js: -------------------------------------------------------------------------------- 1 | const _ = require('lodash') 2 | 3 | const add = (x, y) => x + y 4 | 5 | const curriedAdd = _.curry(add) 6 | 7 | console.log(curriedAdd(1, 2)) // 3 8 | console.log(curriedAdd(1)(2)) // 3 9 | // console.log(curriedAdd(1)) // (y) => 1 + y 10 | 11 | const add4 = (a, b, c, d) => a + b + c + d 12 | 13 | const curriedAdd4 = _.curry(add4) 14 | 15 | console.log(curriedAdd4(1)(2)(3)(4)) 16 | console.log(curriedAdd4(1, 2)(3, 4)) 17 | console.log(curriedAdd4(1, 2, 3)(4)) 18 | 19 | // --------- sourece code ------------ 20 | // curry(add) -> (a) => (b) => add(a, b) 21 | // -> (a, b) => add(a, b) 22 | const partical = (f, ...args) => (...moreargs) => f(...args, ...moreargs) 23 | 24 | const curry = function (add, len = add.length) { 25 | return (...args) => len - args.length === 0 ? add(...args) : curry(partical(add, ...args), len - args.length) 26 | } 27 | 28 | const add6 = (a, b, c, d, e, f) => a + b + c + d + e + f 29 | 30 | console.log(curry(add6)(1, 2, 3)(4, 5, 6)) 31 | console.log(curry(add6)(1)(2, 3)(4, 5, 6)) 32 | console.log(curry(add6)(1, 2)(3)(4, 5, 6)) 33 | console.log(curry(add6)(1, 2)(3)(4)(5, 6)) 34 | -------------------------------------------------------------------------------- /demos/endomor.js: -------------------------------------------------------------------------------- 1 | // uppercase :: String -> String 2 | const uppercase = (str) => str.toUpperCase() 3 | 4 | // decrement :: Number -> Number 5 | const decrement = (x) => x - 1 6 | -------------------------------------------------------------------------------- /demos/functor.js: -------------------------------------------------------------------------------- 1 | const f = x => x + 1 2 | const g = x => x * 2 3 | 4 | const a = [1, 2, 3].map(x => f(g(x))) 5 | const b = [1, 2, 3].map(g).map(f) 6 | 7 | console.log(a, b) 8 | 9 | const Container = function (x) { 10 | this.__value = x 11 | } 12 | 13 | Container.of = (x) => new Container(x) 14 | 15 | // console.log(Container.of(3)) 16 | // console.log(Container.of('hello, world')) 17 | // console.log(Container.of(Container.of(3))) 18 | 19 | Container.prototype.map = function (f) { 20 | return Container.of(f(this.__value)) 21 | } 22 | 23 | // console.log(Container.of(3).map(x => x + 2)) 24 | // console.log(Container.of('hello, world.').map(s => s.toUpperCase())) 25 | const compose = (f, g) => x => f(g(x)) 26 | 27 | const r1 = Container.of(3).map(x => x + 2).map(x => x * 3) 28 | const r2 = Container.of(3).map(compose(x => x * 3, x => x + 2)) 29 | 30 | console.log(r1, r2) 31 | -------------------------------------------------------------------------------- /demos/hoc.js: -------------------------------------------------------------------------------- 1 | const filter = (predicate, xs) => xs.filter(predicate) 2 | 3 | const is = (type) => (x) => Object(x) instanceof type 4 | 5 | const results = filter(is(Number), [0, '1', 2, null]) 6 | 7 | console.log(results) // 0, 2 8 | -------------------------------------------------------------------------------- /demos/idempotent.js: -------------------------------------------------------------------------------- 1 | Math.abs(Math.abs(Math.abs(12.5))) 2 | 3 | 4 | -------------------------------------------------------------------------------- /demos/lazy.js: -------------------------------------------------------------------------------- 1 | const rand = function* () { 2 | while (true) { 3 | yield Math.random() 4 | } 5 | } 6 | 7 | const randIter = rand() 8 | const number = randIter.next() 9 | console.log(number.value) 10 | -------------------------------------------------------------------------------- /demos/lift.js: -------------------------------------------------------------------------------- 1 | Array.prototype.ap = function (xs) { 2 | return this.reduce((acc, f) => acc.concat(xs.map(f)), []) 3 | } 4 | 5 | const liftA2 = (f) => (a, b) => a.map(f).ap(b) 6 | 7 | const mult = (a) => (b) => a * b 8 | 9 | const liftedMult = liftA2(mult) 10 | 11 | const r1 = liftedMult([1, 2], [3, 5]) 12 | const r2 = liftA2(mult)([1, 2], [3, 5]) 13 | -------------------------------------------------------------------------------- /demos/maybe.js: -------------------------------------------------------------------------------- 1 | const Maybe = function (x) { 2 | this.__value = x 3 | } 4 | 5 | Maybe.of = (x) => new Maybe(x) 6 | 7 | Maybe.prototype.isNothing = function () { 8 | return this.__value === null || this.__value === undefined 9 | } 10 | 11 | Maybe.prototype.map = function (f) { 12 | return this.isNothing() ? Maybe.of(null) : Maybe.of(f(this)) 13 | } 14 | -------------------------------------------------------------------------------- /demos/monad.js: -------------------------------------------------------------------------------- 1 | Array.prototype.chain = function (f) { 2 | return this.reduce((acc, it) => acc.concat(f(it)), []) 3 | } 4 | 5 | Array.prototype.ap = function (xs) { 6 | return this.reduce((acc, f) => acc.concat(xs.map(f)), []) 7 | } 8 | 9 | // ['cat', 'dog', 'fish', 'bird'] 10 | const a = Array.of('cat,dog', 'fish,bird').chain(s => s.split(',')) 11 | 12 | // Derived from chain and of 13 | const animals = Array.of('cat,dog', 'fish,bird') 14 | const f = s => s.split(',') 15 | 16 | const b = animals.map(f) 17 | const c = animals.chain(x => { 18 | return Array.of(f(x)) 19 | }) 20 | const d = [f].ap(animals) 21 | 22 | // map :: function(f) { return this.chain(a => this.of(f(a))); } 23 | console.log(a, b, c, d) 24 | 25 | -------------------------------------------------------------------------------- /demos/monoid.js: -------------------------------------------------------------------------------- 1 | Array.empty = () => [] 2 | 3 | [1, 2, 3].concat(Array.empty()) 4 | -------------------------------------------------------------------------------- /demos/option.js: -------------------------------------------------------------------------------- 1 | // 定义 2 | const Some = (v) => ({ 3 | val: v, 4 | map (f) { 5 | return Some(f(this.val)) 6 | }, 7 | chain (f) { 8 | return f(this.val) 9 | } 10 | }) 11 | 12 | const None = () => ({ 13 | map (f) { 14 | return this 15 | }, 16 | chain (f) { 17 | return this 18 | } 19 | }) 20 | 21 | // maybeProp :: (String, {a}) -> Option a 22 | const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]) 23 | 24 | // getItem :: Cart -> Option CartItem 25 | const getItem = (cart) => maybeProp('item', cart) 26 | 27 | // getPrice :: Item -> Option Number 28 | const getPrice = (item) => maybeProp('price', item) 29 | 30 | // getNestedPrice :: cart -> Option a 31 | const getNestedPrice = (cart) => getItem(obj).chain(getPrice) 32 | 33 | getNestedPrice({}) // None() 34 | getNestedPrice({item: {foo: 1}}) // None() 35 | getNestedPrice({item: {price: 9.99}}) // Some(9.99) 36 | -------------------------------------------------------------------------------- /demos/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "functional-programming-demos", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "arity.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC", 11 | "dependencies": { 12 | "lodash": "^4.17.4" 13 | } 14 | } -------------------------------------------------------------------------------- /demos/partial.js: -------------------------------------------------------------------------------- 1 | const partical = (f, ...args) => (...moreArgs) => f(...args, ...moreArgs) 2 | 3 | const add3 = (a, b, c) => a + b + c 4 | 5 | // (...args) => add3(2, 3, ...args) 6 | // (c) => 2 + 3 + c 7 | const fivePlus = partical(add3, 2, 3) 8 | 9 | console.log(fivePlus(4)) // 9 10 | 11 | const add1More = add3.bind(null, 2, 3) 12 | 13 | console.log(add1More(4)) 14 | -------------------------------------------------------------------------------- /demos/pointFree.js: -------------------------------------------------------------------------------- 1 | const map = (fn) => (list) => list.map(fn) 2 | const add = (a) => (b) => a + b 3 | 4 | # Points-Free list 是显式参数 5 | const incrementAll = (numbers) => map(add(1))(numbers) 6 | 7 | # Points-Free list 是隐式参数 8 | const incrementAll2 = map(add(1)) 9 | -------------------------------------------------------------------------------- /demos/pointedFunctor.js: -------------------------------------------------------------------------------- 1 | const l = Array.of(1, 2, 3, 4, 5) 2 | -------------------------------------------------------------------------------- /demos/predicate.js: -------------------------------------------------------------------------------- 1 | const predicate = (a) => a > 2 2 | 3 | const results = [1, 2, 3, 4].filter(predicate) 4 | 5 | console.log(results) 6 | -------------------------------------------------------------------------------- /demos/purity.js: -------------------------------------------------------------------------------- 1 | const greet = (name) => `hello, ${name}` 2 | 3 | greet('world') 4 | -------------------------------------------------------------------------------- /demos/semigroup.js: -------------------------------------------------------------------------------- 1 | const x = [1, 2, 3] 2 | const y = [4, 5, 6] 3 | const z = [7, 8, 9] 4 | 5 | const r1 = x.concat(y).concat(z) 6 | const r2 = x.concat(y.concat(z)) 7 | 8 | console.log(r1, r2) 9 | -------------------------------------------------------------------------------- /demos/setoid.js: -------------------------------------------------------------------------------- 1 | Array.prototype.equals = function (arr) { 2 | const len = this.length 3 | if (len !== arr.length) { 4 | return false 5 | } 6 | for (let i = 0; i < len; i++) { 7 | if (this[i] !== arr[i]) { 8 | return false 9 | } 10 | } 11 | return true 12 | } 13 | 14 | const a = [1, 2].equals([1, 2]) // true 15 | const b = [1, 2].equals([0]) // false 16 | 17 | console.log(a, b) 18 | -------------------------------------------------------------------------------- /demos/sideEffects.js: -------------------------------------------------------------------------------- 1 | const differentEveryTime = new Date() 2 | 3 | -------------------------------------------------------------------------------- /demos/typeSignature.js: -------------------------------------------------------------------------------- 1 | // capitalize :: String -> String 2 | const capitalize = (s) => toUpperCase(head(s)) + toLowerCase(tail(s)) 3 | 4 | // join :: String -> [String] -> String 5 | const join = curry(function(what, xs) { 6 | return xs.join(what); 7 | }); 8 | 9 | 10 | -------------------------------------------------------------------------------- /demos/value.js: -------------------------------------------------------------------------------- 1 | 5 2 | Object.freeze({name: 'John', age: 30}) 3 | ;(a) => a 4 | ;[1] 5 | undefined 6 | --------------------------------------------------------------------------------