How to resolve the algorithm Accumulator factory step by step in the Elixir programming language
How to resolve the algorithm Accumulator factory step by step in the Elixir programming language
Table of Contents
Problem Statement
A problem posed by Paul Graham is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in small italic text).
Create a function that implements the described rules.
It need not handle any special error cases not described above. The simplest way to implement the task as described is typically to use a closure, providing the language supports them. Where it is not possible to hold exactly to the constraints above, describe the deviations.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Accumulator factory step by step in the Elixir programming language
Source code in the elixir programming language
defmodule AccumulatorFactory do
def new(initial) do
{:ok, pid} = Agent.start_link(fn() -> initial end)
fn (a) ->
Agent.get_and_update(pid, fn(old) -> {a + old, a + old} end)
end
end
end
ExUnit.start
defmodule AccumulatorFactoryTest do
use ExUnit.Case
test "Accumulator basic function" do
foo = AccumulatorFactory.new(1)
foo.(5)
bar = AccumulatorFactory.new(3)
assert bar.(4) == 7
assert foo.(2.3) == 8.3
end
end
You may also check:How to resolve the algorithm Last letter-first letter step by step in the BaCon programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the YAMLScript programming language
You may also check:How to resolve the algorithm Koch curve step by step in the Julia programming language
You may also check:How to resolve the algorithm Pascal's triangle step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Problem of Apollonius step by step in the Tcl programming language