Jargon from the functional programming world in simple terms!

Overview

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. This word has the distinction of being composed of two suffixes, "-ary" and "-ity." Addition, for example, takes two arguments, and so it is defined as a binary function or a function with an arity of two. Such a function may sometimes be called "dyadic" by people who prefer Greek roots to Latin. Likewise, a function that takes a variable number of arguments is called "variadic," whereas a binary function must be given two and only two arguments, currying and partial application notwithstanding (see below).

const sum = (a, b) => a + b

const arity = sum.length
console.log(arity) // 2

// The arity of sum is 2

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 way of accessing a variable outside its scope. Formally, a closure is a technique for implementing lexically scoped named binding. It is a way of storing a function with an environment.

A closure is a scope which captures local variables of a function for access even after the execution has moved out of the block in which it is defined. ie. they allow referencing a scope after the block in which the variables were declared has finished executing.

const addTo = x => y => x + y;
var addToFive = addTo(5);
addToFive(3); //returns 8

The function addTo() returns a function(internally called add()), lets store it in a variable called addToFive with a curried call having parameter 5.

Ideally, when the function addTo finishes execution, its scope, with local variables add, x, y should not be accessible. But, it returns 8 on calling addToFive(). This means that the state of the function addTo is saved even after the block of code has finished executing, otherwise there is no way of knowing that addTo was called as addTo(5) and the value of x was set to 5.

Lexical scoping is the reason why it is able to find the values of x and add - the private variables of the parent which has finished executing. This value is called a Closure.

The stack along with the lexical scope of the function is stored in form of reference to the parent. This prevents the closure and the underlying variables from being garbage collected(since there is at least one live reference to it).

Lambda Vs Closure: A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.

A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.

Further reading/Sources

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.

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

Purity

A function is pure if the return value is only determined by its input values, and does not produce side effects.

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!')

Idempotent

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

f(f(x)) ≍ f(x)
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 points-free - `numbers` is an explicit argument
const incrementAll = (numbers) => map(add(1))(numbers)

// Points-free - The list is an implicit argument
const incrementAll2 = map(add(1))

incrementAll identifies and uses the parameter numbers, so it is not points-free. incrementAll2 is written just by combining functions and values, making no mention of its arguments. It is points-free.

Points-free function definitions look just like normal assignments without function or =>.

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 3 rules must be met:

  1. There must be an identity morphism that maps an object to itself. Where a is an object in some category, there must be a function from a -> a.
  2. Morphisms must compose. Where a, b, and c are objects in some category, and f is a morphism from a -> b, and g is a morphism from b -> c; g(f(x)) must be equivalent to (g • f)(x).
  3. Composition must be associative f • (g • h) is the same as (f • g) • h

Since these rules govern composition at very abstract level, category theory is great at uncovering new ways of composing things.

Further reading

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)

Functor

An object that implements a map function which, while running over each value in the object to produce a new object, adheres to two rules:

Preserves identity

object.map(x => x) ≍ object

Composable

object.map(compose(f, g)) ≍ object.map(g).map(f)

(f, g are arbitrary functions)

A common functor in JavaScript is Array since it abides to the two functor rules:

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

and

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

;[1, 2, 3].map(x => f(g(x))) // = [3, 5, 7]
;[1, 2, 3].map(g).map(f)     // = [3, 5, 7]

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], [3, 4]) // [4, 5, 5, 6]

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]

Referential Transparency

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

Say we have function greet:

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

Any invocation of greet() can be replaced with Hello World! hence greet is referentially transparent.

Equational Reasoning

When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.

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.

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)

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

Endomorphism

A function where the input type is the same as the output.

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

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

Isomorphism

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

Homomorphism

A homomorphism is just a structure preserving map. In fact, a functor is just a homomorphism between categories as it preserves the original category's structure under the mapping.

A.of(f).ap(A.of(x)) == A.of(f(x))

Either.of(_.toUpper).ap(Either.of("oreos")) == Either.of(_.toUpper("oreos"))

Catamorphism

A reduceRight function that applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

const sum = xs => xs.reduceRight((acc, x) => acc + x, 0)

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

Anamorphism

An unfold function. An unfold is the opposite of fold (reduce). It generates a list from a single value.

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 combination of anamorphism and catamorphism.

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

it's the opposite of paramorphism, just as anamorphism is the opposite of catamorphism. Whereas with paramorphism, you combine with 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.

See also Set theory.

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-independant, 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 execte, 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 as well as to reason about.

Functional Programming Libraries in JavaScript


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

Comments
  • Rewrite Applicative Functor definition

    Rewrite Applicative Functor definition

    This could, perhaps, use some work, but it’s a difficult concept, and I wanted to take a crack at something more comprehensive and a little more specific than “an object with an ‘ap’ method” just because that doesn’t help people understand the relationship of this structure to other FP structures (and also implies that functions in our world are just another kind of OOP-style method omg).

    opened by sjsyrek 18
  • Explanation of Closure is too complicated

    Explanation of Closure is too complicated

    The explanation of closure uses currying to explain it. The explanation could be far simpler without the use of currying. For people not aquatinted with Function programming, its adds unnecessary complexity to a simple concept.

    Here is a simpler example: var a = 4; function myFunction() { return a * a; }

    opened by afayes 16
  • use js standard style

    use js standard style

    While I recognize that this is no official standard I find it a useful preset.

    https://github.com/feross/standard

    We can mix this with something like https://github.com/eslint/eslint-plugin-markdown To enforce that code examples follow our standards.

    opened by jethrolarson 16
  • Added Contracts

    Added Contracts

    Wrote a definition for contracts in programming with an example in ES6. Since there isn't really a way to enforce contracts natively in JavaScript, I tried to write what I thought was a simple example of a way to enforce a contract while still showing what it is exactly. Any suggestions for improvements are welcome!

    opened by nickzuber 15
  • Would be great to see a 'Why?' section for each entry

    Would be great to see a 'Why?' section for each entry

    Ok, so you've explained... currying or functors. Great. But why would I want to curry a function? What's the benefit of doing that? How is it used in the real world?

    enhancement question 
    opened by dflock 10
  • Sorted

    Sorted

    Not sure if you all are interested in this but some dude on reddit made a comment about how the readme.md isn't alphabetized so I wrote a little script to sort the relevant sections of the readme.md without ruining the markdown. It relies on the format not changing too much, but it works. I've also run it on the readme.md file so I'm submitting the alphabetized version of that too. The intent is that people contributing examples wouldn't need to worry about hand alphabetizing in the future. I'm up for making it more robust, better commented and cleaner if it gets picked up.

    opened by AlexScheller 10
  • In-depth proofreading and correcting

    In-depth proofreading and correcting

    First off, this was very interesting to read and learn from, huge thanks to all contributors!!

    There are quite a lot of changes, so please let me know which ones don't make sense to you and I'll revert them. I've tried to make all the explanations and their respective code examples as "pretty" and consistent as possible.

    Here's a list of what this PR contains:

    • Typo, missing word and duplicate word corrections.
    • Method names at the beginning of a sentence aren't capitalised (e.g. "ap applies a function in the object...")
    • Give code snippets some space (1 empty line before and 1 after).
    • All code snippets are now syntax highlighted with JS.
    • Whitespaces in code snippets corrected.

    Some suggestions / questions:

    • Maybe have a TOC? (table of contents)
    • Semicolons (everywhere vs. nowhere vs. here-and-there): Some code snippets have them, others don't, others have a combination.
    opened by noplanman 10
  • More accurately define union types

    More accurately define union types

    Eliminate inaccuracies and a misleading example. A union type does not necessarily inherit the operations of its component types, much less operations across values of two different component types. The ability to add a string and a number is a quirk in JavaScript and other languages, not a feature of union types.

    opened by thejohnfreeman 8
  • Hindley-Milner type signatures

    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.

    opened by jasonbellamy 8
  • Add more morphisms

    Add more morphisms

    I was watching @DrBoolean's A Million Ways to Fold in JS but I couldn't understand most of the morphism jargons. I presume the video is for experienced devs who are from a FP language background. The moment when I tried to search for "Catamorphism javascript" on google I couldn't get anything. I really hope there would be more in depth FP resources written in JavaScript. Luckily @i-am-tom kindly wrote up something that could be understood by JS devs like me. I have fixed a minor mistake in @i-am-tom's original write up and tweaked a few wording.

    Also cc @joneshf @getify @shineli1984

    Thanks!

    opened by stevemao 7
  • Union type code example misleading

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

    opened by stereobooster 7
  • improving definitions for monoid, comonad, applicative, and ADT

    improving definitions for monoid, comonad, applicative, and ADT

    Addressing some of the feed back in #220

    I looked at "Lift" and while I can see that our definition is more general than "lambda lifting" I kinda prefer that the idea be generalized to all values not just functions. That I think make it easier to teach the idea of computation contexts in the way that Scott W does with the elevated worlds metaphor

    opened by jethrolarson 1
  • Organize for extensibility

    Organize for extensibility

    I like a lot all that I read here - but - I could not figure the logic of the order of the values in the index.

    I think it's time to take a decision that will ensure the growth of this repo Option 1 - sort values alphabetically

    Pro: clear, neutral, streight forward. Con: less approachable: the narrative is lost

    Option 2 - organize values in layers/chopters, each is organized internally by a narrative Pro: able to tell the story and invite to dive deeper Con: it's prone to be disputed, and debated and could depend on personal style

    I'll demonstrate: e.g -

    • layer 1 - functional basics - pure function, arity, closure, idempotence, etc..
    • layer 2 - techniques - currying, contract, etc...
    • layer 3 - design patterns - continuation, functor, point-free, etc...

    Personally I like better then 2nd option, but even I myself cannot make up my mind what comes first - techniques or design patterns, or how to divide between the two. 😛

    But I do think that the basics would better come first...

    I'd love to start a PR and work with you if I knew where to go with this :)

    opened by osher 3
  • Suggestions from HN

    Suggestions from HN

    Since it peaked on HN1 a few hours ago, there were some suggestions on things we could improve:

    From mjburgess:

    These definitions don't really give you the idea, rather often just code examples.. "The ideas", in my view:

    Monoid = units that can be joined together

    Functor = context for running a single-input function

    Applicative = context for multi-input functions

    Monad = context for sequence-dependent operations

    Lifting = converting from one context to another

    Sum type = something is either A or B or C..

    Product type = a record = something is both A and B and C

    Partial application = defaulting an argument to a function

    Currying = passing some arguments later = rephrasing a function to return a functions of n-1 arguments when given 1, st. the final function will compute the desired result

    EDIT: Context = compiler information that changes how the program will be interpreted (, executed, compiled,...)

    Eg., context = run in the future, run across a list, redirect the i/o, ...

    From ncmncm:

    1. It should explain map somewhere before it is used.

    2. For the more abstruse and abstract concepts, a comment suggesting why anybody should care about this idea at all would be helpful. E.g., "A is just a name for what [familiar things] X, Y, and Z have in common."

    3. It goes off the rails halfway through. E.g. Lift.

    From sanderjd: Expanding on your #1, I think they could use some more definitions. As you say, they use "map" in its functional programming sense before defining it, but I think more confusing is this one:

    A category in category theory is a collection of objects and morphisms between them.

    What is a "morphism"?

    I think this is a great starting point though, which could use some expansion.

    opened by engelju 1
  • Category example is a preorder/partial order

    Category example is a preorder/partial order

    The example category, Max, is a preorder. The resulting category is skeletal; there is at most one arrow between any two objects. This is not bad, but most categories will be richer than this, and the example should say so.

    opened by MostAwesomeDude 1
Owner
hemanth.hm
A computer polyglot CLI, web and unix philosophy ❤️'r. Google Developer Expert. Google LaunchPad Mentor Community leader @duckduckgo Delegate at @tc39
hemanth.hm
Simplified JavaScript Jargon

Simplified JavaScript Jargon (short SJSJ) is a community-driven attempt at explaining the loads of buzzwords making the current JavaScript ecosystem i

Kitty Giraudel 2.3k Dec 30, 2022
GitHub Action that checks code and docs for offensive / exclusive terms and provides warnings.

Inclusiveness Analyzer Make your code inclusive! The Inclusiveness Analyzer is a GitHub action that checks your repository for offensive / exclusive t

Microsoft 21 Dec 1, 2022
Fun λ functional programming in JS

fp-js JavaScript Functional Programming Motivation This purposed for learning functional programming (just that). Features Auto-Curry Option Tooling s

RiN 6 Feb 4, 2022
Functional Programming with NestJS, Prisma. immutable, pure, stateless

Functional-NestJS Functional Programming with NestJS, Prisma. immutable, pure, stateless. 1. Introduction A production ready typescript backend reposi

y0on2q 40 Dec 6, 2022
Typescript library for functional programming.

Sa Lambda Typescript library for functional programming. Document TODO Either Maybe Iterator Pipe & Flow Task (Promise-Like) some math utils Installat

SoraLib 9 Dec 6, 2022
A RabbitMQ client for TypeScript, with functional programming in mind.

RabbitMQ-fp Lets feed our Rabbit' nicely ?? This repository contains a wrapper over amqplib written in Typescript with an accent of functionnal progra

MansaGroup 3 Sep 6, 2022
Collection of benchmarks of functional programming languages and proof assistants.

Functional Benchmarks This repository contains a collection of benchmarks of functional programming languages and proof assistants. It is split in two

null 22 Dec 12, 2022
🥰 Mini world simulator is a terminal application made in JavaScript to control the world that is being generated.

Mini-world "Simulator" Mini world simulator is a terminal application made in JavaScript to control the world that is being generated. It has no other

Adrián 2 Mar 14, 2022
When a person that doesn't know how to create a programming language tries to create a programming language

Kochanowski Online Spróbuj Kochanowskiego bez konfiguracji projektu! https://mmusielik.xyz/projects/kochanowski Instalacja Stwórz nowy projekt przez n

Maciej Musielik 18 Dec 4, 2022
Cookbook Method is the process of learning a programming language by building up a repository of small programs that implement specific programming concepts.

CookBook - Hacktoberfest Find the book you want to read next! PRESENTED BY What is CookBook? A cookbook in the programming context is collection of ti

GDSC-NITH 16 Nov 17, 2022
A functional, immutable, type safe and simple dependency injection library inspired by angular.

func-di English | 简体中文 A functional, immutable, type safe and simple dependency injection library inspired by Angular. Why func-di Installation Usage

null 24 Dec 11, 2022
In this project, I implement a Simple To Do List with the CRUD (create, read, update, delete) methods. All the elements of the user interface are fully functional.

To Do list: add & remove In this project, I implement a Simple To Do List with the CRUD (create, read, update, delete) methods. All the elements of th

Olivier 10 Jan 3, 2023
This is a Library project from the Odin Project. A simple book list for my programming books.

Library This is a Library project from the Odin Project. The user can add a book by providing a title and author. Also, the user can mark it if it's r

Virag Kormoczy 8 Nov 26, 2022
POC. Simple plugin-based meta-programming platform on top of Typescript

comp-plugins POC Running: yarn to install dependencies yarn dev to run the script The what The script creates a new typescript compiler instance (prog

Ciobanu Laurentiu 3 Jul 14, 2022
Simple JSON parse/stringify for the Wren programming language

wren-json Simple JSON parse/stringify for the Wren programming language. Parses strict json and relaxed json Comments Unquoted keys Trailing commas St

.ruby 8 May 18, 2022
Simple Math Programming Language (SMPL) for the Web

Simple Math Programming Language (SMPL) for the Web SMPL is a math-oriented programming language that can be interpreted in the browser. Its primary u

mathe:buddy / TH Köln 6 Dec 15, 2022
A simple static type checker that enforces C-style programming in Julia

SimpleTypeChecker is an experimental Julia package designed to enforce C-style programming in Julia language. Note : it won't save you if your codes a

null 21 May 23, 2023