## Simple algebraic data types

1 year, 4 months ago
*It is the sixth article from the cycle "The Category Theory for Programmers". The previous articles were already published on Habré:*

0. The category theory for programmers: preface

1. Category: composition essence

2. Types and functions

3. Categories, big and small

4. Kleysli's categories

5. Works and koproizvedeniye

In the previous article basic operations over types were considered: work and koproizvedeniye. Now we will show that the combination of these mechanisms allows to construct many of daily data structures. Such creation has essential applied relevance. For example, if we are able to check base data types for equality, and also we know how to reduce equality of work and a koproizvedeniye to equality a component, then operators of equality for composite types it is possible to display automatically. In Haskell for an extensive subset of composite types operators of equality and comparison, converting at line and back and many other operations are automatically brought.

Let's consider in more detail the place of work and a koproizvedeniye of types in programming.

## Work of types

Canonical implementation of work of types in programming languages is a couple. In Haskell of steam is a primitive designer of types, and in C ++ it is rather difficult template from standard library.

Strictly speaking, work of types is not commutative: it is impossible to substitute couple of type `(Int, Bool)`

instead of `(Bool, Int)`

, though they also contain the same data. However work is commutative to within the isomorphism set by function `swap`

, which back to:

```
swap :: (a, b) -> (b, a)
swap (x, y) = (y, x)
```

It is possible to consider such couples as different formats of storage of the same information as big endian and little endian.

Read more »

## Multiplication by a method of the Russian peasants

1 year, 4 months ago
Sometimes this method call "country multiplication", sometimes "Ancient Egyptian", sometimes "Ethiopian", sometimes "multiplication through doubling and halving". Some it is well-known, some – is unclear, but at the same time it is rather useful and can be used not only for multiplication, but also for exponentiation and calculations of matrixes.

#### Algorithm

```
13 x 19 -> 0
6 38 19
3 76 ->
1 152 -> 95
0 304 247
^^^
```

Let's write two multiplied numbers nearby – they will become headings of two columns. The third column will contain the increasing sum.

If number in the left column odd, we add number from the right column to the increasing sum. Initially it will be equal to zero.

Then in the left column below we write number from heading, divided in half (with discarding of a remaining balance). 13 / 2 = 6. And in the second column we write the number equal to doubling of column heading, 19*2 = 38.

As number in the left column even, we do not increase the increasing sum.

Read more »