{"id":13394658,"url":"https://github.com/hemanth/functional-programming-jargon","last_synced_at":"2025-05-13T17:04:47.034Z","repository":{"id":27682295,"uuid":"31168578","full_name":"hemanth/functional-programming-jargon","owner":"hemanth","description":"Jargon from the functional programming world in simple terms!","archived":false,"fork":false,"pushed_at":"2023-10-17T12:04:55.000Z","size":453,"stargazers_count":18631,"open_issues_count":29,"forks_count":1011,"subscribers_count":354,"default_branch":"master","last_synced_at":"2025-04-23T22:58:10.493Z","etag":null,"topics":["fp","functional-programming"],"latest_commit_sha":null,"homepage":"http://git.io/fp-jargons","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hemanth.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":"contributing.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null},"funding":{"github":"hemanth","patreon":"fpjargon","custom":"https://paypal.me/gnumanth"}},"created_at":"2015-02-22T16:04:42.000Z","updated_at":"2025-04-23T08:17:27.000Z","dependencies_parsed_at":"2023-01-14T07:16:35.053Z","dependency_job_id":"a4de0a71-0402-4fad-8779-05c3d70a6c98","html_url":"https://github.com/hemanth/functional-programming-jargon","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hemanth%2Ffunctional-programming-jargon","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hemanth%2Ffunctional-programming-jargon/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hemanth%2Ffunctional-programming-jargon/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hemanth%2Ffunctional-programming-jargon/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hemanth","download_url":"https://codeload.github.com/hemanth/functional-programming-jargon/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253990459,"owners_count":21995773,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fp","functional-programming"],"created_at":"2024-07-30T17:01:27.361Z","updated_at":"2025-05-13T17:04:47.006Z","avatar_url":"https://github.com/hemanth.png","language":null,"readme":"# Functional Programming Jargon\n\nFunctional programming (FP) provides many advantages, and its popularity has been increasing as a result. However, each programming paradigm comes with its own unique jargon and FP is no exception. By providing a glossary, we hope to make learning FP easier.\n\nExamples are presented in JavaScript (ES2015). [Why JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F)\n\nWhere applicable, this document uses terms defined in the [Fantasy Land spec](https://github.com/fantasyland/fantasy-land).\n\n__Translations__\n* [Portuguese](https://github.com/alexmoreno/jargoes-programacao-funcional)\n* [Spanish](https://github.com/idcmardelplata/functional-programming-jargon/tree/master)\n* [Chinese](https://github.com/shfshanyue/fp-jargon-zh)\n* [Bahasa Indonesia](https://github.com/wisn/jargon-pemrograman-fungsional)\n* [Python World](https://github.com/jmesyou/functional-programming-jargon.py)\n* [Scala World](https://github.com/ikhoon/functional-programming-jargon.scala)\n* [Rust World](https://github.com/JasonShin/functional-programming-jargon.rs)\n* [Korean](https://github.com/sphilee/functional-programming-jargon)\n* [Polish](https://github.com/Deloryn/functional-programming-jargon)\n* [Haskell Turkish](https://github.com/mrtkp9993/functional-programming-jargon)\n* [Haskell Russian](https://github.com/epogrebnyak/functional-programming-jargon)\n* [Julia World](https://github.com/Moelf/functional-programming-jargon.jl)\n* [French](https://github.com/marcwrobel/functional-programming-jargon-fr)\n\n__Table of Contents__\n\u003c!-- RM(noparent,notop) --\u003e\n\n* [Arity](#arity)\n* [Higher-Order Functions (HOF)](#higher-order-functions-hof)\n* [Closure](#closure)\n* [Partial Application](#partial-application)\n* [Currying](#currying)\n* [Auto Currying](#auto-currying)\n* [Function Composition](#function-composition)\n* [Continuation](#continuation)\n* [Pure Function](#pure-function)\n* [Side effects](#side-effects)\n* [Idempotence](#idempotence)\n* [Point-Free Style](#point-free-style)\n* [Predicate](#predicate)\n* [Contracts](#contracts)\n* [Category](#category)\n* [Value](#value)\n* [Constant](#constant)\n  * [Constant Function](#constant-function)\n  * [Constant Functor](#constant-functor)\n  * [Constant Monad](#constant-monad)\n* [Functor](#functor)\n* [Pointed Functor](#pointed-functor)\n* [Lift](#lift)\n* [Referential Transparency](#referential-transparency)\n* [Equational Reasoning](#equational-reasoning)\n* [Lambda](#lambda)\n* [Lambda Calculus](#lambda-calculus)\n* [Functional Combinator](#functional-combinator)\n* [Lazy evaluation](#lazy-evaluation)\n* [Monoid](#monoid)\n* [Monad](#monad)\n* [Comonad](#comonad)\n* [Kleisli Composition](#kleisli-composition)\n* [Applicative Functor](#applicative-functor)\n* [Morphism](#morphism)\n  * [Homomorphism](#homomorphism)\n  * [Endomorphism](#endomorphism)\n  * [Isomorphism](#isomorphism)\n  * [Catamorphism](#catamorphism)\n  * [Anamorphism](#anamorphism)\n  * [Hylomorphism](#hylomorphism)\n  * [Paramorphism](#paramorphism)\n  * [Apomorphism](#apomorphism)\n* [Setoid](#setoid)\n* [Semigroup](#semigroup)\n* [Foldable](#foldable)\n* [Lens](#lens)\n* [Type Signatures](#type-signatures)\n* [Algebraic data type](#algebraic-data-type)\n  * [Sum type](#sum-type)\n  * [Product type](#product-type)\n* [Option](#option)\n* [Function](#function)\n* [Partial function](#partial-function)\n  * [Dealing with partial functions](#dealing-with-partial-functions)\n* [Total Function](#total-function)\n* [Functional Programming Libraries in JavaScript](#functional-programming-libraries-in-javascript)\n\n\n\u003c!-- /RM --\u003e\n\n## Arity\n\nThe number of arguments a function takes. From words like unary, binary, ternary, etc.\n\n```js\nconst sum = (a, b) =\u003e a + b\n// The arity of sum is 2 (binary)\nconst inc = a =\u003e a + 1\n// The arity of inc is 1 (unary)\nconst zero = () =\u003e 0\n// The arity of zero is 0 (nullary)\n```\n\n__Further reading__\n\n* [Arity](https://en.wikipedia.org/wiki/Arity) on Wikipedia\n\n## Higher-Order Functions (HOF)\n\nA function which takes a function as an argument and/or returns a function.\n\n```js\nconst filter = (predicate, xs) =\u003e xs.filter(predicate)\n```\n\n```js\nconst is = (type) =\u003e (x) =\u003e Object(x) instanceof type\n```\n\n```js\nfilter(is(Number), [0, '1', 2, null]) // [0, 2]\n```\n\n## Closure\n\nA 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.\nThis allows the values in the closure to be accessed by returned functions.\n\n```js\nconst addTo = x =\u003e y =\u003e x + y\nconst addToFive = addTo(5)\naddToFive(3) // =\u003e 8\n```\n\nIn this case the `x` is retained in `addToFive`'s closure with the value `5`. `addToFive` can then be called with the `y`\nto get back the sum.\n\n__Further reading/Sources__\n* [Lambda Vs Closure](http://stackoverflow.com/questions/220658/what-is-the-difference-between-a-closure-and-a-lambda)\n* [JavaScript Closures highly voted discussion](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)\n\n## Partial Application\n\nPartially applying a function means creating a new function by pre-filling some of the arguments to the original function.\n\n```js\n// Helper to create partially applied functions\n// Takes a function and some arguments\nconst partial = (f, ...args) =\u003e\n  // returns a function that takes the rest of the arguments\n  (...moreArgs) =\u003e\n    // and calls the original function with all of them\n    f(...args, ...moreArgs)\n\n// Something to apply\nconst add3 = (a, b, c) =\u003e a + b + c\n\n// Partially applying `2` and `3` to `add3` gives you a one-argument function\nconst fivePlus = partial(add3, 2, 3) // (c) =\u003e 2 + 3 + c\n\nfivePlus(4) // 9\n```\n\nYou can also use `Function.prototype.bind` to partially apply a function in JS:\n\n```js\nconst add1More = add3.bind(null, 2, 3) // (c) =\u003e 2 + 3 + c\n```\n\nPartial application helps create simpler functions from more complex ones by baking in data when you have it. [Curried](#currying) functions are automatically partially applied.\n\n## Currying\n\nThe process of converting a function that takes multiple arguments into a function that takes them one at a time.\n\nEach time the function is called it only accepts one argument and returns a function that takes one argument until all arguments are passed.\n\n```js\nconst sum = (a, b) =\u003e a + b\n\nconst curriedSum = (a) =\u003e (b) =\u003e a + b\n\ncurriedSum(40)(2) // 42.\n\nconst add2 = curriedSum(2) // (b) =\u003e 2 + b\n\nadd2(10) // 12\n```\n\n## Auto Currying\n\nTransforming 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.\n\nLodash \u0026 Ramda have a `curry` function that works this way.\n\n```js\nconst add = (x, y) =\u003e x + y\n\nconst curriedAdd = _.curry(add)\ncurriedAdd(1, 2) // 3\ncurriedAdd(1) // (y) =\u003e 1 + y\ncurriedAdd(1)(2) // 3\n```\n\n__Further reading__\n* [Favoring Curry](http://fr.umio.us/favoring-curry/)\n* [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA)\n\n## Function Composition\n\nThe act of putting two functions together to form a third function where the output of one function is the input of the other. This is one of the most important ideas of functional programming.\n\n```js\nconst compose = (f, g) =\u003e (a) =\u003e f(g(a)) // Definition\nconst floorAndToString = compose((val) =\u003e val.toString(), Math.floor) // Usage\nfloorAndToString(121.212121) // '121'\n```\n\n## Continuation\n\nAt any given point in a program, the part of the code that's yet to be executed is known as a continuation.\n\n```js\nconst printAsString = (num) =\u003e console.log(`Given ${num}`)\n\nconst addOneAndContinue = (num, cc) =\u003e {\n  const result = num + 1\n  cc(result)\n}\n\naddOneAndContinue(2, printAsString) // 'Given 3'\n```\n\nContinuations 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.\n\n```js\nconst continueProgramWith = (data) =\u003e {\n  // Continues program with data\n}\n\nreadFileAsync('path/to/file', (err, response) =\u003e {\n  if (err) {\n    // handle error\n    return\n  }\n  continueProgramWith(response)\n})\n```\n\n## Pure Function\n\nA function is pure if the return value is only determined by its input values, and does not produce side effects. The function must always return the same result when given the same input.\n\n```js\nconst greet = (name) =\u003e `Hi, ${name}`\n\ngreet('Brianne') // 'Hi, Brianne'\n```\n\nAs opposed to each of the following:\n\n```js\nwindow.name = 'Brianne'\n\nconst greet = () =\u003e `Hi, ${window.name}`\n\ngreet() // \"Hi, Brianne\"\n```\n\nThe above example's output is based on data stored outside of the function...\n\n```js\nlet greeting\n\nconst greet = (name) =\u003e {\n  greeting = `Hi, ${name}`\n}\n\ngreet('Brianne')\ngreeting // \"Hi, Brianne\"\n```\n\n... and this one modifies state outside of the function.\n\n## Side effects\n\nA 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.\n\n```js\nconst differentEveryTime = new Date()\n```\n\n```js\nconsole.log('IO is a side effect!')\n```\n\n## Idempotence\n\nA function is idempotent if reapplying it to its result does not produce a different result.\n\n```js\nMath.abs(Math.abs(10))\n```\n\n```js\nsort(sort(sort([2, 1])))\n```\n\n## Point-Free Style\n\nWriting functions where the definition does not explicitly identify the arguments used. This style usually requires [currying](#currying) or other [Higher-Order functions](#higher-order-functions-hof). A.K.A Tacit programming.\n\n```js\n// Given\nconst map = (fn) =\u003e (list) =\u003e list.map(fn)\nconst add = (a) =\u003e (b) =\u003e a + b\n\n// Then\n\n// Not point-free - `numbers` is an explicit argument\nconst incrementAll = (numbers) =\u003e map(add(1))(numbers)\n\n// Point-free - The list is an implicit argument\nconst incrementAll2 = map(add(1))\n```\n\nPoint-free function definitions look just like normal assignments without `function` or `=\u003e`. It's worth mentioning that point-free functions are not necessarily better than their counterparts, as they can be more difficult to understand when complex.\n\n## Predicate\n\nA 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.\n\n```js\nconst predicate = (a) =\u003e a \u003e 2\n\n;[1, 2, 3, 4].filter(predicate) // [3, 4]\n```\n\n## Contracts\n\nA 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.\n\n```js\n// Define our contract : int -\u003e boolean\nconst contract = (input) =\u003e {\n  if (typeof input === 'number') return true\n  throw new Error('Contract violated: expected int -\u003e boolean')\n}\n\nconst addOne = (num) =\u003e contract(num) \u0026\u0026 num + 1\n\naddOne(2) // 3\naddOne('some string') // Contract violated: expected int -\u003e boolean\n```\n\n## Category\n\nA category in category theory is a collection of objects and morphisms between them. In programming, typically types\nact as the objects and functions as morphisms.\n\nTo be a valid category, three rules must be met:\n\n1. There must be an identity morphism that maps an object to itself.\n    Where `a` is an object in some category,\n    there must be a function from `a -\u003e a`.\n2. Morphisms must compose.\n    Where `a`, `b`, and `c` are objects in some category,\n    and `f` is a morphism from `a -\u003e b`, and `g` is a morphism from `b -\u003e c`;\n    `g(f(x))` must be equivalent to `(g • f)(x)`.\n3. Composition must be associative\n    `f • (g • h)` is the same as `(f • g) • h`.\n\nSince these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things.\n\nAs an example we can define a category Max as a class:\n\n```js\n\nclass Max {\n  constructor (a) {\n    this.a = a\n  }\n\n  id () {\n    return this\n  }\n\n  compose (b) {\n    return this.a \u003e b.a ? this : b\n  }\n\n  toString () {\n    return `Max(${this.a})`\n  }\n}\n\nnew Max(2).compose(new Max(3)).compose(new Max(5)).id().id() // =\u003e Max(5)\n```\n\n__Further reading__\n\n* [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)\n\n## Value\n\nAnything that can be assigned to a variable.\n\n```js\n5\nObject.freeze({ name: 'John', age: 30 }) // The `freeze` function enforces immutability.\n;(a) =\u003e a\n;[1]\nundefined\n```\n\n## Constant\n\nA variable that cannot be reassigned once defined.\n\n```js\nconst five = 5\nconst john = Object.freeze({ name: 'John', age: 30 })\n```\n\nConstants are [referentially transparent](#referential-transparency). That is, they can be replaced with the values that they represent without affecting the result.\n\nWith the above two constants the following expression will always return `true`.\n\n```js\njohn.age + five === ({ name: 'John', age: 30 }).age + 5\n```\n\n### Constant Function\n\nA [curried](#currying) function that ignores its second argument:\n\n```js\nconst constant = a =\u003e () =\u003e a\n\n;[1, 2].map(constant(0)) // =\u003e [0, 0]\n```\n\n### Constant Functor\n\nObject whose `map` doesn't transform the contents. See [Functor](#functor).\n\n```js\nConstant(1).map(n =\u003e n + 1) // =\u003e Constant(1)\n```\n\n### Constant Monad\n\nObject whose `chain` doesn't transform the contents. See [Monad](#monad).\n\n```js\nConstant(1).chain(n =\u003e Constant(n + 1)) // =\u003e Constant(1)\n```\n\n## Functor\n\nAn object that implements a `map` function that takes a function which is run on the contents of that object. A functor must adhere to two rules:\n\n__Preserves identity__\n\n```js\nobject.map(x =\u003e x)\n```\n\nis equivalent to just `object`.\n\n__Composable__\n\n```js\nobject.map(x =\u003e g(f(x)))\n```\n\nis equivalent to\n\n```js\nobject.map(f).map(g)\n```\n\n(`f`, `g` are arbitrary composable functions)\n\nThe reference implementation of [Option](#option) is a functor as it satisfies the rules:\n\n```js\nSome(1).map(x =\u003e x) // = Some(1)\n```\n\nand\n\n```js\nconst f = x =\u003e x + 1\nconst g = x =\u003e x * 2\n\nSome(1).map(x =\u003e g(f(x))) // = Some(4)\nSome(1).map(f).map(g) // = Some(4)\n```\n\n## Pointed Functor\n\nAn object with an `of` function that puts _any_ single value into it.\n\nES2015 adds `Array.of` making arrays a pointed functor.\n\n```js\nArray.of(1) // [1]\n```\n\n## Lift\n\nLifting is when you take a value and put it into an object like a [functor](#pointed-functor). If you lift a function into an [Applicative Functor](#applicative-functor) then you can make it work on values that are also in that functor.\n\nSome implementations have a function called `lift`, or `liftA2` to make it easier to run functions on functors.\n\n```js\nconst liftA2 = (f) =\u003e (a, b) =\u003e a.map(f).ap(b) // note it's `ap` and not `map`.\n\nconst mult = a =\u003e b =\u003e a * b\n\nconst liftedMult = liftA2(mult) // this function now works on functors like array\n\nliftedMult([1, 2], [3]) // [3, 6]\nliftA2(a =\u003e b =\u003e a + b)([1, 2], [30, 40]) // [31, 41, 32, 42]\n```\n\nLifting a one-argument function and applying it does the same thing as `map`.\n\n```js\nconst increment = (x) =\u003e x + 1\n\nlift(increment)([2]) // [3]\n;[2].map(increment) // [3]\n```\n\nLifting simple values can be simply creating the object.\n\n```js\nArray.of(1) // =\u003e [1]\n```\n\n## Referential Transparency\n\nAn expression that can be replaced with its value without changing the\nbehavior of the program is said to be referentially transparent.\n\nGiven the function greet:\n\n```js\nconst greet = () =\u003e 'Hello World!'\n```\n\nAny invocation of `greet()` can be replaced with `Hello World!` hence greet is\nreferentially transparent. This would be broken if greet depended on external\nstate like configuration or a database call. See also [Pure Function](#pure-function) and\n[Equational Reasoning](#equational-reasoning).\n\n## Equational Reasoning\n\nWhen an application is composed of expressions and devoid of side effects,\ntruths about the system can be derived from the parts. You can also be confident\nabout details of your system without having to go through every function.\n\n```js\nconst grainToDogs = compose(chickenIntoDogs, grainIntoChicken)\nconst grainToCats = compose(dogsIntoCats, grainToDogs)\n```\n\nIn the example above, if you know that `chickenIntoDogs` and `grainIntoChicken`\nare [pure](#pure-function) then you know that the composition is pure. This can be taken further\nwhen more is known about the functions (associative, commutative, idempotent, etc...).\n\n## Lambda\n\nAn anonymous function that can be treated like a value.\n\n```js\n;(function (a) {\n  return a + 1\n})\n\n;(a) =\u003e a + 1\n```\n\nLambdas are often passed as arguments to Higher-Order functions:\n\n```js\n;[1, 2].map((a) =\u003e a + 1) // [2, 3]\n```\n\nYou can assign a lambda to a variable:\n\n```js\nconst add1 = (a) =\u003e a + 1\n```\n\n## Lambda Calculus\n\nA branch of mathematics that uses functions to create a [universal model of computation](https://en.wikipedia.org/wiki/Lambda_calculus).\n\n## Functional Combinator\n\nA higher-order function, usually curried, which returns a new function changed in some way. Functional combinators are often used in [Point-Free Style](#point-free-style) to write especially terse programs.\n\n```js\n// The \"C\" combinator takes a curried two-argument function and returns one which calls the original function with the arguments reversed.\nconst C = (f) =\u003e (a) =\u003e (b) =\u003e f(b)(a)\n\nconst divide = (a) =\u003e (b) =\u003e a / b\n\nconst divideBy = C(divide)\n\nconst divBy10 = divideBy(10)\n\ndivBy10(30) // =\u003e 3\n```\n\nSee also [List of Functional Combinators in JavaScript](https://gist.github.com/Avaq/1f0636ec5c8d6aed2e45) which includes links to more references.\n\n## Lazy evaluation\n\nLazy evaluation is a call-by-need evaluation mechanism that delays the evaluation of an expression until its value is needed. In functional languages, this allows for structures like infinite lists, which would not normally be available in an imperative language where the sequencing of commands is significant.\n\n```js\nconst rand = function * () {\n  while (1 \u003c 2) {\n    yield Math.random()\n  }\n}\n```\n\n```js\nconst randIter = rand()\nrandIter.next() // Each execution gives a random value, expression is evaluated on need.\n```\n\n## Monoid\n\nAn object with a function that \"combines\" that object with another of the same type (semigroup) which has an \"identity\" value.\n\nOne simple monoid is the addition of numbers:\n\n```js\n1 + 1 // 2\n```\n\nIn this case number is the object and `+` is the function.\n\nWhen any value is combined with the \"identity\" value the result must be the original value. The identity must also be commutative.\n\nThe identity value for addition is `0`.\n\n```js\n1 + 0 // 1\n0 + 1 // 1\n1 + 0 === 0 + 1\n```\n\nIt's also required that the grouping of operations will not affect the result (associativity):\n\n```js\n1 + (2 + 3) === (1 + 2) + 3 // true\n```\n\nArray concatenation also forms a monoid:\n\n```js\n;[1, 2].concat([3, 4]) // [1, 2, 3, 4]\n```\n\nThe identity value is empty array `[]`:\n\n```js\n;[1, 2].concat([]) // [1, 2]\n```\n\nAs a counterexample, subtraction does not form a monoid because there is no commutative identity value:\n\n```js\n0 - 4 === 4 - 0 // false\n```\n\n## Monad\n\nA monad is an object with [`of`](#pointed-functor) and `chain` functions. `chain` is like [`map`](#functor) except it un-nests the resulting nested object.\n\n```js\n// Implementation\nArray.prototype.chain = function (f) {\n  return this.reduce((acc, it) =\u003e acc.concat(f(it)), [])\n}\n\n// Usage\nArray.of('cat,dog', 'fish,bird').chain((a) =\u003e a.split(',')) // ['cat', 'dog', 'fish', 'bird']\n\n// Contrast to map\nArray.of('cat,dog', 'fish,bird').map((a) =\u003e a.split(',')) // [['cat', 'dog'], ['fish', 'bird']]\n```\n\n`of` is also known as `return` in other functional languages.\n`chain` is also known as `flatmap` and `bind` in other languages.\n\n## Comonad\n\nAn object that has `extract` and `extend` functions.\n\n```js\nconst CoIdentity = (v) =\u003e ({\n  val: v,\n  extract () {\n    return this.val\n  },\n  extend (f) {\n    return CoIdentity(f(this))\n  }\n})\n```\n\n`extract` takes a value out of a functor:\n\n```js\nCoIdentity(1).extract() // 1\n```\n\n`extend` runs a function on the comonad. The function should return the same type as the comonad:\n\n```js\nCoIdentity(1).extend((co) =\u003e co.extract() + 1) // CoIdentity(2)\n```\n\n## Kleisli Composition\n\nAn operation for composing two [monad](#monad)-returning functions (Kleisli Arrows) where they have compatible types. In Haskell this is the `\u003e=\u003e` operator.\n\nUsing [Option](#option):\n\n```js\n// safeParseNum :: String -\u003e Option Number\nconst safeParseNum = (b) =\u003e {\n  const n = parseNumber(b)\n  return isNaN(n) ? None() : Some(n)\n}\n\n// validatePositive :: Number -\u003e Option Number\nconst validatePositive = (a) =\u003e a \u003e 0 ? Some(a) : None()\n\n// kleisliCompose :: Monad M =\u003e ((b -\u003e M c), (a -\u003e M b)) -\u003e a -\u003e M c\nconst kleisliCompose = (g, f) =\u003e (x) =\u003e f(x).chain(g)\n\n// parseAndValidate :: String -\u003e Option Number\nconst parseAndValidate = kleisliCompose(validatePositive, safeParseNum)\n\nparseAndValidate('1') // =\u003e Some(1)\nparseAndValidate('asdf') // =\u003e None\nparseAndValidate('999') // =\u003e Some(999)\n```\n\nThis works because:\n\n * [option](#option) is a [monad](#monad),\n * both `validatePositive` and `safeParseNum` return the same kind of monad (Option),\n * the type of `validatePositive`'s argument matches `safeParseNum`'s unwrapped return.\n\n## Applicative Functor\n\nAn applicative functor is an object with an `ap` function. `ap` applies a function in the object to a value in another object of the same type.\n\n```js\n// Implementation\nArray.prototype.ap = function (xs) {\n  return this.reduce((acc, f) =\u003e acc.concat(xs.map(f)), [])\n}\n\n// Example usage\n;[(a) =\u003e a + 1].ap([1]) // [2]\n```\n\nThis is useful if you have two objects and you want to apply a binary function to their contents.\n\n```js\n// Arrays that you want to combine\nconst arg1 = [1, 3]\nconst arg2 = [4, 5]\n\n// combining function - must be curried for this to work\nconst add = (x) =\u003e (y) =\u003e x + y\n\nconst partiallyAppliedAdds = [add].ap(arg1) // [(y) =\u003e 1 + y, (y) =\u003e 3 + y]\n```\n\nThis gives you an array of functions that you can call `ap` on to get the result:\n\n```js\npartiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8]\n```\n\n## Morphism\n\nA relationship between objects within a [category](#category). In the context of functional programming all functions are morphisms.\n\n### Homomorphism\n\nA function where there is a structural property that is the same in the input as well as the output.\n\nFor example, in a [Monoid](#monoid) homomorphism both the input and the output are monoids even if their types are different.\n\n```js\n// toList :: [number] -\u003e string\nconst toList = (a) =\u003e a.join(', ')\n```\n\n`toList` is a homomorphism because:\n* array is a monoid - has a `concat` operation and an identity value (`[]`),\n* string is a monoid - has a `concat` operation and an identity value (`''`).\n\nIn this way, a homomorphism relates to whatever property you care about in the input and output of a transformation.\n\n[Endomorphisms](#endomorphism) and [Isomorphisms](#isomorphism) are examples of homomorphisms.\n\n__Further Reading__\n* [Homomorphism | Learning Functional Programming in Go](https://subscription.packtpub.com/book/application-development/9781787281394/11/ch11lvl1sec90/homomorphism#:~:text=A%20homomorphism%20is%20a%20correspondence,pointing%20to%20it%20from%20A.)\n\n### Endomorphism\n\nA function where the input type is the same as the output. Since the types are identical, endomorphisms are also [homomorphisms](#homomorphism).\n\n```js\n// uppercase :: String -\u003e String\nconst uppercase = (str) =\u003e str.toUpperCase()\n\n// decrement :: Number -\u003e Number\nconst decrement = (x) =\u003e x - 1\n```\n\n### Isomorphism\n\nA morphism made of a pair of transformations between 2 types of objects that is structural in nature and no data is lost.\n\nFor example, 2D coordinates could be stored as an array `[2,3]` or object `{x: 2, y: 3}`.\n\n```js\n// Providing functions to convert in both directions makes the 2D coordinate structures isomorphic.\nconst pairToCoords = (pair) =\u003e ({ x: pair[0], y: pair[1] })\n\nconst coordsToPair = (coords) =\u003e [coords.x, coords.y]\n\ncoordsToPair(pairToCoords([1, 2])) // [1, 2]\n\npairToCoords(coordsToPair({ x: 1, y: 2 })) // {x: 1, y: 2}\n```\n\nIsomorphisms are an interesting example of [morphism](#morphism) because more than single function is necessary for it to be satisfied. Isomorphisms are also [homomorphisms](#homomorphism) since both input and output types share the property of being reversible.\n\n### Catamorphism\n\nA function which deconstructs a structure into a single value. `reduceRight` is an example of a catamorphism for array structures.\n\n```js\n// sum is a catamorphism from [Number] -\u003e Number\nconst sum = xs =\u003e xs.reduceRight((acc, x) =\u003e acc + x, 0)\n\nsum([1, 2, 3, 4, 5]) // 15\n```\n\n### Anamorphism\n\nA function that builds up a structure by repeatedly applying a function to its argument. `unfold` is an example which generates an array from a function and a seed value. This is the opposite of a [catamorphism](#catamorphism). You can think of this as an anamorphism builds up a structure and catamorphism breaks it down.\n\n```js\nconst unfold = (f, seed) =\u003e {\n  function go (f, seed, acc) {\n    const res = f(seed)\n    return res ? go(f, res[1], acc.concat([res[0]])) : acc\n  }\n  return go(f, seed, [])\n}\n```\n\n```js\nconst countDown = n =\u003e unfold((n) =\u003e {\n  return n \u003c= 0 ? undefined : [n, n - 1]\n}, n)\n\ncountDown(5) // [5, 4, 3, 2, 1]\n```\n\n### Hylomorphism\n\nThe function which composes an [anamorphism](#anamorphism) followed by a [catamorphism](#catamorphism).\n\n```js\nconst sumUpToX = (x) =\u003e sum(countDown(x))\nsumUpToX(5) // 15\n```\n\n### Paramorphism\n\nA function just like `reduceRight`. However, there's a difference:\n\nIn paramorphism, your reducer's arguments are the current value, the reduction of all previous values, and the list of values that formed that reduction.\n\n```js\n// Obviously not safe for lists containing `undefined`,\n// but good enough to make the point.\nconst para = (reducer, accumulator, elements) =\u003e {\n  if (elements.length === 0) { return accumulator }\n\n  const head = elements[0]\n  const tail = elements.slice(1)\n\n  return reducer(head, tail, para(reducer, accumulator, tail))\n}\n\nconst suffixes = list =\u003e para(\n  (x, xs, suffxs) =\u003e [xs, ...suffxs],\n  [],\n  list\n)\n\nsuffixes([1, 2, 3, 4, 5]) // [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []]\n```\n\nThe third parameter in the reducer (in the above example, `[x, ... xs]`) is kind of like having a history of what got you to your current acc value.\n\n### Apomorphism\n\nThe opposite of paramorphism, just as anamorphism is the opposite of catamorphism. With paramorphism, you retain access to the accumulator and what has been accumulated, apomorphism lets you `unfold` with the potential to return early.\n\n## Setoid\n\nAn object that has an `equals` function which can be used to compare other objects of the same type.\n\nMake array a setoid:\n\n```js\nArray.prototype.equals = function (arr) {\n  const len = this.length\n  if (len !== arr.length) {\n    return false\n  }\n  for (let i = 0; i \u003c len; i++) {\n    if (this[i] !== arr[i]) {\n      return false\n    }\n  }\n  return true\n}\n\n;[1, 2].equals([1, 2]) // true\n;[1, 2].equals([0]) // false\n```\n\n## Semigroup\n\nAn object that has a `concat` function that combines it with another object of the same type.\n\n```js\n;[1].concat([2]) // [1, 2]\n```\n\n## Foldable\n\nAn object that has a `reduce` function that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.\n\n```js\nconst sum = (list) =\u003e list.reduce((acc, val) =\u003e acc + val, 0)\nsum([1, 2, 3]) // 6\n```\n\n## Lens\n\nA lens is a structure (often an object or function) that pairs a getter and a non-mutating setter for some other data\nstructure.\n\n```js\n// Using [Ramda's lens](http://ramdajs.com/docs/#lens)\nconst nameLens = R.lens(\n  // getter for name property on an object\n  (obj) =\u003e obj.name,\n  // setter for name property\n  (val, obj) =\u003e Object.assign({}, obj, { name: val })\n)\n```\n\nHaving the pair of get and set for a given data structure enables a few key features.\n\n```js\nconst person = { name: 'Gertrude Blanch' }\n\n// invoke the getter\nR.view(nameLens, person) // 'Gertrude Blanch'\n\n// invoke the setter\nR.set(nameLens, 'Shafi Goldwasser', person) // {name: 'Shafi Goldwasser'}\n\n// run a function on the value in the structure\nR.over(nameLens, uppercase, person) // {name: 'GERTRUDE BLANCH'}\n```\n\nLenses are also composable. This allows easy immutable updates to deeply nested data.\n\n```js\n// This lens focuses on the first item in a non-empty array\nconst firstLens = R.lens(\n  // get first item in array\n  xs =\u003e xs[0],\n  // non-mutating setter for first item in array\n  (val, [__, ...xs]) =\u003e [val, ...xs]\n)\n\nconst people = [{ name: 'Gertrude Blanch' }, { name: 'Shafi Goldwasser' }]\n\n// Despite what you may assume, lenses compose left-to-right.\nR.over(compose(firstLens, nameLens), uppercase, people) // [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]\n```\n\nOther implementations:\n* [partial.lenses](https://github.com/calmm-js/partial.lenses) - Tasty syntax sugar and a lot of powerful features\n* [nanoscope](http://www.kovach.me/nanoscope/) - Fluent-interface\n\n## Type Signatures\n\nOften functions in JavaScript will include comments that indicate the types of their arguments and return values.\n\nThere's quite a bit of variance across the community, but they often follow the following patterns:\n\n```js\n// functionName :: firstArgType -\u003e secondArgType -\u003e returnType\n\n// add :: Number -\u003e Number -\u003e Number\nconst add = (x) =\u003e (y) =\u003e x + y\n\n// increment :: Number -\u003e Number\nconst increment = (x) =\u003e x + 1\n```\n\nIf a function accepts another function as an argument it is wrapped in parentheses.\n\n```js\n// call :: (a -\u003e b) -\u003e a -\u003e b\nconst call = (f) =\u003e (x) =\u003e f(x)\n```\n\nThe letters `a`, `b`, `c`, `d` are used to signify that the argument can be of any type. The following version of `map` takes a function that transforms a value of some type `a` into another type `b`, an array of values of type `a`, and returns an array of values of type `b`.\n\n```js\n// map :: (a -\u003e b) -\u003e [a] -\u003e [b]\nconst map = (f) =\u003e (list) =\u003e list.map(f)\n```\n\n__Further reading__\n* [Ramda's type signatures](https://github.com/ramda/ramda/wiki/Type-Signatures)\n* [Mostly Adequate Guide](https://web.archive.org/web/20170602130913/https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch7.html#whats-your-type)\n* [What is Hindley-Milner?](http://stackoverflow.com/a/399392/22425) on Stack Overflow\n\n## Algebraic data type\n\nA composite type made from putting other types together. Two common classes of algebraic types are [sum](#sum-type) and [product](#product-type).\n\n### Sum type\n\nA Sum type is the combination of two types together into another one. It is called sum because the number of possible values in the result type is the sum of the input types.\n\nJavaScript doesn't have types like this, but we can use `Set`s to pretend:\n\n```js\n// imagine that rather than sets here we have types that can only have these values\nconst bools = new Set([true, false])\nconst halfTrue = new Set(['half-true'])\n\n// The weakLogic type contains the sum of the values from bools and halfTrue\nconst weakLogicValues = new Set([...bools, ...halfTrue])\n```\n\nSum types are sometimes called union types, discriminated unions, or tagged unions.\n\nThere's a [couple](https://github.com/paldepind/union-type) [libraries](https://github.com/puffnfresh/daggy) in JS which help with defining and using union types.\n\nFlow includes [union types](https://flow.org/en/docs/types/unions/) and TypeScript has [Enums](https://www.typescriptlang.org/docs/handbook/enums.html) to serve the same role.\n\n### Product type\n\nA **product** type combines types together in a way you're probably more familiar with:\n\n```js\n// point :: (Number, Number) -\u003e {x: Number, y: Number}\nconst point = (x, y) =\u003e ({ x, y })\n```\nIt's called a product because the total possible values of the data structure is the product of the different values. Many languages have a tuple type which is the simplest formulation of a product type.\n\n__Further reading__\n* [Set theory](https://en.wikipedia.org/wiki/Set_theory) on Wikipedia\n\n## Option\n\nOption is a [sum type](#sum-type) with two cases often called `Some` and `None`.\n\nOption is useful for composing functions that might not return a value.\n\n```js\n// Naive definition\n\nconst Some = (v) =\u003e ({\n  val: v,\n  map (f) {\n    return Some(f(this.val))\n  },\n  chain (f) {\n    return f(this.val)\n  }\n})\n\nconst None = () =\u003e ({\n  map (f) {\n    return this\n  },\n  chain (f) {\n    return this\n  }\n})\n\n// maybeProp :: (String, {a}) -\u003e Option a\nconst maybeProp = (key, obj) =\u003e typeof obj[key] === 'undefined' ? None() : Some(obj[key])\n```\n\nUse `chain` to sequence functions that return `Option`s:\n\n```js\n\n// getItem :: Cart -\u003e Option CartItem\nconst getItem = (cart) =\u003e maybeProp('item', cart)\n\n// getPrice :: Item -\u003e Option Number\nconst getPrice = (item) =\u003e maybeProp('price', item)\n\n// getNestedPrice :: cart -\u003e Option a\nconst getNestedPrice = (cart) =\u003e getItem(cart).chain(getPrice)\n\ngetNestedPrice({}) // None()\ngetNestedPrice({ item: { foo: 1 } }) // None()\ngetNestedPrice({ item: { price: 9.99 } }) // Some(9.99)\n```\n\n`Option` is also known as `Maybe`. `Some` is sometimes called `Just`. `None` is sometimes called `Nothing`.\n\n## Function\n\nA **function** `f :: A =\u003e B` is an expression - often called arrow or lambda expression - with **exactly one (immutable)** parameter of type `A` and **exactly one** return value of type `B`. That value depends entirely on the argument, making functions context-independent, or [referentially transparent](#referential-transparency). What is implied here is that a function must not produce any hidden [side effects](#side-effects) - a function is always [pure](#pure-function), by definition. These properties make functions pleasant to work with: they are entirely deterministic and therefore predictable. Functions enable working with code as data, abstracting over behaviour:\n\n```js\n// times2 :: Number -\u003e Number\nconst times2 = n =\u003e n * 2\n\n;[1, 2, 3].map(times2) // [2, 4, 6]\n```\n\n## Partial function\n\nA partial function is a [function](#function) which is not defined for all arguments - it might return an unexpected result or may never terminate. Partial functions add cognitive overhead, they are harder to reason about and can lead to runtime errors. Some examples:\n\n```js\n// example 1: sum of the list\n// sum :: [Number] -\u003e Number\nconst sum = arr =\u003e arr.reduce((a, b) =\u003e a + b)\nsum([1, 2, 3]) // 6\nsum([]) // TypeError: Reduce of empty array with no initial value\n\n// example 2: get the first item in list\n// first :: [A] -\u003e A\nconst first = a =\u003e a[0]\nfirst([42]) // 42\nfirst([]) // undefined\n// or even worse:\nfirst([[42]])[0] // 42\nfirst([])[0] // Uncaught TypeError: Cannot read property '0' of undefined\n\n// example 3: repeat function N times\n// times :: Number -\u003e (Number -\u003e Number) -\u003e Number\nconst times = n =\u003e fn =\u003e n \u0026\u0026 (fn(n), times(n - 1)(fn))\ntimes(3)(console.log)\n// 3\n// 2\n// 1\ntimes(-1)(console.log)\n// RangeError: Maximum call stack size exceeded\n```\n\n### Dealing with partial functions\n\nPartial functions are dangerous as they need to be treated with great caution. You might get an unexpected (wrong) result or run into runtime errors. Sometimes a partial function might not return at all. Being aware of and treating all these edge cases accordingly can become very tedious.\nFortunately a partial function can be converted to a regular (or total) one. We can provide default values or use guards to deal with inputs for which the (previously) partial function is undefined. Utilizing the [`Option`](#Option) type, we can yield either `Some(value)` or `None` where we would otherwise have behaved unexpectedly:\n\n```js\n// example 1: sum of the list\n// we can provide default value so it will always return result\n// sum :: [Number] -\u003e Number\nconst sum = arr =\u003e arr.reduce((a, b) =\u003e a + b, 0)\nsum([1, 2, 3]) // 6\nsum([]) // 0\n\n// example 2: get the first item in list\n// change result to Option\n// first :: [A] -\u003e Option A\nconst first = a =\u003e a.length ? Some(a[0]) : None()\nfirst([42]).map(a =\u003e console.log(a)) // 42\nfirst([]).map(a =\u003e console.log(a)) // console.log won't execute at all\n// our previous worst case\nfirst([[42]]).map(a =\u003e console.log(a[0])) // 42\nfirst([]).map(a =\u003e console.log(a[0])) // won't execute, so we won't have error here\n// more of that, you will know by function return type (Option)\n// that you should use `.map` method to access the data and you will never forget\n// to check your input because such check become built-in into the function\n\n// example 3: repeat function N times\n// we should make function always terminate by changing conditions:\n// times :: Number -\u003e (Number -\u003e Number) -\u003e Number\nconst times = n =\u003e fn =\u003e n \u003e 0 \u0026\u0026 (fn(n), times(n - 1)(fn))\ntimes(3)(console.log)\n// 3\n// 2\n// 1\ntimes(-1)(console.log)\n// won't execute anything\n```\n\nMaking your partial functions total ones, these kinds of runtime errors can be prevented. Always returning a value will also make for code that is both easier to maintain and to reason about.\n\n## Total Function\n\nA function which returns a valid result for all inputs defined in its type. This is as opposed to [Partial Functions](#partial-function) which may throw an error, return an unexpected result, or fail to terminate.\n\n## Functional Programming Libraries in JavaScript\n\n* [mori](https://github.com/swannodette/mori)\n* [Immutable](https://github.com/facebook/immutable-js/)\n* [Immer](https://github.com/mweststrate/immer)\n* [Ramda](https://github.com/ramda/ramda)\n* [ramda-adjunct](https://github.com/char0n/ramda-adjunct)\n* [ramda-extension](https://github.com/tommmyy/ramda-extension)\n* [Folktale](http://folktale.origamitower.com/)\n* [monet.js](https://cwmyers.github.io/monet.js/)\n* [lodash](https://github.com/lodash/lodash)\n* [Underscore.js](https://github.com/jashkenas/underscore)\n* [Lazy.js](https://github.com/dtao/lazy.js)\n* [maryamyriameliamurphies.js](https://github.com/sjsyrek/maryamyriameliamurphies.js)\n* [Haskell in ES6](https://github.com/casualjavascript/haskell-in-es6)\n* [Sanctuary](https://github.com/sanctuary-js/sanctuary)\n* [Crocks](https://github.com/evilsoft/crocks)\n* [Fluture](https://github.com/fluture-js/Fluture)\n* [fp-ts](https://github.com/gcanti/fp-ts)\n\n---\n\n__P.S:__ This repo is successful due to the wonderful [contributions](https://github.com/hemanth/functional-programming-jargon/graphs/contributors)!\n","funding_links":["https://github.com/sponsors/hemanth","https://patreon.com/fpjargon","https://paypal.me/gnumanth"],"categories":["FP","Others","Functional Programming","Javascript","miscellaneous","functional-programming","Resources","Uncategorized","Table of Contents"],"sub_categories":["Articles","[Elm](http://elm-lang.org)","Uncategorized","Repos"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhemanth%2Ffunctional-programming-jargon","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhemanth%2Ffunctional-programming-jargon","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhemanth%2Ffunctional-programming-jargon/lists"}