A library for functional programming in Rust

Overview

Build Status

The project is a library for functional programming in Rust.

fp-core.rs

A library for functional programming in Rust.

It contains purely functional data structures to supplement the functional programming needs alongside with the Rust Standard Library.

Installation

Add below line to your Cargo.toml

fp-core = "0.1.9"

If you have Cargo Edit you may simply

$ cargo add fp-core

functional programming jargon in rust

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.

The content of this section was drawn from Functional Programming Jargon in Javascript and we sincerely appreciate them for providing the initial baseline.

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

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.

let filter = | predicate: fn(&i32) -> bool, xs: Vec<i32> | {
    xs.into_iter().filter(predicate).collect::<Vec<i32>>()
};
let is_even = |x: &i32| { x % 2 == 0 };
filter(is_even, vec![1, 2, 3, 4, 5, 6]);

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.

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

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

#[macro_use]
extern crate partial_application;

fn foo(a: i32, b: i32, c: i32, d: i32, mul: i32, off: i32) -> i32 {
    (a + b*b + c.pow(3) + d.pow(4)) * mul - off
}

let bar = partial!( foo(_, _, 10, 42, 10, 10) );

assert_eq!(
    foo(15, 15, 10, 42, 10, 10),
    bar(15, 15)
); // passes

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.

fn add(x: i32) -> impl Fn(i32)-> i32 {
    move |y| x + y
}

let add5 = add(5);
add5(10); // 15

Further reading

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.

Although Auto Currying is not possible in Rust right now, there is a debate on this issue on the Rust forum: https://internals.rust-lang.org/t/auto-currying-in-rust/149/22

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:

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.

Lambda Calculus

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

This is in contrast to a Turing machine, an equivalent model.

Lambda calculus has three key components: variables, abstraction, and application. A variable is just some symbol, say x. An abstraction is sort of a function: it binds variables into "formulae". Applications are function calls. This is meaningless without examples.

The identity function (|x| x in rust) looks like \ x. x in most literature (\ is a Lambda where Latex or Unicode make it available). It is an abstraction. If 1 were a value we could use, (\ x. x) 1 would be an application (and evaluating it gives you 1).

But there's more...

Computation in Pure Lambda Calculus

Let's invent booleans. \ x y. x can be true and \ x y. y can be false. If so, \ b1 b2. b1(b2,(\x y. y)) is and. Let's evaluate it to show how:

b1 b2 Their and
\ x y. x \x y. x \x y. x
\ x y. x \x y. y \x y. y
\ x y. y \x y. y \x y. y
\ x y. y \x y. x \x y. y

I'll leave or as an exercise. Furthermore, if can now be implemented: \c t e. c(t, e) where c is the condition, t the consequent (then) and e the else clause.

SICP leaves numbers as an exercise. They define 0 as \f . \x. x and adding one as \n. \f. \x. f(n(f)(x)). That isn't even ASCII art, so let's add: 0 + 1:

(\n. \f. \x. f(n(f)(x)))(\f. \x. x) = \f. \x. f((\x'. x')(x)) = \f. \x. f(x)

Basically, the number of fs in the expression is the number. I'll leave figuring out larger numbers as a exercise. With patience, you can show that \f. \x. f(f(x)) is two. This will help with addition: \n m. \f. \x. n(m(f)(x)) should add two numbers. Let's make 4:

(\n m. \f. \x. n(f)(m(f)(x)))(\f. x. f(f(x)), \f. \x. f(f(x)))
  = \f. \x. (\f'. \x'. f'(f'(x')))(f)((\f'. \x'. f'(f'(x')))(f)(x))
  = \f. \x. (\x'. f(f(x')))(f(f(x')))
  = \f. \x. f(f(f(f(x))))

Multiplication is harder and there's better exposition on Wikipedia. Another good reference is on stackoverflow.

Purity

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

let greet = |name: &str| { format!("Hi! {}", name) };

greet("Jason"); // Hi! Jason

As opposed to each of the following:

String { format!("Hi! {}", name) }; greet(); // String = "Hi! Jason" ">
let name = "Jason";

let greet = || -> String {
    format!("Hi! {}", name)
};

greet(); // String = "Hi! Jason"

The above example's output is based on data stored outside of the function...

let mut greeting: String = "".to_string();

let mut greet = |name: &str| {
    greeting = format!("Hi! {}", name);
};

greet("Jason");

assert_eq!("Hi! Jason", greeting); // Passes

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

// Custom immutable sort method
let sort = |x: Vec<i32>| -> Vec<i32> {
    let mut x = x;
    x.sort();
    x
};

Then we can use the sort method like

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

macro_rules! compose {
    ( $last:expr ) => { $last };
    ( $head:expr, $($tail:expr), +) => {
        compose_two($head, compose!($($tail),+))
    };
}

fn compose_two(f: F, g: G) -> impl Fn(A) -> C
where
    F: Fn(A) -> B,
    G: Fn(B) -> C,
{
    move |x| g(f(x))
}

Then we can use it like

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

Continuation

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

let print_as_string = |num: i32| println!("Given {}", num);

let add_one_and_continue = |num: i32, cc: fn(i32)| {
    let result = num + 1;
    cc(result)
};

add_one_and_continue(1, print_as_string); // Given 2

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.

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 {
    x > &10
};

let add_one = | x: &i32 | -> Result<i32, String> {
    if contract(x) {
        return Ok(x + 1);
    }
    Err("Cannot add one".to_string())
};

Then you can use add_one like

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:

  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. In particular, many see this as another foundation of mathematics (so, everything would be a category from this view of math). Various definitions in this guide are related to category theory since this approach applies elegantly to functional programming.

Examples of categories

When one specifies a category, the objects and morphisms are essential. Additionally, showing that the rules are met is nice though usually left to the reader as an exercise.

  • Any type and pure functions on the type. (Note, we require purity since side-effects affect associativity (the third rule).)

These examples come up in mathematics:

  • 1: the category with 1 object and its identity morphism.
  • Monoidal categories: monoids are defined later but any monoid is a category with 1 object and many morphisms from the object to itself. (Yes, there is also a category of monoids -- this is not that -- this example is that any monoid is its own category.)

Further reading

Value

Anything that can be assigned to a variable.

let a = 5;
let b = vec![1, 2, 3];
let c = "test";

Constant

A variable that cannot be reassigned once defined.

let a = 5;
a = 3; // error!

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:

  • 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 or UnsafeCell in PhatomData

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

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:

pub trait HKT {
    type URI;
    type Target;
}

// Lifted Option
impl HKT for Option {
    type URI = Self;
    type Target = Option;
}

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

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

pub trait Functor: HKT {
    fn fmap(self, f: F) -> <Self as HKT>::Target
        where F: FnOnce(A) -> B;
}

Then use it against a type such as Option like

The Underlying Math

The confusing fact is that functors are morphisms in the category of categories. Really, this means that a functor from category C into D preserves properties of the category, so that the data is somewhat preserved.

Technically, every category has a functor into the simplest (non-empty) category (1): since the category 1 just has one object and one function, map all the objects and functions in whatever category you start from into the thing in 1. So, data isn't quite preserved in a "nice" sense. Such functors are called forgetful sometimes as they drop structure.

However, less forgetful examples provide more insight and empower useful statements about types. Unfortunately, these are rather heavy-handed in the mathematics they evoke.

Pointed Functor

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

#[derive(Debug, PartialEq, Eq)]
enum Maybe {
    Nothing,
    Just(T),
}


impl Maybe {
    fn of(x: T) -> Self {
        Maybe::Just(x)
    }
}

Then use it like

let pointed_functor = Maybe::of(1);

assert_eq!(pointed_functor, Maybe::Just(1));

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 a List then the signature would look like List[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 set with a binary function that "combines" pairs from that set into another element of the set.

One simple monoid is the addition of numbers:

1 + 1
// i32: 2

In this case numbers are the set 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):

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

Array concatenation also forms a monoid:

[vec![1, 2, 3], vec![4, 5, 6]].concat();
// Vec: vec![1, 2, 3, 4, 5, 6]

The identity value is empty array []

[vec![1, 2], vec![]].concat();
// Vec: vec![1, 2]

If identity and compose functions are provided, functions themselves form a monoid:

fn identity(a: A) -> A {
    a
}

foo is any function that takes one argument.

compose(foo, identity) ≍ compose(identity, foo) ≍ foo

We can express Monoid as a Rust trait and the type signature would look like below

According to Fantasy Land Specification, Monoid should implement Empty and Applicative.

Monad

A Monad is a trait that implements Applicative and Chain specifications. chain is like map except it un-nests the resulting nested object.

First, Chain type can be implemented like below:

pub trait Chain: HKT {
    fn chain(self, f: F) -> <Self as HKT>::Target
        where F: FnOnce(A) -> <Self as HKT>::Target;
}

impl Chain for Option {
    fn chain(self, f: F) -> Self::Target
        where F: FnOnce(A) -> <Self as HKT>::Target {
        self.and_then(f)
    }
}

Then Monad itself can simply derive Chain and Applicative

pure is also known as return in other functional languages. flat_map is also known as bind in other languages.

Importantly, it is worth noting that monads are a rather advanced topic in category theory. In fact, they are called triples by some as they involve adjoint functors and their unit -- both of which are rare to see in functional programming. The meme is to think of a monad as a burrito with "pure" being the act of taking a tortilla (the empty burrito) and adding ingredients using "chain".

The purely mathematical presentation of monads does not look anything like this, but there is an equivalence.

Comonad

An object that has extract and extend functions.

trait Extend: Functor + Sized {
    fn extend(self, f: W) -> <Self as HKT>::Target
    where
        W: FnOnce(Self) -> B;
}

trait Extract {
    fn extract(self) -> A;
}

trait Comonad: Extend + Extract {}

Then we can implement these types for Option

Extract takes a value out of a comonad.

Some(1).extract(); // 1

Extend runs a function on the Comonad.

Some(1).extend(|co| co.extract() + 1); // Some(2)

This can be thought of as the reverse of a monad. In fact, this is called the "dual" in category theory. (Basically, if you know what A is, a coA is everything in A's definition with the arrows reversed.)

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) -> F. 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 {
    type Target2;
}

impl HKT3 for Option {
    type Target2 = Option;
}

Since Applicative implements Apply for ap and Pure for of according to Fantasy Land specification we must implement the types like below:

Then we can use Option Applicative like this:

let x = Option::of(Some(1)).ap(Some(|x| x + 1));
assert_eq!(x, Some(2));

Morphism

A function that preserves the structure of its domain. See the category definition from more.

The first few (endomorphism, homomorphism, and isomorphism) are easier to understand than the rest. The rest require the notion of an F-algebra. The simpler Haskell declarations are listed in the wikipedia on paramorphisms but the notions have yet to be extended to more general category theory. Briefly, the view of F-algebras is to take the set-theoretic definition of algebraic objects and redefined them on a purely category theoretic footing: to move the ideas away from sets containing elements to collections of objects with morphisms. However, some of the ideas here have yet to be generalised into this movement.

Endomorphism

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

// uppercase :: &str -> String
let uppercase = |x: &str| x.to_uppercase();

// decrement :: i32 -> i32
let decrement = |x: i32| x - 1;

Isomorphism

A pair of transformations between 2 types of objects that is invertible.

For example, 2D coordinates could be stored as a i32 vector [2,3] or a struct {x: 2, y: 3}.

#[derive(PartialEq, Debug)]
struct Coords {
    x: i32,
    y: i32,
}

let pair_to_coords = | pair: (i32, i32) | Coords { x: pair.0, y: pair.1 };
let coords_to_pair = | coords: Coords | (coords.x, coords.y);
assert_eq!(
    pair_to_coords((1, 2)),
    Coords { x: 1, y: 2 },
); // passes
assert_eq!(
    coords_to_pair(Coords { x: 1, y: 2 }),
    (1, 2),
); // passes

Isomorphisms are critical in making structures identical. Since we know that the struct above is identical to a pair, all the functions that exist on the pair can exist on the struct. If f is the isomorphism and g and endomorphism on the codomain: f^{-1} g f would extend g to apply on the domain.

Homomorphism

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

assert_eq!(A::of(f).ap(A::of(x)), A::of(f(x))); // passes
assert_eq!(
    Either::of(|x: &str| x.to_uppercase(x)).ap(Either::of("oreos")),
    Either::of("oreos".to_uppercase),
); // passes

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.

let sum = |xs: Vec<i32>| xs.iter().fold(0, |mut sum, &val| { sum += val; sum });

assert_eq!(sum(vec![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.

let count_down = unfold((8_u32, 1_u32), |state| {
    let (ref mut x1, ref mut x2) = *state;

    if *x1 == 0 {
        return None;
    }

    let next = *x1 - *x2;
    let ret = *x1;
    *x1 = next;

    Some(ret)
});

assert_eq!(
    count_down.collect::<Vec<u32>>(),
    vec![8, 7, 6, 5, 4, 3, 2, 1],
);

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

This is a set with an equivalence relation.

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

  1. a.equals(a) == true (reflexivity)
  2. a.equals(b) == b.equals(a) (symmetry)
  3. a.equals(b) and b.equals(c) then a.equals(c) (transitivity)

Make a Vector a setoid:

Note that I am treating Self / self like a.

trait Setoid {
    fn equals(&self, other: &Self) -> bool;
}

impl Setoid for Vec<i32> {
    fn equals(&self, other: &Self) -> bool {
        self.len() == other.len()
    }
}

assert_eq!(vec![1, 2].equals(&vec![1, 2]), true); // passes

In Rust standard library, it already provides Eq, which resembles Setoid that was discussed in this section. Also Eq has equals implementations that covers a range of data structures that already exist in Rust.

Ord

An object or value that implements Ord specification, also implements Setoid specification.

The Ord object or value must satisfy below rules for all a, b or c:

  1. totality: a <= b or b <= a
  2. antisymmetric: a <= b and b <= a, then a == b
  3. transivity: a <= b and b <= c, then a <= c

Rust documentation for Ord can be found here Ord

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

  1. a.add(b).add(c) is equivalent to a.add(b.add(c)) (associativity)
use std::ops::Add;

pub trait Semigroup: Add {
}

assert_eq!(
    vec![1, 2].add(&vec![3, 4]),
    vec![1, 2, 3, 4],
); // passes

assert_eq!(
    a.add(&b).add(&c),
    a.add(&b.add(&c)),
); // passes

Foldable

An object that has a foldr/l function that can transform that object into some other type.

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 fp_core::foldable::*;

let k = vec![1, 2, 3];
let result = k.reduce(0, |i, acc| i + acc);
assert_eq!(result, 6);

If you were to implement Foldable manually, the trait of it would look like below

use crate::hkt::HKT;
use crate::monoid::Monoid;

pub trait Foldable: HKT {
    fn reduce(b: B, ba: F) -> <Self as HKT>::Target
    where
        F: FnOnce(B, A) -> (B, B);

    fn fold_map(m: M, fa: F) -> M
    where
        M: Monoid,
        F: FnOnce(<Self as HKT>::URI) -> M;

    fn reduce_right(b: B, f: F) -> <Self as HKT>::Target
    where
        F: FnOnce(A, B) -> (B, B);
}

Lens

A lens is a type that pairs a getter and a non-mutating setter for some other data structure.

trait Lens {
    fn over(s: &S, f: &Fn(Option<&A>) -> A) -> S {
        let result: A = f(Self::get(s));
        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,
}

#[derive(Debug)]
struct PersonNameLens;

impl LensString> for PersonNameLens {
    fn get(s: &Person) -> Option<&String> {
       Some(&s.name)
    }

    fn set(a: String, s: &Person) -> Person {
        Person {
            name: a,
        }
    }
}

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

| { match x { Some(y) => y.to_uppercase(), None => panic!("T_T") // lol... } }); assert_eq!(*name.unwrap(), e1.name); // passes assert_eq!(e2, expected); // passes assert_eq!(e3, Person { name: "JASON".to_string() }); // passes ">
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...
    }
});

assert_eq!(*name.unwrap(), e1.name); // passes
assert_eq!(e2, expected); // passes
assert_eq!(e3, Person { name: "JASON".to_string() }); // passes

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.

// add :: i32 -> i32 -> i32
fn add(x: i32) -> impl Fn(i32)-> i32 {
    move |y| x + y
}

// increment :: i32 -> i32
fn increment(x: i32) -> i32 {
    x + 1
}

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

// call :: (a -> b) -> a -> b
fn call(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
    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(f: &Fn(A) -> B) -> impl Fn(A) -> B + '_ {
    move |x| f(x)
}

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 represent sum in ADT.

enum WeakLogicValues {
   True(bool),
   False(bool),
   HalfTrue(bool),
}
// WeakLogicValues = bool + otherbool + anotherbool

Product Type

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.

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.

>) -> Option<&HashMap> { cart.get("item") } fn get_price(item: &HashMap) -> Option<&i32> { item.get("price") } ">
let mut cart = HashMap::new();
let mut item = HashMap::new();
item.insert(
    "price".to_string(),
    12
);
cart.insert(
    "item".to_string(),
    item,
);

fn get_item(cart: &HashMap<String, HashMap<String, i32>>) -> Option<&HashMap<String, i32>> {
    cart.get("item")
}

fn get_price(item: &HashMap<String, i32>) -> Option<&i32> {
    item.get("price")
}

Use and_then or map to sequence functions that return Options

fn get_nested_price(cart: &HashMap<String, HashMap<String, i32>>) -> Option<&i32> {
    return get_item(cart).and_then(get_price);
}

let price = get_nested_price(&cart);

match price {
    Some(v) => assert_eq!(v, &12),
    None => panic!("T_T"),
}

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

Functional Programming references

Functional Programming development in Rust Language

Inspiration

As a community, we have chosen our value as "learn by teaching". We want to share our knowledge with the world while we are learning.

Comments
  • citation source needed

    citation source needed

    Why not mention you are drawing the contents of the jargon from https://github.com/hemanth/functional-programming-jargon? This some else's writing and should be credited.

    opened by epogrebnyak 4
  • Feature request:: add fold to Monoid

    Feature request:: add fold to Monoid

    One nice thing for Monoids is that we can call a fold directly on a monoidal structure without needing to specify the empty element manually when calling fold. It might be nice to have this added in as a trait method for monoid.

    opened by bbarker 2
  • Support Result<T,_> in a way similar to Option<T>.

    Support Result in a way similar to Option.

    On similar "functional programming adaptation projects" I have seen Option types where the None branch actually carries a value and is used to describe errors.

    An example is fp-ts for Typescript.

    This is exactly what the Rust Result type does, so I added support for it handling it just like Option.

    This can be useful to chain computations on the "happy path", like when chaining and_then calls.

    opened by massimiliano-mantione 2
  • Massive issues with naming convention for generics throughout fp-core

    Massive issues with naming convention for generics throughout fp-core

    The aim of this ticket is to come up with a standard for naming convention used for generics throughout fp-core.

    Right now we are facing major issues with this and it eventually leads to incorrect type class signatures.

    For example, I came up with below signature for traverse

    trait Traverse<A, B, F, G>: HKT<G, B> + HKT3<G, F, B> + Applicative<A, F, B> {
        fn traverse<FB>(&self, f: FB) -> <Self as HKT3<G, F, B>>::Target2
        where
            FB: FnOnce(A) -> <Self as HKT<G, B>>::Target;
    }
    

    G here is used for Applicative and F is for Functor. However, due to the nature of Rust, which requires you to pass-through generics to its children, F in Apply is currently used for f (mappable) and it is already incorrect.

    The ticket aims to standardise this process and come up with rules around generic name usage.

    bug help wanted 
    opened by JasonShin 2
  • Semigroup, tweaks HKT, removes type parameters

    Semigroup, tweaks HKT, removes type parameters

    Specifically, I did the following:

    • Added a semigroup trait
    • Made HKT not have the Current type as an extra generic parameter.
    • Propagated the above change to remove various generic parameters in things that depend on HKT.
    • Fixed impl Pure<A> for Option<A> and Pure<A> itself.
    • Fixed foldable (Vec is a HKT now, so there's a concrete instance for us to play with).

    What was wrong with:

    • HKT: nothing technical, I think. It was just really really confusing, so re-reading the gist from the readme led me to the current notion. The point is to store the currently contained type and a way to produce a container for the extra type (B in HKT<B>). The names make a lot more sense and implementing it is very straight-forward. The only current quirk is documented in a comment on Foldable: in essence, we don't neatly just say "this type contains another type": we still insist that "this type contains some Current and can be converted to Target". We now have what I might call the "A B B A idiom" dotting the code: impl<A, B> ___<B> for ___<A> (where ___<A>: HKT<B>). This arises so that we can access both the type we want to convert to (HKT<B>::Target) and the type we're starting with (HKT<B>::Current which seems to always be A).
    • Pure: the type was off: Self<A> -> Self<A> was apparently what the type implied, but we really wanted a A -> Self<A>. This might be because HKT was harder to reason about. The discrepancy should be made clear in the instance for Option: originally, there was nothing especially default-y about it, we just had an identity (None.pure(), for example, should not exist, but Option::pure(3) should be Some(3)).
    • Foldable: It's just that fold_map made a big mess, so I moved it out of the trait (it's easy to just implement for any Foldable<M> where M: Monoid). Also, adding an instance for Vec was eye-opening: FnOnce is very wrong for folding since folding expressly calls the closure more than once. This will have to be fixed everywhere a FnOnce is used: we might as well just use a Fn or discuss the correct trait further.
    opened by hemangandhi 2
  • Monoid -> Semigroup -> Magma refactor

    Monoid -> Semigroup -> Magma refactor

    I think we've reached the point where we need to do a proper refactoring around Monoid, Semigroup and Magma.

    As a result of introducing the initial baseline for traverse (https://github.com/JasonShin/fp-core.rs/blob/feature%2Ftraverse/fp-core/src/traverse.rs), we need to deal with data structures such as Vectors.

    The current algebraic data structure implementations are not scalable, it's already very difficult to extend it to work with Vectors or even HashMap.

    The goal of this ticket is to come up with a more scalable alternative to abovementioned data structures and adapt it into the existing type classes that rely on them, pretty much everything that we have built so far.

    Ideally, we should structure it so it resembles https://github.com/freebroccolo/algebra.rs

    Also, think about the possibility of integrating im.rs for parallelism

    Goals:

    • Traverse should work with the new data structures and should have an example code that traverses

    vec![Some(1), Some(2), Some(3)] with fa of |x| x + 1 and returns Some(vec![2, 3, 4])

    help wanted 
    opened by JasonShin 1
  • Category theory cleanup

    Category theory cleanup

    Some more examples/description on the category theory.

    I do intend to move some stuff around if possible. Particularly, a discussion of these might help:

    • initial and terminal objects
    • products
    • duality
    • adjunctions

    I have a branch with some of those that I can try to merge in later.

    I'm not sure if my mention of monoidal categories would close #9 Also, I think #14 can be closed?

    opened by hemangandhi 1
  • Continuation

    Continuation

    Add continuation

    References: https://github.com/hemanth/functional-programming-jargon#continuation https://github.com/ikhoon/functional-programming-jargon.scala#continuation

    Example help wanted Description 
    opened by JasonShin 1
  • Lightweight Higher Kinded Types

    Lightweight Higher Kinded Types

    Rust does not natively support HKT. Instead, we should use lightweight HKT as a replacement.

    https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf

    Example help wanted Description 
    opened by JasonShin 1
  • lifetime

    lifetime

    The lifetime here seem very restrictive

    https://github.com/JasonShin/fp-core.rs/blob/4564c429f2ebc89a810f3e064f7db5e76ac68f6e/fp-core/src/semigroup.rs#L2

    Shouldn't that be more something like

    fn combine(self, other: &Self) -> Self;

    opened by nrolland 1
  • Where is the Currying implementation?

    Where is the Currying implementation?

    Currying is a fundamental feature and it's talked about in the README.md but I couldn't find any implementation -- as opposed to a single example -- of it in the actual lib. This looks like a missing feature.

    Any plan on adding it?

    opened by why-not-try-calmer 2
Owner
Jason Shin
Node, Python, Rust, Machine Learning, Functional Programming, React, Vue, Kubernetes and Scala.
Jason Shin
luau bindings for the Rust programming language

?? luau-rs Luau bindings for the Rust programming language using bindgen ⚠️ Disclaimer This does not provide bindings for everything as luau does not

Vurv 18 Aug 3, 2022
Czech for the Rust programming language

rez Nejsi you tired from writing Rust programs in English? Do you like saying do prdele or pivo a lot? Would you like to try something different, in a

Radek Vít 13 Oct 9, 2022
The official home of the Nyson Programming Language, built off Rust.

Nyson Programming Language The official home of the Nyson Programming Language, built off Rust. (created by Nyelsonon and AMTitan, 2021) Advertisement

Nyson-Programing-Language 19 Aug 10, 2022
A simple programming language made for scripting inspired on rust and javascript.

FnXY Programming Language Quick move: CONTRIBUTING | LICENSE What? FnXY is a simple programming language made for scripting inspired on rust and javas

null 2 Nov 27, 2021
A programming environment that aims to help people learn how to program in JavaScript, while giving them a tour on how old computers and their limitations used to be.

This repository is for the new under renovation rewrite of the LIKO-12 project. The legacy version with the original stars and contributions is still

null 1k Jan 5, 2023
An OOP programming language I am making by following Crafting Interpreters.

horba An OOP programming language I am making by following Crafting Interpreters. https://craftinginterpreters.com/ I intend it to have a somewhat C-s

Thomas 3 Dec 5, 2021
Yet Another Programming Language

Yet Another Programming Language

null 4 Sep 15, 2021
The programming language for scalable development

Pen programming language Pen is the programming language that makes software development scalable, focusing on software maintainability and portabilit

Pen programming language 390 Dec 30, 2022
A newborn programming language for extensible software

A newborn programming language for extensible software.

Alexey Shmalko 17 Nov 29, 2022
A multithreaded programming language!

hydracane A multithreaded programming language! Getting started Coming Soon! Features: Multithreaded Platform independent Folders: src/vm: The Virtual

Krishna Ramasimha 0 Dec 10, 2021
CARBON is an interface-centric programming language named after the concept of an allotropy.

CARBON programming language Status: just an idea CARBON is an interface-centric programming language named after the concept of an allotropy. It is an

Tim McNamara 4 Aug 18, 2022
Lisp-style programming language

Bobbylisp A programming language, syntax are like mal and clojure. This project follow mal guides, Planning to add some more features after finishing

azur 36 Dec 19, 2022
An interpreter for the esoteric programming language, Brainf*ck.

Brainf*ck Interpreter This is just a normal Brainf*ck interpreter written in Rust. If you don't know what Brainf*ck is, you can check out the wikipedi

Callum Irving 0 Dec 23, 2021
Pua-lang - a dialect of The Monkey Programming Language

pua-lang PUA Programming Language written in Rust. What's pua-lang? pua-lang is a dialect of The Monkey Programming Language, intended to mirror the i

flaneur 3.2k Jan 6, 2023
The Fluet programming language.

fluet Fluet is a scripting language. License Fluet is licensed under the Mozilla Public License, v. 2.0. Contributors may dual license their contribut

null 11 May 4, 2022
Ethereal - a general-purpose programming language that is designed to be fast and simple

Ethereal is a general-purpose programming language that is designed to be fast and simple. Heavly inspired by Monkey and written in Rust

Synthesized Infinity 21 Nov 25, 2022
Dc improved: Feature-added rewrite of a 50+ year old RPN calculator/stack machine/programming language

dcim [WIP] dc improved: Feature-added rewrite of a 50+ year old RPN calculator/stack machine/programming language This readme is currently incomplete.

null 3 Jun 18, 2022
Squirt is a easy-to-use programming language.

Squirt is a easy-to-use programming language.

QuqqU 5 Nov 30, 2022
Osmon's compiler crate. Programming language made for starter & novice Uzbek audience.

Osmon Tili Osmon bu registrlarga asoslangan virtual mashinalik va yengil dasturlash tili Osmon boshqa o'zbek open source dasturchisi Sukhrob Khakimovn

Osmon 31 Dec 22, 2022