You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
Where applicable, this document uses terms defined in the Fantasy Land spec and Rust programming language to give code examples.
Also please be mindful that the project sometimes utilises FP related crates that are unfinished but contains a specific typeclass or data type that is appropriate to give an explanation. Many of them are experimental and are not suitable for production usage.
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).
let sum = |a: i32, b: i32| { a + b }; // The arity of sum is 2
Higher-Order Functions (HOF)
A function which takes a function as an argument and/or returns a function.
A closure is a scope which retains variables available to a function when it's created. This is important for partial application to work.
let add_to = | x: i32 | { move | y: i32 | { x + y } };
We can call add_to with a number and get back a function with a baked-in x. Notice that we also need to move the ownership of the y to the internal lambda.
let add_to_five = add_to(5);
In this case the x is retained in add_to_five's closure with the value 5. We can then call add_to_five with the y and get back the desired number.
add_to_five(3); // => 8
Closures are commonly used in event handlers so that they still have access to variables defined in their parents when they are eventually called.
The partial application helps create simpler functions from more complex ones by baking in data when you have it. Curried functions are automatically partially applied.
Transforming a function that takes multiple arguments into one that is 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.
Although Auto Currying is not possible in Rust right now, there is a debate on this issue on the Rust forum: https://ift.tt/34rgRlW
Referential Transparency
An expression that can be replaced with its value without changing the behaviour of the program is said to be referentially transparent.
Say we have function greet:
let greet = || "Hello World!";
Any invocation of greet() can be replaced with Hello World! hence greet is referentially transparent.
Lambda
An anonymous function that can be treated like a value.
fn increment(i: i32) -> i32 { i + 1 }
let closure_annotated = |i: i32| { i + 1 };
let closure_inferred = |i| i + 1;
Lambdas are often passed as arguments to Higher-Order Functions. You can assign a lambda to a variable, as shown above.
... 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.
use std::time::SystemTime;
let now = SystemTime::now();
println!("IO is a side effect!");
// IO is a side effect!
Idempotent
A function is idempotent if reapplying it to its result does not produce a different result.
let x = vec![2 ,1];
let sorted_x = sort(sort(x.clone()));
let expected = vec![1, 2];
assert_eq!(sorted_x, expected); // passes
let abs = | x: i32 | -> i32 {
return x.abs();
};
let x: i32 = 10;
let result = abs(abs(x));
assert_eq!(result, x); // passes
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. Below is an example of compose function is Rust.
let add = | x: i32 | x + 2;
let multiply = | x: i32 | x * 2;
let divide = | x: i32 | x / 2;
let intermediate = compose!(add, multiply, divide);
let subtract = | x: i32 | x - 1;
let finally = compose!(intermediate, subtract);
let expected = 11;
let result = finally(10);
assert_eq!(result, expected); // passes
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.
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.
let predicate = | a: &i32 | a.clone() > 2;
let result = (vec![1, 2, 3, 4]).into_iter().filter(predicate).collect::<Vec<i32>>();
assert_eq!(result, vec![3, 4]); // passes
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.
let contract = | x: &i32 | -> bool {
return x > &10;
};
let expected = 12;
match add_one(&11) {
Ok(x) => assert_eq!(x, expected),
_ => panic!("Failed!")
}
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:
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.
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).
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.
Variance in Rust is used during the type checking against type and lifetime parameters. Here are examples:
By default, all lifetimes are co-variant except for 'static because it outlives all others
'static is always contra-variant to others regardless of where it appears or used
It is in-variant if you use Cell<T> or UnsafeCell<T> in PhatomData
Further Reading
https://ift.tt/2UyXz9n
https://ift.tt/34ugpDa
Higher Kinded Type (HKT)
Rust does not support Higher Kinded Types yet. First of all, HKT is a type with a "hole" in it, so you can declare a type signature such as trait Functor<F<A>>.
An implementation example of above theory in Rust would look like below:
pub trait HKT<A, B> {
type URI;
type Target;
}
// Lifted Option
impl<A, B> HKT<A, B> for Option<A> {
type URI = Self;
type Target = Option<B>;
}
Higher Kinded Type is crucial for functional programming in general.
Further Reading
https://ift.tt/2UyXAdr
https://www.youtube.com/watch?v=ERM0mBPNLHc
Functor
An object that implements a map function which, while running over each value in the object to produce a new functor of the same type, 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)
For example, below can be considered as a functor-like operation
let v: Vec<i32> = vec![1, 2, 3].into_iter().map(| x | x + 1).collect();
assert_eq!(v, vec![2, 3, 4]); // passes while mapping the original vector and returns a new vector
While leveraging the HKT implementation, You can define a trait that represents Functor like below
Lifting in functional programming typically means to lift a function into a context (a Functor or Monad). For example, give a function a -> b and lift it into a List then the signature would look like List[a] -> List[b].
Further Reading
https://ift.tt/1KNDw9b
https://ift.tt/2UyWY7R
https://ift.tt/34ovTsu
Equational Reasoning
When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.
Monoid
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
// i32: 2
In this case number is the object and + is the function.
An "identity" value must also exist that when combined with a value doesn't change it.
The identity value for addition is 0.
1 + 0
// i32: 1
It's also required that the grouping of operations will not affect the result (associativity):
impl<A> Extract<A> for Option<A> {
fn extract(self) -> A {
self.unwrap() // is there a better way to achieve this?
}
}
Extract takes a value out of a functor.
Some(1).extract(); // 1
Extend runs a function on the Comonad.
Some(1).extend(|co| co.extract() + 1); // Some(2)
Applicative
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. Given a pure program g: (b: A) -> B, we must lift it to g: (fb: F<A>) -> F<B>. In order to achieve this, we will introduce another higher kinded type, called HKT3 that is capable of doing this.
For this example, we will use Option datatype.
trait HKT3<A, B, C> {
type Target2;
}
impl<A, B, C> HKT3<A, B, C> for Option<A> {
type Target2 = Option<B>;
}
Since Applicative implements Apply for ap and Pure for of according to Fantasy Land specification we must implement the types like below:
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.
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.
It must obey following rules to be Setoid
a.equals(a) == true (reflexivity)
a.equals(b) == b.equals(a) (symmetry)
a.equals(b) and b.equals(c) then a.equals(c) (transitivity)
An object that has a foldr/l function that can transform that object into some other type. We are using rats to give an example but the crate only implements fold_right.
fold_right is equivalent to Fantasy Land Foldable's reduce, which goes like:
fantasy-land/reduce :: Foldable f => f a ~> ((b, a) -> b, b) -> b
use rats::foldable::Foldable;
use rats::kind::IntoKind;
use rats::kinds::VecKind;
let k = vec![1, 2, 3].into_kind();
let result = VecKind::fold_right(k, 0, | (i, acc) | i + acc);
assert_eq!(result, 6);
Lens
A lens is a type that pairs a getter and a non-mutating setter for some other data structure.
trait Lens<S, A> {
fn over(s: &S, f: &Fn(Option<&A>) -> A) -> S {
let result: A = f(Self::get(s));
return Self::set(result, &s);
}
fn get(s: &S) -> Option<&A>;
fn set(a: A, s: &S) -> S;
}
#[derive(Debug, PartialEq, Clone)]
struct Person {
name: String,
}
fn set(a: String, s: &Person) -> Person {
return Person {
name: a,
}
}
}
Having the pair of get and set for a given data structure enables a few key features.
let e1 = Person {
name: "Jason".to_string(),
};
let name = PersonNameLens::get(&e1);
let e2 = PersonNameLens::set("John".to_string(), &e1);
let expected = Person {
name: "John".to_string()
};
let e3 = PersonNameLens::over(&e1, &|x: Option<&String>| {
match x {
Some(y) => y.to_uppercase(),
None => panic!("T_T") // lol...
}
});
If a function accepts another function as an argument it is wrapped in parentheses.
// call :: (a -> b) -> a -> b
fn call<A, B>(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
return move |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]
fn map<A, B>(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
return move |x| f(x);
}
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.
Rust has enum that literally represent sum in ADT.
A product type combines types together in a way you're probably more familiar with:
struct Point {
x: i32,
y: i32,
}
// Point = i32 x i32
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.
Please be mindful that the project does not fully cover every single definition with code examples since it does not worth investing too much time in a glossary project. I have put extra effort into adding complementary external references that you can check out for further study.
via Functional Works https://ift.tt/2FO07J7
September 6, 2019 at 11:42AM
The text was updated successfully, but these errors were encountered:
Functional Programming Jargon in Rust
https://ift.tt/2G9Q6YG
About 0 Minutes
Github Repository: https://github.com/JasonShin/functional-programming-jargon.rs
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.
Where applicable, this document uses terms defined in the Fantasy Land spec and Rust programming language to give code examples.
Also please be mindful that the project sometimes utilises FP related crates that are unfinished but contains a specific typeclass or data type that is appropriate to give an explanation. Many of them are experimental and are not suitable for production usage.
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).
Higher-Order Functions (HOF)
A function which takes a function as an argument and/or returns a function.
Closure
A closure is a scope which retains variables available to a function when it's created. This is important for partial application to work.
We can call
add_to
with a number and get back a function with a baked-inx
. Notice that we also need to move the ownership of the y to the internal lambda.In this case the
x
is retained inadd_to_five
's closure with the value5
. We can then calladd_to_five
with they
and get back the desired number.Closures are commonly used in event handlers so that they still have access to variables defined in their parents when they are eventually called.
Further reading
Partial Application
Partially applying a function means creating a new function by pre-filling some of the arguments to the original function.
To achieve this easily, we will be using a partial application crate
The partial application helps create simpler functions from more complex ones by baking in data when you have it. Curried functions are automatically partially applied.
Further reading
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.
Further reading
Auto Currying
Transforming a function that takes multiple arguments into one that is 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.
Although Auto Currying is not possible in Rust right now, there is a debate on this issue on the Rust forum: https://ift.tt/34rgRlW
Referential Transparency
An expression that can be replaced with its value without changing the behaviour of the program is said to be referentially transparent.
Say we have function greet:
Any invocation of
greet()
can be replaced withHello World!
hence greet is referentially transparent.Lambda
An anonymous function that can be treated like a value.
Lambdas are often passed as arguments to Higher-Order Functions. You can assign a lambda to a variable, as shown above.
Lambda Calculus
A branch of mathematics that uses functions to create a universal model of computation.
Purity
A function is pure if the return value is only determined by its input values, and does not produce side effects.
As opposed to each of the following:
The above example's output is based on data stored outside of the function...
... 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.
Idempotent
A function is idempotent if reapplying it to its result does not produce a different result.
Then we can use the sort method like
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. Below is an example of compose function is Rust.
Then we can use it like
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.
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.
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.
Then you can use
add_one
likeCategory
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:
a
is an object in some category, there must be a function froma -> a
.a
,b
, andc
are objects in some category, andf
is a morphism froma -> b
, andg
is a morphism fromb -> c
;g(f(x))
must be equivalent to(g • f)(x)
.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.
Constant
A variable that cannot be reassigned once defined.
Constants are referentially transparent. That is, they can be replaced with the values that they represent without affecting the result.
Variance
Variance in functional programming refers to subtyping between more complex types related to subtyping between their components.
Unlike other usage of variance in Object Oriented Programming like Typescript or C# or functional programming language like Scala or Haskell
Variance in Rust is used during the type checking against type and lifetime parameters. Here are examples:
'static
because it outlives all others'static
is always contra-variant to others regardless of where it appears or usedin-variant
if you useCell<T>
orUnsafeCell<T>
inPhatomData
Further Reading
Higher Kinded Type (HKT)
Rust does not support Higher Kinded Types yet. First of all, HKT is a type with a "hole" in it, so you can declare a type signature such as
trait Functor<F<A>>
.Although Rust lacks in a native support for HKT, we always have a walk around called Lightweight Higher Kinded Type
An implementation example of above theory in Rust would look like below:
Higher Kinded Type is crucial for functional programming in general.
Further Reading
Functor
An object that implements a map function which, while running over each value in the object to produce a new functor of the same type, adheres to two rules:
Preserves identity
Composable
(
f
,g
are arbitrary functions)For example, below can be considered as a functor-like operation
While leveraging the HKT implementation, You can define a trait that represents Functor like below
Then use it against a type such as Option like
Pointed Functor
An object with an of function that puts any single value into it.
Then use it like
Lifting
Lifting in functional programming typically means to lift a function into a context (a Functor or Monad). For example, give a function
a -> b
and lift it into aList
then the signature would look likeList[a] -> List[b]
.Further Reading
Equational Reasoning
When an application is composed of expressions and devoid of side effects, truths about the system can be derived from the parts.
Monoid
An object with a function that "combines" that object with another of the same type.
One simple monoid is the addition of numbers:
In this case number is the object and
+
is the function.An "identity" value must also exist that when combined with a value doesn't change it.
The identity value for addition is
0
.It's also required that the grouping of operations will not affect the result (associativity):
Array concatenation also forms a monoid:
The identity value is empty array
[]
If identity and compose functions are provided, functions themselves form a monoid:
foo
is any function that takes one argument.Monad
A Monad is a trait that implements
Applicative
andChain
specifications.chain
is likemap
except it un-nests the resulting nested object.First,
Chain
type can be implemented like below:Then
Monad
itself can simply deriveChain
andApplicative
pure
is also known asreturn
in other functional languages.flat_map
is also known asbind
in other languages.Comonad
An object that has
extract
andextend
functions.Then we can implement these types for Option
Extract takes a value out of a functor.
Extend runs a function on the Comonad.
Applicative
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. Given a pure programg: (b: A) -> B
, we must lift it tog: (fb: F<A>) -> F<B>
. In order to achieve this, we will introduce another higher kinded type, calledHKT3
that is capable of doing this.For this example, we will use Option datatype.
Since Applicative implements Apply for
ap
andPure
forof
according to Fantasy Land specification we must implement the types like below:Then we can use Option Applicative like this:
Morphism
A transformation function.
Endomorphism
A function where the input type is same as the output.
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 a i32 vector [2,3] or a struct {x: 2, y: 3}.
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.
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.Anamorphism
An
unfold
function. Anunfold
is the opposite offold
(reduce
). It generates a list from a single value.Hylomorphism
The combination of anamorphism and catamorphism.
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.It must obey following rules to be
Setoid
a.equals(a) == true
(reflexivity)a.equals(b) == b.equals(a)
(symmetry)a.equals(b)
andb.equals(c)
thena.equals(c)
(transitivity)Make a Vector a setoid:
Note that I am treating
Self
/self
likea
.Semigroup
An object that has a
combine
function that combines it with another object of the same type.It must obey following rules to be
Semigroup
a.combine(b).combine(c)
is equivalent toa.combine(b.combine(c))
(associativity)Foldable
An object that has a
foldr/l
function that can transform that object into some other type. We are usingrats
to give an example but the crate only implementsfold_right
.fold_right
is equivalent to Fantasy Land Foldable'sreduce
, which goes like:fantasy-land/reduce :: Foldable f => f a ~> ((b, a) -> b, b) -> b
Lens
A lens is a type that pairs a getter and a non-mutating setter for some other data structure.
Having the pair of get and set for a given data structure enables a few key features.
Lenses are also composable. This allows easy immutable updates to deeply nested data.
Further Reading
Type Signature
Every function in Rust will indicate the types of their arguments and return values.
If a function accepts another function as an argument it is wrapped in parentheses.
The letters
a
,b
,c
,d
are used to signify that the argument can be of any type. The following version of map takesa
function that transformsa
value of some typea
into another typeb
, an array of values of typea
, and returns an array of values of typeb
.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.
Rust has
enum
that literally representsum
in ADT.Product Type
A product type combines types together in a way you're probably more familiar with:
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
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.
Use and_then or map to sequence functions that return Options
Option
is also known asMaybe
.Some
is sometimes calledJust
.None
is sometimes calledNothing
.Functional Programming references
Functional Programming development in Rust Language
My thought on this project
Please be mindful that the project does not fully cover every single definition with code examples since it does not worth investing too much time in a glossary project. I have put extra effort into adding complementary external references that you can check out for further study.
via Functional Works https://ift.tt/2FO07J7
September 6, 2019 at 11:42AM
The text was updated successfully, but these errors were encountered: