Jump to content

Accumulator factory: Difference between revisions

→‎{{header|Quackery}}: added static, named version
m (→‎{{header|Quackery}}: more commentary)
(→‎{{header|Quackery}}: added static, named version)
Line 2,905:
 
=={{header|Quackery}}==
 
===Dynamic, Lambda===
 
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>.
Line 2,937 ⟶ 2,939:
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> 100000010 6 ** factory
...
 
Line 2,963 ⟶ 2,965:
...
 
Stack empty.</pre>
 
===Static, Named===
 
We can create a named version by extending the Quackery compiler, <code>build</code>.
 
This version does not need to leave a lambda function on the stack, as it can be referred to by name.
 
In accordance with The Building Regulations, it starts with some sanity checks to enable the compiler to fail gracefully. For details see [https://github.com/GordonCharlton/Quackery/blob/main/The%20Book%20of%20Quackery.pdf The Book of Quackery.]
 
<lang Quackery> [ 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 ( [ $ --> [ $ )</lang>
 
{{out}}
 
First we will check that it complies with The Building Regulations, then we will create two accumulators, <code>foo</code> and <code>bar</code> and use them alternately to confirm they do not affect each other.
 
<pre>/O> accumulator is foobar
...
accumulator needs a starting value.
Stack empty.
 
/O> $ "this is a string" accumulator is foobar
...
accumulator needs a number.
Stack empty.
 
/O> 23 accumulator is foo
... [ 10 6 ** ] accumulator is bar
...
 
Stack empty.
 
/O> 100 foo echo
...
123
Stack empty.
 
/O> 234567 bar echo
...
1234567
Stack empty.
 
/O> 123 foo echo
...
246
Stack empty.</pre>
 
1,462

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.