Created
March 31, 2020 06:38
-
-
Save houmanka/399e5ab46f58797b6a1875cadad506ff to your computer and use it in GitHub Desktop.
RussianPeasantMultiplication.Sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule RussianPeasantMultiplication.Sum do | |
import Monad.Result | |
@doc """ | |
Accepts a list and return sum of the numbers | |
### Examples | |
iex> import Monad.Result | |
iex> alias RussianPeasantMultiplication.Sum, as: RPM_Sum | |
RussianPeasantMultiplication.Sum | |
iex> result = RPM_Sum.sum_of([238, 952, 1904]) | |
iex> unwrap!(result) | |
3094 | |
""" | |
def sum_of([head | tail]) do | |
sum_of(tail, success(head) ) | |
end | |
def sum_of([], state), do: state | |
def sum_of([head | tail], state) do | |
new_state = head |> sum(state) | |
sum_of(tail, new_state) | |
end | |
defp sum(num, state) do | |
sum = fn(state) -> num + state end | |
state | |
|> unwrap!() | |
|> sum.() | |
|> success() | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment