8000 GitHub - bitnom/functional-jargon-python at 48f21d824b6716ce6a19e468ff163ff5226afa2b
[go: up one dir, main page]

Skip to content

bitnom/functional-jargon-python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 

Repository files navigation

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.

This is a fork of Functional Programming Jargon.

This document is WIP and pull requests are welcome!

Table of Contents

Arity (TODO)

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

# TODO

Higher-Order Functions (HOF) (TODO)

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

# TODO

Closure (TODO)

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.

# TODO

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 (TODO)

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

# TODO

You can also use functools.partial to partially apply a function in Python:

# TODO

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 (TODO)

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.

# TODO

Auto Currying (TODO)

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.

# TODO

Further reading

Function Composition (TODO)

The act of putting two functions together to form a third function where the output of one function is the input of the other.

# TODO

Continuation (TODO)

At any given point in a program, the part of the code that's yet to be executed is known as a continuation.

# TODO

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.

# TODO

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:

print('This is a side effect!')

Or:

result_sums = []

def add(first: int, second: int) -> int:
    result_sum = first + second
    result_sums.append(result_sum)  # this is a side effect
    return result_sum

Purity

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

This function is pure:

def add(first: int, second: int) -> int:
    return first + second

As opposed to each of the following:

def add_and_log(first: int, second: int) -> int:
    print('Sum is:', first + second)  # print is a side effect
    return first + second

Idempotent (TODO)

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

# TODO

Point-Free Style (TODO)

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.

# TODO

Points-free function definitions look just like normal assignments without def or lambda.

Predicate (TODO)

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.

# TODO

Contracts (TODO)

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.

# TODO

Category (TODO)

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 (TODO)

Anything that can be assigned to a variable.

# TODO

Constant (TODO)

A variable that cannot be reassigned once defined.

# TODO

Constants are referentially transparent. That is, they can be replaced with the values that they represent without affecting the result.

# TODO

Functor (TODO)

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)
# TODO

Pointed Functor (TODO)

An object with an of function that puts any number of values into it. The following property of(f(x)) == of(x).map(f) must also hold for any pointed functor.

# TODO

Lift (TODO)

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.

# TODO

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

# TODO

Referential Transparency (TODO)

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:

# TODO

Equational Reasoning (TODO)

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

Lambda (TODO)

An anonymous function that can be treated like a value.

def f(a):
  return a + 1

lambda a: a + 1

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

List([1, 2]).map(lambda x: x + 1) # [2, 3]

You can assign a lambda to a variable.

add1 = lambda a: a + 1

Lambda Calculus (TODO)

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

Lazy evaluation (TODO)

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.

# TODO

Monoid (TODO)

An object with a function that "combines" that object with another of the same type.

One simple monoid is the addition of numbers:

1 + 1 # 2

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

Monad (TODO)

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

# TODO

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

Comonad (TODO)

An object that has extract and extend functions.

# TODO

Applicative Functor (TODO)

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.

# TODO

Morphism (TODO)

A transformation function.

Endomorphism (TODO)

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

# uppercase :: String -> String
uppercase = lambda s: s.upper() 

# decrement :: Number -> Number
decrement = lambda x: x - 1

Isomorphism (TODO)

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

# TODO

Homomorphism (TODO)

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.

# TODO

Catamorphism (TODO)

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

# TODO

Anamorphism (TODO)

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

# TODO

Hylomorphism (TODO)

The combination of anamorphism and catamorphism.

Paramorphism (TODO)

A function just like reduce_right. 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.

# TODO

Apomorphism (TODO)

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 (TODO)

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

Make array a setoid:

# TODO

Semigroup (TODO)

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

# TODO

Foldable (TODO)

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.

# TODO

Lens (TODO)

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

# TODO

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

# TODO

Type Signatures (TODO)

Further reading

Algebraic data type (TODO)

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

Sum type (TODO)

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.

# TODO

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

The sumtypes library in Python helps with defining and using union types.

Product type (TODO)

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

# TODO

See also Set theory.

Option (TODO)

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.

# TODO

Option is also known as Maybe. Some is sometimes called Just. None is sometimes called Nothing.

Function (TODO)

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:

# TODO

Partial function (TODO)

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:

# TODO

Dealing with partial functions (TODO)

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:

# TODO

Functional Programming Libraries in Python

In This Doc (TODO)

A comprehensive curated list of functional programming libraries for Python can be found here

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
0