From a67155dd446734957321c43101b08c9bd2b447b4 Mon Sep 17 00:00:00 2001 From: Jethro Larson Date: Tue, 30 Aug 2016 17:29:53 -0700 Subject: [PATCH 01/32] Added npm test for using code standards in the examples. Fixed all discrepencies. #111 (#112) --- .eslintrc.yml | 7 ++ contributing.md | 8 +- package.json | 5 +- readme.md | 280 +++++++++++++++++++++++++----------------------- 4 files changed, 161 insertions(+), 139 deletions(-) create mode 100644 .eslintrc.yml diff --git a/.eslintrc.yml b/.eslintrc.yml new file mode 100644 index 0000000..c3505d9 --- /dev/null +++ b/.eslintrc.yml @@ -0,0 +1,7 @@ +--- + extends: "standard" + plugins: [markdown] + rules: + no-unused-vars: 0 + no-undef: 0 + no-extend-native: 0 diff --git a/contributing.md b/contributing.md index 1ae1362..138a49a 100644 --- a/contributing.md +++ b/contributing.md @@ -2,6 +2,10 @@ This project is a work in progress. Contributions are very welcome. +## Hard rules +* Run `npm test` to lint the code examples. Your changes must pass. +* If you add a new definition or reorder them run `npm run toc` to regenerate the table of contents. + That said, we'd like to maintain some consistency across the document. ## Style guide @@ -14,12 +18,12 @@ That said, we'd like to maintain some consistency across the document. 1. Avoid big walls of text ## Code conventions -Be consistent with other examples +[![JavaScript Style Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) +* Be consistent with other examples * Prefer arrow functions * Parenthesis around function arguments * Put output values in comments -* Use semi-colons * Keep it short and simple This styleguide is a WIP too! Send PRs :) diff --git a/package.json b/package.json index e77e457..e7cfe68 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "Jargon from the functional programming world in simple terms!", "main": "index.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", + "test": "eslint readme.md", "toc": "roadmarks" }, "repository": { @@ -18,6 +18,9 @@ }, "homepage": "https://github.com/hemanth/functional-programming-jargon#readme", "devDependencies": { + "eslint": "^3.4.0", + "eslint-config-standard": "^6.0.0", + "eslint-plugin-markdown": "^1.0.0-beta.2", "roadmarks": "^1.6.3" } } diff --git a/readme.md b/readme.md index cd3450f..3206093 100644 --- a/readme.md +++ b/readme.md @@ -63,10 +63,10 @@ __Table of Contents__ The number of arguments a function takes. From words like unary, binary, ternary, etc. This word has the distinction of being composed of two suffixes, "-ary" and "-ity." Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two. Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin. Likewise, a function that takes a variable number of arguments is called "variadic," whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below). ```js -const sum = (a, b) => a + b; +const sum = (a, b) => a + b -const arity = sum.length; -console.log(arity); // 2 +const arity = sum.length +console.log(arity) // 2 // The arity of sum is 2 ``` @@ -77,22 +77,22 @@ A function which takes a function as an argument and/or returns a function. ```js const filter = (predicate, xs) => { - const result = []; - for (let idx = 0; idx < xs.length; idx++) { - if (predicate(xs[idx])) { - result.push(xs[idx]); - } + const result = [] + for (let idx = 0; idx < xs.length; idx++) { + if (predicate(xs[idx])) { + result.push(xs[idx]) } - return result; -}; + } + return result +} ``` ```js -const is = (type) => (x) => Object(x) instanceof type; +const is = (type) => (x) => Object(x) instanceof type ``` ```js -filter(is(Number), [0, '1', 2, null]); // [0, 2] +filter(is(Number), [0, '1', 2, null]) // [0, 2] ``` ## Partial Application @@ -104,24 +104,24 @@ Partially applying a function means creating a new function by pre-filling some // Helper to create partially applied functions // Takes a function and some arguments const partial = (f, ...args) => - // returns a function that takes the rest of the arguments - (...moreArgs) => - // and calls the original function with all of them - f(...args, ...moreArgs); + // returns a function that takes the rest of the arguments + (...moreArgs) => + // and calls the original function with all of them + f(...args, ...moreArgs) // Something to apply -const add3 = (a, b, c) => a + b + c; +const add3 = (a, b, c) => a + b + c // Partially applying `2` and `3` to `add3` gives you a one-argument function -const fivePlus = partial(add3, 2, 3); // (c) => 2 + 3 + c +const fivePlus = partial(add3, 2, 3) // (c) => 2 + 3 + c -fivePlus(4); // 9 +fivePlus(4) // 9 ``` You can also use `Function.prototype.bind` to partially apply a function in JS: ```js -const add1More = add3.bind(null, 2, 3); // (c) => 2 + 3 + c +const add1More = add3.bind(null, 2, 3) // (c) => 2 + 3 + c ``` Partial application helps create simpler functions from more complex ones by baking in data when you have it. [Curried](#currying) functions are automatically partially applied. @@ -133,13 +133,13 @@ The process of converting a function that takes multiple arguments into a functi Each time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed. ```js -const sum = (a, b) => a + b; +const sum = (a, b) => a + b -const curriedSum = (a) => (b) => a + b; +const curriedSum = (a) => (b) => a + b curriedSum(40)(2) // 42. -const add2 = curriedSum(2); // (b) => 2 + b +const add2 = curriedSum(2) // (b) => 2 + b add2(10) // 12 @@ -151,9 +151,9 @@ Transforming a function that takes multiple arguments into one that if given les Underscore, lodash, and ramda have a `curry` function that works this way. ```js -const add = (x, y) => x + y; +const add = (x, y) => x + y -const curriedAdd = _.curry(add); +const curriedAdd = _.curry(add) curriedAdd(1, 2) // 3 curriedAdd(1) // (y) => 1 + y curriedAdd(1)(2) // 3 @@ -170,7 +170,7 @@ The act of putting two functions together to form a third function where the out ```js const compose = (f, g) => (a) => f(g(a)) // Definition const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage -floorAndToString(121.212121) // "121" +floorAndToString(121.212121) // '121' ``` ## Purity @@ -179,9 +179,9 @@ A function is pure if the return value is only determined by its input values, and does not produce side effects. ```js -const greet = (name) => "Hi, " + name ; +const greet = (name) => 'Hi, ' + name -greet("Brianne") // "Hi, Brianne" +greet('Brianne') // 'Hi, Brianne' ``` @@ -189,11 +189,13 @@ As opposed to: ```js -let greeting; +let greeting -const greet = () => greeting = "Hi, " + window.name; +const greet = () => { + greeting = 'Hi, ' + window.name +} -greet(); // "Hi, Brianne" +greet() // "Hi, Brianne" ``` @@ -202,19 +204,19 @@ greet(); // "Hi, Brianne" A function or expression is said to have a side effect if apart from returning a value, it interacts with (reads from or writes to) external mutable state. ```js -const differentEveryTime = new Date(); +const differentEveryTime = new Date() ``` ```js -console.log("IO is a side effect!"); +console.log('IO is a side effect!') ``` ## Idempotent A function is idempotent if reapplying it to its result does not produce a different result. -```js -f(f(x)) = f(x) +``` +f(f(x)) ≍ f(x) ``` ```js @@ -222,7 +224,7 @@ Math.abs(Math.abs(10)) ``` ```js -sort(sort(sort([2,1]))) +sort(sort(sort([2, 1]))) ``` ## Point-Free Style @@ -231,16 +233,16 @@ Writing functions where the definition does not explicitly identify the argument ```js // Given -const map = (fn) => (list) => list.map(fn); -const add = (a) => (b) => a + b; +const map = (fn) => (list) => list.map(fn) +const add = (a) => (b) => a + b // Then // Not points-free - `numbers` is an explicit argument -const incrementAll = (numbers) => map(add(1))(numbers); +const incrementAll = (numbers) => map(add(1))(numbers) // Points-free - The list is an implicit argument -const incrementAll2 = map(add(1)); +const incrementAll2 = map(add(1)) ``` `incrementAll` identifies and uses the parameter `numbers`, so it is not points-free. `incrementAll2` is written just by combining functions and values, making no mention of its arguments. It __is__ points-free. @@ -251,9 +253,9 @@ Points-free function definitions look just like normal assignments without `func A predicate is a function that returns true or false for a given value. A common use of a predicate is as the callback for array filter. ```js -const predicate = (a) => a > 2; +const predicate = (a) => a > 2 -[1, 2, 3, 4].filter(predicate); // [3, 4] +;[1, 2, 3, 4].filter(predicate) // [3, 4] ``` ## Contracts @@ -275,8 +277,8 @@ Anything that can be assigned to a variable. ```js 5 Object.freeze({name: 'John', age: 30}) // The `freeze` function enforces immutability. -(a) => a -[1] +;(a) => a +;[1] undefined ``` @@ -318,17 +320,17 @@ object.map(x => f(g(x))) === object.map(g).map(f) A common functor in JavaScript is `Array` since it abides to the two functor rules: ```js -[1, 2, 3].map(x => x); // = [1, 2, 3] +[1, 2, 3].map(x => x) // = [1, 2, 3] ``` and ```js -const f = x => x + 1; -const g = x => x * 2; +const f = x => x + 1 +const g = x => x * 2 -[1, 2, 3].map(x => f(g(x))); // = [3, 5, 7] -[1, 2, 3].map(g).map(f); // = [3, 5, 7] +;[1, 2, 3].map(x => f(g(x))) // = [3, 5, 7] +;[1, 2, 3].map(g).map(f) // = [3, 5, 7] ``` ## Pointed Functor @@ -347,23 +349,23 @@ Lifting is when you take a value and put it into an object like a [functor](#poi Some implementations have a function called `lift`, or `liftA2` to make it easier to run functions on functors. ```js -const liftA2 = (f) => (a, b) => a.map(f).ap(b); +const liftA2 = (f) => (a, b) => a.map(f).ap(b) -const mult = a => b => a * b; +const mult = a => b => a * b -const liftedMult = liftA2(mult); // this function now works on functors like array +const liftedMult = liftA2(mult) // this function now works on functors like array -liftedMult([1, 2], [3]); // [3, 6] -liftA2((a, b) => a + b)([1, 2], [3, 4]); // [4, 5, 5, 6] +liftedMult([1, 2], [3]) // [3, 6] +liftA2((a, b) => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] ``` Lifting a one-argument function and applying it does the same thing as `map`. ```js -const increment = (x) => x + 1; +const increment = (x) => x + 1 -lift(increment)([2]); // [3] -[2].map(increment); // [3] +lift(increment)([2]) // [3] +;[2].map(increment) // [3] ``` @@ -375,7 +377,7 @@ behavior of the program is said to be referentially transparent. Say we have function greet: ```js -const greet = () => "Hello World!"; +const greet = () => 'Hello World!' ``` Any invocation of `greet()` can be replaced with `Hello World!` hence greet is @@ -390,22 +392,22 @@ When an application is composed of expressions and devoid of side effects, truth An anonymous function that can be treated like a value. ```js -function(a){ - return a + 1; -}; +;(function (a) { + return a + 1 +}) -(a) => a + 1; +;(a) => a + 1 ``` Lambdas are often passed as arguments to Higher-Order functions. ```js -[1, 2].map((a) => a + 1); // [2, 3] +[1, 2].map((a) => a + 1) // [2, 3] ``` You can assign a lambda to a variable. ```js -const add1 = (a) => a + 1; +const add1 = (a) => a + 1 ``` ## Lambda Calculus @@ -417,15 +419,15 @@ Lazy evaluation is a call-by-need evaluation mechanism that delays the evaluatio ```js const rand = function*() { - while (1 < 2) { - yield Math.random(); - } + while (1 < 2) { + yield Math.random() + } } ``` ```js -const randIter = rand(); -randIter.next(); // Each execution gives a random value, expression is evaluated on need. +const randIter = rand() +randIter.next() // Each execution gives a random value, expression is evaluated on need. ``` ## Monoid @@ -435,7 +437,7 @@ An object with a function that "combines" that object with another of the same t One simple monoid is the addition of numbers: ```js -1 + 1; // 2 +1 + 1 // 2 ``` In this case number is the object and `+` is the function. @@ -443,33 +445,35 @@ An "identity" value must also exist that when combined with a value doesn't chan The identity value for addition is `0`. ```js -1 + 0; // 1 +1 + 0 // 1 ``` It's also required that the grouping of operations will not affect the result (associativity): ```js -1 + (2 + 3) === (1 + 2) + 3; // true +1 + (2 + 3) === (1 + 2) + 3 // true ``` Array concatenation also forms a monoid: ```js -[1, 2].concat([3, 4]); // [1, 2, 3, 4] +;[1, 2].concat([3, 4]) // [1, 2, 3, 4] ``` The identity value is empty array `[]` ```js -[1, 2].concat([]); // [1, 2] +;[1, 2].concat([]) // [1, 2] ``` If identity and compose functions are provided, functions themselves form a monoid: ```js -const identity = (a) => a; -const compose = (f, g) => (x) => f(g(x)); - +const identity = (a) => a +const compose = (f, g) => (x) => f(g(x)) +``` +`foo` is any function that takes one argument. +``` compose(foo, identity) ≍ compose(identity, foo) ≍ foo ``` @@ -479,15 +483,15 @@ A monad is an object with [`of`](#pointed-functor) and `chain` functions. `chain ```js // Implementation -Array.prototype.chain = function(f){ - return this.reduce((acc, it) => acc.concat(f(it)), []); -}; +Array.prototype.chain = function (f) { + return this.reduce((acc, it) => acc.concat(f(it)), []) +} // Usage -['cat,dog', 'fish,bird'].chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] +;['cat,dog', 'fish,bird'].chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] // Contrast to map -['cat,dog', 'fish,bird'].map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] +;['cat,dog', 'fish,bird'].map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] ``` `of` is also known as `return` in other functional languages. @@ -499,9 +503,13 @@ An object that has `extract` and `extend` functions. ```js const CoIdentity = (v) => ({ - val: v, - extract() { return this.val }, - extend(f) { return CoIdentity(f(this)) } + val: v, + extract () { + return this.val + }, + extend (f) { + return CoIdentity(f(this)) + } }) ``` @@ -523,31 +531,31 @@ An applicative functor is an object with an `ap` function. `ap` applies a functi ```js // Implementation -Array.prototype.ap = function(xs){ - return this.reduce((acc, f) => acc.concat(xs.map(f)), []); -}; +Array.prototype.ap = function (xs) { + return this.reduce((acc, f) => acc.concat(xs.map(f)), []) +} // Example usage -[(a) => a + 1].ap([1]) // [2] +;[(a) => a + 1].ap([1]) // [2] ``` This is useful if you have two objects and you want to apply a binary function to their contents. ```js // Arrays that you want to combine -const arg1 = [1, 3]; -const arg2 = [4, 5]; +const arg1 = [1, 3] +const arg2 = [4, 5] // combining function - must be curried for this to work -const add = (x) => (y) => x + y; +const add = (x) => (y) => x + y -const partiallyAppliedAdds = [add].ap(arg1); // [(y) => 1 + y, (y) => 3 + y] +const partiallyAppliedAdds = [add].ap(arg1) // [(y) => 1 + y, (y) => 3 + y] ``` This gives you an array of functions that you can call `ap` on to get the result: ```js -partiallyAppliedAdds.ap(arg2); // [5, 6, 7, 8] +partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8] ``` ## Morphism @@ -560,10 +568,10 @@ A function where the input type is the same as the output. ```js // uppercase :: String -> String -const uppercase = (str) => str.toUpperCase(); +const uppercase = (str) => str.toUpperCase() // decrement :: Number -> Number -const decrement = (x) => x - 1; +const decrement = (x) => x - 1 ``` ### Isomorphism @@ -593,20 +601,20 @@ Make array a setoid: ```js Array.prototype.equals = (arr) => { - const len = this.length - if (len !== arr.length) { - return false + const len = this.length + if (len !== arr.length) { + return false + } + for (let i = 0; i < len; i++) { + if (this[i] !== arr[i]) { + return false } - for (let i = 0; i < len; i++) { - if (this[i] !== arr[i]) { - return false - } - } - return true + } + return true } -[1, 2].equals([1, 2]) // true -[1, 2].equals([0]) // false +;[1, 2].equals([1, 2]) // true +;[1, 2].equals([0]) // false ``` ## Semigroup @@ -614,7 +622,7 @@ Array.prototype.equals = (arr) => { An object that has a `concat` function that combines it with another object of the same type. ```js -[1].concat([2]) // [1, 2] +;[1].concat([2]) // [1, 2] ``` ## Foldable @@ -622,7 +630,7 @@ An object that has a `concat` function that combines it with another object of t An object that has a `reduce` function that can transform that object into some other type. ```js -const sum = (list) => list.reduce((acc, val) => acc + val, 0); +const sum = (list) => list.reduce((acc, val) => acc + val, 0) sum([1, 2, 3]) // 6 ``` @@ -674,11 +682,11 @@ The `+` operator in JS works on strings and numbers so we can use this new type ```js // add :: (NumOrString, NumOrString) -> NumOrString -const add = (a, b) => a + b; +const add = (a, b) => a + b -add(1, 2); // Returns number 3 -add('Foo', 2); // Returns string "Foo2" -add('Foo', 'Bar'); // Returns string "FooBar" +add(1, 2) // Returns number 3 +add('Foo', 2) // Returns string "Foo2" +add('Foo', 'Bar') // Returns string "FooBar" ``` Union types are also known as algebraic types, tagged unions, or sum types. @@ -691,7 +699,7 @@ A **product** type combines types together in a way you're probably more familia ```js // point :: (Number, Number) -> {x: Number, y: Number} -const point = (x, y) => ({x: x, y: y}); +const point = (x, y) => ({x: x, y: y}) ``` It's called a product because the total possible values of the data structure is the product of the different values. @@ -706,42 +714,42 @@ Option is useful for composing functions that might not return a value. // Naive definition const Some = (v) => ({ - val: v, - map(f) { - return Some(f(this.val)); - }, - chain(f) { - return f(this.val); - } -}); + val: v, + map (f) { + return Some(f(this.val)) + }, + chain (f) { + return f(this.val) + } +}) const None = () => ({ - map(f){ - return this; - }, - chain(f){ - return this; - } -}); + map (f) { + return this + }, + chain (f) { + return this + } +}) // maybeProp :: (String, {a}) -> Option a -const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]); +const maybeProp = (key, obj) => typeof obj[key] === 'undefined' ? None() : Some(obj[key]) ``` Use `chain` to sequence functions that return `Option`s ```js // getItem :: Cart -> Option CartItem -const getItem = (cart) => maybeProp('item', cart); +const getItem = (cart) => maybeProp('item', cart) // getPrice :: Item -> Option Number -const getPrice = (item) => maybeProp('price', item); +const getPrice = (item) => maybeProp('price', item) // getNestedPrice :: cart -> Option a -const getNestedPrice = (cart) => getItem(obj).chain(getPrice); +const getNestedPrice = (cart) => getItem(obj).chain(getPrice) -getNestedPrice({}); // None() -getNestedPrice({item: {foo: 1}}); // None() -getNestedPrice({item: {price: 9.99}}); // Some(9.99) +getNestedPrice({}) // None() +getNestedPrice({item: {foo: 1}}) // None() +getNestedPrice({item: {price: 9.99}}) // Some(9.99) ``` `Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`. From 52b9f361b64db3c7d4b9fdc5aeeb0e92f8e33abf Mon Sep 17 00:00:00 2001 From: Chandan Rai Date: Thu, 1 Sep 2016 20:17:48 +0530 Subject: [PATCH 02/32] corrected typo (#113) --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 3206093..57b0296 100644 --- a/readme.md +++ b/readme.md @@ -670,7 +670,7 @@ const map = (f) => (list) => list.map(f) __Further reading__ * [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures) -* [Mostly Adaquate Guide](https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type) +* [Mostly Adequate Guide](https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type) * [What is Hindley-Milner?](http://stackoverflow.com/a/399392/22425) on Stack Overflow ## Union type From d1f6c16a92ba13767fd6b1dcbbb76381cfd35f32 Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Fri, 9 Sep 2016 13:30:41 +0530 Subject: [PATCH 03/32] Adding Closure --- readme.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/readme.md b/readme.md index 57b0296..7bda73d 100644 --- a/readme.md +++ b/readme.md @@ -18,6 +18,7 @@ __Table of Contents__ * [Higher-Order Functions (HOF)](#higher-order-functions-hof) * [Partial Application](#partial-application) * [Currying](#currying) +* [Closure](#closure) * [Auto Currying](#auto-currying) * [Function Composition](#function-composition) * [Purity](#purity) @@ -144,6 +145,35 @@ const add2 = curriedSum(2) // (b) => 2 + b add2(10) // 12 ``` +##Closure + +A very simplistic definition - A closure is a way of accessing a variable outside its scope. +Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment. + +A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined. +ie. they allow referencing a scope after the block in which the variables were declared has finished executing. + + +```js +function getTicker () { + var tick = 0; + function ticker () { + tick = tick + 1; + return tick; + } + return ticker; + } + var tickTock = getTicker(); + tickTock(); //returns 1 + tickTock(); //returns 2 +``` +The function getTimer() returns a function(internally called ticker), lets call it tickTock. + +Ideally, when the getTimer finishes execution, its scope, with local variable tick should also not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick. + +Lexical scoping is the reason why it is able to find the value of tick, the private variable of the parent which has finished executing. This value is called a closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored. + + ## Auto Currying Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. From e0ae226d99c3808011160eb51b1a6ca7b973b359 Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Fri, 9 Sep 2016 13:34:17 +0530 Subject: [PATCH 04/32] Fixed typos in Closure --- readme.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/readme.md b/readme.md index 7bda73d..03ed7d6 100644 --- a/readme.md +++ b/readme.md @@ -145,6 +145,7 @@ const add2 = curriedSum(2) // (b) => 2 + b add2(10) // 12 ``` + ##Closure A very simplistic definition - A closure is a way of accessing a variable outside its scope. @@ -167,13 +168,11 @@ function getTicker () { tickTock(); //returns 1 tickTock(); //returns 2 ``` -The function getTimer() returns a function(internally called ticker), lets call it tickTock. +The function getTimer() returns a function(internally called ticker), lets store it in a variabke called tickTock. Ideally, when the getTimer finishes execution, its scope, with local variable tick should also not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick. -Lexical scoping is the reason why it is able to find the value of tick, the private variable of the parent which has finished executing. This value is called a closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored. - - +Lexical scoping is the reason why it is able to find the value of tick - the private variable of the parent which has finished executing. This value is called a Closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored. ## Auto Currying Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. From a5eaf03818a621730a0c921c3d719ba185b43e03 Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Fri, 9 Sep 2016 13:35:49 +0530 Subject: [PATCH 05/32] Fixed typos in Closure --- readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 03ed7d6..fa277f3 100644 --- a/readme.md +++ b/readme.md @@ -168,9 +168,9 @@ function getTicker () { tickTock(); //returns 1 tickTock(); //returns 2 ``` -The function getTimer() returns a function(internally called ticker), lets store it in a variabke called tickTock. +The function getTicker() returns a function(internally called ticker), lets store it in a variabke called tickTock. -Ideally, when the getTimer finishes execution, its scope, with local variable tick should also not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick. +Ideally, when the function getTicker finishes execution, its scope, with local variable tick should not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick. Lexical scoping is the reason why it is able to find the value of tick - the private variable of the parent which has finished executing. This value is called a Closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored. From e918b396ecd14c61f40b6350841999eb0333b992 Mon Sep 17 00:00:00 2001 From: Iain Diamond Date: Sat, 10 Sep 2016 06:39:05 +0100 Subject: [PATCH 06/32] Update monad example (#115) Monad description mentions 'of' function; update the example to use this. --- readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 57b0296..7a28a12 100644 --- a/readme.md +++ b/readme.md @@ -488,10 +488,10 @@ Array.prototype.chain = function (f) { } // Usage -;['cat,dog', 'fish,bird'].chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] +;Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird'] // Contrast to map -;['cat,dog', 'fish,bird'].map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] +;Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']] ``` `of` is also known as `return` in other functional languages. From 9d14bcf9433ec83dd97ff94db3119a662a7881a1 Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Sun, 18 Sep 2016 00:22:40 +0530 Subject: [PATCH 07/32] Update readme.md --- readme.md | 29 ++++++++++++++--------------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/readme.md b/readme.md index fa277f3..059a0e4 100644 --- a/readme.md +++ b/readme.md @@ -148,7 +148,7 @@ add2(10) // 12 ##Closure -A very simplistic definition - A closure is a way of accessing a variable outside its scope. +A closure is a way of accessing a variable outside its scope. Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment. A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined. @@ -156,23 +156,22 @@ ie. they allow referencing a scope after the block in which the variables were d ```js -function getTicker () { - var tick = 0; - function ticker () { - tick = tick + 1; - return tick; - } - return ticker; - } - var tickTock = getTicker(); - tickTock(); //returns 1 - tickTock(); //returns 2 +var addTo = function(x) { + function add(y) { + return x + y; + } + return add; +} +var addToFive = addTo(5); +addToFive(3); //returns 8 ``` -The function getTicker() returns a function(internally called ticker), lets store it in a variabke called tickTock. +The function ```addTo()``` returns a function(internally called ```add()```), lets store it in a variable called ```addToFive``` with a curried call having parameter 5. -Ideally, when the function getTicker finishes execution, its scope, with local variable tick should not be accessible. But, it returns 1, 2, 3.. on calling tickTock(). This simply means that, somewhere it keeps a track of the variable tick. +Ideally, when the function ```addoTo``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```addToFive()```. This means that the state of the function ```addTo``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```addTo``` was called as ```addTo(5)``` and the value of x was set to 5. -Lexical scoping is the reason why it is able to find the value of tick - the private variable of the parent which has finished executing. This value is called a Closure. The stack along with the lexical scope of the function is stored and upon re-execution same stack is restored. +Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure. + +The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it). ## Auto Currying Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. From ff29eb4abde5fc978a401eacc30a0442b7efa56c Mon Sep 17 00:00:00 2001 From: Alex LaFroscia Date: Sun, 25 Sep 2016 12:17:37 -0700 Subject: [PATCH 08/32] Update the Purity example code Reading through this, the example code for the Purity information was a bit confusing. The original example tried to show both using and changing global state in one function, but because of that the "pure" example and "unpure" example didn't actually do the same thing. I think it's a little more clear if the two concepts are broken up, instead showing the "pure" version, one that uses global state, and one that modifies global state. --- readme.md | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/readme.md b/readme.md index 7a28a12..7b91f4a 100644 --- a/readme.md +++ b/readme.md @@ -182,23 +182,35 @@ input values, and does not produce side effects. const greet = (name) => 'Hi, ' + name greet('Brianne') // 'Hi, Brianne' - ``` -As opposed to: +As opposed to each of the following: ```js - -let greeting +window.name = 'Brianne' const greet = () => { - greeting = 'Hi, ' + window.name + return 'Hi, ' + window.name } greet() // "Hi, Brianne" - ``` +The above example's output is based on data stored outside of the function... + +```js +let greeting + +const greet = (name) => { + greeting = 'Hi, ' + name +} + +greet() +greeting // "Hi, Brianne" +``` + +... and this one modifies state outside of the function. + ## Side effects A function or expression is said to have a side effect if apart from returning a value, it interacts with (reads from or writes to) external mutable state. From d1faf8b4f103411c0933328d2f2c62b16356ddb1 Mon Sep 17 00:00:00 2001 From: "hemanth.hm" Date: Wed, 26 Oct 2016 06:14:24 +0530 Subject: [PATCH 09/32] Added a note for `ap` We've got this pr like 4 times now thinking that it's a typo. --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 7a28a12..2a92506 100644 --- a/readme.md +++ b/readme.md @@ -349,7 +349,7 @@ Lifting is when you take a value and put it into an object like a [functor](#poi Some implementations have a function called `lift`, or `liftA2` to make it easier to run functions on functors. ```js -const liftA2 = (f) => (a, b) => a.map(f).ap(b) +const liftA2 = (f) => (a, b) => a.map(f).ap(b) // note it's `ap` and not `map`. const mult = a => b => a * b From f55916cac09caa85b8ed685edad27bc0716b9d25 Mon Sep 17 00:00:00 2001 From: Alex LaFroscia Date: Tue, 25 Oct 2016 18:22:00 -0700 Subject: [PATCH 10/32] Update Purity code examples to use interpolation Also, add in the missing argument to `greet` in the changing-global-state example code. --- readme.md | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/readme.md b/readme.md index 7b91f4a..dc4ecdc 100644 --- a/readme.md +++ b/readme.md @@ -179,7 +179,7 @@ A function is pure if the return value is only determined by its input values, and does not produce side effects. ```js -const greet = (name) => 'Hi, ' + name +const greet = (name) => `Hi, ${name}` greet('Brianne') // 'Hi, Brianne' ``` @@ -189,9 +189,7 @@ As opposed to each of the following: ```js window.name = 'Brianne' -const greet = () => { - return 'Hi, ' + window.name -} +const greet = () => `Hi, ${window.name}` greet() // "Hi, Brianne" ``` @@ -202,10 +200,10 @@ The above example's output is based on data stored outside of the function... let greeting const greet = (name) => { - greeting = 'Hi, ' + name + greeting = `Hi, ${name}` } -greet() +greet('Brianne') greeting // "Hi, Brianne" ``` From eceef7553d361f7faf8410d8f39bd06430c81eb2 Mon Sep 17 00:00:00 2001 From: Jethro Larson Date: Fri, 4 Nov 2016 14:57:48 -0700 Subject: [PATCH 11/32] Using equivalent operator for functor laws ...as opposed to threequals --- readme.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/readme.md b/readme.md index f6cbf40..d624e89 100644 --- a/readme.md +++ b/readme.md @@ -313,16 +313,15 @@ john.age + five === ({name: 'John', age: 30}).age + (5) An object that implements a `map` function which, while running over each value in the object to produce a new object, adheres to two rules: -```js -// preserves identity -object.map(x => x) === object +### Preserves identity +``` +object.map(x => x) ≍ object ``` -and +### Composable -```js -// composable -object.map(x => f(g(x))) === object.map(g).map(f) +``` +object.map(compose(f, g)) ≍ object.map(g).map(f) ``` (`f`, `g` be arbitrary functions) From b77effbd0247522177e8845ef73505c64d60dafe Mon Sep 17 00:00:00 2001 From: Nick Zuber Date: Mon, 19 Dec 2016 23:28:45 -0500 Subject: [PATCH 12/32] Added Contracts (#127) * Added description of contracts * Added ES6 example * linted and toc --- readme.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index d624e89..b398ca4 100644 --- a/readme.md +++ b/readme.md @@ -31,6 +31,8 @@ __Table of Contents__ * [Value](#value) * [Constant](#constant) * [Functor](#functor) + * [Preserves identity](#preserves-identity) + * [Composable](#composable) * [Pointed Functor](#pointed-functor) * [Lift](#lift) * [Referential Transparency](#referential-transparency) @@ -270,7 +272,20 @@ const predicate = (a) => a > 2 ## Contracts -TODO +A contract specifies the obligations and guarentees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated. + +```js +// Define our contract : int -> int +const contract = (input) => { + if (typeof input === 'number') return true + throw new Error('Contract violated: expected int -> int') +} + +const addOne = (num) => contract(num) && num + 1 + +addOne(2) // 3 +addOne('some string') // Contract violated: expected int -> int +``` ## Guarded Functions From 02b0546772559fd68210365142b58d783bd656d5 Mon Sep 17 00:00:00 2001 From: Vincent Sisk Date: Tue, 20 Dec 2016 10:10:35 -0700 Subject: [PATCH 13/32] Update readme.md (#129) --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index b398ca4..a56ec49 100644 --- a/readme.md +++ b/readme.md @@ -272,7 +272,7 @@ const predicate = (a) => a > 2 ## Contracts -A contract specifies the obligations and guarentees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated. +A contract specifies the obligations and guarantees of the behavior from a function or expression at runtime. This acts as a set of rules that are expected from the input and output of a function or expression, and errors are generally reported whenever a contract is violated. ```js // Define our contract : int -> int From b8d5028816fde0fb1727cd125537bfa49856b65a Mon Sep 17 00:00:00 2001 From: Nicholas Zuber Date: Wed, 21 Dec 2016 13:10:16 -0500 Subject: [PATCH 14/32] continuations --- readme.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/readme.md b/readme.md index a56ec49..421feef 100644 --- a/readme.md +++ b/readme.md @@ -20,6 +20,7 @@ __Table of Contents__ * [Currying](#currying) * [Auto Currying](#auto-currying) * [Function Composition](#function-composition) +* [Continuation](#continuation) * [Purity](#purity) * [Side effects](#side-effects) * [Idempotent](#idempotent) @@ -175,6 +176,37 @@ const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage floorAndToString(121.212121) // '121' ``` +## Continuation + +At any given point in a program, the collection of instructions that still need to be processed in order for the program to complete is known as a continuation. + +```js +const printAsString = (num) => console.log(`Given ${num}`) + +const addOneAndContinue = (num, cc) => { + const result = num + 1 + cc(result) +} + +addOneAndContinue(2, printAsString) // 'Given 3' +``` + +Continuations are often seen in asynchronous programming when the program needs to wait to receive data before it can continue. The response is often passed off to the rest of the program, which is the continuation, once it's been received. + +```js +const continueProgramWith = (data) => { + // Continues program with data +} + +readFileAsync('path/to/file', (err, response) => { + if (err) { + // handle error + return + } + continueProgramWith(response) +}) +``` + ## Purity A function is pure if the return value is only determined by its From 4bcf39d586cdbd2523fb2bd70e659436ba61f1a9 Mon Sep 17 00:00:00 2001 From: Artem Riasnianskyi Date: Thu, 22 Dec 2016 09:58:06 +0100 Subject: [PATCH 15/32] const is not constant fix add `Object.freeze()` to object defenition in Constant section --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index a56ec49..7b8b386 100644 --- a/readme.md +++ b/readme.md @@ -313,7 +313,7 @@ A variable that cannot be reassigned once defined. ```js const five = 5 -const john = {name: 'John', age: 30} +const john = Object.freeze({name: 'John', age: 30}) ``` Constants are [referentially transparent](#referential-transparency). That is, they can be replaced with the values that they represent without affecting the result. From e8ce4d0c173e869c21968b1d5dad1d97b73d9da1 Mon Sep 17 00:00:00 2001 From: Nicholas Zuber Date: Fri, 23 Dec 2016 03:29:22 -0500 Subject: [PATCH 16/32] changed wording --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 421feef..5134cd8 100644 --- a/readme.md +++ b/readme.md @@ -178,7 +178,7 @@ floorAndToString(121.212121) // '121' ## Continuation -At any given point in a program, the collection of instructions that still need to be processed in order for the program to complete is known as a continuation. +At any given point in a program, the part of the code that's yet to be executed is known as a continuation. ```js const printAsString = (num) => console.log(`Given ${num}`) From 1341b6f6729ae7d6b96f3023f122d79ea6ba41f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82?= Date: Tue, 27 Dec 2016 14:28:10 +0100 Subject: [PATCH 17/32] add monet.js to functional programming libraries --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 7b8b386..0f567a9 100644 --- a/readme.md +++ b/readme.md @@ -782,6 +782,7 @@ getNestedPrice({item: {price: 9.99}}) // Some(9.99) * [Ramda](https://github.com/ramda/ramda) * [Folktale](http://folktalejs.org) +* [monet.js](https://cwmyers.github.io/monet.js/) * [lodash](https://github.com/lodash/lodash) * [Underscore.js](https://github.com/jashkenas/underscore) * [Lazy.js](https://github.com/dtao/lazy.js) From 3f8c8a59834610b873c4ad91aa3b970fbc67c74e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Alga=C3=B1araz?= Date: Sun, 1 Jan 2017 12:23:36 -0300 Subject: [PATCH 18/32] Added the translation into Spanish I have translated the document completely into Spanish, I hope you can add me to the list of translations. Greetings and happy new year :) --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 0f567a9..f0d67d1 100644 --- a/readme.md +++ b/readme.md @@ -10,6 +10,7 @@ Where applicable, this document uses terms defined in the [Fantasy Land spec](ht __Translations__ * [Portuguese](https://github.com/alexmoreno/jargoes-programacao-funcional) +* [Spanish](https://github.com/idcmardelplata/functional-programming-jargon/tree/master) __Table of Contents__ From 02b776ede50ef83c152188b4c18de4ba8116bfa3 Mon Sep 17 00:00:00 2001 From: Saar Wexler Date: Mon, 2 Jan 2017 11:19:29 +0200 Subject: [PATCH 19/32] Two new js libraries- mori and Immutable --- readme.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/readme.md b/readme.md index e74ddcc..450f88c 100644 --- a/readme.md +++ b/readme.md @@ -812,7 +812,8 @@ getNestedPrice({item: {price: 9.99}}) // Some(9.99) `Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`. ## Functional Programming Libraries in JavaScript - +* [mori](https://github.com/swannodette/mori) +* [Immutable](https://github.com/facebook/immutable-js/) * [Ramda](https://github.com/ramda/ramda) * [Folktale](http://folktalejs.org) * [monet.js](https://cwmyers.github.io/monet.js/) From 1de3d692f8ca5fd36801237ca368f190fc9cc30f Mon Sep 17 00:00:00 2001 From: Saar Wexler Date: Mon, 2 Jan 2017 11:19:29 +0200 Subject: [PATCH 20/32] Two new js libraries- mori and Immutable --- readme.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/readme.md b/readme.md index e74ddcc..a6870e8 100644 --- a/readme.md +++ b/readme.md @@ -813,6 +813,8 @@ getNestedPrice({item: {price: 9.99}}) // Some(9.99) ## Functional Programming Libraries in JavaScript +* [mori](https://github.com/swannodette/mori) +* [Immutable](https://github.com/facebook/immutable-js/) * [Ramda](https://github.com/ramda/ramda) * [Folktale](http://folktalejs.org) * [monet.js](https://cwmyers.github.io/monet.js/) From 1105aae3e1eb01e360445a15b895564d3216d74c Mon Sep 17 00:00:00 2001 From: Dmitri Zaitsev Date: Mon, 23 Jan 2017 23:55:09 +0000 Subject: [PATCH 21/32] Corrected definition of Category (#138) --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index a6870e8..44a61e4 100644 --- a/readme.md +++ b/readme.md @@ -326,7 +326,7 @@ TODO ## Categories -Objects with associated functions that adhere to certain rules. E.g. [Monoid](#monoid) +A Category is a collection of objects (types) and functions (aka morphisms) between those types, typically sending values to values. Further, functions `a->b` and `b->c` can be composed into a new function `a->c`, the composition is associative, and there is identity function `a->a` for each object `a` that does not change functions by composing from right or from left. ## Value From 38cd3bebb1b69c365b9915673a083508ba84da64 Mon Sep 17 00:00:00 2001 From: Jethro Larson Date: Mon, 23 Jan 2017 16:01:44 -0800 Subject: [PATCH 22/32] Extend category definition --- readme.md | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/readme.md b/readme.md index 44a61e4..2875c43 100644 --- a/readme.md +++ b/readme.md @@ -29,7 +29,7 @@ __Table of Contents__ * [Predicate](#predicate) * [Contracts](#contracts) * [Guarded Functions](#guarded-functions) -* [Categories](#categories) +* [Category](#category) * [Value](#value) * [Constant](#constant) * [Functor](#functor) @@ -324,9 +324,27 @@ addOne('some string') // Contract violated: expected int -> int TODO -## Categories +## Category -A Category is a collection of objects (types) and functions (aka morphisms) between those types, typically sending values to values. Further, functions `a->b` and `b->c` can be composed into a new function `a->c`, the composition is associative, and there is identity function `a->a` for each object `a` that does not change functions by composing from right or from left. +A category in category theory is a collection of objects and morphisms between them. In programming, typically types +act as the objects and functions as morphisms. + +To be a valid category 3 rules must be met: + +1. There must be an identity morphism that maps an object to itself. + Where `a` is an object in some category, + there must be a function from `a -> a`. +2. Morphisms must compose. + Where `a`, `b`, and `c` are objects in some category, + and `f` is a morphism from `a -> b`, and `g` is a morphism from `b -> c`; + `g(f(x))` must be equivalent to `(g • f)(x)`. +3. Composition must be associative + `f • (g • h)` is the same as `(f • g) * h` + +Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things. + +### Further reading +* [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/) ## Value From 50b46665ffa0b11cb713d64e635f41b1dee4d5f8 Mon Sep 17 00:00:00 2001 From: shfshanyue Date: Fri, 3 Mar 2017 11:15:50 +0800 Subject: [PATCH 23/32] fix: arrow function in setoid --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 2875c43..95f31f0 100644 --- a/readme.md +++ b/readme.md @@ -675,7 +675,7 @@ An object that has an `equals` function which can be used to compare other objec Make array a setoid: ```js -Array.prototype.equals = (arr) => { +Array.prototype.equals = function (arr) { const len = this.length if (len !== arr.length) { return false From 25bd92ce9438c131fcf9d767c7ee4ca6fd382407 Mon Sep 17 00:00:00 2001 From: shfshanyue Date: Tue, 7 Mar 2017 16:54:47 +0800 Subject: [PATCH 24/32] Make easy for example of hoc --- readme.md | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/readme.md b/readme.md index 95f31f0..d76d4c4 100644 --- a/readme.md +++ b/readme.md @@ -80,15 +80,7 @@ console.log(arity) // 2 A function which takes a function as an argument and/or returns a function. ```js -const filter = (predicate, xs) => { - const result = [] - for (let idx = 0; idx < xs.length; idx++) { - if (predicate(xs[idx])) { - result.push(xs[idx]) - } - } - return result -} +const filter = (predicate, xs) => xs.filter(predicate) ``` ```js From b58ed9bea64ad19b81d56c9e061cd9c88a692544 Mon Sep 17 00:00:00 2001 From: shfshanyue Date: Thu, 9 Mar 2017 19:43:23 +0800 Subject: [PATCH 25/32] fix typo: middle dot --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index d76d4c4..2e19ff9 100644 --- a/readme.md +++ b/readme.md @@ -331,7 +331,7 @@ To be a valid category 3 rules must be met: and `f` is a morphism from `a -> b`, and `g` is a morphism from `b -> c`; `g(f(x))` must be equivalent to `(g • f)(x)`. 3. Composition must be associative - `f • (g • h)` is the same as `(f • g) * h` + `f • (g • h)` is the same as `(f • g) • h` Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things. From 6da52dbd2ba1e01a8c3a1780246695ca8a5451eb Mon Sep 17 00:00:00 2001 From: shfshanyue Date: Thu, 9 Mar 2017 22:00:49 +0800 Subject: [PATCH 26/32] Add Chinese --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 2e19ff9..db9199f 100644 --- a/readme.md +++ b/readme.md @@ -11,6 +11,7 @@ Where applicable, this document uses terms defined in the [Fantasy Land spec](ht __Translations__ * [Portuguese](https://github.com/alexmoreno/jargoes-programacao-funcional) * [Spanish](https://github.com/idcmardelplata/functional-programming-jargon/tree/master) +* [Chinese](https://github.com/shfshanyue/fp-jargon-zh) __Table of Contents__ From 841ed85f81fb72e81e6ea11b0d13bad923667cdf Mon Sep 17 00:00:00 2001 From: "hemanth.hm" Date: Sun, 26 Mar 2017 12:58:48 +0530 Subject: [PATCH 27/32] Fixes #145 --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index db9199f..684831d 100644 --- a/readme.md +++ b/readme.md @@ -145,7 +145,7 @@ add2(10) // 12 ## Auto Currying Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. -Underscore, lodash, and ramda have a `curry` function that works this way. +lodash & ramda have a `curry` function that works this way. ```js const add = (x, y) => x + y From b01d0f6cfcb4052ce7e64d6e2762d1540385baa9 Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Sun, 9 Apr 2017 10:54:48 +0530 Subject: [PATCH 28/32] Update readme.md Added closure vs lambda as suggested. --- readme.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/readme.md b/readme.md index 059a0e4..7c7f5bd 100644 --- a/readme.md +++ b/readme.md @@ -146,7 +146,7 @@ add2(10) // 12 ``` -##Closure +## Closure A closure is a way of accessing a variable outside its scope. Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment. @@ -156,23 +156,26 @@ ie. they allow referencing a scope after the block in which the variables were d ```js -var addTo = function(x) { - function add(y) { - return x + y; - } - return add; -} +const addTo = x => y => x + y; var addToFive = addTo(5); addToFive(3); //returns 8 ``` The function ```addTo()``` returns a function(internally called ```add()```), lets store it in a variable called ```addToFive``` with a curried call having parameter 5. -Ideally, when the function ```addoTo``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```addToFive()```. This means that the state of the function ```addTo``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```addTo``` was called as ```addTo(5)``` and the value of x was set to 5. +Ideally, when the function ```addTo``` finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling ```addToFive()```. This means that the state of the function ```addTo``` is saved even after the block of code has finished executing, otherwise there is no way of knowing that ```addTo``` was called as ```addTo(5)``` and the value of x was set to 5. Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure. The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it). +Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects. +A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure. + + +__Further reading/Sources__ +* [Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda) +* [JavaScript Closures highly voted disucussion](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) + ## Auto Currying Transforming a function that takes multiple arguments into one that if given less than its correct number of arguments returns a function that takes the rest. When the function gets the correct number of arguments it is then evaluated. From a07df820ca7b8b1a9ea3bd21e9ffdca7a219c3ee Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Sun, 9 Apr 2017 11:25:21 +0530 Subject: [PATCH 29/32] Update readme.md --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 7c7f5bd..36ff36e 100644 --- a/readme.md +++ b/readme.md @@ -169,6 +169,7 @@ Lexical scoping is the reason why it is able to find the values of x and add - t The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it). Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects. + A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure. From 0cd5973ddf7baf0a69b902d056d0b2562b1ead3a Mon Sep 17 00:00:00 2001 From: Sean-Lan Date: Fri, 14 Apr 2017 18:43:39 +0800 Subject: [PATCH 30/32] fix: fix the lift example error --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 34faf12..a3e7507 100644 --- a/readme.md +++ b/readme.md @@ -456,7 +456,7 @@ const mult = a => b => a * b const liftedMult = liftA2(mult) // this function now works on functors like array liftedMult([1, 2], [3]) // [3, 6] -liftA2((a, b) => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] +liftA2(a => b => a + b)([1, 2], [3, 4]) // [4, 5, 5, 6] ``` Lifting a one-argument function and applying it does the same thing as `map`. From 9045867897550bee7a2fbac360cc959911114bcc Mon Sep 17 00:00:00 2001 From: Sunny Patel Date: Wed, 10 May 2017 09:45:10 +0530 Subject: [PATCH 31/32] Fix Typo in Closure Replaced Scopped with Scoped --- readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/readme.md b/readme.md index 36ff36e..0d67777 100644 --- a/readme.md +++ b/readme.md @@ -149,7 +149,7 @@ add2(10) // 12 ## Closure A closure is a way of accessing a variable outside its scope. -Formally, a closure is a technique for implementing lexically scopped named binding. It is a way of storing a function with an environment. +Formally, a closure is a technique for implementing lexically scoped named binding. It is a way of storing a function with an environment. A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined. ie. they allow referencing a scope after the block in which the variables were declared has finished executing. From 916d87505cce2f80679f9c316820e4599a90f9a3 Mon Sep 17 00:00:00 2001 From: Vladimir Gorej Date: Wed, 17 May 2017 00:32:37 +0200 Subject: [PATCH 32/32] docs(readme.md): add ramda-adjunct as FL ramda-adjunct is rapidly growing adjunct or core ramda library. --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 03d1d07..50af36b 100644 --- a/readme.md +++ b/readme.md @@ -859,6 +859,7 @@ getNestedPrice({item: {price: 9.99}}) // Some(9.99) * [mori](https://github.com/swannodette/mori) * [Immutable](https://github.com/facebook/immutable-js/) * [Ramda](https://github.com/ramda/ramda) +* [ramda-adjunct](https://github.com/char0n/ramda-adjunct) * [Folktale](http://folktalejs.org) * [monet.js](https://cwmyers.github.io/monet.js/) * [lodash](https://github.com/lodash/lodash)