Russian Peasant Multiplication — with Elixir — Part 2
Glad to see you back here :)
In Part 1 we worked through the Decrement recursion.
iex> RussianPeasantMultiplication.Decrement.decrement(13) |> unwrap!
[13, 6, 3, 1]
Also if you remember, we are pushing number in Decrement and getting a Monad.Result
struct back. It is not a good practice as we want to keep things as pure as we can and we want Monad helps us by managing the side effects better and we have a unified structure across our application.
Increment — recursion with boundaries
Test
Now, the increment.
Ok, let’t walk through the code.
Same as Decrement
module, Increment
uses the same approach with a bit more checks and a new feature.
We are using a boundary. This is where we confine our recursion by an external factor.
Pay attention to max_round
.
In the test I imported Monad.Result
to use our unified structural system.
We basically want to increment the second number by 2. The number of time we increment it will be equal to the number of time our first number decremented in part 1 (hence the max_number
).
From line 26
to line 29
I am using guard
it is a bit ugly. Later on you will see that we will be using custom guard
to keep things cleaner.
Again in line 31
you don’t need to code like this as it will add extra layer of complexity. I like to keep my initial variables in the pipeline clean so line 34
to line 36
are telling us the story without anything extra added to them.
line 44
is where we are creating the state, so line 44
to line 47
can be extracted into its own little function. I left it there just because I am lazy :)
I have extracted line 42
for one simple reason. There is a chance that I change this function, so I have extracted in its own function.
iex> alias RussianPeasantMultiplication.Increment, as: RPM_Inc
RussianPeasantMultiplication.Increment
iex> result = RPM_Inc.increment(238, 4)
iex> unwrap!(result)
[238, 476, 952, 1904]
(remember our technical debt)
we will pay the price at the very end. For now all good :)
Hope it all make sense :)
In the next article we will work on Higher order function.
Stay Tune!