Accumulator factory: Difference between revisions

 
(131 intermediate revisions by 55 users not shown)
Line 1:
{{task}}{{requires|Mutable State}}
{{requires|Mutable State}}
{{Omit from|MUMPS|Creating a function implies that there is routine somewhere that has the function stored, and that function could be modified}}
 
A problem posed by [[wp:Paul Graham|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).
 
 
;Rules:
The detailed rules are at http://paulgraham.com/accgensub.html and are reproduced here for simplicity (with additions in <small>''small italic text''</small>).
:Before you submit an example, make sure the function
Line 11 ⟶ 16:
:# Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code. <small>''(No global variables or other such things.)''</small>
: E.g. if after the example, you added the following code (in a made-up language) <small>''where the factory function is called foo''</small>:
:: <langsyntaxhighlight lang="pseudocode">x = foo(1);
x(5);
foo(3);
print x(2.3);</langsyntaxhighlight>
: It should print <tt>8.3</tt>. <small>''(There is no need to print the form of the accumulator function returned by <tt>foo(3)</tt>; it's not part of the task at all.)''</small>
 
The purpose of this task is to 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 [[Closures|closure]], providing the language supports them.
 
;Task:
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 [[Closures|closure]], providing the language supports them.
 
Where it is not possible to hold exactly to the constraints above, describe the deviations.
<br><br>
{{Omit from|MUMPS|Creating a function implies that there is routine somewhere that has the function stored, and that function could be modified}}
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F accumulator(n)
T Accumulator
Float s
F (Float n)
.s = n
F ()(Float n)
.s += n
R .s
R Accumulator(n)
 
V x = accumulator(1)
print(x(5))
print(x(2.3))
 
V x2 = accumulator(3)
print(x2(5))
print(x2(3.3))
print(x2(0))</syntaxhighlight>
 
{{out}}
<pre>
6
8.3
8
11.3
11.3
</pre>
 
=={{header|8th}}==
<syntaxhighlight lang="forth">
\ 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</syntaxhighlight>
 
{{out}}
<pre>
11
13
16
</pre>
 
=={{header|ABAP}}==
Line 26 ⟶ 101:
Another possible solution would be to use the languages in-built JavaScript processing capabilities to dynamically construct a JS source at run-time, which implements the JS Accumulator factory.
=== Object Oriented Solution ===
<langsyntaxhighlight ABAPlang="abap">report z_accumulator
class acc definition.
public section.
Line 52 ⟶ 127:
cl_acc->call( exporting iv_i = '2.3' importing ev_r = lv_ret2 ).
cl_acc->call( exporting iv_i = 2 importing ev_r = lv_ret1 ).
write : / lv_ret2 decimals 2 exponent 0 left-justified, / lv_ret1 left-justified.</langsyntaxhighlight>
{{out}}
<pre>
Line 59 ⟶ 134:
</pre>
=== JavaScript Solution ===
<langsyntaxhighlight ABAPlang="abap">data: lv_source type string,
cl_processor type ref to cl_java_script,
lv_ret type string.
Line 82 ⟶ 157:
write lv_ret.
write / 'Done'.
endif.</langsyntaxhighlight>
 
<pre>#function (n) {# return sum += n;#}#8.3</pre>
Line 89 ⟶ 164:
Closures work the same in ActionScript as in JavaScript. ActionScript will transparently convert integers to reals if the function is given a real argument, but the typeof operator must be used to ensure the function isn't sent invalid arguments, such as strings (which would silently convert the accumulated number to a string without throwing an error).
{{trans|Javascript}}
<langsyntaxhighlight ActionScriptlang="actionscript">//Throw an error if a non-number argument is used. (typeof evaluates to
// "number" for both integers and reals)
function checkType(obj:Object):void {
Line 102 ⟶ 177:
trace(acc(10));
trace(acc(4));
trace(acc("123")); //This causes an ArgumentError to be thrown.</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Accumulator;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 115 ⟶ 190:
Put_Line (Integer'Image (B.The_Function (3)));
Put_Line (Float'Image (A.The_Function (2.3)));
end;</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="ada">generic package Accumulator is
 
-- This Ada generic package represents an accumulator factory.
Line 127 ⟶ 202:
function The_Function (X : Integer) return Float;
function The_Function (X : Float) return Float;
end;</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="ada">package body Accumulator is
 
-- The accumulator lives through three states. It is in Virgin_State
Line 192 ⟶ 267:
end;
 
end;</langsyntaxhighlight>
 
=={{header|Aikido}}==
{{trans|Javascript}}
<langsyntaxhighlight lang="aikido">function accumulator (sum:real) {
return function(n:real) { return sum += n }
}
Line 203 ⟶ 278:
x(5)
println (accumulator)
println (x(2.3))</langsyntaxhighlight>
{{out}}
accumulator
8.3
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">af(list l, object o)
{
l[0] = l[0] + o;
}
 
main(void)
{
object (*f)(object);
 
f = af.apply(list(1));
 
f(5);
af.apply(list(3));
o_(f(2.3), "\n");
 
0;
}</syntaxhighlight>
{{Out}}
<pre>8.3</pre>
The type is properly preserved over summing:
<syntaxhighlight lang="aime"> f = af.apply(list(5));
 
f(-6);
f(7);
o_form("~: ~\n", f(0).__type, f(0));
 
f = af.apply(list(8));
 
f(-6.6);
f(4.2);
o_form("~: /d1/\n", f(0).__type, f(0));</syntaxhighlight>
{{Out}}
<pre>integer: 6
real: 5.6</pre>
 
=={{header|ALGOL 68}}==
Line 213 ⟶ 324:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
Note: Standard ALGOL 68's scoping rules forbids exporting a '''procedure''' (or '''format''') out of it's scope (closure). Hence this specimen will run on [[ELLA ALGOL 68]], but is non-standard. For a discussion of first-class functions in ALGOL 68 consult [http://www.cs.ru.nl/~kees/home/papers/psi96.pdf "The Making of Algol 68"] - [[wp:Cornelis_H.A._Koster|C.H.A. Koster]] (1993). <!-- Retrieved April 28, 2007 -->
<langsyntaxhighlight lang="algol68">MODE NUMBER = UNION(INT,REAL,COMPL);
 
PROC plus = (NUMBER in a, in b)NUMBER: (
Line 245 ⟶ 356:
print(("x:",x(0), new line))
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 256 ⟶ 367:
This has one deviation. AppleScript needs a script object for the closure on the sum <code>n</code>. So this factory returns a script object, not a handler by itself. One must call the handler through its script object, as in <code>x's call(1)</code>.
 
<langsyntaxhighlight lang="applescript">on accumulator(n)
-- Returns a new script object
-- containing a handler.
Line 271 ⟶ 382:
log y's call(2)
log x's call(3.5)
-- Event Log: (*11*) (*7*) (*14.5*)</langsyntaxhighlight>
 
 
Or, to match the task spec and output a little more closely:
 
<syntaxhighlight lang="applescript">on run
set x to foo(1)
x's |λ|(5)
foo(3)
x's |λ|(2.3)
end run
 
-- foo :: Int -> Script
on foo(sum)
script
on |λ|(n)
set sum to sum + n
end |λ|
end script
end foo</syntaxhighlight>
{{Out}}
<pre>8.3</pre>
 
=={{header|Argile}}==
{{works with|Argile|1.1.1}}
<langsyntaxhighlight Argilelang="argile">use std, array
 
let A = accumulator 42
Line 327 ⟶ 462:
Accumulator.suffix
 
autocast accumulator<->Accumulator</langsyntaxhighlight>
 
=={{header|Astro}}==
<syntaxhighlight lang="python">fun accumulator(var sum): :: Real -> _
n => sum += n
 
let f = accumulator!(5)
print f(5) # 10
print f(10) # 20
print f(2.4) # 22.4</syntaxhighlight>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
This code works by copying the function FNdummy() onto the heap and returning a pointer to it.
<langsyntaxhighlight lang="bbcbasic"> x = FNaccumulator(1)
dummy = FN(x)(5)
dummy = FNaccumulator(3)
Line 348 ⟶ 493:
PRIVATE sum
sum += n
= sum</langsyntaxhighlight>
 
=={{header|Bracmat}}==
NoticeUntil that2023 Bracmat hashad no facility for handling floating point numbers,. This solution handles only rational numbers.
<langsyntaxhighlight lang="bracmat">( ( accumulator
=
.
Line 366 ⟶ 511:
& accumulator$3
& out$(x$23/10)
)</langsyntaxhighlight>
Output:
<pre>83/10</pre>
 
The following solution uses UFP (UnIfancyfied Floating Point) objects to handle the terms in case not both are rational numbers.
<syntaxhighlight lang="bracmat">( ( accumulator
=
.
' ( add sum object addFunction
. ( addFunction
= A B
. !arg:(?A.?B)
& ( !A:#
& !B:#
& "If both values are recognized as integer or fractional values, just use '+'."
& !A+!B
| "Otherwise, create an object for adding two C doubles and let that run."
& ( new
$ (UFP,'(.$($A)+$($B)))
. go
)
$
)
)
& ( object
= add
= addFunction$($arg.!arg)
)
& !(object.add):?sum
& 'addFunction$($($sum).!arg)
: (=?(object.add))
& !sum
)
)
& accumulator$1:(=?x)
& x$5
& accumulator$1:(=?y)
& y$"5.0"
& out$(x$23/10)
& out$(y$"2.3")
)</syntaxhighlight>
 
Output
<pre>83/10
8.3000000000000007E+00</pre>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">accumulator = { sum |
{ n | sum = sum + n }
}
Line 377 ⟶ 565:
x 5
accumulator 3 #Does not affect x
p x 2.3 #Prints 8.3 (1 + 5 + 2.3)</langsyntaxhighlight>
 
=={{header|BQN}}==
 
Ported from [[Ruby]].
 
<syntaxhighlight lang="bqn">Acc ← {
𝕊 sum:
{sum+↩𝕩}
}
x ← Acc 1
X 5
Acc 3
X 2.3</syntaxhighlight>
 
[https://mlochbaum.github.io/BQN/try.html#code=QWNjIOKGkCB7CiAg8J2ViiBzdW06CiAge3N1bSvihqnwnZWpfQp9Cngg4oaQIEFjYyAxClggNQpBY2MgMwpYIDIuMw== Try It!]
 
=={{header|C}}==
Deviation: Not in standard C, but several compilers include the typeof operator as an extension which can be used like a typedef. Functions must be defined outside of the main program body and they retain the same type throughout their life. C11 is supposed to give us some Type-generic macro expressions.
 
<langsyntaxhighlight Clang="c">#include <stdio.h>
//~ Take a number n and return a function that takes a number i
#define ACCUMULATOR(name,n) __typeof__(n) name (__typeof__(n) i) { \
Line 399 ⟶ 602:
printf ("%c\n", z(5)); /* f */
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|4.0}}
<syntaxhighlight lang="csharp">using System;
 
class Program
{
static Func<dynamic, dynamic> Foo(dynamic n)
{
return i => n += i;
}
 
static void Main(string[] args)
{
var x = Foo(1);
x(5);
Foo(3);
Console.WriteLine(x(2.3));
}
}</syntaxhighlight>
 
=={{header|C++}}==
First solution has a deviation: The return type is wrong when the accumulator is called with an integer argument after is has been called with a float argument. Later it is explained how to correct this.
 
<langsyntaxhighlight lang="cpp">#include <iostream>
 
class Acc
Line 460 ⟶ 683:
std::cout << a(2.3f);
return 0;
}</langsyntaxhighlight>
{{works with|C++11}}
The following is similar to the above, using lambda functions from C++11. Note that we declared the lambda <code>mutable</code>, which allows us to modify variables that were captured by value. This feature allows us to maintain mutable state, which is essential for an accumulator.
 
It suffers from the same deviation as the former, where the return type is wrong when the accumulator is called with a float argument after is has been called with an integer argument.
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <functional>
 
Line 481 ⟶ 704:
std::cout << acc(2.3) << std::endl;
return 0;
}</langsyntaxhighlight>
 
The deviation stems from two sources. First, a C++ object (such as the accumulator) has an immutable type. To correct this, we must separate the accumulator from the cumulant value it holds. For example:
<langsyntaxhighlight lang="cpp">struct CumulantBase_
{
virtual ~CumulantBase_();
Line 505 ⟶ 728:
template<class T_> Accumulator_(const T_& val) { Set(val); }
template<class T_> void Set(const T_& val) { val_.reset(new Cumulant_<T_>(val)); }
</syntaxhighlight>
</lang>
(This is Coplien's "State" pattern.)
 
The second issue is that the built-in operator + is a multimethod, implementing a compile-time dispatch and promotion which we must manually reproduce.
<langsyntaxhighlight lang="cpp">// still inside struct Accumulator_
// various operator() implementations provide a de facto multimethod
Accumulator_& operator()(int more)
Line 538 ⟶ 761:
}
};
</syntaxhighlight>
</lang>
 
These rely on coercion functions which switch on the so-far-accumulated type:
<langsyntaxhighlight lang="cpp">// recognize cumulants by type
boost::optional<int> CoerceInt(const CumulantBase_& c)
{
Line 562 ⟶ 785:
return boost::optional<String_>();
}
</syntaxhighlight>
</lang>
 
All that remains is to write to the stream:
<langsyntaxhighlight lang="cpp">std::ostream& operator<<(std::ostream& dst, const Accumulator_& acc)
{
return acc.val_->Write(dst);
}
</syntaxhighlight>
</lang>
 
=={{header|C sharp|C#}}==
{{works with|C sharp|4.0}}
<lang csharp>using System;
 
class Program
{
static Func<dynamic, dynamic> Foo(dynamic n)
{
return i => n += i;
}
 
static void Main(string[] args)
{
var x = Foo(1);
x(5);
Foo(3);
Console.WriteLine(x(2.3));
}
}</lang>
 
=={{header|Ceylon}}==
<langsyntaxhighlight Ceylonlang="ceylon">shared void run() {
Integer|Float accumulator
(variable Integer|Float n)
Line 608 ⟶ 811:
print(accumulator(3));
print(x(2.3));
}</langsyntaxhighlight>
 
{{out}}
Line 619 ⟶ 822:
=={{header|Clay}}==
To my knowledge Clay does not admit of an elegant solution to this problem, although it should be stated that I am still exploring the language. But a clean solution mirroring that for other static languages is quite simple (one in which the operative numeric type is constrained by the original call to acc):
<langsyntaxhighlight Claylang="clay">acc(n) {
return (m) => {
n = n + m;
Line 631 ⟶ 834:
acc(3);
println(x(2.3)); // Prints “8.300000000000001”.
}</langsyntaxhighlight>
Although statically typed, due to Clay’s everywhere-genericity this has the advantage of working out of the box for any type that defines addition:
<langsyntaxhighlight Claylang="clay"> var y = acc(Vector[Char]("Hello"));
println(y(" World!")); // Prints "Hello World!”.</langsyntaxhighlight>
But you could constrain the function to numeric types were you so inclined:
<langsyntaxhighlight Claylang="clay">[N | Numeric?(N)] acc(n: N) {
return (m) => {
n = n + m;
return n;
};
}</langsyntaxhighlight>
One could go crazy with tagged unions and runtime dispatching to rig something up that adhered more closely to the problem’s specification. But I know of no easier way to “change types” in the fashion necessary.
 
=={{header|Clojure}}==
The ''atom'' function creates an atomically updatable identity holding a value. The ''swap!'' function atomically updates the atom's value, returning the new value. The function returned from an ''accum'' call satisfies all the requirements.
<langsyntaxhighlight lang="clojure">(defn accum [n]
(let [acc (atom n)]
(fn [m] (swap! acc + m))))</langsyntaxhighlight>
Similarly, a ''ref'' could be used.
<langsyntaxhighlight lang="clojure">(defn accum [n]
(let [acc (ref n)]
#(dosync (alter acc + %))))</langsyntaxhighlight>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">accumulator = (sum) ->
(n) -> sum += n
f = accumulator(1)
console.log f(5)
console.log f(2.3)</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
{{trans|TXR}}
<langsyntaxhighlight lang="lisp">(defun accumulator (sum)
(lambda (n)
(incf sum n)))</langsyntaxhighlight>
Example usage:
<langsyntaxhighlight lang="lisp">(defvar x (accumulator 1))
(funcall x 5)
(accumulator 3)
(funcall x 2.3)</langsyntaxhighlight>
{{out}}
<pre>
Line 679 ⟶ 882:
8.3
</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">
# Make types a bit easier with an alias
alias Num = Int32 | Int64 | Float32 | Float64
 
def accumulator(sum : Num)
# This proc is very similar to a Ruby lambda
->(n : Num){ sum += n }
end
 
x = accumulator(5)
puts x.call(5) #=> 10
puts x.call(10) #=> 20
puts x.call(2.4) #=> 22.4
</syntaxhighlight>
 
=={{header|D}}==
 
<langsyntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 694 ⟶ 913:
auto accum = cast(U)initvalue ;
return (U n) { return accum += n ; } ;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
 
The <code>=></code> operator is Dart's special syntax for single line closures. When you use it the value of the expression is automatically returned without the return statement.
 
<code>num</code> is base type for <code>int</code> and <code>double</code>.
note: Function is the return type of the accumulator function, not the keyword used to define functions. There is no function keyword in Dart. The return type is optional, just like all types in Dart. The declaration could just be: accumulator(var n) => ...
 
Implementation with dynamic typing:
<lang dart>Function accumulator(var n) => (var i) => n += i;
<syntaxhighlight lang="dart">makeAccumulator(s) => (n) => s += n;</syntaxhighlight>
 
Implementation with static typing (preferred in Dart 2):
void main() {
<syntaxhighlight lang="dart">typedef Accumulator = num Function(num);
var a = accumulator(42);
print("${a(0)}, ${a(1)}, ${a(10)}, ${a(100)}");
 
Accumulator makeAccumulator(num s) => (num n) => s += n;</syntaxhighlight>
var b = accumulator(4.2);
 
print("${b(0)}, ${b(1)}, ${b(10.0)}, ${b(100.4)}");
Verbose version:
}</lang>
<syntaxhighlight lang="dart">typedef Accumulator = num Function(num);
 
Accumulator makeAccumulator(num initial) {
num s = initial;
num accumulator(num n) {
s += n;
return s;
}
return accumulator;
}</syntaxhighlight>
 
Usage example for any of above:
<syntaxhighlight lang="dart">void main() {
var x = makeAccumulator(1);
x(5);
makeAccumulator(3);
print(x(2.3));
}</syntaxhighlight>
 
{{out}}
<pre>42, 43, 53, 1538.3</pre>
 
4.2, 5.2, 15.2, 115.60000000000001</pre>
Type checking:
<syntaxhighlight lang="dart">void main() {
var x = makeAccumulator(1);
print(x(5).runtimeType); // int
print(x(2.3).runtimeType); // double
print(x(4).runtimeType); // double
}</syntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">accum n:
labda i:
set :n + n i
Line 725 ⟶ 969:
drop x 5
drop accum 3
!print x 2.3</langsyntaxhighlight>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Variants}}
<syntaxhighlight lang="delphi">
program Accumulator_factory;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Variants;
 
type
TFn = TFunc<variant, variant>;
 
function Foo(n: variant): TFn;
begin
Result :=
function(i: variant): variant
begin
n:= n + i;
Result := n;
end;
end;
 
begin
var x := Foo(1);
x(5);
Foo(3); // do nothing
Writeln(x(2.3));
Readln;
end.</syntaxhighlight>
=={{header|E}}==
<langsyntaxhighlight lang="e">def foo(var x) {
return fn y { x += y }
}</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="lisp">
(define-syntax-rule (inc x v) (set! x (+ x v)))
(define (accumulator (sum 0)) (lambda(x) (inc sum x) sum))
Line 744 ⟶ 1,019:
 
(x 2.3) → 8.3
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 6.x :
<lang elena>#import system.
<syntaxhighlight lang="elena">function(acc)
#import system'dynamic.
= (n => acc.append(n));
 
accumulator(n)
#symbol Function =
= function(new Variable(n));
(:x) [ this append:x ].
 
public program()
#class(extension)op
{
var x := accumulator(1);
#method Accumulator
= Variable new:self mix &into:Function.
}
 
#symbol program =
[
#var x := 1 Accumulator.
x:(5.);
#var y := accumulator(3 Accumulator.);
console .write:(x:(2.3r).)
}</syntaxhighlight>
].</lang>
{{out}}
<pre>
8.3
</pre>
 
=={{header|Elixir}}==
Elixir provides Agents to simplify creating a process to maintain state where mutable variables aren't allowed.
<syntaxhighlight lang="elixir">defmodule AccumulatorFactory do
def new(initial) do
{:ok, pid} = Agent.start_link(fn() -> initial end)
fn (a) ->
Agent.get_and_update(pid, fn(old) -> {a + old, a + old} end)
end
end
end</syntaxhighlight>
The passing test to exercise the Accumulator and show usage:
<syntaxhighlight lang="elixir">ExUnit.start
 
defmodule AccumulatorFactoryTest do
use ExUnit.Case
 
test "Accumulator basic function" do
foo = AccumulatorFactory.new(1)
foo.(5)
bar = AccumulatorFactory.new(3)
assert bar.(4) == 7
assert foo.(2.3) == 8.3
end
end</syntaxhighlight>
 
{{out}}
<pre>
.
 
Finished in 0.06 seconds (0.06s on load, 0.00s on tests)
1 test, 0 failures
 
Randomized with seed 587000
</pre>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
in Org:RosettaCode
^|EMal has a mechanism to force the type system to allow nulls on types
|that are usually not nullable, such as int or real.
|In the following code we are telling EMal that int and real implement
|the Number virtual interface, so that it can only
|accept null (because it is an interface), int, and real values.
|^
type Number allows int, real
type AccumulatorUsingNumber
fun foo = fun by Number n
fun g = Number by Number i
return n += i
end
return g
end
type AccumulatorUsingVar
^|EMal has an universal supertype Variable (var) that can be used.
|Some manual type checks are required.
|^
fun checkType = void by var value
if generic!value != real and generic!value != int
Event.error(1, "Only real and int values can be used").raise()
end
end
fun foo = fun by var n
checkType(n)
fun g = var by var i
checkType(i)
return n += i
end
return g
end
type Main
^|we have developed two solutions,
|it is time to create a list holding both data types.
|We iterate over the solutions in order to test them.
|^
List solutions = generic[AccumulatorUsingNumber, AccumulatorUsingVar]
for int i = 0; i < solutions.length; ++i
generic solution = solutions[i]
writeLine("=== solution " + (i + 1) + " ===")
fun x = :solution.foo(1)
x(5)
:solution.foo(3)
watch(x(2.3))
fun y = :solution.foo(1)
y(5)
:solution.foo(3)
watch(y(2))
end
</syntaxhighlight>
{{out}}
<pre>
=== solution 1 ===
Org:RosettaCode:Number, Real: <8.3>
Org:RosettaCode:Number, Integer: <8>
=== solution 2 ===
Variable, Real: <8.3>
Variable, Integer: <8>
</pre>
 
=={{header|Erlang}}==
Erlang doesn't allow for mutable variables, but does have variable capture in closures. By spawning a process which loops endlessly, incrementing the sum and returning it to the caller, this mutable state can be imitated.
<langsyntaxhighlight lang="erlang">
-module(acc_factory).
-export([loop/1,new/1]).
Line 794 ⟶ 1,162:
end
end.
</syntaxhighlight>
</lang>
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM ACCUMULATOR
 
PROCEDURE ACCUMULATOR(SUM,N,A->SUM)
Line 813 ⟶ 1,181:
ACCUMULATOR(Z,2.3,TRUE->Z)
PRINT(X,Z)
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>
-11.7 10.3
</pre>
 
=={{header|F Sharp|F#}}==
A statically typed version is not possible, but it is quite easy to write dynamically typed functions in F#:
<syntaxhighlight lang="fsharp">// dynamically typed add
let add (x: obj) (y: obj) =
match x, y with
| (:? int as m), (:? int as n) -> box(m+n)
| (:? int as n), (:? float as x)
| (:? float as x), (:? int as n) -> box(x + float n)
| (:? float as x), (:? float as y) -> box(x + y)
| _ -> failwith "Run-time type error"
 
let acc init =
let state = ref (box init)
fun y ->
state := add !state (box y)
!state
 
do
let x : obj -> obj = acc 1
printfn "%A" (x 5) // prints "6"
acc 3 |> ignore
printfn "%A" (x 2.3) // prints "8.3"</syntaxhighlight>
 
Actually, it is possible to create a statically typed version by using an inline accumulator creation function.
<syntaxhighlight lang="fsharp">let inline makeAccumulator init =
let acc = ref init
fun i ->
acc := !acc + i
!acc
 
do
let acc = makeAccumulator 1.0 // create a float accumulator
 
acc 5.0 |> ignore
let _ = makeAccumulator 3 // create an unused integer accumulator
printfn "%A" (acc 2.3)</syntaxhighlight>
{{out}}
<pre>8.3</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USE: locals
<lang factor>:: accumulator ( n! -- quot ) [ n + dup n! ] ;
:: accumulator ( n! -- quot ) [ n + dup n! ] ;
 
1 accumulator
[ 5 swap call drop ]
[ drop 3 accumulator drop ]
[ 2.3 swap call ] tri .</langsyntaxhighlight>
 
=={{header|Fantom}}==
The accumulator function is a little unwieldy using multiple ifs to maintain the type of 'sum' until forced to change. Again, a result of the three concrete Num types, Int, Float and Decimal, all being separated in the API.
<langsyntaxhighlight lang="fantom">class AccumulatorFactory
{
static |Num -> Num| accumulator (Num sum)
Line 878 ⟶ 1,286:
echo (x(2.3)) // the Int sum is now a Decimal
}
}</langsyntaxhighlight>
 
=={{header|Forth}}==
Forth is untyped; this works on integers.
<langsyntaxhighlight lang="forth">: accumulator
create ( n -- ) ,
does> ( n -- acc+n ) tuck +! @ ;
Line 890 ⟶ 1,298:
1 foo . \ 1
2 foo . \ 3
3 foo . \ 6</langsyntaxhighlight>
 
The idiomatic way to deal with floats is to have a float version of this code; for a mixture of integers and floats, you decide at the start to use a float accumulator, and convert integers to floats explicitly:
=={{header|F Sharp|F#}}==
A statically typed version is not possible, but it is quite easy to write dynamically typed functions in F#:
<lang fsharp>// dynamically typed add
let add (x: obj) (y: obj) =
match x, y with
| (:? int as m), (:? int as n) -> box(m+n)
| (:? int as n), (:? float as x)
| (:? float as x), (:? int as n) -> box(x + float n)
| (:? float as x), (:? float as y) -> box(x + y)
| _ -> failwith "Run-time type error"
 
<syntaxhighlight lang="forth">
let acc init =
: faccumulator ( r "name" -- )
let state = ref (box init)
funcreate yfalign ->f,
does> ( r1 -- r2 )
state := add !state (box y)
faligned dup f@ f+ fdup f! ;
!state
 
do
let x : obj -> obj = acc 1
printfn "%A" (x 5) // prints "6"
acc 3 |> ignore
printfn "%A" (x 2.3) // prints "8.3"</lang>
 
Actually, it is possible to create a statically typed version by using an inline accumulator creation function.
<lang fsharp>let inline makeAccumulator init =
let acc = ref init
fun i ->
acc := !acc + i
!acc
 
do
let acc = makeAccumulator 1.0 // create a float accumulator
 
acc 5.0 |> ignore
let _ = makeAccumulator 3 // create an unused integer accumulator
printfn "%A" (acc 2.3)</lang>
{{out}}
<pre>8.3</pre>
 
1 s>f faccumulator x
5 s>f x fdrop
3 s>f faccumulator y \ unused
2.3e x f.
</syntaxhighlight>
 
=={{header|Fortran}}==
Line 948 ⟶ 1,330:
in Fortran77 but was accepted by virtually all compilers.
 
<langsyntaxhighlight Fortranlang="fortran">#define foo(type,g,nn) \
typex function g(i);\
typex i,s,n;\
Line 967 ⟶ 1,349:
print *, y(2)
stop
end</langsyntaxhighlight>
{{out}}
<pre>
Line 977 ⟶ 1,359:
Fortran2003 and later supports objects and overloading. The overloaded functions are encapsulated in an object.
 
<syntaxhighlight lang="fortran">
<lang Fortran>
module modAcc
implicit none
Line 1,056 ⟶ 1,438:
itemp = y%fun(5)
print *, y%fun(2)
end program test</langsyntaxhighlight>
{{out}}
<pre>
8.3000000000000007
10
</pre>
 
=={{header|FreeBASIC}}==
It doesn't appear to be possible to program this task in FreeBASIC in the precise way it is posed.
 
The problem is that FB doesn't support closures and, whilst we can manufacture an equivalent object, we'd then have the further problem that you can't pass pointers to object methods, only to static procedures.
 
To get around this restriction we'd normally wrap the object method in a static procedure and pass an object pointer to that followed by any other arguments required by the method. However, this won't work here because the task specifies that the method can take only a single number argument and the object pointer would be internal to 'foo' in any case.
 
Probably the best we can do is for 'foo' to return the object and then to call the method 'g' directly on that:
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' uses overloaded methods to deal with the integer/float aspect (long and single are both 4 bytes)
Type Bar
Public:
Declare Constructor(As Long)
Declare Constructor(As Single)
Declare Function g(As Long) As Long
Declare Function g(As Single) As Single
Private:
As Single sum_ '' can't be altered by external code
End Type
 
Constructor Bar(i As Long)
sum_ = i
End Constructor
 
Constructor Bar(s As Single)
sum_ = s
End Constructor
 
Function Bar.g(i As Long) As Long
sum_ += i
Return sum_ '' would round down to a Long if non-integral Singles had been added previously
End Function
 
Function Bar.g(s As Single) As Single
sum_ += s
Return sum_
End Function
 
Function foo Overload(i As Long) As Bar '' returns a Bar object rather than a pointer to Bar.g
Dim b As Bar = Bar(i)
Return b
End Function
 
Function foo Overload(s As Single) As Bar '' overload of foo to deal with Single argument
Dim b As Bar = Bar(s)
Return b
End Function
 
Dim x As Bar = foo(1) '' assigns Bar object to x
x.g(5) '' calls the Long overload of g on the Bar object
foo(3) '' creates a separate Bar object which is unused
print x.g(2.3) '' calls the Single overload of g on the Bar object and should print 1 + 5 + 2.3 = 8.3
 
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
8.3
</pre>
 
=={{header|Go}}==
Small deviation on condition 2. The task specifies to handle all numeric types, and only int and float64 are shown here. The technique would extend to all types just as easily, but Go has lots of numeric types and the program would be big.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,098 ⟶ 1,543:
accumulator(3)
fmt.Println(x(2.3))
}</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
 
=={{header|Golo}}==
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
An accumulator factory example for Rosetta Code.
This one uses the box function to create an AtomicReference.
----
module rosetta.AccumulatorFactory
 
function accumulator = |n| {
let number = box(n)
return |i| -> number: accumulateAndGet(i, |a, b| -> a + b)
}
 
function main = |args| {
let acc = accumulator(3)
println(acc(1))
println(acc(1.1))
println(acc(10))
println(acc(100.101))
}</syntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def accumulator = { Number n ->
def value = n;
{ it = 0 -> value += it}
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">def x = accumulator(1)
 
println x()
Line 1,131 ⟶ 1,597:
 
println y(2.25D)
assert y() instanceof Double</langsyntaxhighlight>
{{out}}
<pre>1
Line 1,143 ⟶ 1,609:
=={{header|Haskell}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="haskell">import Control.Monad.ST
import Data.STRef
 
Line 1,159 ⟶ 1,625:
x 5
accumulator 3
x 2.3</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
 
'''Note''' The <code>accumulator</code> function could be written in applicative style:
<syntaxhighlight lang="haskell">accumulator = newSTRef >=> return . factory
where factory s n = modifySTRef s (+ n) >> readSTRef s</syntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,167 ⟶ 1,637:
 
Strictly speaking, <tt>genAcc(n)</tt> returns a <i>co-expression</i>, not a function. However, the invocation syntax here is indistinguishable from calling a function.
<langsyntaxhighlight Uniconlang="unicon">procedure main()
a := genAcc(3)
b := genAcc(5)
Line 1,183 ⟶ 1,653:
procedure makeProc(A) # A Programmer-Defined Control Operation
return (@A[1],A[1])
end</langsyntaxhighlight>
This example produces the output:
<pre>
Line 1,192 ⟶ 1,662:
</pre>
To adapt the above for use in Icon, the function-syntax for activating co-expressions (e.g. <tt>a(4)</tt>) available in Unicon would have to be replaced with the <i>activation</i> operator (e.g. <tt>[4]@a</tt>). The use of a list as the value passed through activation is to retain compatibility with the Unicon approach.
 
=={{header|Io}}==
<syntaxhighlight lang="io">accumulator := method(sum,
block(x, sum = sum + x) setIsActivatable(true)
)
x := accumulator(1)
x(5)
accumulator(3)
x(2.3) println // --> 8.3000000000000007</syntaxhighlight>
 
=={{header|J}}==
See http[[j://www.jsoftware.com/jwiki/Guides/Lexical_Closure]], including the [[j:Guides/Lexical%20Closure#dissent|dissent]] section.
<langsyntaxhighlight Jlang="j">oleg=:1 :0
a=. cocreate''
n__a=: m
a&(4 : 'n__x=: n__x + y')
)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="j"> F=: 10 oleg
F 11
21
Line 1,207 ⟶ 1,686:
33
F 11
44</langsyntaxhighlight>
 
=={{header|Java}}==
Java has no first-class functions;, so an accumulator can't use the <code>x(5)</code> syntax. The standard syntactic workaround is to use a standard method name, like <code>x.call(5)</code> Javaor uses<code>x.apply(5)</code>. objects toThis is a deviation maintainfrom statetask.
 
<lang java>public class Accumulator {
Our accumulator sums with long integers as far as possible before switching to floats. This requires the use of the <code>Number</code> class. The code needs Java 5 to autobox primitive values <code>1</code> or <code>2.3</code> into instances of Number. The <code>apply</code> method is ready to implement interface UnaryOperator in Java 8.
private double sum;
 
public Accumulator(double sum0) {
{{works with|Java|5 and up}}
sum = sum0;
<syntaxhighlight lang="java">public class Accumulator
}
//implements java.util.function.UnaryOperator<Number> // Java 8
public double call(double n) {
{
return sum += n;
private Number sum;
 
public Accumulator(Number sum0) {
sum = sum0;
}
 
public staticNumber void mainapply(String[]Number argsn) {
// Acts like sum += n, but chooses long or double.
Accumulator x = new Accumulator(1);
// Converts weird types (like BigInteger) to double.
x.call(5);
return (longable(sum) && longable(n)) ?
System.out.println(new Accumulator(3));
(sum = sum.longValue() + n.longValue()) :
System.out.println(x.call(2.3));
(sum = sum.doubleValue() + n.doubleValue());
}
 
}</lang>
private static boolean longable(Number n) {
{{out}}
return n instanceof Byte || n instanceof Short ||
<pre>Accumulator@42e816
n instanceof Integer || n instanceof Long;
8.3</pre>
To do a full version that sums with integers as long as possible before switching to double-precision floats requires a little more work and the use of the <code>Number</code> clalang java>public class Accumulator {
private double sum;
public Accumulator(double sum0) {
sum = sum0;
}
public double call(double n) {
return sum += n;
}
 
public static void main(String[] args) {
Accumulator x = new Accumulator(1);
x.callapply(5);
System.out.println( new Accumulator(3));
System.out.println(x.callapply(2.3));
}
}
}ss...
</syntaxhighlight>
{{out}}
<pre>8.3</pre>
 
A printed Accumulator would look like <code>Accumulator@42e816</code>
;Optimized
 
Java has no first-class functions, but with minor syntaxical sugar it does (and yes, this will work in Java 6 and up).
Java 8 added the lambda syntax. A lambda is an anonymous inner class that implements a one-method interface. We can make the accumulator as a lambda, but it must store the sum in another object. We use a one-element array.
<lang java>import com.google.common.base.Function;
 
{{works with|Java|8 and up}}
<syntaxhighlight lang="java">import java.util.function.UnaryOperator;
 
public class AccumulatorFactory {
private static Function<Double, Double> accumulator(final Double elem) {
return new Function<Double, Double>() {
Double sum = elem;
@Override public Double apply(Double val) {
return sum += val;
}
};
}
 
public static voidUnaryOperator<Number> mainaccumulator(String[]Number argssum0) {
// Allows sum[0] = ... inside lambda.
Function<Double, Double> x = accumulator(1d);
Number[] sum = { sum0 };
x.apply(5d);
System.out.println(accumulator(3d));
System.out.println(x.apply(2.3));
}
}</lang>
{{out}}
<pre>AccumulatorFactory$1@e86da0
8.3</pre>
{{works with|Java|8.0+}}
<lang java>import java.util.function.DoubleUnaryOperator;
 
// Acts like n -> sum[0] += n, but chooses long or double.
public interface AccumulatorFactory {
// Converts weird types (like BigInteger) to double.
public static DoubleUnaryOperator accumulator(double element) {
return n -> (longable(sum[0]) && longable(n)) ?
double[] sum = new double[] { element };
return(sum[0] value ->= sum[0].longValue() += value;n.longValue()) :
(sum[0] = sum[0].doubleValue() + n.doubleValue());
}
}
 
public private static voidboolean mainlongable(String...Number argumentsn) {
return n instanceof Byte || n instanceof Short ||
DoubleUnaryOperator x = accumulator(1d);
n instanceof Integer || n instanceof Long;
x.applyAsDouble(5d);
System.out.println(accumulator(3d));
System.out.println(x.applyAsDouble(2.3));
}
}</lang>
{{out}}
<pre>AccumulatorFactory$$Lambda$1/2055281021@4517d9a3
8.3</pre>
{{works with|Java|5.0}}
<lang java5>public class Accumulator {
private Long sumA; // non-null if we're working in the integer domain
private double sumB;
public Accumulator(Number sum0) {
if (sum0 instanceof Double) {
sumB = sum0.doubleValue();
} else {
sumA = sum0.longValue();
}
}
 
public Number call(Number n) {
if (sumA != null) {
if (n instanceof Double) {
sumB = n.doubleValue() + sumA;
sumA = null;
return sumB;
}
return sumA += n.longValue();
}
return sumB += n.doubleValue();
}
public static void main(String[] args) {
UnaryOperator<Number> x = accumulator(1);
Accumulator x = new Accumulator(1);
x.callapply(5);
accumulator(3);
Accumulator y = new Accumulator(3);
System.out.println(y+" has value "+yx.callapply(02.3));
System.out.println(x.call(2.3));
}
}</langsyntaxhighlight>
Producing this sample output:
<pre>
Accumulator@6100ab23 has value 3
8.3
</pre>
 
=={{header|JavaScript}}==
===ES5===
<langsyntaxhighlight lang="javascript">function accumulator(sum) {
return function(n) {
return sum += n;
Line 1,337 ⟶ 1,770:
x(5);
console.log(accumulator(3).toString() + '<br>');
console.log(x(2.3));</langsyntaxhighlight>
{{out}}
<pre>function (n) { return sum += n; }
Line 1,343 ⟶ 1,776:
 
===ES6===
<langsyntaxhighlight lang="javascript">let accumulator = sum => (n => sum += n);
let x = accumulator(1);
console.log(x(5));
accumulator(3);
console.log(x(2.3));</langsyntaxhighlight>
{{out}}
<pre>6
Line 1,353 ⟶ 1,786:
 
===JavaScript 1.8 (SpiderMonkey Only)===
<langsyntaxhighlight lang="javascript">function accumulator(sum) function(n) sum += n;
var x = accumulator(1);
x(5);
console.log(accumulator(3).toSource());
console.log(x(2.3));</langsyntaxhighlight>
{{out}}
<pre>(function (n) sum += n)
8.3</pre>
 
=={{header|Jsish}}==
From Javascript ES5 entry.
<syntaxhighlight lang="javascript">/* Accumulator factory, in Jsish */
function accumulator(sum) {
return function(n) {
return sum += n;
};
}
 
provide('accumulatorFactory', '0.6');
 
if (Interp.conf('unitTest')) {
var x,y;
;x = accumulator(1);
;accumulator;
;x;
;x(5);
;accumulator(3);
;x(2.3);
 
;y = accumulator(0);
;y;
;x(1);
;y(2);
;x(3);
;y(4);
;x(5);
}
 
/*
=!EXPECTSTART!=
x = accumulator(1) ==> "function(n) {\n return sum += n;\n }"
accumulator ==> "function accumulator(sum) {\n return function(n) {\n return sum += n;\n };\n}"
x ==> "function(n) {\n return sum += n;\n }"
x(5) ==> 6
accumulator(3) ==> "function(n) {\n return sum += n;\n }"
x(2.3) ==> 8.3
y = accumulator(0) ==> "function(n) {\n return sum += n;\n }"
y ==> "function(n) {\n return sum += n;\n }"
x(1) ==> 9.3
y(2) ==> 2
x(3) ==> 12.3
y(4) ==> 6
x(5) ==> 17.3
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish -u accumulatorFactory.jsi
[PASS] accumulatorFactory.jsi</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Using the convenient, assignment syntax for function definition:
 
<lang julia>
<syntaxhighlight lang="julia">function accumulator(i)
f(n) = i += n
return f
end
 
x = accumulator(1)
@show x(5)
 
accumulator(3)
@show x(2.3)</langsyntaxhighlight>
Output
<pre>julia> function accumulator(i)
f(n) = i += n
end
# methods for generic function accumulator
accumulator(i) at none:2
 
{{out}}
julia> x = accumulator(1)
<pre>x(5) = 6
# methods for generic function f
fx(n2.3) at= none:28.3</pre>
 
=={{header|Kotlin}}==
julia> x(5)
Overloads would be needed for all six primitive numeric types but, in the interests of brevity, only two overloads of 'foo' have been coded:
6
<syntaxhighlight lang="scala">// version 1.1
 
fun foo(n: Double): (d: Double) -> Double {
julia> accumulator(3)
var nn = n
# methods for generic function f
return { nn += it; nn }
f(n) at none:2
}
 
fun foo(n: Int): (i: Int) -> Int {
julia> x(2.3)
var nn = n
8.3</pre>
return { nn += it; nn }
}
 
fun main(args: Array<String>) {
val x = foo(1.0) // calls 'Double' overload
x(5.0)
foo(3.0)
println(x(2.3))
val y = foo(1) // calls 'Int' overload
y(5)
foo(5)
println(y(2))
}</syntaxhighlight>
 
{{out}}
<pre>
8.3
8
</pre>
 
=={{header|Lambdatalk}}==
Lambdatlk is a functional programming language without closures but with mutable arrays.
<syntaxhighlight lang="scheme">
{def acc
{lambda {:a :n}
{+ {A.toS {A.addlast! :n :a}}}}}
-> acc
 
1) using a global:
 
{def A {A.new 1}}
-> A
{acc {A} 5}
-> 6
{acc {A} 2.3}
-> 8.3
 
2) inside a local context:
 
{let { {:a {A.new 1}}
} {br}{acc :a 5}
{br}{acc :a 2.3}
} ->
6
8.3
</syntaxhighlight>
 
=={{header|Lang}}==
Lang does not support closures. The use of combinator functions and pointers allows a function to store state.
<syntaxhighlight lang="lang">
fp.accumulator = ($sum) -> {
$sumPtr = $[sum]
fp.f = ($sumPtr, $n) -> {
$*sumPtr += $n
return $*sumPtr
}
return fn.argCnt1(fn.combA2(fp.f, $sumPtr))
}
 
$x = fp.accumulator(1)
fn.println($x(5))
fp.accumulator(3)
fn.println($x(2.3))
 
fn.println()
 
$y = fp.accumulator(1.)
fn.println($y(5))
fn.println($y(2.3))
</syntaxhighlight>
 
{{out}}
<pre>
6
8.3
 
6.0
8.3
</pre>
 
=={{header|LFE}}==
Line 1,399 ⟶ 1,964:
=== Traditional closure ===
 
<langsyntaxhighlight lang="lisp">
(defun accum (m)
(lambda (n)
Line 1,405 ⟶ 1,970:
`(#(func ,(accum sum))
#(sum ,sum)))))
</syntaxhighlight>
</lang>
 
Since we want to use both the returned function as well as the data for the call, we return a tuple containing both. Using standard LFE pattern matching, we can extract these.
Line 1,428 ⟶ 1,993:
We can creating a looping process which provides the same functionality as the self-calling function in the "traditional closure" approach:
 
<langsyntaxhighlight lang="lisp">
(defun loop (m)
(receive
Line 1,442 ⟶ 2,007:
(receive
(sum sum)))))
</syntaxhighlight>
</lang>
 
Usage (in the REPL):
Line 1,463 ⟶ 2,028:
=={{header|Lua}}==
A simple implementation:
<langsyntaxhighlight Lualang="lua">function acc(init)
init = init or 0
return function(delta)
Line 1,469 ⟶ 2,034:
return init
end
end</langsyntaxhighlight>
An expanded example of similar but more complex functionality:
{{works with|Lua|5.1}}
<langsyntaxhighlight lang="lua">do
local accSum = 0; -- accumulator factory 'upvalue'
function acc(v) -- the accumulator factory
Line 1,484 ⟶ 2,049:
end--acc
end--end of factory closure</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight lang="lua">x = acc(1) -- x stores the product with initial value = 1
x(5) -- add 5 to x's sum
acc(3) -- add 3 to factory's sum
print (x(2.3)) --> 8.3 -- add 2.3 to x's sum then print the result
y = acc() -- create new function with factory's sum as initial value
print (y()) --> 4 -- print the accumulated value inside the product y</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">\\ M2000 Interpreter
\\ accumulator factory
foo=lambda acc=0 (n as double=0) -> {
\\ interpreter place this: read n as double=0 as first line of lambda function
if n=0 then =acc : exit
acc+=n
\\ acc passed as a closuer to lambda (a copy of acc in the result lambda function)
=lambda acc -> {
' if stack of values is empty then return a copy of acc
if empty then =acc : exit
read x
\\ x has no type here, can be any numeric type (also can be an object too)
\\ accumulator is double, and is a closure (a copy of acc in foo)
acc+=x
\\ any variable in M2000 hold first type
\\ if x is an object then we get error, except if object use this operator
x=acc
\\ so we return x type
=x
}
}
x=foo(1&) ' 1& is long type (32bit)
call void x(5) ' 5 is double type (the default type for M2000)
call void foo(3#) ' void tell to interpreter to throw result, 3# is Currency type
print x(2.3@) ' print 8.3, 2.3@ is Decimal type
print foo()=4 ' print true
def ExpType$(z)=type$(z)
print ExpType$(foo())="Double"
print ExpType$(x(0&))="Long"
print ExpType$(x(0@))="Decimal"
print ExpType$(x())="Double"
print ExpType$(foo(20))="lambda"</syntaxhighlight>
 
=={{header|Maple}}==
This creates a procedure closed over the local variable total in the factory procedure. The initial value, if not passed to the factory procedure, is taken to be 0 and, if the generated accumulator is given no value, it increments the total by 1.
<langsyntaxhighlight Maplelang="maple">AccumulatorFactory := proc( initial := 0 )
local total := initial;
proc( val := 1 ) total := total + val end
end proc:</langsyntaxhighlight>
Running this, we get:
<langsyntaxhighlight Maplelang="maple">> acc := AccumulatorFactory( 1 ):
> acc( 5 );
6
Line 1,515 ⟶ 2,114:
 
> acc( I ); # add the imaginary unit
12.3 - 3. I</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">accFactory[initial_] :=
Module[{total = initial},
Function[x, total += x]
Line 1,525 ⟶ 2,124:
x[5.0];
accFactory[3];
x[2.3]</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
 
=={{header|Mercury}}==
 
===Strict-adherence-to-the-task solution===
 
Deviations:
 
1. this doesn't work with "any numerical type" out of the box, but requires that users add numerical types to a typeclass.
 
2. this likely violates some hidden taste requirements of the task, as used by Paul Graham to dismiss Forth solutions. Certainly, this is not really an example of Mercury that anyone would want to use in a Mercury project.
 
<syntaxhighlight lang="mercury">:- module accum.
:- interface.
 
:- typeclass addable(T) where [
func T + T = T
].
 
:- impure func gen(T) = (impure (func(T)) = T) <= addable(T).
 
:- implementation.
:- import_module bt_array, univ, int.
 
:- mutable(states, bt_array(univ), make_empty_array(0), ground, [untrailed]).
 
gen(N) = F :-
some [!S] (
semipure get_states(!:S),
size(!.S, Size),
resize(!.S, 0, Size + 1, univ(N), !:S),
impure set_states(!.S)
),
F = (impure (func(Add)) = M :-
some [!SF] (
semipure get_states(!:SF),
!.SF ^ elem(Size) = U,
det_univ_to_type(U, M0),
M = M0 + Add,
!SF ^ elem(Size) := univ(M),
impure set_states(!.SF)
)).</syntaxhighlight>
 
As used:
 
<syntaxhighlight lang="mercury">:- module accumuser.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module accum, list, string, int, float.
 
:- instance addable(int) where [
A + B = int.(A + B)
].
 
:- instance addable(float) where [
A + B = float.(A + B)
].
 
:- pragma promise_pure main/2.
main(!IO) :-
impure F = accum.gen(1),
impure N1 = impure_apply(F, 1),
impure N2 = impure_apply(F, 1),
impure G = accum.gen(500.0),
impure R1 = impure_apply(G, -10.0),
impure R2 = impure_apply(G, -50.0),
io.format("%d, %d\n", [i(N1), i(N2)], !IO),
io.format("%.0f, %.0f\n", [f(R1), f(R2)], !IO).</syntaxhighlight>
 
{{out}}
<pre>
2, 3
490, 440
</pre>
 
===Realistic solution===
 
Deviations:
 
1. This still requires addition of numeric types to a typeclass, for a generic +
 
2. This doesn't return a closure with mutable state, but the state itself, which the caller can thread through rules that apply to them.
 
<syntaxhighlight lang="mercury">:- module accum2.
:- interface.
 
:- typeclass addable(T) where [
func T + T = T
].
 
:- type accum(T).
 
% init(N) = Acc
% Return an accumulator with initial value of N
%
:- func init(T) = accum(T)
<= addable(T).
 
% bump(By, N, !Acc)
% Add By to accumulator !Acc, yielding the next number as N
%
:- pred bump(T::in, T::out, accum(T)::in, accum(T)::out) is det
<= addable(T).
 
:- implementation.
 
:- type accum(T) == T.
 
init(N) = N.
 
bump(X, N, N0, N) :-
N = X + N0.</syntaxhighlight>
 
As used, with the same output:
 
<syntaxhighlight lang="mercury">:- module accumuser2.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module accum2, list, string, int, float.
 
:- instance addable(int) where [
A + B = int.(A + B)
].
 
:- instance addable(float) where [
A + B = float.(A + B)
].
 
main(!IO) :-
some [!A1] (
!:A1 = accum2.init(1),
accum2.bump(1, N1, !A1),
accum2.bump(1, N2, !.A1, _)
),
some [!A2] (
!:A2 = accum2.init(500.0),
accum2.bump(-10.0, R1, !A2),
accum2.bump(-50.0, R2, !.A2, _)
),
io.format("%d, %d\n", [i(N1), i(N2)], !IO),
io.format("%.0f, %.0f\n", [f(R1), f(R2)], !IO).</syntaxhighlight>
 
=={{header|MiniScript}}==
 
<syntaxhighlight lang="miniscript">
Accumulator = function(n)
adder = {"sum": n}
adder.plus = function(n)
self.sum += n
return self.sum
end function
adder.getSum = function(n)
obj = self
_sum = function(n)
return obj.plus(n)
end function
return @_sum
end function
return adder.getSum
end function
 
acc1 = Accumulator(0)
print acc1(10) // prints 10
print acc1(2) // prints 12
 
acc2 = Accumulator(1)
print acc2(100) // prints 101
 
print acc1(0) // prints 12
 
</syntaxhighlight>
 
{{out}}
<pre>miniscript.exe accumulator.ms
10
12
101
12</pre>
 
=={{header|Nemerle}}==
Nemerle doesn't have a <tt>dynamic</tt> type, but we can use matching to bind types to <tt>object</tt>s.
<langsyntaxhighlight Nemerlelang="nemerle">def Foo(n) {
mutable value : object = n;
fun (i : object) {
Line 1,552 ⟶ 2,333:
x(5);
System.Console.WriteLine(x(2.3));
System.Console.WriteLine(y(3));</langsyntaxhighlight>
Output:
<pre>8.3
Line 1,558 ⟶ 2,339:
 
=={{header|NewLisp}}==
<langsyntaxhighlight NewLisplang="newlisp">(define (sum (x 0)) (inc 0 x))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,579 ⟶ 2,360:
>
</pre>
 
=={{header|NGS}}==
<syntaxhighlight lang="ngs">{
F Acc(start:Int) {
sum = start
F acc(i:Int) {
sum = sum + i
sum
}
}
 
acc = Acc(10)
echo(acc(5))
echo(acc(2))
}</syntaxhighlight>
{{out}}
<pre>15
17</pre>
 
=={{header|Nim}}==
Nim being a static typed language, if the accumulator function was created with an integer, it will always return an integer. So, it isn’t possible to fulfill the second requirement, at least by using standard types.
<lang nim>proc accumulator(sum: float): auto =
var sum = sum
return proc (n: float): float =
sum += n
return sum
 
Three solutions are possible:
var x = accumulator(1)
:– convert all values to float;
echo x(5) # 6
:– give the accumulator type the type of the initial value provided at the creation;
echo x(2.3) # 8.3
:– use a customized type.
We provide the code for the three solutions.
 
var=== yUsing =float accumulator(1) ===
Argument to the factory function may be any signed integer, unsigned integer or float.
echo y(5) # 6
Argument to the created accumulator function must be float.
echo y(2.3) # 8.3
Result is always float.
<syntaxhighlight lang="nim">
proc accumulator[T: SomeNumber](x: T): auto =
var sum = float(x)
result = proc (n: float): float =
sum += n
result = sum
 
let acc = accumulator(1)
echo acc(5) # 6
discard accumulator(3) # Create another accumulator.
echo acc(2.3) # 8.3
</syntaxhighlight>
 
{{out}}
<pre>
6.0
8.300000000000001
</pre>
 
=== Fixed accumulator type ===
Argument to the factory function nay be any signed integer, unsigned integer or float.
Argument to the accumulator function must be of the same type.
Result of the accumulator function is also of the same type.
<syntaxhighlight lang="nim">
proc accumulator[T: SomeNumber](x: T): auto =
var sum = x
result = proc (n: T): T =
sum += n
result = sum
 
let x = accumulator(1)
echo x(5) # 6
echo x(2) # 8
let y = accumulator(3.5)
echo y(2) # 5.5
echo y(3) # 8.5
</syntaxhighlight>
{{out}}
<pre>
6
8
5.5
8.5
</pre>
 
=== Customized number type ===
Argument to the factory function must be "int" or "float" (extension to other types is possible).
Argument of the accumulator function is of the customized type "Number" but may be "int" or "float"
thanks to the converters.
Result of the accumulator function is of type "Number" but will be displayed either as "int" or "float"
according to the actual contents.
 
This solution fulfills the requirements.
<syntaxhighlight lang="nim">
type
 
# Kind of numbers. We limit this example to "int" and "float".
NumberKind = enum kInt, kFloat
 
# Customized number type (using variants).
Number = object
case kind: NumberKind
of kInt:
ival: int
of kFloat:
fval: float
 
# The converters allow transparent conversion from int or float to Number.
converter toNumber(n: int): Number = Number(kind: kInt, ival: n)
converter toNumber(n: float): Number = Number(kind: kFloat, fval: n)
 
#---------------------------------------------------------------------------------------------------
 
proc accumulator[T: int|float](x: T): auto =
## Factory procedure.
 
# Allocate the accumulator storage.
when T is int:
var sum = Number(kind: kInt, ival: x)
elif T is float:
var sum = Number(kind: kFloat, fval: x)
 
# Create the accumulator procedure.
result = proc (n: Number): Number =
# Create the accumulator procedure.
result = proc (n: Number): Number =
case sum.kind
of kInt:
case n.kind
of kInt:
# Add an int to an int.
sum.ival += n.ival
of kFloat:
# Add a float to an int => change the kind of accumulator to float.
sum = Number(kind: kFloat, fval: sum.ival.toFloat + n.fval)
of kFloat:
case n.kind
of kInt:
# Add an int to a float.
sum.fval += n.ival.toFloat
of kFloat:
# Add a float to a float.
sum.fval += n.fval
result = sum
 
#---------------------------------------------------------------------------------------------------
 
proc `$`(n: Number): string =
## Display the accumulator contents as an int or a float depending of its kind.
case n.kind
of kInt: $n.ival
of kFloat: $n.fval
 
#---------------------------------------------------------------------------------------------------
 
let acc = accumulator(1)
echo acc(5) # 6
discard accumulator(3) # Create another accumulator.
echo acc(2.3) # 8.3
</syntaxhighlight>
 
{{out}}
<pre>
6
8.300000000000001
</pre>
 
=={{header|Nit}}==
 
Source: [https://github.com/nitlang/nit/blob/master/examples/rosettacode/accumulator_factory.nit the official Nit repository]
 
<syntaxhighlight lang="nit"># The `accumulator factory` task.
#
# Nit has no first-class function.
# A class is used to store the state.
module accumulator_factory
 
class Accumulator
# The accumulated sum
# Numeric is used, so Int and Float are accepted
private var sum: Numeric
fun call(n: Numeric): Numeric
do
# `add` is the safe `+` method on Numeric
sum = sum.add(n)
return sum
end
end
 
var x = new Accumulator(1)
x.call(5)
var y = new Accumulator(3)
print x.call(2.3)</syntaxhighlight>
 
var z = accumulator(3)
echo z(5) # 8
echo z(2.3) # 10.3
echo x(0) # 8.3
echo z(0) # 10.3</lang>
Output:
<pre>68.0000000000000000e+003</pre>
8.3000000000000007e+00
6.0000000000000000e+00
8.3000000000000007e+00
8.0000000000000000e+00
1.0300000000000001e+01
8.3000000000000007e+00
1.0300000000000001e+01</pre>
 
=={{header|Objeck}}==
Uses objects instead of first class functions.
<langsyntaxhighlight lang="objeck">bundle Default {
class Accumulator {
@sum : Float;
Line 1,631 ⟶ 2,570:
}
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
{{works with|Mac OS X|10.6+}}
<langsyntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
typedef double (^Accumulator)(double);
Line 1,657 ⟶ 2,596:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>8.300000</pre>
Line 1,664 ⟶ 2,603:
{{trans|Ruby}}
Deviations: An accumulator instance can take ''either'' integers ''or'' floats, but not both mixed (due to lack of runtime polymorphism).
<langsyntaxhighlight lang="ocaml">let accumulator sum0 =
let sum = ref sum0 in
fun n ->
Line 1,675 ⟶ 2,614:
let _ = accumulator 3.0 in
Printf.printf "%g\n" (x 2.3)
;;</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
Line 1,681 ⟶ 2,620:
=={{header|Octave}}==
 
<langsyntaxhighlight lang="octave"># not a function file:
1;
function fun = foo(init)
Line 1,691 ⟶ 2,630:
x(5);
foo(3);
disp(x(2.3));</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,697 ⟶ 2,636:
Oforth can only returns blocks, not functions, but a block can be used wherever a function is used.
 
The block returned by foo (a closure), when performed, retrieves the current value from the closure parameter, adds the top of stack, and stores the result back to the closure's parameter. The result is dup, so it is also returned.
foo creates a channel to hold the current value. Because foo does not return this channel, it can by used only by the block returned by foo.
 
<syntaxhighlight lang="oforth">: foo( n -- bl )
The block returned by foo (a closure with the channel value), when performed, retrieves the current value from the channel, adds the number, stores it back to the channel and returns it.
#[ n swap + dup ->n ] ;</syntaxhighlight>
 
Not part of the task, but, because of channel use, the accumulator is safe if used concurrently by multiple tasks (a task will block on receive if the channel is empty, waiting for the new value to be available).
 
<lang Oforth>: foo(n)
| ch |
Channel new dup ->ch send(n) drop
#[ ch receive swap + dup ch send drop ] ;</lang>
 
Usage :
<langsyntaxhighlight Oforthlang="oforth">: testfoo
| x y z |
foo(1) foo ->x
5 x perform .
foo(3) foo ->y
2.3 x perform dup . ", x accumulator value is a " . class .cr
10 y perform dup . ", y accumulator value is a " . class .cr
foo("aaa") foo ->z
"bbb" z perform dup . ", z accumulator value is a " . class .cr ;</lang>
;</syntaxhighlight>
 
{{out}}
<pre>
>testfoo
6 8.3 , x accumulator value is a #Float
13 , y accumulator value is a #Integer
aaabbb , z accumulator value is a #String
ok</pre>
 
=={{header|ooRexx}}==
ooRexx does not have functions that can maintain state between calls. The standard work around is to use an object instance and a defined method name.
<syntaxhighlight lang="oorexx">
<lang ooRexx>
x = .accumulator~new(1) -- new accumulator with initial value of "1"
x~call(5)
Line 1,754 ⟶ 2,688:
return sum
 
</syntaxhighlight>
</lang>
 
=={{header|OxygenBasic}}==
Line 1,819 ⟶ 2,753:
del af : del a : del b : del c
</pre>
 
 
=={{header|Oz}}==
A bit unwieldy because the '+' operator does not allow mixed type operands. The implementation is thread-safe (atomic Exchange operation).
<langsyntaxhighlight lang="oz">declare
fun {Acc Init}
State = {NewCell Init}
Line 1,850 ⟶ 2,783:
{X 5 _}
{Acc 3 _}
{Show {X 2.3}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
<syntaxhighlight lang="parigp">stack = List([1]);
factory(b,c=0) = my(a=stack[1]++);listput(stack,c);(b)->stack[a]+=b;
 
foo(f) = factory(0, f); \\ initialize the factory</syntaxhighlight>
 
Run the factory:<pre>gp > x = foo(1);
gp > x(5);
gp > y = foo(3);
gp > print(x(2.3));
8.300000000000
gp > print(y(1));
4
gp > print(x(1));
9.300000000000
gp > print(y(1/3));
13/3</pre>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
function foo(n: real): real -> real :=
i -> begin
n += i;
Result := n;
end;
 
begin
var x := foo(1);
x(5);
foo(3);
print(x(2.3));
end.
</syntaxhighlight>
 
{{out}}
<pre>
8.3
</pre>
 
 
=={{header|Perl}}==
There's a little deviation: the syntax <code>$x->(5)</code> differs from the usual <code>x(5)</code>.
 
{{trans|Ruby}}
<langsyntaxhighlight lang="perl">sub accumulator {
my $sum = shift;
sub { $sum += shift }
Line 1,861 ⟶ 2,837:
my $x = accumulator(1);
$x->(5);
print accumulator(3), "\n";
print $x->(2.3), "\n";</langsyntaxhighlight>
{{out}}
<pre>CODE(0x91131f0)8.3</pre>
8.3</pre>
 
=={{header|Perl 6Phix}}==
Emulated. There is nothing clever about this - both the answer and the task requirements!<br>
{{works with|Rakudo|2015.12}}
Numeric polymorphism is inherently supported in phix. While technically this does not return
<lang perl6>sub accum ($n is copy) { sub { $n += $^x } }</lang>
a function, the following demonstrates how the "standard_function" can be invoked in exactly
Example use:
the same manner as a result from the factory, without the caller knowing which is which, and
<lang perl6>my $a = accum 5;
I would guess that is one of the more important motivations for the original task. But it is
$a(4.5);
worth stating there are much easier ways to do this, hence generally speaking this approach
say $a(.5); # Prints "10".</lang>
is not particularly recommended or advocated.
You can also use the "&" sigil to create a function that behaves syntactically like any other function (i.e. no sigil nor parentheses needed to call it):
 
<lang perl6>my &b = accum 5;
A variation on [[Closures/Value_capture#Phix]], only in this case the inner function is kept
say b 3; # Prints "8".</lang>
in the returned variable and for simplicity there are no partial args - but it would be easy
enough to add that sort of flexibility here if needed.
 
Rule#5 is deliberately ignored: if rogue code can corrupt the accumulators variable, it can
just as easily corrupt the "closure" it would otherwise be held in, however well-hidden some
other programming language would like to pretend that is, and of course the latter sort of
corruption would be <i>significantly</i> harder to debug. Obviously, for safety, you would
normally make the accumulators variable private(/non-global) in a separate source file,
along with accumulate/accumulate_factory/call_function, and if you <i>really</i> don't like
accumulators being visible (??) I suppose you could always just allocate a bit of memory in
accumulator_factory() and return a pointer to that instead of an id/length.
 
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">accumulators</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">accumulate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">id</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">accumulators</span><span style="color: #0000FF;">[</span><span style="color: #000000;">id</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">v</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">accumulators</span><span style="color: #0000FF;">[</span><span style="color: #000000;">id</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">r_accumulate</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"accumulate"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">accumulator_factory</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">initv</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">accumulators</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">accumulators</span><span style="color: #0000FF;">,</span><span style="color: #000000;">initv</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">r_accumulate</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">accumulators</span><span style="color: #0000FF;">)}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #004080;">object</span> <span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">object</span> <span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #004080;">sequence</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">id</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">rid</span>
<span style="color: #000000;">args</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">id</span><span style="color: #0000FF;">&</span><span style="color: #000000;">args</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">call_func</span><span style="color: #0000FF;">(</span><span style="color: #000000;">rid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">args</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">standard_function</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">return</span> <span style="color: #008000;">"standard function"</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">r_standard_function</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">routine_id</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"standard_function"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">accumulator_factory</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">accumulator_factory</span><span style="color: #0000FF;">(</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2.3</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #000000;">y</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">call_function</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r_standard_function</span><span style="color: #0000FF;">,{})</span>
<!--</syntaxhighlight>-->
 
{{out}}
<pre>
8.3
10
"standard function"
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php"><?php
function accumulator($start){
return create_function('$x','static $v='.$start.';return $v+=$x;');
Line 1,886 ⟶ 2,915:
echo $acc(5), "\n"; //prints 10
echo $acc(10), "\n"; //prints 20
?></langsyntaxhighlight>
{{works with|PHP|5.3+}}
<langsyntaxhighlight lang="php"><?php
function accumulator($sum){
return function ($x) use (&$sum) { return $sum += $x; };
Line 1,895 ⟶ 2,924:
echo $acc(5), "\n"; //prints 10
echo $acc(10), "\n"; //prints 20
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de accumulator (Sum)
(curry (Sum) (N)
(inc 'Sum N) ) )
Line 1,905 ⟶ 2,934:
(a 1) # Output: -> 8
(a 2) # Output: -> 10
(a -5) # Output: -> 5</langsyntaxhighlight>
 
=={{header|Pony}}==
 
<syntaxhighlight lang="pony">
use "assert"
class Accumulator
var value:(I64|F64)
new create(v:(I64|F64))=>
value=v
fun ref apply(v:(I64|F64)=I64(0)):(I64|F64)=>
value=match value
| let x:I64=>match v
| let y:I64=>x+y
| let y:F64=>x.f64()+y
end
| let x:F64=>match v
| let y:I64=>x+y.f64()
| let y:F64=>x+y
end
end
value
 
actor Main
new create(env:Env)=>
var r:Accumulator=Accumulator(I64(0))
r(I64(5))
r(I64(2))
try
Fact(match r()
|let x:I64=>x==7
|let y:F64=>y==7.0
end)?
env.out.print("The value I have so far is " + r().string())
else
env.out.print("An error of some sort happened!")
end
r(F64(5.5))
env.out.print("This is okay..." + r().string())
</syntaxhighlight>
 
=={{header|PostScript}}==
<langsyntaxhighlight PostScriptlang="postscript">/mk-acc { % accumulator generator
{0 add 0 0 2 index put}
7 array copy
Line 1,924 ⟶ 2,992:
dup 100 exch exec = % add 100 to 13.14, print it
12 a = % add 12 to 8.71, print it
% accumulator #2 is still available on the stack</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Wikipedia says, “In programming languages, a closure is a function or reference to a function together with a referencing
environment. A closure—unlike a plain function pointer—allows a function to access those non-local variables even when invoked
outside its immediate lexical scope.”
 
The GetNewClosure method returns a ScriptBlock with captured variables.
<syntaxhighlight lang="powershell">
function Get-Accumulator ([double]$Start)
{
{param([double]$Plus) return $script:Start += $Plus}.GetNewClosure()
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
$total = Get-Accumulator -Start 1
& $total -Plus 5.0 | Out-Null
& $total -Plus 2.3
</syntaxhighlight>
{{Out}}
<pre>
8.3
</pre>
 
=={{header|Prolog}}==
{{works with|SWI Prolog}}
Uses the module '''lambda''' written by '''Ulrich Neumerkel'''.
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(lambda)).
 
define_g(N, G) :-
Line 1,943 ⟶ 3,033:
writeln(S),
call(G, 2.3, R1),
writeln(R1).</langsyntaxhighlight>
{{out}}
<pre>8 ?- accumulator.
Line 1,953 ⟶ 3,043:
=={{header|Python}}==
{{works with|Python|2.x/3.x}}
<langsyntaxhighlight lang="python">>>> def accumulator(sum):
def f(n):
f.sum += n
Line 1,978 ⟶ 3,068:
8.3000000000000007
>>> x2(0)
11.300000000000001</langsyntaxhighlight>
 
{{trans|Ruby}}
{{works with|Python|3.x}}
<langsyntaxhighlight lang="python">def accumulator(sum):
def f(n):
nonlocal sum
Line 1,992 ⟶ 3,082:
x(5)
print(accumulator(3))
print(x(2.3))</langsyntaxhighlight>
{{out}}
<pre><function f at 0xb7c2d0ac>
Line 1,998 ⟶ 3,088:
 
{{works with|Python|2.5+}}
<langsyntaxhighlight lang="python">def accumulator(sum):
while True:
sum += yield sum
Line 2,006 ⟶ 3,096:
x.send(5)
print(accumulator(3))
print(x.send(2.3))</langsyntaxhighlight>
{{out}}
<pre><generator object accumulator at 0x106555e60>
8.3</pre>
 
=={{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>.
 
<syntaxhighlight lang="quackery"> [ tuck tally share ]this[ swap ] is accumulate ( n s --> [ n )
 
[ [ stack ] copy tuck put nested
' accumulate nested join ] is factory ( n --> [ )</syntaxhighlight>
 
{{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 the updated accumulator function has remained on the stack. (Everything in Quackery is immutable ''except for'' ancillary stacks (created with <code>[ stack ]</code>), which Quackery has instead of variables. It is rare to embed an ancillary stack in a nest, but this is a good use case.)
 
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> 10 6 ** 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>
 
===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.]
 
<syntaxhighlight 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 ( [ $ --> [ $ )</syntaxhighlight>
 
{{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>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">accumulatorFactory <- function(init) {
currentSum <- init
function(add) {
Line 2,018 ⟶ 3,226:
currentSum
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,029 ⟶ 3,237:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">#lang racket
(define ((accumulator n) i)
(set! n (+ n i))
n)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang="raku" line>sub accum ($n is copy) { sub { $n += $^x } }
 
#Example use:
my $a = accum 5;
$a(4.5);
say $a(.5); # Prints "10".
 
# You can also use the "&" sigil to create a function that behaves syntactically
# like any other function (i.e. no sigil nor parentheses needed to call it):
 
my &b = accum 5;
say b 3; # Prints "8".</syntaxhighlight>
 
=={{header|REBOL}}==
<langsyntaxhighlight lang="rebol">make-acc-gen: func [start-val] [
use [state] [
state: start-val
Line 2,043 ⟶ 3,267:
]
]
]</langsyntaxhighlight>
{{out}}
<pre>>> x: make-acc-gen 1
Line 2,054 ⟶ 3,278:
=={{header|Retro}}==
Retro only supports integers.
<lang Retro> : acc here swap , [ &+! &@ bi ] curry ;
 
<syntaxhighlight lang="retro">:acc (ns-)
( create an accumulator function )
d:create , [ [ fetch ] [ v:inc ] bi ] does ;</syntaxhighlight>
1 acc
{{out}}
<pre> #10 'foo acc
foo
foo
foo
 
dump-stack
( and give it a name )
constant x
 
10 11 12
( add values to it and display the results )
Ok</pre>
5 x do putn
2 x do putn</lang>
 
=={{header|REXX}}==
This REXX program is partially modeled after the ooRexx example.
<br><br>This example will handle any kind of number: integer, floating point.
<langsyntaxhighlight lang="rexx">/*REXX program shows one method an accumulator factory could be implemented. */
x=.accumulator(new(1)) /*initialize accumulator with a 1 value*/
x=call(5)
x=call(2.3)
say "' X value is now"' x /*displays the current value of X. */
say "'Accumulator value is now"' sum /*displays the current value of accum.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
.accumulator: procedure expose sum; if symbol('SUM')=='"LIT'" then sum=0 /*1st time?*/
sum=sum + arg(1) /*add──►sum*/
return sum
/*──────────────────────────────────────────────────────────────────────────────────────*/
/*────────────────────────────────────────────────────────────────────────────*/
call: procedure expose sum; sum=sum+arg(1); return sum /*addsadd arg1 ──► sum.*/</syntaxhighlight>
new: procedure; return arg(1) /*long way 'round of using one.*/</lang>
'''output'''
<pre>
Line 2,090 ⟶ 3,315:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">oGenerator = new Generator
 
Func main
Line 2,111 ⟶ 3,336:
return aN[#id#]
}
}","#id#",string(len(aN))))</langsyntaxhighlight>
 
{{out}}
Line 2,117 ⟶ 3,342:
6
8.30
</pre>
 
=={{header|RPL}}==
 
This implementation complies with all the rules except maybe the last one ("Doesn't store the accumulated value or the returned functions in a way that could cause them to be inadvertently modified by other code"). The accumulated value is actually stored in a global variable, but as its name is generated with the system time, the likelihood of another code guessing it is very low - unless that code deliberately intends to do so.
{{works with|HP|48}}
{| class="wikitable" ≪
! RPL code
! Comment
|-
|
"M" TIME →STR + SWAP
OVER OBJ→ STO
"≪ '" SWAP + "' STO+ SWAP DROP RCL ≫" + OBJ→
≫ ‘<span style="color:blue">FOO</span>’ STO
|
<span style="color:blue">FOO</span> ''( n → ≪ accumulator ≫ ) ''
create a global variable with a timestamp name
initialize variable with n
create lambda function
.
|}
Let's check it works:
{| class="wikitable" ≪
! Command line
! Test example
|-
|
1 <span style="color:blue">FOO</span> 'X' STO
5 X DROP
3 <span style="color:blue">FOO</span> DROP
2.3 X
|
x = foo(1); <span style="color:grey">// X contains ≪ 'M17.3741285888' STO+ LASTARG SWAP DROP RCL ≫</span>
x(5);
foo(3);
print x(2.3);
|}
{{out}}
<pre>
1: 8.3
</pre>
 
=={{header|Ruby}}==
Ruby hasdeviates methodsfrom andthe blocks.task Thesebecause aremethods bothand realProc functions,objects buthave not with the samedifferent syntax. Our accumulator factory is a method that returns a block (in a Proc object). So, <tt>x = accumulator(1)</tt> is valid, but <tt>x(5)</tt> is an error: the syntax must be <tt>x.call(5)</tt> or <tt>x[5]</tt> (with square brackets). Ruby 1.9 also allows <tt>x.(5)</tt> (with an extra dot).
 
<lang ruby>def accumulator(sum)
<syntaxhighlight lang="ruby">def accumulator(sum)
lambda {|n| sum += n}
end
Line 2,128 ⟶ 3,396:
x = accumulator(1)
x.call(5)
p accumulator(3) # add some output to show what it returns
puts x.call(2.3) # prints 8.3</syntaxhighlight>
 
The output of <tt>p accumulator(3)</tt> looks like
 
<pre>
#<Proc:0x0000000207ba7f30@/tmp/accumulator.rb:2> # Ruby 1.8.6
#<Proc:0x000002060d1788@/tmp/accumulator.rb:2 (lambda)> # Ruby 1.9.2
</pre>
 
This accumulator also works with other types that have a <tt>+</tt> method.
 
<syntaxhighlight lang="ruby">require 'rational'
# mixing Rational and Complex
require 'rational'
require 'complex'
y = accumulator(Rational(2, 3))
puts y.call([Rational(1, 2))] # 7/6
puts y[4] # 31/6
puts y.call(4)
puts y.call([Complex(0, 1))] # 31/6+1i
puts y.call(Complex.polar(6, 5 * Math::PI / 4))
puts x.call(0) # again prints 8.3
 
# using other things that have a + method
t = accumulator(Time.utc(1999, 8, 7, 6, 5))
# (Ruby 1.8.6) (Ruby 1.9.2)
puts t.call(4) # prints 1999-08-07 06:05:04 UTC
puts t[4] # Sat Aug 07 06:05:04 UTC 1999 1999-08-07 06:05:04 UTC
puts t[-12 * 60 * 60] # Fri Aug 06 18:05:04 UTC 1999 1999-08-06 18:05:04 UTC
 
require 'matrix'
m = accumulator(Matrix[[1, 2], [3, 4]])
puts m.call([Matrix[[5, 6], [7, 8]])] # Matrix[[6, 8], [10, 12]]</syntaxhighlight>
 
puts t.call(-12 * 60 * 60) # subtracts 12 hours
If we define x as a method of self, then the syntax <code>x(5)</code> works, but we deviate more from the task, because x might get "inadvertently modified" by other methods of self.
puts y.call(1e200)
 
puts x.call(0) # again prints 8.3</lang>
<syntaxhighlight lang="ruby">def accumulator(sum)
{{out}}
lambda {|n| sum += n}
{| class="wikitable"
end
! Output from Ruby 1.8.6
class << self
! Output from Ruby 1.9.2
define_method :x, &accumulator(1)
|-
end
| <pre>#<Proc:0x0000000207ba7f30@/tmp/accumulator.rb:2>
x(5)
8.3
accumulator(3)
31/6
puts x(2.3) # prints 8.3</syntaxhighlight>
31/6+1i
0.924025979547381-3.24264068711928i
8.3
Sat Aug 07 06:05:04 UTC 1999
Matrix[[6, 8], [10, 12]]
Fri Aug 06 18:05:04 UTC 1999
1.0e+200-3.24264068711928i
8.3</pre>
| <pre>#<Proc:0x000002060d1788@/tmp/accumulator.rb:2 (lambda)>
8.3
31/6
31/6+1i
0.9240259795473813-3.2426406871192848i
8.3
1999-08-07 06:05:04 UTC
Matrix[[6, 8], [10, 12]]
1999-08-06 18:05:04 UTC
1.0e+200-3.2426406871192848i
8.3</pre>
|}
 
=={{header|Rust}}==
Line 2,185 ⟶ 3,441:
Changing "x = foo(1.)" to "x = foo(1)" in the code below should not change the output (it does).
 
<langsyntaxhighlight lang="rust">// rustc -V1.26.0 or later
// rustc 1.2.0-nightly (0cc99f9cc 2015-05-17) (built 2015-05-18)
 
use std::ops::Add;
 
fn foo<Num>(n: Num) -> Box<impl FnMut(Num) -> Num>
where Num: Add<Output=Num> + Copy + 'static {
let mut acc = n;
Box::new(move |i: Num| {
acc = acc + i;
acc
})
}
 
Line 2,204 ⟶ 3,459:
foo(3.);
println!("{}", x(2.3));
}</langsyntaxhighlight>
{{out}}
<pre>
8.3
</pre>
 
=== Over-engineered Solution ===
This solution uses a custom number type that can be either an i64 or f64. It also creates a generic struct that is callable using the unstable fn traits, which can be called to add anything that can be added to it's accumulator value.
<syntaxhighlight lang="rust">// Accumulator
#![feature(unboxed_closures, fn_traits)]
 
pub struct Accumulator<T> {
value: T,
}
 
impl<T> Accumulator<T> {
pub fn new(value: T) -> Self {
Self { value }
}
}
 
impl<T, N> FnOnce<(N,)> for Accumulator<T>
where
T: std::ops::AddAssign<N> + Clone,
{
type Output = T;
extern "rust-call" fn call_once(mut self, (n,): (N,)) -> T {
self.value += n;
self.value
}
}
 
impl<T, N> FnMut<(N,)> for Accumulator<T>
where
T: std::ops::AddAssign<N> + Clone,
{
extern "rust-call" fn call_mut(&mut self, (n,): (N,)) -> T {
self.value += n;
self.value.clone()
}
}
 
// Number
#[derive(Copy, Clone, Debug)]
pub enum Number {
Int(i64),
Float(f64),
}
 
impl From<i64> for Number {
fn from(int: i64) -> Number {
Number::Int(int)
}
}
 
impl From<f64> for Number {
fn from(float: f64) -> Number {
Number::Float(float)
}
}
 
impl std::ops::AddAssign<i64> for Number {
fn add_assign(&mut self, n: i64) {
match self {
Number::Int(s) => *s += n,
Number::Float(s) => *s += n as f64,
}
}
}
 
impl std::ops::AddAssign<f64> for Number {
fn add_assign(&mut self, n: f64) {
*self = match *self {
Number::Int(s) => Number::Float(s as f64 + n),
Number::Float(s) => Number::Float(s + n),
}
}
}
 
impl std::fmt::Display for Number {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Number::Int(x) => write!(f, "{}", x),
Number::Float(x) => write!(f, "{}", x),
}
}
}
 
// Demonstration
fn foo(n: impl Into<Number>) -> Accumulator<Number> {
Accumulator::new(n.into())
}
 
fn main() {
let mut x = foo(1);
x(5);
foo(3);
println!("{}", x(2.3));
 
let mut s = Accumulator::new(String::from("rosetta"));
s(" ");
println!("{}", s("code"));
}</syntaxhighlight>
{{out}}
<pre>8.3
rosetta code</pre>
 
=={{header|Scala}}==
The type of a function can't change in Scala, and there is no "numeric" type that is a supertype of all such types. So, if the accumulator is declared as integer, it can only receive and return integers, and so on.
<langsyntaxhighlight lang="scala">def AccumulatorFactory[N](n: N)(implicit num: Numeric[N]) = {
import num._
var acc = n
Line 2,219 ⟶ 3,575:
acc
}
}</langsyntaxhighlight>
{{out|Sample}}
<pre>
Line 2,237 ⟶ 3,593:
=={{header|Scheme}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="scheme">(define (accumulator sum)
(lambda (n)
(set! sum (+ sum n))
Line 2,251 ⟶ 3,607:
(x 5)
(display (accumulator 3)) (newline)
(display (x 2.3)) (newline)</langsyntaxhighlight>
{{out}}
<pre>#<procedure>
Line 2,257 ⟶ 3,613:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Accumulator(sum) {
method add(num) {
sum += num;
Line 2,266 ⟶ 3,622:
x.add(5);
Accumulator(3);
say x.add(2.3); # prints: 8.3</langsyntaxhighlight>
 
The same thing can be achieved by returning a closure from the '''Accumulator''' function.
 
<langsyntaxhighlight lang="ruby">func Accumulator(sum) {
func(num) { sum += num };
}
Line 2,277 ⟶ 3,633:
x(5);
Accumulator(3);
say x(2.3); # prints: 8.3</langsyntaxhighlight>
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
! ABSTRACTION FOR SIMULA'S TWO NUMERIC TYPES ;
CLASS NUMBER;
VIRTUAL:
PROCEDURE OUT IS PROCEDURE OUT;;
BEGIN
END NUMBER;
 
NUMBER CLASS INTEGERNUMBER(INTVAL); INTEGER INTVAL;
BEGIN
PROCEDURE OUT; OUTINT(INTVAL, 10);
END INTEGERNUMBER;
 
NUMBER CLASS REALNUMBER(REALVAL); REAL REALVAL;
BEGIN
PROCEDURE OUT; OUTFIX(REALVAL, 4, 10);
END REALNUMBER;
 
 
! SIMULA CANNOT RETURN FUNCTIONS - SIMULATE FUNCTIONS WITH CLASSES ;
CLASS ACCUMULATOR(ACC); REF(NUMBER) ACC;
BEGIN
 
PROCEDURE SWITCHTOREAL(Y); REAL Y;
BEGIN
REF(REALNUMBER) NEWACC;
NEWACC :- NEW REALNUMBER(ACC QUA INTEGERNUMBER.INTVAL);
NEWACC.REALVAL:= NEWACC.REALVAL + Y;
ACC :- NEWACC;
END SWITCHTOREAL;
 
REF(NUMBER) PROCEDURE ACCUMULATE(OTHERNUM); REF(NUMBER) OTHERNUM;
BEGIN
INSPECT ACC
WHEN INTEGERNUMBER DO
BEGIN
INSPECT OTHERNUM
WHEN INTEGERNUMBER DO
ACC QUA INTEGERNUMBER.INTVAL
:= ACC QUA INTEGERNUMBER.INTVAL + INTVAL
WHEN REALNUMBER DO
SWITCHTOREAL(REALVAL)
END
WHEN REALNUMBER DO
BEGIN
INSPECT OTHERNUM
WHEN INTEGERNUMBER DO
ACC QUA REALNUMBER.REALVAL
:= ACC QUA REALNUMBER.REALVAL + INTVAL
WHEN REALNUMBER DO
ACC QUA REALNUMBER.REALVAL
:= ACC QUA REALNUMBER.REALVAL + REALVAL
END;
ACCUMULATE :- ACC;
END ACCUMULATE;
 
PROCEDURE OUT; ACC.OUT;
 
END FOO;
 
 
REF(ACCUMULATOR) FOO;
FOO :- NEW ACCUMULATOR(NEW INTEGERNUMBER(1)); FOO.OUT; OUTIMAGE;
FOO.ACCUMULATE(NEW INTEGERNUMBER(5)); FOO.OUT; OUTIMAGE;
NEW ACCUMULATOR(NEW INTEGERNUMBER(3));
FOO.ACCUMULATE(NEW REALNUMBER(2.3)); FOO.OUT; OUTIMAGE;
 
END.
</syntaxhighlight>
{{out}}
<pre>
1
6
8.3000
</pre>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">Object subclass: AccumulatorFactory [
AccumulatorFactory class >> new: aNumber [
|r sum|
Line 2,299 ⟶ 3,733:
(x value: 2.3) displayNl.
"x inspect."
"de-comment the previous line to show that x is a block closure"</langsyntaxhighlight>
 
the above can also be done without a class to hold the block, simply by putting it into another block (i.e. an outer closure for the sum, returning an inner function which updates that sum):
{{works with|Smalltalk/X}}
<langsyntaxhighlight lang="smalltalk">|factory aaccu1 accu2|
 
factory := [:initial |
Line 2,314 ⟶ 3,748:
].
 
aaccu1 := factory value:1.
aaccu1 value:5.
accu2 := factory value:310.
accu2 value:5.
(a value:2.3) printCR "-> 8.3 "</lang>
(accu1 value:2.3) printCR. "-> 8.3 (a float)"
(accu2 value:0) printCR. "-> 15 (an integer)"
(accu2 value:22 factorial) printCR. "-> a large integer"</syntaxhighlight>
{{out}}
<pre>8.3
15
1124000727777607680015</pre>
 
=={{header|Standard ML}}==
{{trans|OCaml}}
Deviations: An accumulator instance can take ''either'' integers ''or'' reals, but not both mixed (due to lack of runtime polymorphism).
<langsyntaxhighlight lang="sml">fun accumulator (sum0:real) : real -> real = let
val sum = ref sum0
in
Line 2,336 ⟶ 3,777:
in
print (Real.toString (x 2.3) ^ "\n")
end;</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func makeAccumulator(var sum: Double) -> Double -> Double {
return {
sum += $0
Line 2,351 ⟶ 3,792:
x(5)
let _ = makeAccumulator(3)
println(x(2.3))</langsyntaxhighlight>
{{out}}
<pre>8.3</pre>
Line 2,358 ⟶ 3,799:
{{works with|Tcl|8.6}}
This uses nested [[wp:coroutine|coroutine]]s to manage the state, which for the outer coroutine is a counter used to generate unique instances of the inner coroutine, and for the inner coroutine it is the actual accumulator variable. Note that Tcl commands (including coroutines) are ''never'' nameless, but it is trivial to synthesize a name for them. It's possible to guarantee uniqueness of names, but just using a simple sequence generator gets 90% of the effect for 10% of the effort.
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
# make the creation of coroutines without procedures simpler
Line 2,385 ⟶ 3,826:
} $n
}
}</langsyntaxhighlight>
Sample usage (extra characters over Paul's example to show more clearly what is going on):
<langsyntaxhighlight lang="tcl">% set x [accumulator 1]
::accumulator.1
% $x 5
Line 2,394 ⟶ 3,835:
::accumulator.2
% puts ">>[$x 2.3]<<"
>>8.3<<</langsyntaxhighlight>
 
=={{header|Unicon}}==
Strictly speaking, <tt>genAcc(n)</tt> returns a <i>co-expression</i>, not a function. However, the invocation syntax here is indistinguishable from calling a function.
<lang Unicon>procedure main()
a := genAcc(3)
b := genAcc(5)
write(" " ,center("a",5), " ", center("b", 5))
write("genAcc: ", right(a(4),5), " ", right(b(4), 5))
write("genAcc: ", right(a(2),5), " ", right(b(3),5))
write("genAcc: ", right(a(4.5),5)," ", right(b(1.3),5))
end
 
procedure genAcc(n) # The generator factory
return makeProc { while i := (n@&source)[1] do n +:= i }
end
 
procedure makeProc(A) # A Programmer-Defined Control Operation
return (@A[1],A[1])
end</lang>
Note: The co-expression calling sequence used is Unicon specific.
{{out}}
<pre>
a b
genAcc: 7 9
genAcc: 9 12
genAcc: 13.5 13.3
</pre>
 
=={{header|TXR}}==
Line 2,428 ⟶ 3,841:
===Verbose===
 
<langsyntaxhighlight lang="txrlisp">(defun accumulate (sum)
(lambda (n)
(inc sum n)))
Line 2,436 ⟶ 3,849:
((set num (iread : : nil)))
((format t "~s -> ~s\n" num [f num])))
(exit 0)</langsyntaxhighlight>
 
{{out|Run}}
Line 2,458 ⟶ 3,871:
===Sugared===
 
<langsyntaxhighlight lang="txrlisp">(let ((f (let ((sum 0)) (do inc sum @1))))
(mapdo (do put-line `@1 -> @[f @1]`) (gun (iread : : nil))))</langsyntaxhighlight>
{{out}}
<pre>$ echo "1 2 3 4.5" | txr accumulator-factory2.tl
Line 2,471 ⟶ 3,884:
Using the <code>obtain</code>/<code>yield</code> interface to delimited continuations, we can turn an imperative for loop into an accumulation function:
 
<langsyntaxhighlight lang="txrlisp">(defun accum ()
(for ((sum (yield-from accum)))
()
Line 2,477 ⟶ 3,890:
 
(let ((f (obtain (accum))))
(mapdo (do put-line `@1 -> @[f @1]`) (gun (iread : : nil))))</langsyntaxhighlight>
{{out}}
<pre>$ echo "1 2 3 4.5" | txr accumulator-factory2.tl
Line 2,489 ⟶ 3,902:
OOP languages can use objects to simulate closures. In particular, function-objects which can be called as if they were functions, without any visible method being referenced. TXR Lisp supports functors as an expression of irony in language design. A structure object for which a method named <code>lambda</code> is defined can be used as function. Arguments applied to the objects are applied to lambda, preceded by the object itself as the leftmost argument:
 
<langsyntaxhighlight lang="txrlisp">(defstruct (accum count) nil
(count 0))
 
Line 2,498 ⟶ 3,911:
;; the construction of the function object bound to variable f.
(let ((f (new (accum 0))))
(mapdo (do put-line `@1 -> @[f @1]`) (gun (iread : : nil))))</langsyntaxhighlight>
 
=={{header|Unicon}}==
Strictly speaking, <tt>genAcc(n)</tt> returns a <i>co-expression</i>, not a function. However, the invocation syntax here is indistinguishable from calling a function.
<syntaxhighlight lang="unicon">procedure main()
a := genAcc(3)
b := genAcc(5)
write(" " ,center("a",5), " ", center("b", 5))
write("genAcc: ", right(a(4),5), " ", right(b(4), 5))
write("genAcc: ", right(a(2),5), " ", right(b(3),5))
write("genAcc: ", right(a(4.5),5)," ", right(b(1.3),5))
end
 
procedure genAcc(n) # The generator factory
return makeProc { while i := (n@&source)[1] do n +:= i }
end
 
procedure makeProc(A) # A Programmer-Defined Control Operation
return (@A[1],A[1])
end</syntaxhighlight>
Note: The co-expression calling sequence used is Unicon specific.
{{out}}
<pre>
a b
genAcc: 7 9
genAcc: 9 12
genAcc: 13.5 13.3
</pre>
 
=={{header|UNIX Shell}}==
Line 2,505 ⟶ 3,946:
The shell is a bad choice for this task. This example plays tricks with <tt>eval</tt>. The difficulty with <tt>eval</tt> is to put the quotation marks " and dollar signs <tt>$</tt> in the correct place, and escape them with the correct number of backslashes \. One missing (or one extra) backslash can ruin the entire program.
{{works with|pdksh}}
<langsyntaxhighlight lang="bash">#!/bin/sh
accumulator() {
# Define a global function named $1
Line 2,522 ⟶ 3,963:
echo $r
y r -3000
echo $r</langsyntaxhighlight>
{{out}}
<pre>$ sh accumulator.sh
Line 2,530 ⟶ 3,971:
==={{header|es}}===
A better shell for this task is ''es'', because it has lexical variables and closures. <code>@ i {code}</code> is a lambda with parameter ''i'', and <code>fn accumulator n {code}</code> is sugar for <code>fn-accumulator = @ n {code}</code>.
<langsyntaxhighlight lang="es">fn accumulator n {
result @ i {
n = `{echo $n + $i | bc}
Line 2,541 ⟶ 3,982:
fn-y = <={accumulator 3}
echo <={x 2.3}
echo <={y -3000}</langsyntaxhighlight>
 
== {{header|Ursalang}} ==
Ursalang has only a single number type.
<syntaxhighlight lang="ursalang">let fac = fn(n) {
fn(i) {
n := n + i
}
}
 
let x = fac(1)
x(5)
fac(3)
print(x(2.3))</syntaxhighlight>
 
=={{header|VBScript}}==
I'm not entirely convinced that this is actually doing what is asked. A VBScript guru I'm not. The answer's right, though.
;Implementation
<langsyntaxhighlight lang="vb">class accumulator
dim A
public default function acc(x)
Line 2,555 ⟶ 4,010:
accum = A
end property
end class</langsyntaxhighlight>
;Invocation
<langsyntaxhighlight lang="vb">dim a
set a = new accumulator
x = a( 1 )
Line 2,564 ⟶ 4,019:
set b = new accumulator
b 3
wscript.echo a(2.3)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,571 ⟶ 4,026:
 
=={{header|Wart}}==
<langsyntaxhighlight lang="python">def (accumulator n)
(fn() ++n)</langsyntaxhighlight>
 
Example usage:
Line 2,585 ⟶ 4,040:
(a)
=> 6</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var accumulator = Fn.new { |acc| Fn.new { |n| acc = acc + n } }
 
var x = accumulator.call(1)
x.call(5)
accumulator.call(3)
System.print(x.call(2.3))</syntaxhighlight>
 
{{out}}
<pre>
8.3
</pre>
 
=={{header|x86 Assembly}}==
{{works with|NASM}}
{{works with|Linux}}
32 bit
 
The accumulator function that is returned uses a section of its instruction space to store the accumulated sum.
This way it works without having to keep track of any addresses external to the function itself.
The only deviation from the spec is that this only works with integer values.
With some extra work, floating point numbers can be incorporated, but outputting would be trickier.
 
<syntaxhighlight lang="asm">
; Accumulator factory
; Returns a function that returns the sum of all numbers ever passed in
; Build:
; nasm -felf32 af.asm
; ld -m elf32_i386 af.o -o af
 
global _start
section .text
 
_start:
mov eax, 0x2D ; sys_brk(unsigned long brk)
xor ebx, ebx ; Returns current break on an error
int 0x80 ; syscall
push eax ; Save the initial program break
 
push 2 ; Get an accumulator initialized to 2
call factory
mov [acc1], eax ; Save the pointer in acc1
 
push 5 ; Get an accumulator initialized to 5
call factory
mov [acc2], eax ; Save the pointer in acc2
 
push 4 ; Call acc1 with 4
lea eax, [acc1]
call [eax]
 
push 4 ; Call acc2 with 4
lea eax, [acc2]
call [eax]
 
push -9 ; Call acc1 with -9
lea eax, [acc1]
call [eax]
 
push 13 ; Call acc1 with 13
lea eax, [acc1]
call [eax]
 
push eax ; Print the number, should be 10
call print_num
 
push -5 ; Call acc2 with -5
lea eax, [acc2]
call [eax]
 
push eax ; Print the number, should be 4
call print_num
 
mov eax, 0x2D ; Reset the program break
pop ebx
int 0x80
 
mov eax, 0x01 ; sys_exit(int error)
xor ebx, ebx ; error = 0 (success)
int 0x80
 
; int (*function)(int) factory (int n)
; Returns a pointer to a function that returns the sum of all numbers passed
; in to it, including the initial parameter n;
factory:
push ebp ; Create stack frame
mov ebp, esp
push ebx
push edi
push esi
 
mov eax, 0x2D ; Allocate memory for the accumulator
xor ebx, ebx
int 0x80
push eax ; Save the current program break
mov ebx, .acc_end ; Calculate the new program break
sub ebx, .acc
push ebx ; Save the length
add ebx, eax
mov eax, 0x2D
int 0x80
 
pop ecx ; Copy the accumulator code into memory
pop eax ; Set the returned address
mov edi, eax
mov esi, .acc
rep movsb
lea edi, [eax + 10] ; Copy the parameter to initialize accumulator
lea esi, [ebp + 8]
movsd
 
pop esi ; Tear down stack frame
pop edi
pop ebx
mov esp, ebp
pop ebp
ret 4 ; Return and remove parameter from stack
 
.acc: ; Start of the returned accumulator
push ebp
mov ebp, esp
push edi
push esi
 
call .acc_skip ; Jumps over storage, pushing address to stack
dd 0 ; The accumulator storage (32 bits)
.acc_skip:
pop esi ; Retrieve the accumulator using address on stack
lodsd
add eax, [ebp + 8] ; Add the parameter
lea edi, [esi - 4]
stosd ; Save the new value
 
pop esi
pop edi
mov esp, ebp
pop ebp
ret 4
.acc_end: ; End of accumulator
 
; void print_num (int n)
; Prints a positive integer and a newline
print_num:
push ebp
mov ebp, esp
 
mov eax, [ebp + 8] ; Get the number
lea ecx, [output + 10] ; Put a newline at the end
mov BYTE [ecx], 0x0A
mov ebx, 10 ; Divisor
.loop:
dec ecx ; Move backwards in string
xor edx, edx
div ebx
add edx, 0x30 ; Store ASCII digit
mov [ecx], dl
cmp eax, 0 ; Loop until all digits removed
jnz .loop
 
mov eax, 0x04 ; sys_write(int fd, char *buf, int len)
mov ebx, 0x01 ; stdout
lea edx, [output + 11] ; Calulate length
sub edx, ecx
int 0x80
 
mov esp, ebp
pop ebp
ret 4
 
section .bss
acc1: ; Variable that stores the first accumulator
resd 1
acc2: ; Variable that stores the second accumulator
resd 1
output: ; Holds the output buffer
resb 11
</syntaxhighlight>
 
Output
 
<pre>
10
4
</pre>
 
=={{header|XLISP}}==
There are probably other ways of doing it, but this is one way.
<syntaxhighlight lang="lisp">(defun accumulator (x)
(lambda (n)
(setq x (+ n x))
x ) )</syntaxhighlight>
Test it in a REPL:
<pre>[1] (define f (accumulator 1))
 
F
[2] (define g (accumulator 3))
 
G
[3] (f 5)
 
6
[4] (g 1.7)
 
4.7
[5] (f 9)
 
15</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">sub foo$(n)
local f$
f$ = "f" + str$(int(ran(1000000)))
compile("sub " + f$ + "(n): static acum : acum = acum + n : return acum : end sub")
execute(f$, n)
return f$
end sub
 
x$ = foo$(1)
execute(x$, 5)
foo$(3)
print execute(x$, 2.3)
</syntaxhighlight>
 
=={{header|Yorick}}==
Yorick cannot dynamically create new functions. Instead, the accum function can be called in two ways: directly, in which case its first argument is numerical; or through a closure, where its first argument is implicitly an object and the second is the user-provided argument. This example uses closures and group objects, which require Yorick 2.2 or later.
<langsyntaxhighlight lang="yorick">func accum(data, n) {
if(!is_obj(data))
return closure(accum, save(total=data));
save, data, total=data.total + n;
return data.total;
}</langsyntaxhighlight>
Example of use (interactive session):
<pre>> x = accum(1)
Line 2,605 ⟶ 4,284:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn foo(n){ fcn(n,acc){ acc.set(n+acc.value).value }.fp1(Ref(n)) }</langsyntaxhighlight>
A strong reference (Ref) is used as the accumulator, a Ref acts like a one element list. The Ref is bound to the new functions second parameter with the .fp1 method.
<pre>
Line 2,619 ⟶ 4,298:
The output switches between int and float based on the most recent input: With addition, the first operand casts the second: int + int|float --> int and float + int|float --> float. If the desire is to make the behavior "once float, always float", a 0 or 0.0 can be used to start the sum and stashed in a another bit of state.
 
{{omit from|ARM Assembly}}
{{omit from|Scratch|cannot generate functions nor pass them as arguments or values}}
{{omit from|Commodore BASIC}}
{{omit from|C}} <!-- C's type system imcompatible with task spec -->
{{omit from|ML/I}}
{{omit from|PhixScratch|cannot generate generalfunctions toolnor factorypass factorythem factory,as eitherarguments or values}}
46

edits