Skip to content

Instantly share code, notes, and snippets.

@natalie-o-perret
Last active February 18, 2019 22:07
Show Gist options
  • Save natalie-o-perret/122ffa6c6e7e718fa5cde12a985c9386 to your computer and use it in GitHub Desktop.
Save natalie-o-perret/122ffa6c6e7e718fa5cde12a985c9386 to your computer and use it in GitHub Desktop.
Functional Programming Concepts

Algebraic structures groups

Monoids

Function that operates on a data type (or set)

Laws:

  • Associative, eg. 2 + 3 <=> 3 + 2
  • Binary Operations, eg. public static Foo Op(Foo x, Foo y)
  • With a neutral element (identity), eg. 2 + 3 + 0 <=> 3 + 2 + 0

Examples:

  • Maybe
  • Endomorphism
  • Tuple
  • Either

Semigroups

Laws:

  • Binary Operation
  • Associative
  • No identity required

Examples:

  • Min / Max
  • First / Last
  • Aggregation

Quasigroup

Laws:

  • Inversion
  • No associativity required
  • No identity required

Example: substraction

Magmas

Law: binary operation with no constraints on its behaviour

Examples:

  • Rock, paper, scissors
  • Colour Mixing

Category Theory

Category

Collection of objects / points with morphisms (ie. functions, transformations) between them:

  • f: a -> b
  • g: b -> c
  • g.f: a -> c

Btw, composition is associative: h.(g.f) = (h.g).f

Functors

A functor F is a mapping between 2 categories, not only between their objects but also between their morphisms.

Laws:

  • f: a -> b
  • F(f): F(a) -> F(b)

Endofunctors

Functor from a category to itself.

Monad

Monoids in the category of endofunctors


Ok cool but what does it mean for C#?

Basically a monad in the C# context, is a type that gives some additional features to an 1-ary generic type T.

Examples:

  • IEnumerable<T>: gives T non-determinism (multiple values)
  • Nullable<T>: gives T nullability
  • Task<T>: gives T asynchronicity

To resp. play with them and get the inner value:

  • LINQ
  • ?? or GetValue
  • await

In other languages like F# or Haskell, you could define two methods to create a new monad, in C# it would look like:

  • public static Monad<T> Return<T>(T value)
  • public static Monad<U> Bind<T, U>(Monad<T> value, Func<T, Monad<U>> operation)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment