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

Published on 12 May 2024 09:40 PM

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

Source code in the smalltalk programming language

Object subclass: AccumulatorFactory [
  AccumulatorFactory class >> new: aNumber [
    |r sum|
    sum := aNumber.
    r := [ :a |
           sum := sum +  a.
           sum
         ].
    ^r
  ]
]

|x y|
x := AccumulatorFactory new: 1.
x value: 5.
y := AccumulatorFactory new: 3.
(x value: 2.3) displayNl.
"x inspect."
"de-comment the previous line to show that x is a block closure"

|factory accu1 accu2|

factory := [:initial |
    [
        |sum|

        sum := initial.
        [:addend | sum := sum + addend].
    ] value.
].

accu1 := factory value:1.
accu1 value:5.
accu2 := factory value:10.
accu2 value:5.
(accu1 value:2.3) printCR.  "-> 8.3 (a float)"
(accu2 value:0) printCR.    "-> 15 (an integer)"
(accu2 value:22 factorial) printCR.    "-> a large integer"

  

You may also check:How to resolve the algorithm Harmonic series step by step in the Wren programming language
You may also check:How to resolve the algorithm Evolutionary algorithm step by step in the MATLAB programming language
You may also check:How to resolve the algorithm Jewels and stones step by step in the Delphi programming language
You may also check:How to resolve the algorithm Polyspiral step by step in the C programming language
You may also check:How to resolve the algorithm Detect division by zero step by step in the Eiffel programming language