How to resolve the algorithm Accumulator factory step by step in the Golo programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Accumulator factory step by step in the Golo 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 Golo programming language

Source code in the golo programming language

#!/usr/bin/env golosh
----
An accumulator factory example for Rosetta Code.
This one uses the box function to create an AtomicReference.
----
module rosetta.AccumulatorFactory

function accumulator = |n| {
  let number = box(n)
  return |i| -> number: accumulateAndGet(i, |a, b| -> a + b)
}

function main = |args| {
  let acc = accumulator(3)
  println(acc(1))
  println(acc(1.1))
  println(acc(10))
  println(acc(100.101))
}


  

You may also check:How to resolve the algorithm MD5 step by step in the Fortran programming language
You may also check:How to resolve the algorithm Arithmetic evaluation step by step in the Oz programming language
You may also check:How to resolve the algorithm Ormiston triples step by step in the Phix programming language
You may also check:How to resolve the algorithm Ruth-Aaron numbers step by step in the Pascal programming language
You may also check:How to resolve the algorithm Define a primitive data type step by step in the jq programming language