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:

- Non-empty set A (called
**domain**), - Collection of (usually binary) operations (with specified type signature) on A
- 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:

- If
*u *is a Functor then calling *u.map( x => x)* must be *u.* (**Identity Law**) - 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.

### Like this:

Like Loading...

*Related*

## Published by Raghav

A passionate technologist who has worked with a vast number of technologies, and yet still retain the same passion and drive for learning new things as I did when I took my first programming class in college
View all posts by Raghav