Accumulator factory: Difference between revisions
Content added Content deleted
(add BQN) |
(Added Quackery.) |
||
Line 2,903: | Line 2,903: | ||
<pre><generator object accumulator at 0x106555e60> |
<pre><generator object accumulator at 0x106555e60> |
||
8.3</pre> |
8.3</pre> |
||
=={{header|Quackery}}== |
|||
Quackery is untyped. This solution works with bignums. <code>factory</code> returns a lambda function. (In Quackery terminology, it leaves a nest on the stack.) Nests on the stack are performed (i.e. executed or evaluated) with <code>do</code>. |
|||
<lang Quackery> [ tuck tally share ]this[ swap ] is accumulate ( n s --> [ n ) |
|||
[ [ stack ] copy tuck put nested |
|||
' accumulate nested join ] is factory ( n --> [ )</lang> |
|||
{{out}} |
|||
Let's see this in action in the Quackery shell. |
|||
<pre>/O> 23 factory |
|||
... |
|||
Stack: [ [ stack 23 ] accumulate ] |
|||
</pre> |
|||
<code>23 factory</code> has returned an accumulator function initialised to <code>23</code>. |
|||
Now let's put <code>100</code> underneath it using <code>swap</code>, perform the accumulator using <code>do</code> and then print the top of stack using <code>echo</code>. |
|||
<pre>/O> 100 swap do echo |
|||
... |
|||
123 |
|||
Stack: [ [ stack 123 ] accumulate ] |
|||
</pre> |
|||
The running total has been printed, and there is an updated version of the accumulator function on the stack. |
|||
Now let's create a second accumulator function with <code>factory</code> and confirm that the two accumulator functions behave independently of one another by <code>do</code>-ing first one of them, then the other. |
|||
<pre>/O> 1000000 factory |
|||
... |
|||
Stack: [ [ stack 123 ] accumulate ] [ [ stack 1000000 ] accumulate ] |
|||
/O> 234567 swap do echo |
|||
... |
|||
1234567 |
|||
Stack: [ [ stack 123 ] accumulate ] [ [ stack 1234567 ] accumulate ] |
|||
/O> swap |
|||
... |
|||
Stack: [ [ stack 1234567 ] accumulate ] [ [ stack 123 ] accumulate ] |
|||
/O> 123 swap do echo |
|||
... |
|||
246 |
|||
Stack: [ [ stack 1234567 ] accumulate ] [ [ stack 246 ] accumulate ] |
|||
</pre> |
|||
And since we've finished testing, we should tidy up after ourselves. |
|||
<pre>/O> empty |
|||
... |
|||
Stack empty.</pre> |
|||
=={{header|R}}== |
=={{header|R}}== |