Russian Peasant Multiplication — with Elixir — Part 4
In this article we will be working on Higher order function with statements. We want to explore how to encapsulate all the mess that a function deals with inside a box and pass it around.
If you have followed part 1, part 2, part 3 by now you would know what we are doing and how are we tackling this problem.
We have decrement, increment, combine and now we need filter. Last time we ended up with with this:
[{13, 238}, {6, 476}, {3, 952}, {1, 1904}]
We need to loop through this list, if the first number is even then we need to remove it and return a list of second numbers. We need to end up with something like this:
[238, 952, 1904]
As you can see we can do this with Enum.filter
easily. With Enum.filter
we push a higher order function and then we pipe the result into an Enum.map
where we can patten match and return our list (not fun :) and too easy.
Test
defmodule RussianPeasantMultiplication.FilterTest do
use ExUnit.Case
doctest RussianPeasantMultiplication.Filter
end
Code
As usual we are using Monad.Result
to keep things the same across our applications.
line 34
We are using we are creating a function to pattern match and remove the even number if the first number in our tuple is even.
Then we start the recursion. Again in line 50
we are creating our own concat/2
version. It will unwrap!/1
our Monad.Result
and update the state.
line 54
you can make your own concat
where add new item to your list, however to keep things short I used Enum.concat
Run the test and it should pass.
I think this should do it for now. Tune in to next for the last piece of the puzzle where we create a simple sum
with recursion.
Technical Debt
We still got our 2 technical debt remains. We should be able to look after them in later date.
Cheers.