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

Published on 12 May 2024 09:40 PM

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

Source code in the quackery programming language

  [ tuck tally share ]this[ swap ] is accumulate ( n s --> [ n )

  [ [ stack ] copy tuck put nested 
    ' accumulate nested join ]     is factory    (   n --> [   )

  [ dip
      [ -1 split dup [] = if
          [ $ "accumulator needs a starting value."
            message put bail ]
        do dup number? not if
          [ $ "accumulator needs a number."
            message put bail ]
        [ stack ] copy 
        tuck put nested
        ' [ tuck tally share ]
        join nested join ] ]   builds accumulator ( [ $ --> [ $ )

  

You may also check:How to resolve the algorithm Test a function step by step in the Tcl programming language
You may also check:How to resolve the algorithm Bitmap/Flood fill step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Last Friday of each month step by step in the Python programming language
You may also check:How to resolve the algorithm Averages/Mean angle step by step in the Tcl programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the Io programming language