项目 / hemanth/functional-programming-jargon
一份函数式编程术语表,用 JavaScript(ES2015)示例解释常见概念,并尽量采用 Fantasy Land 规范中的用语,方便入门。
本站整理,非 GitHub 官方 description。
官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。
以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。
打开[交互式图谱](https://hemanth.github.io/functional-programming-jargon)按术语点选查看解释,或直接打开[仓库 README](https://github.com/hemanth/functional-programming-jargon),从目录跳到对应词条阅读 JavaScript 示例。这是一份术语表,在浏览器里阅读即可,不必先安装软件。
按术语分条解释并附示例;另有交互式图谱,以及多种语言译本和 Python、Scala、Rust、Julia 等实现。
来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 58,249 字节),完整内容见 GitHub 仓库。
# Functional Programming Jargon
Functional 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.
Examples are presented in JavaScript (ES2015). [Why JavaScript?](https://github.com/hemanth/functional-programming-jargon/wiki/Why-JavaScript%3F)
Where applicable, this document uses terms defined in the [Fantasy Land spec](https://github.com/fantasyland/fantasy-land).
**Interactive Graph**: [hemanth.github.io/functional-programming-jargon](https://hemanth.github.io/functional-programming-jargon)
__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)
* [Bahasa Indonesia](https://github.com/wisn/jargon-pemrograman-fungsional)
* [Python World](https://github.com/jmesyou/functional-programming-jargon.py)
* [Scala World](https://github.com/ikhoon/functional-programming-jargon.scala)
* [Rust World](https://github.com/JasonShin/functional-programming-jargon.rs)
* [Korean](https://github.com/sphilee/functional-programming-jargon)
* [Polish](https://github.com/Deloryn/functional-programming-jargon)
* [Haskell Turkish](https://github.com/mrtkp9993/functional-programming-jargon)
* [Haskell Russian](https://github.com/epogrebnyak/functional-programming-jargon)
* [Julia World](https://github.com/Moelf/functional-programming-jargon.jl)
* [French](https://github.com/marcwrobel/functional-programming-jargon-fr)
__Table of Contents__
<!-- RM(noparent,notop) -->
* [Arity](#arity)
* [Higher-Order Functions (HOF)](#higher-order-functions-hof)
* [Closure](#closure)
* [Partial Application](#partial-application)
* [Currying](#currying)
* [Auto Currying](#auto-currying)
* [Function Composition](#function-composition)
* [Continuation](#continuation)
* [IO](#io)
* [Trampoline](#trampoline)
* [Thunk](#thunk)
* [Algebraic Effects](#algebraic-effects)
* [Pure Function](#pure-function)
* [Side effects](#side-effects)
* [Idempotence](#idempotence)
* [Point-Free Style](#point-free-style)
* [Predicate](#predicate)
* [Contracts](#contracts)
* [Category](#category)
* [Semigroupoid](#semigroupoid)
* [Value](#value)
* [Constant](#constant)
* [Constant Function](#constant-function)
* [Constant Functor](#constant-functor)
* [Constant Monad](#constant-monad)
* [Functor](#functor)
* [Pointed Functor](#pointed-functor)
* [Lift](#lift)
* [Referential Transparency](#referential-transparency)
* [Equational Reasoning](#equational-reasoning)
* [Memoization](#memoization)
* [Lambda](#lambda)
* [Lambda Calculus](#lambda-calculus)
* [Functional Combinator](#functional-combinator)
* [Lazy evaluation](#lazy-evaluation)
* [Monoid](#monoid)
* [Monad](#monad)
* [Comonad](#comonad)
* [Kleisli Composition](#kleisli-composition)
* [Free Monad](#free-monad)
* [Monad Transformer](#monad-transformer)
* [Applicative Functor](#applicative-functor)
* [Bifunctor](#bifunctor)
* [Contravariant Functor](#contravariant-functor)
* [Profunctor](#profunctor)
* [Alternative](#alternative)
* [Morphism](#morphism)
* [Homomorphism](#homomorphism)
* [Endomorphism](#endomorphism)
* [Isomorphism](#isomorphism)
* [Catamorphism](#catamorphism)
* [Anamorphism](#anamorphism)
* [Hylomorphism](#hylomorphism)
* [Paramorphism](#paramorphism)
* [Apomorphism](#apomorphism)
* [Natural Transformation](#natural-transformation)
* [Setoid](#setoid)
* [Semigroup](#semigroup)
* [Foldable](#foldable)
* [Traversable](#traversable)
* [Lens](#lens)
* [Prism](#prism)
* [Iso](#iso)
* [Traversal](#traversal)
* [Type Signatures](#type-signatures)
* [Algebraic data type](#algebraic-data-type)
* [Sum type](#sum-type)
* [Product type](#product-type)
* [Option](#option)
* [Either](#either)
* [Function](#function)
* [Partial function](#partial-function)
* [Dealing with partial functions](#dealing-with-partial-functions)
* [Total Function](#total-function)
* [Functional Programming Libraries in JavaScript](#functional-programming-libraries-in-javascript)
<!-- /RM -->
## Arity
The number of arguments a function takes. From words like unary, binary, ternary, etc.
```js
const sum = (a, b) => a + b
// The arity of sum is 2 (binary)
const inc = a => a + 1
// The arity of inc is 1 (unary)
const zero = () => 0
// The arity of zero is 0 (nullary)
```
__Further reading__
* [Arity](https://en.wikipedia.org/wiki/Arity) on Wikipedia
## Higher-Order Functions (HOF)
A function which takes a function as an argument and/or returns a function.
```js
const filter = (predicate, xs) => xs.filter(predicate)
```
```js
const is = (type) => (x) => Object(x) instanceof type
```
```js
filter(is(Number), [0, '1', 2, null]) // [0, 2]
```
## Closure
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.
This allows the values in the closure to be accessed by returned functions.
```js
const addTo = x => y => x + y
const addToFive = addTo(5)
addToFive(3) // => 8
```
In this case the `x` is retained in `addToFive`'s closure with the value `5`. `addToFive` can then be called with the `y`
to get back the sum.
__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 discussion](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work)
## Partial Application
Partially applying a function means creating a new function by pre-filling some of the arguments to the original function.
```js
// 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)
// Something to apply
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
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
```
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.
## Currying
The process of converting a function that takes multiple arguments into a function that takes them one at a time.
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 curriedSum = (a) => (b) => a + b
curriedSum(40)(2) // 42.
const add2 = curriedSum(2) // (b) => 2 + b
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.
Lodash & Ramda have a `curry` function that works this way.
```js
const add = (x, y) => x + y
const curriedAdd = _.curry(add)
curriedAdd(1, 2) // 3
curriedAdd(1) // (y) => 1 + y
curriedAdd(1)(2) // 3
```
__Further reading__
* [Favoring Curry](http://fr.umio.us/favoring-curry/)
* [Hey Underscore, You're Doing It Wrong!](https://www.youtube.com/watch?v=m3svKOdZijA)
## Function Composition
The 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.
```js
const compose = (f, g) => (a) => f(g(a)) // Definition
const floorAndToString = compose((val) => val.toString(), Math.floor) // Usage
floorAndToString(121.212121) // '121'
```
## 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}`)
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)
})
```
## IO
A pure data structure that encapsulates a side effect. Instead of performing the effect immediately, `IO` wraps the action in a nullary function ([thunk](#thunk)), allowing effectful operations to be transformed, chained, and composed as pure [values](#value) without actually executing them until explicitly triggered.
```js
const IO = (run) => ({
run,
map: (f) => IO(() => f(run())),
chain: (f) => IO(() => f(run()).run())
})
// Pure description - nothing executes yet
const readTimestamp = IO(() => Date.now())
const formatted = readTimestamp.map((ts) => new Date(ts).toISOString())
// Side effect executes only when calling .run()
formatted.run()
```
__Further reading__
* [IO container](https://drboolean.gitbooks.io/mostly-adequate-guide/content/ch8.html#pure-functional-magic) in Mostly Adequate Guide
## Trampoline
A mechanism that enables deep or mutually recursive functions to run without exceeding the maximum call stack limit.
In environments without Tail Call Optimization (TCO), recursive calls return a function (a thunk) instead of invoking themselves directly. The trampoline runs a while-loop that unwinds each thunk until a final value is reached.
```js
const trampoline = (fn) => (...args) => {
let result = fn(...args)
while (typeof result === 'function') {
result = result()
}
return result
}
// Without trampoline: sumBelow(1000000) throws "Maximum call stack size exceeded"
const sumBelow = (n, acc = 0) =>
n === 0
? acc
: () => sumBelow(n - 1, acc + n) // returns a thunk instead of recursing directly
const safeSum = trampoline(sumBelow)
safeSum(1000000) // 500000500000
```
__Further reading__
* [Trampolining in JavaScript](https://raganwald.com/2013/03/28/trampolines-in-javascript.html)
## Thunk
A nullary function (a function taking zero arguments) that wraps an expression to delay its evaluation until called. Thunks are the fundamental mechanism for implementing [lazy evaluation](#lazy-evaluation), [trampolines](#trampoline), and deferred side effects.
```js
// An eager calculation executes immediately:
// const data = expensiveCalculation()
// A thunk wraps the expression in a function, deferring execution:
const thunk = () => 42 * 2
// The expression is only evaluated when explicitly called:
thunk() // 84
```
__Further reading__
* [Thunk](https://en.wikipedia.org/wiki/Thunk) on Wikipedia
## Algebraic Effects
A computational effect system that separates the invocation of an effect from its handling. Rather than coupling a function directly to its runtime environment, the function "performs" an effect operation (such as reading state, requesting configuration, or logging). An enclosing "handler" intercepts the performed effect and supplies the result, with the ability to resume or abort the computation—generalizing exceptions, async/await, and generators without requiring complex monad transformer stacks.
```js
// Generators model delimited continuations / algebraic effects:
const perform = (effect) => ({ [Symbol.for('effect')]: true, effect })
// Program performs effects without knowing who handles them:
function * fetchUserProfile (userId) {
const config = yield perform({ type: 'ask_config' })
yield perform({ type: 'log', message: `Fetching user ${userId} from ${config.apiUrl}` })
return { id: userId, name: 'Alice' }
}
// Effect handler interprets effects and resumes the computation:
const handle = (generator, handlers) => {
const iter = generator()
const step = (value) => {
const { done, value: yielded } = iter.next(value)
if (done) return yielded
if (yielded && yielded[Symbol.for('effect')]) {
const { type } = yielded.effect
if (handlers[type]) {
return handlers[type](yielded.effect, (resumeVal) => step(resumeVal))
}
}
return step(yielded)
}
return step()
}
// Running with an interpreter / handler:
handle(
() => fetchUserProfile(42),
{
ask_config: (effect, resume) => resume({ apiUrl: 'https://api.test.local' }),
log: (effect, resume) => {
console.log(effect.message)
return resume()
}
}
)
```
__Further reading__
* [Algebraic Effects for the Rest of Us](https://overreacted.io/algebraic-effects-for-the-rest-of-us/)
* [What is Algebraic Effects?](https://koka-lang.github.io/koka/doc/book.html#why-effects)
## Pure Function
A 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.
```js
const greet = (name) => `Hi, ${name}`
greet('Brianne') // 'Hi, Brianne'
```
As opposed to each of the following:
```js
window.name = 'Brianne'
const greet = () => `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('Brianne')
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.
```js
const differentEveryTime = new Date()
```
```js
console.log('IO is a side effect!')
```
## Idempotence
A function is idempotent if reapplying it to its result does not produce a different result.
```js
Math.abs(Math.abs(10))
```
```js
sort(sort(sort([2, 1])))
```
## Point-Free Style
Writing 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.
```js
// Given
const map = (fn) => (list) => list.map(fn)
const add = (a) => (b) => a + b
// Then
// Not point-free - `numbers` is an explicit argument
const incrementAll = (numbers) => map(add(1))(numbers)
// Point-free - The list is an implicit argument
const incrementAll2 = map(add(1))
```
Point-free function definitions look just like normal assignments without `function` or `=>`. 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.
## Predicate
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
;[1, 2, 3, 4].filter(predicate) // [3, 4]
```
## Contracts
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 -> boolean
const contract = (input) => {
if (typeof input === 'number') return true
throw new Error('Contract violated: expected int -> boolean')
}
const addOne = (num) => contract(num) && num + 1
addOne(2) // 3
addOne('some string') // Contract violated: expected int -> boolean
```
## Category
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, three 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.
As an example we can define a category Max as a class:
```js
class Max {
constructor (a) {
this.a = a
}
id () {
return this
}
compose (b) {
return this.a > b.a ? this : b
}
toString () {
return `Max(${this.a})`
}
}
new Max(2).compose(new Max(3)).compose(new Max(5)).id().id() // => Max(5)
```
__Further reading__
* [Category Theory for Programmers](https://bartoszmilewski.com/2014/10/28/category-theory-for-programmers-the-preface/)
## Semigroupoid
An algebraic structure with objects and morphisms that can be associatively composed, but does not guarantee the existence of an identity morphism for each object.
A semigroupoid satisfies the associativity property for [composition](#function-composition):
`f.compose(g).compose(h) === f.compose(g.compose(h))`
Every [category](#category) is a semigroupoid, but a semigroupoid does not require an identity (`id`) morphism. Functions under composition form a natural semigroupoid:
```js
const Semigroupoid = (fn) => ({
run: fn,
compose: (other) => Semigroupoid((x) => fn(other.run(x)))
})
const toUpper = Semigroupoid((s) => s.toUpperCase())
const exclaim = Semigroupoid((s) => `${s}!`)
const loudGreeting = exclaim.compose(toUpper)
loudGreeting.run('hello') // 'HELLO!'
```
__Further reading__
* [Semigroupoid](https://github.com/fantasyland/fantasy-land#semigroupoid) in Fantasy Land
## Value
Anything that can be assigned to a variable.
```js
5
Object.freeze({ name: 'John', age: 30 }) // The `freeze` function enforces immutability.
;(a) => a
;[1]
undefined
```
## Constant
A variable that cannot be reassigned once defined.
```js
const five = 5
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.
With the above two constants the following expression will always return `true`.
```js
john.age + five === ({ name: 'John', age: 30 }).age + 5
```
### Constant Function
A [curried](#currying) function that ignores its second argument:
```js
const constant = a => () => a
;[1, 2].map(constant(0)) // => [0, 0]
```
### Constant Functor
Object whose `map` doesn't transform the contents. See [Functor](#functor).
```js
Constant(1).map(n => n + 1) // => Constant(1)
```
### Constant Monad
Object whose `chain` doesn't transform the contents. See [Monad](#monad).
```js
Constant(1).chain(n => Constant(n + 1)) // => Constant(1)
```
## Functor
An 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:
__Preserves identity__
```js
object.map(x => x)
```
is equivalent to just `object`.
__Composable__
```js
object.map(x => g(f(x)))
```
is equivalent to
```js
object.map(f).map(g)
```
(`f`, `g` are arbitrary composable functions)
The reference implementation of [Option](#option) is a functor as it satisfies the rules:
```js
Some(1).map(x => x) // = Some(1)
```
and
```js
const f = x => x + 1
const g = x => x * 2
Some(1).map(x => g(f(x))) // = Some(4)
Some(1).map(