How to resolve the algorithm Accumulator factory step by step in the 8th programming language
How to resolve the algorithm Accumulator factory step by step in the 8th 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 8th programming language
Source code in the 8th programming language
\ RossetaCode 'accumulator factory'
\ The 'accumulate' word stores the accumulated value in an array, because arrays
\ are mutable:
: accumulate \ n [m] -- n+m \ [m] -> [n+m]
a:pop rot n:+
tuck a:push swap ;
\ To comply with the rules, this takes a number and wraps it in an array, and
\ then curries it. Since 'curry:' is "immediate", we need to postpone its
\ action using 'p:.
: make-accumulator
1 a:close
' accumulate
p: curry: ;
\ We 'curry' the initial value along with 'accumulate' to create
\ a new word, '+10', which will give us the accumulated values
10 make-accumulator +10
\ This loop will add 1, then 2, then 3, to the accumulator, which prints the
\ results 11,13,16:
( +10 . cr ) 1 3 loop
bye
You may also check:How to resolve the algorithm Logical operations step by step in the AWK programming language
You may also check:How to resolve the algorithm Empty string step by step in the CoffeeScript programming language
You may also check:How to resolve the algorithm Walk a directory/Non-recursively step by step in the Gambas programming language
You may also check:How to resolve the algorithm Address of a variable step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the GAP programming language