Russian Peasant Multiplication — with Elixir — Part 5
If you have followed my past articles, part 1, part 2, part 3, part 4 you would have known by now that we have been building this application in small increments.
We have been using recursion, higher order function and closures. Also we used MonandEx
to use Monad.Result
struct to have a unified object across our applications.
Now it is time for the last piece before we stitch them all together.
In this article we are going to create sum
. As usual you can use Enum.sum
. Well I am not going to do that just because I want to do more stuff with it. Also it is cooler to write our own.
Test
defmodule RussianPeasantMultiplication.SumTest do
use ExUnit.Case
doctest RussianPeasantMultiplication.Sum
end
Code
As usual we are using Monad.Result
in order to be able to use success/1
and error/1
Again I am using a simple recursion on line 20
Creating the state at line 30
on line 31
I am using closure to create a new state.
This way I can keep my pipe line more readable and hide the calculation in a function.
line 36
we are wrapping all into another success/1
function.
to use this:
RussianPeasantMultiplication.Sum.sum_of([238, 952, 1904])
3094
This was very easy and straight forward. It could have been even simpler.
Anyway, I think it should be enough for now.
In the next article we will stitch everything together and will look after our Technical debt (one in particular)
Enjoy, stay safe and happy coding!