Functional Programming in scala

If you are coming from imperative programming language background like C/C++/Java, you need to understand the concepts of functional programming to appreciate Type classes. The problem with typical Functional Programming literature is it is too terse and keep on referring Category Theory time to time. I wish someone could have explained these concepts in simple terms to me to get me started on this.

You need to learn the design patterns (besides programming language syntax) to write good software. Design patterns have been evolved based on observations over time to solve an abstract problem. For example, Singleton is a well established solution when exactly one object is needed to coordinate actions across the system.

In functional programming paradigm, Algebraic structures are equivalent to design patterns of imperative world. Type classes are just a way to implement algebraic structures. This is the key to understand the rationale behind type classes. As opposed to design patterns algebraic structures are based on mathematical theory and that’s why they have very tight specification. Examples of such algebraic structures are Applicative, Functor, Monoid, Monad etc.

As per wikipedia, Algebraic structure consists of:

  1. Non-empty set A (called domain),
  2. Collection of (usually binary) operations (with specified type signature) on A
  3. Finite set of laws (called axioms) that these operations must satisfy.

Sometimes such a set A (with operations) is referred as algebra.

Let’s take example of such algebraic structure Functor.

trait Functor[F[_], A] {
  def map[B](f: A => B): F[B]
}

In the example above map function has to satisfy the following laws:

  1. If u is a Functor then calling u.map( x => x) must be u. (Identity Law)
  2. If u is a Functor, and f and g are pure functions, then u.map(g).map(f) = u.map(x => f(g(x)). (Composition Law)

Type classes, in scala, are just group of types that satisfy a contract typically defined by a trait.

You may like to see Part II and Part III of functional programming series.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s