A lot of time without new blog posts. Fortunately found a time to write about an interesting thing for me. Currently, I’m trying to refresh my math skills and reading some math books. It is always interesting to start from the base things and try to rethink them from the other point of view. So, I started to think about zero and sum and other basic things in terms of programming. And this blog post is an experiment to write about math and replace formulas with programs.

Let’s start with the number. Initially, we have only nothing(zero) and to count something we need to have something nonzero. We are like Hegel now :-). And we need a way to combine things together and express any natural number even infinity.

We could use the idea of lazy lists but without values.

Additionally, we need two additional helper functions. You will see later why we need them.

Now we need to express basic functions to work with our numbers like increment, decrement, printing, and translating into int numbers. But actually, we could use fold and unfold to express them. The fold function will iterate a number and create an aggregate. Unfold function will generate a number from some state.

Now we are ready to start with arithmetic. But even a simple decrement from zero is not supported in our numbers. We need to return an optional answer in case of unsupported operation. Probably in future we will add support for negative numbers, maybe with zippers or something like that.

We are ready for addition and subtraction. One interesting thing to note, I expected to see unfold in subtraction, but it is fold, probably because of unsupported negative numbers. We can see sum as an increment in a for loop. And minus to find the argument of the sum function with a given result and argument. And we don’t need two functions because addition is commutative. So “swap sum” function is equal to sum.

Now we are ready for more advanced functions and they look interesting, we can see some patterns. Unfortunately, we do not support rational numbers so we implement division as a function that will return how many times (rounded to integer) numerator contains denominator.

It was fun to see that arithmetic looks so interesting in a functional manner.

The next steps will be to support all real numbers (including irrational) and root function.

One interesting thing is about div by zero. If we divide any number (even zero) by zero, we will have an infinite sequence as a result. It is a great start to check different kinds of infinity and to add infinity detector into fold, unfold functions. For example, we can keep the whole history of a state and try to find a current state in the state history. And extend our number with Infinity case. We will be able to express rational numbers. Unfortunately, it will not work for irrational numbers but who knows about other ways to check for infinity. Probably we can express them as a continued fraction.

Math is fun.