Giter VIP home page Giter VIP logo

functional-programming-jargon's Introduction

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?

Where applicable, this document uses terms defined in the Fantasy Land spec.

Translations

Table of Contents

Arity

The number of arguments a function takes. From words like unary, binary, ternary, etc.

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

Higher-Order Functions (HOF)

A function which takes a function as an argument and/or returns a function.

const filter = (predicate, xs) => xs.filter(predicate)
const is = (type) => (x) => Object(x) instanceof type
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.

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

Partial Application

Partially applying a function means creating a new function by pre-filling some of the arguments to the original function.

// 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:

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 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.

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.

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

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.

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.

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.

const continueProgramWith = (data) => {
  // Continues program with data
}

readFileAsync('path/to/file', (err, response) => {
  if (err) {
    // handle error
    return
  }
  continueProgramWith(response)
})

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.

const greet = (name) => `Hi, ${name}`

greet('Brianne') // 'Hi, Brianne'

As opposed to each of the following:

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...

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.

const differentEveryTime = new Date()
console.log('IO is a side effect!')

Idempotence

A function is idempotent if reapplying it to its result does not produce a different result.

Math.abs(Math.abs(10))
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 or other Higher-Order functions. A.K.A Tacit programming.

// 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.

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.

// 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:

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

Value

Anything that can be assigned to a variable.

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.

const five = 5
const john = Object.freeze({ name: 'John', age: 30 })

Constants are referentially transparent. 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.

john.age + five === ({ name: 'John', age: 30 }).age + 5

Constant Function

A curried function that ignores its second argument:

const constant = a => () => a

;[1, 2].map(constant(0)) // => [0, 0]

Constant Functor

Object whose map doesn't transform the contents. See Functor.

Constant(1).map(n => n + 1) // => Constant(1)

Constant Monad

Object whose chain doesn't transform the contents. See Monad.

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

object.map(x => x)

is equivalent to just object.

Composable

object.map(x => g(f(x)))

is equivalent to

object.map(f).map(g)

(f, g are arbitrary composable functions)

The reference implementation of Option is a functor as it satisfies the rules:

Some(1).map(x => x) // = Some(1)

and

const f = x => x + 1
const g = x => x * 2

Some(1).map(x => g(f(x))) // = Some(4)
Some(1).map(f).map(g) // = Some(4)

Pointed Functor

An object with an of function that puts any single value into it.

ES2015 adds Array.of making arrays a pointed functor.

Array.of(1) // [1]

Lift

Lifting is when you take a value and put it into an object like a functor. If you lift a function into an Applicative Functor then you can make it work on values that are also in that functor.

Some implementations have a function called lift, or liftA2 to make it easier to run functions on functors.

const liftA2 = (f) => (a, b) => a.map(f).ap(b) // note it's `ap` and not `map`.

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], [30, 40]) // [31, 41, 32, 42]

Lifting a one-argument function and applying it does the same thing as map.

const increment = (x) => x + 1

lift(increment)([2]) // [3]
;[2].map(increment) // [3]

Lifting simple values can be simply creating the object.

Array.of(1) // => [1]

Referential Transparency

An expression that can be replaced with its value without changing the behavior of the program is said to be referentially transparent.

Given the function greet:

const greet = () => 'Hello World!'

Any invocation of greet() can be replaced with Hello World! hence greet is referentially transparent. This would be broken if greet depended on external state like configuration or a database call. See also Pure Function and Equational Reasoning.

Equational Reasoning

When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts. You can also be confident about details of your system without having to go through every function.

const grainToDogs = compose(chickenIntoDogs, grainIntoChicken)
const grainToCats = compose(dogsIntoCats, grainToDogs)

In the example above, if you know that chickenIntoDogs and grainIntoChicken are pure then you know that the composition is pure. This can be taken further when more is known about the functions (associative, commutative, idempotent, etc...).

Lambda

An anonymous function that can be treated like a value.

;(function (a) {
  return a + 1
})

;(a) => a + 1

Lambdas are often passed as arguments to Higher-Order functions:

;[1, 2].map((a) => a + 1) // [2, 3]

You can assign a lambda to a variable:

const add1 = (a) => a + 1

Lambda Calculus

A branch of mathematics that uses functions to create a universal model of computation.

Functional Combinator

A higher-order function, usually curried, which returns a new function changed in some way. Functional combinators are often used in Point-Free Style to write especially terse programs.

// The "C" combinator takes a curried two-argument function and returns one which calls the original function with the arguments reversed.
const C = (f) => (a) => (b) => f(b)(a)

const divide = (a) => (b) => a / b

const divideBy = C(divide)

const divBy10 = divideBy(10)

divBy10(30) // => 3

See also List of Functional Combinators in JavaScript which includes links to more references.

Lazy evaluation

Lazy 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.

const rand = function * () {
  while (1 < 2) {
    yield Math.random()
  }
}
const randIter = rand()
randIter.next() // Each execution gives a random value, expression is evaluated on need.

Monoid

An object with a function that "combines" that object with another of the same type (semigroup) which has an "identity" value.

One simple monoid is the addition of numbers:

1 + 1 // 2

In this case number is the object and + is the function.

When any value is combined with the "identity" value the result must be the original value. The identity must also be commutative.

The identity value for addition is 0.

1 + 0 // 1
0 + 1 // 1
1 + 0 === 0 + 1

It's also required that the grouping of operations will not affect the result (associativity):

1 + (2 + 3) === (1 + 2) + 3 // true

Array concatenation also forms a monoid:

;[1, 2].concat([3, 4]) // [1, 2, 3, 4]

The identity value is empty array []:

;[1, 2].concat([]) // [1, 2]

As a counterexample, subtraction does not form a monoid because there is no commutative identity value:

0 - 4 === 4 - 0 // false

Monad

A monad is an object with of and chain functions. chain is like map except it un-nests the resulting nested object.

// Implementation
Array.prototype.chain = function (f) {
  return this.reduce((acc, it) => acc.concat(f(it)), [])
}

// Usage
Array.of('cat,dog', 'fish,bird').chain((a) => a.split(',')) // ['cat', 'dog', 'fish', 'bird']

// Contrast to map
Array.of('cat,dog', 'fish,bird').map((a) => a.split(',')) // [['cat', 'dog'], ['fish', 'bird']]

of is also known as return in other functional languages. chain is also known as flatmap and bind in other languages.

Comonad

An object that has extract and extend functions.

const CoIdentity = (v) => ({
  val: v,
  extract () {
    return this.val
  },
  extend (f) {
    return CoIdentity(f(this))
  }
})

extract takes a value out of a functor:

CoIdentity(1).extract() // 1

extend runs a function on the comonad. The function should return the same type as the comonad:

CoIdentity(1).extend((co) => co.extract() + 1) // CoIdentity(2)

Kleisli Composition

An operation for composing two monad-returning functions (Kleisli Arrows) where they have compatible types. In Haskell this is the >=> operator.

Using Option:

// safeParseNum :: String -> Option Number
const safeParseNum = (b) => {
  const n = parseNumber(b)
  return isNaN(n) ? None() : Some(n)
}

// validatePositive :: Number -> Option Number
const validatePositive = (a) => a > 0 ? Some(a) : None()

// kleisliCompose :: Monad M => ((b -> M c), (a -> M b)) -> a -> M c
const kleisliCompose = (g, f) => (x) => f(x).chain(g)

// parseAndValidate :: String -> Option Number
const parseAndValidate = kleisliCompose(validatePositive, safeParseNum)

parseAndValidate('1') // => Some(1)
parseAndValidate('asdf') // => None
parseAndValidate('999') // => Some(999)

This works because:

  • option is a monad,
  • both validatePositive and safeParseNum return the same kind of monad (Option),
  • the type of validatePositive's argument matches safeParseNum's unwrapped return.

Applicative Functor

An 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.

// Implementation
Array.prototype.ap = function (xs) {
  return this.reduce((acc, f) => acc.concat(xs.map(f)), [])
}

// Example usage
;[(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.

// Arrays that you want to combine
const arg1 = [1, 3]
const arg2 = [4, 5]

// combining function - must be curried for this to work
const add = (x) => (y) => x + 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:

partiallyAppliedAdds.ap(arg2) // [5, 6, 7, 8]

Morphism

A relationship between objects within a category. In the context of functional programming all functions are morphisms.

Homomorphism

A function where there is a structural property that is the same in the input as well as the output.

For example, in a Monoid homomorphism both the input and the output are monoids even if their types are different.

// toList :: [number] -> string
const toList = (a) => a.join(', ')

toList is a homomorphism because:

  • array is a monoid - has a concat operation and an identity value ([]),
  • string is a monoid - has a concat operation and an identity value ('').

In this way, a homomorphism relates to whatever property you care about in the input and output of a transformation.

Endomorphisms and Isomorphisms are examples of homomorphisms.

Further Reading

Endomorphism

A function where the input type is the same as the output. Since the types are identical, endomorphisms are also homomorphisms.

// uppercase :: String -> String
const uppercase = (str) => str.toUpperCase()

// decrement :: Number -> Number
const decrement = (x) => x - 1

Isomorphism

A morphism made of a pair of transformations between 2 types of objects that is structural in nature and no data is lost.

For example, 2D coordinates could be stored as an array [2,3] or object {x: 2, y: 3}.

// Providing functions to convert in both directions makes the 2D coordinate structures isomorphic.
const pairToCoords = (pair) => ({ x: pair[0], y: pair[1] })

const coordsToPair = (coords) => [coords.x, coords.y]

coordsToPair(pairToCoords([1, 2])) // [1, 2]

pairToCoords(coordsToPair({ x: 1, y: 2 })) // {x: 1, y: 2}

Isomorphisms are an interesting example of morphism because more than single function is necessary for it to be satisfied. Isomorphisms are also homomorphisms since both input and output types share the property of being reversible.

Catamorphism

A function which deconstructs a structure into a single value. reduceRight is an example of a catamorphism for array structures.

// sum is a catamorphism from [Number] -> Number
const sum = xs => xs.reduceRight((acc, x) => acc + x, 0)

sum([1, 2, 3, 4, 5]) // 15

Anamorphism

A 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. You can think of this as an anamorphism builds up a structure and catamorphism breaks it down.

const unfold = (f, seed) => {
  function go (f, seed, acc) {
    const res = f(seed)
    return res ? go(f, res[1], acc.concat([res[0]])) : acc
  }
  return go(f, seed, [])
}
const countDown = n => unfold((n) => {
  return n <= 0 ? undefined : [n, n - 1]
}, n)

countDown(5) // [5, 4, 3, 2, 1]

Hylomorphism

The function which composes an anamorphism followed by a catamorphism.

const sumUpToX = (x) => sum(countDown(x))
sumUpToX(5) // 15

Paramorphism

A function just like reduceRight. However, there's a difference:

In paramorphism, your reducer's arguments are the current value, the reduction of all previous values, and the list of values that formed that reduction.

// Obviously not safe for lists containing `undefined`,
// but good enough to make the point.
const para = (reducer, accumulator, elements) => {
  if (elements.length === 0) { return accumulator }

  const head = elements[0]
  const tail = elements.slice(1)

  return reducer(head, tail, para(reducer, accumulator, tail))
}

const suffixes = list => para(
  (x, xs, suffxs) => [xs, ...suffxs],
  [],
  list
)

suffixes([1, 2, 3, 4, 5]) // [[2, 3, 4, 5], [3, 4, 5], [4, 5], [5], []]

The 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.

Apomorphism

The 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.

Setoid

An object that has an equals function which can be used to compare other objects of the same type.

Make array a setoid:

Array.prototype.equals = function (arr) {
  const len = this.length
  if (len !== arr.length) {
    return false
  }
  for (let i = 0; i < len; i++) {
    if (this[i] !== arr[i]) {
      return false
    }
  }
  return true
}

;[1, 2].equals([1, 2]) // true
;[1, 2].equals([0]) // false

Semigroup

An object that has a concat function that combines it with another object of the same type.

;[1].concat([2]) // [1, 2]

Foldable

An 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.

const sum = (list) => list.reduce((acc, val) => acc + val, 0)
sum([1, 2, 3]) // 6

Lens

A lens is a structure (often an object or function) that pairs a getter and a non-mutating setter for some other data structure.

// Using [Ramda's lens](http://ramdajs.com/docs/#lens)
const nameLens = R.lens(
  // getter for name property on an object
  (obj) => obj.name,
  // setter for name property
  (val, obj) => Object.assign({}, obj, { name: val })
)

Having the pair of get and set for a given data structure enables a few key features.

const person = { name: 'Gertrude Blanch' }

// invoke the getter
R.view(nameLens, person) // 'Gertrude Blanch'

// invoke the setter
R.set(nameLens, 'Shafi Goldwasser', person) // {name: 'Shafi Goldwasser'}

// run a function on the value in the structure
R.over(nameLens, uppercase, person) // {name: 'GERTRUDE BLANCH'}

Lenses are also composable. This allows easy immutable updates to deeply nested data.

// This lens focuses on the first item in a non-empty array
const firstLens = R.lens(
  // get first item in array
  xs => xs[0],
  // non-mutating setter for first item in array
  (val, [__, ...xs]) => [val, ...xs]
)

const people = [{ name: 'Gertrude Blanch' }, { name: 'Shafi Goldwasser' }]

// Despite what you may assume, lenses compose left-to-right.
R.over(compose(firstLens, nameLens), uppercase, people) // [{'name': 'GERTRUDE BLANCH'}, {'name': 'Shafi Goldwasser'}]

Other implementations:

Type Signatures

Often functions in JavaScript will include comments that indicate the types of their arguments and return values.

There's quite a bit of variance across the community, but they often follow the following patterns:

// functionName :: firstArgType -> secondArgType -> returnType

// add :: Number -> Number -> Number
const add = (x) => (y) => x + y

// increment :: Number -> Number
const increment = (x) => x + 1

If a function accepts another function as an argument it is wrapped in parentheses.

// call :: (a -> b) -> a -> b
const call = (f) => (x) => f(x)

The 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.

// map :: (a -> b) -> [a] -> [b]
const map = (f) => (list) => list.map(f)

Further reading

Algebraic data type

A composite type made from putting other types together. Two common classes of algebraic types are sum and product.

Sum type

A 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.

JavaScript doesn't have types like this, but we can use Sets to pretend:

// imagine that rather than sets here we have types that can only have these values
const bools = new Set([true, false])
const halfTrue = new Set(['half-true'])

// The weakLogic type contains the sum of the values from bools and halfTrue
const weakLogicValues = new Set([...bools, ...halfTrue])

Sum types are sometimes called union types, discriminated unions, or tagged unions.

There's a couple libraries in JS which help with defining and using union types.

Flow includes union types and TypeScript has Enums to serve the same role.

Product type

A product type combines types together in a way you're probably more familiar with:

// point :: (Number, Number) -> {x: Number, y: Number}
const point = (x, y) => ({ x, y })

It'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.

Further reading

Option

Option is a sum type with two cases often called Some and None.

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)
  }
})

const None = () => ({
  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])

Use chain to sequence functions that return Options:

// getItem :: Cart -> Option CartItem
const getItem = (cart) => maybeProp('item', cart)

// getPrice :: Item -> Option Number
const getPrice = (item) => maybeProp('price', item)

// getNestedPrice :: cart -> Option a
const getNestedPrice = (cart) => getItem(cart).chain(getPrice)

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.

Function

A function f :: A => 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. What is implied here is that a function must not produce any hidden side effects - a function is always pure, 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:

// times2 :: Number -> Number
const times2 = n => n * 2

;[1, 2, 3].map(times2) // [2, 4, 6]

Partial function

A partial function is a 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:

// example 1: sum of the list
// sum :: [Number] -> Number
const sum = arr => arr.reduce((a, b) => a + b)
sum([1, 2, 3]) // 6
sum([]) // TypeError: Reduce of empty array with no initial value

// example 2: get the first item in list
// first :: [A] -> A
const first = a => a[0]
first([42]) // 42
first([]) // undefined
// or even worse:
first([[42]])[0] // 42
first([])[0] // Uncaught TypeError: Cannot read property '0' of undefined

// example 3: repeat function N times
// times :: Number -> (Number -> Number) -> Number
const times = n => fn => n && (fn(n), times(n - 1)(fn))
times(3)(console.log)
// 3
// 2
// 1
times(-1)(console.log)
// RangeError: Maximum call stack size exceeded

Dealing with partial functions

Partial 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. Fortunately 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 type, we can yield either Some(value) or None where we would otherwise have behaved unexpectedly:

// example 1: sum of the list
// we can provide default value so it will always return result
// sum :: [Number] -> Number
const sum = arr => arr.reduce((a, b) => a + b, 0)
sum([1, 2, 3]) // 6
sum([]) // 0

// example 2: get the first item in list
// change result to Option
// first :: [A] -> Option A
const first = a => a.length ? Some(a[0]) : None()
first([42]).map(a => console.log(a)) // 42
first([]).map(a => console.log(a)) // console.log won't execute at all
// our previous worst case
first([[42]]).map(a => console.log(a[0])) // 42
first([]).map(a => console.log(a[0])) // won't execute, so we won't have error here
// more of that, you will know by function return type (Option)
// that you should use `.map` method to access the data and you will never forget
// to check your input because such check become built-in into the function

// example 3: repeat function N times
// we should make function always terminate by changing conditions:
// times :: Number -> (Number -> Number) -> Number
const times = n => fn => n > 0 && (fn(n), times(n - 1)(fn))
times(3)(console.log)
// 3
// 2
// 1
times(-1)(console.log)
// won't execute anything

Making 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.

Total Function

A function which returns a valid result for all inputs defined in its type. This is as opposed to Partial Functions which may throw an error, return an unexpected result, or fail to terminate.

Functional Programming Libraries in JavaScript


P.S: This repo is successful due to the wonderful contributions!

functional-programming-jargon's People

Contributors

alexlafroscia avatar brunops avatar crosseye avatar desfero avatar emarukyan avatar ethagnawl avatar hekmekk avatar hemanth avatar jethrolarson avatar lovasoa avatar marcusradell avatar marcwrobel avatar mrtkp9993 avatar neighborhood999 avatar nickzuber avatar paulbone avatar pgs-pliulia avatar raine avatar renaudtertrais avatar rootulp avatar saarwexler avatar sean-lan avatar shfshanyue avatar sjsyrek avatar stevemao avatar stoeffel avatar sumbach avatar sunnypatel165 avatar therealklanni avatar trueproof avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

functional-programming-jargon's Issues

Monoid is a bad example when explaining a category

Monoid is given as example of Category?

https://github.com/hemanth/functional-programming-jargon#categories

Monoid comes with binary operation, whereas functions (morphisms)
in a Catgory are unary, not binary. So it is very confusing to use Monoid as explanation.

A Category is really a collection of objects (types) and functions (aka morphisms) between types, sending values to values. Further, functions a->b and b->c can be composed, the composition is associative, and there is identity function a->a for each object a.

Various wording problems

A number of problems with confusing or dubious words in some of the explanations:

(About currying)

into the same function with an arity of one

This is, very obviously, wrongly worded. It cannot be, in the general case, the same function with an arity of one. Saying that does not really explain at all what it means.

(About composition)

A function which

Composition is an operation, a process... not necessarily a function.

(About purity)

The example shows lack of side effects (which are explained in a later section) but it doesn't show the constrain of depending only on input values.

(About idempotence)

if it has no side-effects on multiple executions

Again, wrongly worded, or at least confusingly worded. It means multiple executions do not change the result further. Exactly what the f( f( f(x) ) ) === f(x) says. Mentioning side-effects in here does not help in any way; it just confuses things.

(About point-free style)

the definition does not explicitly define arguments

To be more precise and avoid repetition of definition-define, it would be better to say it doesn't identify, mention or name the arguments, not that it doesn't define them.

(About Categories)

Objects with associated functions

The use of "Objects" there is potentially very misleading. The same happens later when Functor is defined as "An object with a map function". Generally, a much more clear word there would be types instead of objects. The explanation of Functor seems to go back and forth between insinuating that a particular array is a Functor and saying that Array itself is the Functor. Later still, in Monoid, the reference to types is finally made. But then again Monad, Setoid, Foldable... go back to using "object" instead of "type".

(About lift)

Lift is like map except it can be applied to multiple functors.

This seems to be (sort of) a particular definition of lift, but I wonder just how general this is and I feel it raises confusion with the more general transformation of lifting. Maybe a reference to the Fantasy Land Spec should be made right at the start of the document?

(About Monad)

of is mentioned but neither explained nor shown in examples.

(About Isomorphism)

The definition is anything but clear... "structural in nature and no data is lost" doesn't really help.

Option elaboration

If we explain Option as union type it would make sense to state that:

  • Some higher order type e.g. type that can wrap other type
  • None is unit type whose only value is None
Option = Some<Type> | None

But given JS code has nothing to do with types, it is rather explains Option as monad (Maybe monad in Haskell classification).

Create a section/wiki page for unfamiliar or potentially confusing notation

Thank you for putting this together! I've been studying functional programming on and off for years, and this has reinforced some of the concepts I've learned, clarified others, and taught me new ones. Very nice work.

As I was reading, I came across two notation idioms that confused me, that I'm pretty sure have nothing to do with FP:

  • The symbol ≍ (which is a black box on my Android, fwiw). From googling, I think it means either logical equivalence, or just equivalence. Not being a mathematician, I'm not sure which it is, and what, specifically, the differences between those are. I can guess why it's preferred over = (which means assignment), but I'm not completely sure why it's different from === (I'm also not a JavaScript expert).
  • This pattern: ;[1] I'm guessing it means: here's a plain value? and that it's written that way, because of the linter?

Anyway, these details can confuse, and like I said, they're not about FP, so I was thinking it might be nice to have a section, or a wiki page, for them - almost like the sections at the front of many programming books, where they explain how code sections are formatted, that kind of thing. I'm happy to create a wiki page, but I don't know the explanations for either ≍ or ;[1].

Partial application as currying

The simplest example for currying:

(A,B) -> C convert to (A) -> (B -> C)

So partial application is application to curried function

((A,B) -> C)(A)  convert to ((A) -> (B -> C))(A)

From this definition I can not see difference between Auto-currying and partial application. Am I wrong?

Constant definition

I think it's not correct to define a constant as a variable that can only be assigned once; that's the mechanism that most programming languages use to implement constants, but it's not a definition.
I would just define it as a symbolic name for a value.

Etymology is missing

I find that it would be much easier to understand and remember unknown terms, if etymology (origin) of their name is given. At the moment not a single entry has it.

Do you have any plan/wish to include it?

Monad description too brief

It doesn't cover what bind is supposed to accomplish or it's rules. It also doesn't state why someone would want to use it nor problems it solves.

I know this would be better stated as a pull-request but I wanted to throw this out there.

A question about the use `chain` and `of` in the Monad entry

Is there any reason chain and of were used instead of the more common (Wikipedia, Haskell, etc.) bind and return in the Monad entry? Are these names commonly used in some other literature, language or library?

My concern is that people who read/grok the (great!) example contained herein and want to explore further will be thrown when they see bind and return used in most other definitions, tutorials, etc.

Avoid confusing different meanings of the same word, eg Functor

Even within FP there are multiple meanings of some terms, a good example is functor. You've covered one meaning and might not be aware of the other two meanings.

  1. In OCaml a functor is part of the parametric module system. I think that it means parametric module but I'm not certain, and I don't feel confident writing this section myself. https://realworldocaml.org/v1/en/html/functors.html
  2. In languages using DU types (Haskell, Mercury etc), Functor is another word for constructor.

Add note which explains the Fantasy Land connection

I wasn't familiar with the Fantasy Land spec before coming across this project and was initially confused by some of the associated nomenclature. It might help to have a top-level note which links to the Fantasy Land spec and explains that the examples contained herein aim to conform to it.

Hindley-Milner type signatures

Should there be a small section describing Hindley-Milner type signatures? I am just recently getting into the world of functional programming and know that at first I was confused about all these "strange comments" in the code.

Endofunctors & Bind

You should add an endo functor definition to better explain monadic binds.

"lift" is wrong, confusing

The definition of Lift is pretty incorrect. It states

Lift is like map except it can be applied to multiple functors.

but that has nothing to do with lift, that's a property of the functor being applicative. Given an applicative functor, you can apply a function over multiple functor arguments without lift: arg1.of(f).ap(arg1).ap(arg2). (It's definitely not pretty, which is one reason why lifting is so much better, but still.)

The definition is further wrong because it talks about the map-equivalent version of lift, which definitely doesn't have the property being discussed; it only makes the function handle plain functors, not applicative functors. You need the ap-equivalent version (in Haskell, liftA).

lift is just the name given to map/ap/chain when the arguments are reversed (function first, then data) and partially applied.

Here's a suggested rewrite:


"Lift" has a few meanings. Sometimes people will talking about "lifting a value" into a functor; this refers to calling the of function on the value.

When "lift" is referred to as a function, though, it's just a variation of map, ap, or chain that takes the function argument first, and returns a new function that takes the functor value and maps/aps/chains on it. That is, given the map-equivalent version of lift, arg.map(f) is identical to lift(f)(arg). Lifting the function, rather than using map directly, makes it easier to pass the function around and apply it to other values, as it lets you use normal function-call syntax, passing arguments, rather than having to specially use the map method.

This is more obvious when you're using an applicative functor, which allows a function to be called with multiple functor arguments. Using the ap function, you'd have to write [].of(f).ap(arg1).ap(arg2), while lifting lets you just write liftA(f)(arg1, arg2). (You do need to specify which version of lift you're using; traditionally this is done with lift for plain functors, liftA for applicative functors, and liftM for monadic functors.

Table of Contents -> Alphabetic Ordering

It would be easier to use this repo if the table of contents / terms at the beginning of the main README.md file were listed in alphabetical order, in case the user is trying to search for a particular term.

Congrats on the success!

We now have more stars than ramda. This is quite an achievement. Props to all the contributors, especially those that have only just begun.

Feel free to just close this :)

Functor identity not ===

const before = [1,2,3]
const after = before.map(x => x)
before === after // Returns false
for(let i = 0; i < before.length; i++) {
  before[i] === after[i] // Returns true
}
before.length === after.length // Returns true

First equals-check is for the reference, and after is a shallow copy of before. Easiest way to explain might be to write Assert.deepEqual(before, after) and define Assert.deepEqual somewhere so the code still looks minimal.

Union type code example misleading

Hi. First of all thanks for starting this repo.

Union type code is a bit misleading from my POV. It is rather shows concepts of polymorphic function and coercion. Polymorphic functions are functions whose parameters can have more than one type.

Polymorphic function in dynamic language (JavaScript, Ruby, etc)

function draw(shape) { ... }

There is no type check so you do not need to do anything special. Pros: polymorphic functions for free. Cons: runtime errors e.g. undefined is not a function etc.

Polymorphic function in static language without ADT (Go; C++, Java etc)

type Shape interface { ... }
type Circle struct { ... }
type Square struct { ... }

func draw(a Shape) { 
  // type of value common interface  e.g. Shape, not exact type (Circle or Square)
}

There is slight difference between structural and nominal type systems.

Polymorphic function in static language with ADT (TypeScript etc)

interface Circle {
    kind: "circle";
    radius: number;
}

interface Square {
    kind: "square";
    sideLength: number;
}

type Shape = Circle | Square;

function draw(shape: Shape) {
    switch (shape.kind) {
        case "circle": ... //type of value Circle, not Shape
        case "square": ... //type of value Square, not Shape
    }
}

The main power of disjoint union shines in static type system with support of match statement (so compiler tracks if you handling all cases).

Applicative Functor

I think the the output for the example described is not accurate.

`
// Implementation
Array.prototype.ap = function(xs){
return this.reduce((acc, f) => acc.concat(xs.map(f)), []);
};

// Arrays that you want to combine
const arg1 = [1, 2];
const arg2 = [3, 4];

// combining function - must be curried for this to work
const add = (x) => (y) => x + y;

const partiallyAppliedAdds = [add].ap(arg1); // [(y) => 1 + y, (y) => 2 + y]
`

The following would result in
partiallyAppliedAdds.ap(arg2); // [4, 5, 5, 6]

"Applicative Functor" has zero detail

The "Applicative Functor" section has basically zero detail, giving no insight as to what the concept is useful for. Suggested rewrite:


Ordinary functors "stand alone" - you can map functions over them, but if you've got two functors, you can't do anything with them as a pair. An "applicative" functor knows how to combine with other functors of its type, allowing you to work with multiple functor values at the same time.

In addition to the standard map, an applicative functor has an ap function, which combines together

  1. A function wrapped in the functor, and
  2. An argument wrapped in the functor

For example, if you have an array of functions:

let funcs = [a => a+1, b => b*5];

and an array of values you want to map those functions over:

let vals = [1, 10, 100];

The standard applicative implementation of Array will do that for you, applying each function to all of the values, using ap:

funcs.ap(vals) == [2, 11, 101, 5, 50, 500];

(There are other ways to make Array applicative; for example, a "ziplist" implementation would instead combine the first function with the first argument, the second function with the second argument, etc, yielding [2, 50] from the code above.)

More usefully, applicative functors let the mapping function take multiple arguments:

let plus = (x,y) => x+y;
let arg1 = [1, 2, 3];
let arg2 = [10, 100];
[plus].ap(arg1).ap(arg2) == [11, 101, 12, 102, 13, 103]

(Note that for this to work, you still need to put the function into the functor. Also, the function has to be capable of being partially-applied, so the first ap can give it the first argument, resulting in an array of partially-applied functions, then the second ap can finish them off by giving the second argument.)

Inaccuracy in the "Constants" section

From the section on constants:

With the above two constants the following expression will always return true.

john.age + five === ({name: 'John', age: 30}).age + (5)

This above statement isn't true; while john is declared as a constant; that only means that john can't be replaced with a different object, not that its fields can't be modified. A simple john.age = 10 would cause the above expression to return false, despite the definition of john as a constant.

Use of blockquote

The current use of blockquote makes it look as if paragraphs are quoting some other sources.

additional terms

Hi,

I'd be more than happy to submit some pull requests on these various terms. I'd much rather get an opinion first before starting on a PR:

  • application (as a compliment to partial application)
  • thunk
  • tail-call optimization
  • trampolines
  • functor
  • reducer
  • transducer
  • homomorphism

Supplementary wiki

Its clear that the main document needs to be kept brief in its descriptions, but many people are asking for more detail on the definitions of the terms. Some want more accurate definitions, some want more justification, some want more examples. I think we should discuss what we want to put on the wiki a little.

I think the last thing we want is a super academic definition of monad or 10 confusingly opaque analogies to describe it.

I still think that our wiki should focus on examples but it can maybe use other types than Array to describe categories. E.g. applicative is way more useful on a Maybe

What do y'all think?

Setoid example

The example of setoid uses equality between the elements of the array but it assumes there's an equality operator (==) between the elements of the setoid.

I would do the following:

Number.prototype.equals = function(num) {
  return num.valueOf() === this.valueOf();
}

(2).equals(2) // true
(2).equals(3) // false

Array.prototype.equals = function(arr) {
    var len = this.length
    if (len !== arr.length) {
        return false
    }
    for (var i = 0; i < len; i++) {
        if (! this[i].equals(arr[i])) {
            return false
        }
    }
    return true
}


[1,2].equals([1,2]) // true
[1,2].equals([1,2,3]) // false
[1,2].equals([2,3]) // false

ambiguity in definitions of purity and side effects

The definitions of purity and side effects are ambiguous. For instance, suppose we have a function that reads, but does modify, state that is reachable from its inputs. Is that a "pure" function? Typically it wouldn't be considered to be pure, but it does not have side effects as-defined, and whether it should be considered to return a value that only depends on its inputs is unclear (since the definition doesn't say that the inputs must be stateless values).

Add real world examples and alternative names

Add examples from real world examples.

For example section on monads. Alternative name for chain is flatMap (or flat_map or flatmap). Real world example is streams for instance in highland.

For example section on functors. Real world example: of course Array. But also Streams and Promises. In Promises map is called then.

I believe this can be helpful.

Pointed Functor Example

Array.prototype.of = (v) => [v];

[].of(1) // [1]

However, there is only Array.of, not Array.prototype.of. Is this an error, or is an Array.prototype.of implementation details missing here?

Define Argument and Parameter

If I understand correctly, the therm argument is used here both for local variable name set in function declaration (or expression) phase and its value passed into function in execution phase. It probably doesn't make a significant diference in context this dictionary (or functional programming in general(?)), but some academic nitpickers might be upset about lack of definition at least.

https://www.coati.io/blog/parameter_or_argument/
tl;dr: Parameter = Placeholder ; Argument = Actual value

Inconsistencies in types definitions

The following two definitions are both correct, but they are inconsistent:

A monoid is some data type and a two parameter function ...

An object with a map function that adhere to certains rules. ...

I don't know which of the two is better. The "object with some methods" style of definition, limits us in some ways, for example we cannot say "pure functions form a monoid under functional composition". The other one seems impractical. Maybe we should incorporate both.

Add Styleguide

It be good to document a little of how we'd like this document to be written so contributors can understand our goals and guidelines.

tweak repository name

"Jargon" is a mass noun, so the trailing "s" should be dropped (unless "jargons" is a reference to a meme with which I'm unfamiliar).

Continuations

How do we feel about adding continuations to this list? Especially in FP with JavaScript, continuations are pretty important and can be confusing to understand for beginners without having a simple definition to reference.

If we want to add continuations, I can submit a PR for this!

Writing style

In Higher-Order Function,

const filter = (pred, xs) => ...

For this one, is it better to explicitly use predicate rather than pred? Because the former one is more explicit, and for documentation we tend to favor explicit.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.