Accumulator factory: Difference between revisions

added RPL
m (syntax highlighting fixup automation)
(added RPL)
(14 intermediate revisions by 9 users not shown)
Line 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>:
:: <syntaxhighlight lang="pseudocode">x = foo(1);
x(5);
foo(3);
Line 33:
 
=={{header|11l}}==
<syntaxhighlight lang="11l">F accumulator(n)
T Accumulator
Float s
Line 62:
 
=={{header|8th}}==
<syntaxhighlight lang=Forth"forth">
\ RossetaCode 'accumulator factory'
 
Line 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 ===
<syntaxhighlight lang=ABAP"abap">report z_accumulator
class acc definition.
public section.
Line 134:
</pre>
=== JavaScript Solution ===
<syntaxhighlight lang=ABAP"abap">data: lv_source type string,
cl_processor type ref to cl_java_script,
lv_ret type string.
Line 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}}
<syntaxhighlight lang=ActionScript"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 180:
 
=={{header|Ada}}==
<syntaxhighlight lang=Ada"ada">with Accumulator;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 192:
end;</syntaxhighlight>
 
<syntaxhighlight lang=Ada"ada">generic package Accumulator is
 
-- This Ada generic package represents an accumulator factory.
Line 204:
end;</syntaxhighlight>
 
<syntaxhighlight lang=Ada"ada">package body Accumulator is
 
-- The accumulator lives through three states. It is in Virgin_State
Line 271:
=={{header|Aikido}}==
{{trans|Javascript}}
<syntaxhighlight lang="aikido">function accumulator (sum:real) {
return function(n:real) { return sum += n }
}
Line 284:
 
=={{header|Aime}}==
<syntaxhighlight lang="aime">af(list l, object o)
{
l[0] = l[0] + o;
Line 304:
<pre>8.3</pre>
The type is properly preserved over summing:
<syntaxhighlight lang="aime"> f = af.apply(list(5));
 
f(-6);
Line 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 -->
<syntaxhighlight lang="algol68">MODE NUMBER = UNION(INT,REAL,COMPL);
 
PROC plus = (NUMBER in a, in b)NUMBER: (
Line 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>.
 
<syntaxhighlight lang="applescript">on accumulator(n)
-- Returns a new script object
-- containing a handler.
Line 387:
Or, to match the task spec and output a little more closely:
 
<syntaxhighlight lang=AppleScript"applescript">on run
set x to foo(1)
Line 410:
=={{header|Argile}}==
{{works with|Argile|1.1.1}}
<syntaxhighlight lang=Argile"argile">use std, array
 
let A = accumulator 42
Line 464:
autocast accumulator<->Accumulator</syntaxhighlight>
 
{{omit from|ARM Assembly}}
 
=={{header|Astro}}==
<syntaxhighlight lang="python">fun accumulator(var sum): :: Real -> _
n => sum += n
 
Line 478 ⟶ 477:
{{works with|BBC BASIC for Windows}}
This code works by copying the function FNdummy() onto the heap and returning a pointer to it.
<syntaxhighlight lang="bbcbasic"> x = FNaccumulator(1)
dummy = FN(x)(5)
dummy = FNaccumulator(3)
Line 497 ⟶ 496:
 
=={{header|Bracmat}}==
NoticeUntil that2023 Bracmat hashad no facility for handling floating point numbers,. This solution handles only rational numbers.
<syntaxhighlight lang="bracmat">( ( accumulator
=
.
Line 515 ⟶ 514:
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}}==
<syntaxhighlight lang="brat">accumulator = { sum |
{ n | sum = sum + n }
}
Line 530 ⟶ 571:
Ported from [[Ruby]].
 
<syntaxhighlight lang="bqn">Acc ← {
𝕊 sum:
{sum+↩𝕩}
Line 544 ⟶ 585:
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.
 
<syntaxhighlight lang=C"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 565 ⟶ 606:
=={{header|C sharp|C#}}==
{{works with|C sharp|4.0}}
<syntaxhighlight lang="csharp">using System;
 
class Program
Line 586 ⟶ 627:
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.
 
<syntaxhighlight lang="cpp">#include <iostream>
 
class Acc
Line 647 ⟶ 688:
 
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.
<syntaxhighlight lang="cpp">#include <iostream>
#include <functional>
 
Line 666 ⟶ 707:
 
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:
<syntaxhighlight lang="cpp">struct CumulantBase_
{
virtual ~CumulantBase_();
Line 691 ⟶ 732:
 
The second issue is that the built-in operator + is a multimethod, implementing a compile-time dispatch and promotion which we must manually reproduce.
<syntaxhighlight lang="cpp">// still inside struct Accumulator_
// various operator() implementations provide a de facto multimethod
Accumulator_& operator()(int more)
Line 723 ⟶ 764:
 
These rely on coercion functions which switch on the so-far-accumulated type:
<syntaxhighlight lang="cpp">// recognize cumulants by type
boost::optional<int> CoerceInt(const CumulantBase_& c)
{
Line 747 ⟶ 788:
 
All that remains is to write to the stream:
<syntaxhighlight lang="cpp">std::ostream& operator<<(std::ostream& dst, const Accumulator_& acc)
{
return acc.val_->Write(dst);
Line 754 ⟶ 795:
 
=={{header|Ceylon}}==
<syntaxhighlight lang=Ceylon"ceylon">shared void run() {
Integer|Float accumulator
(variable Integer|Float n)
Line 781 ⟶ 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):
<syntaxhighlight lang=Clay"clay">acc(n) {
return (m) => {
n = n + m;
Line 795 ⟶ 836:
}</syntaxhighlight>
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:
<syntaxhighlight lang=Clay"clay"> var y = acc(Vector[Char]("Hello"));
println(y(" World!")); // Prints "Hello World!”.</syntaxhighlight>
But you could constrain the function to numeric types were you so inclined:
<syntaxhighlight lang=Clay"clay">[N | Numeric?(N)] acc(n: N) {
return (m) => {
n = n + m;
Line 808 ⟶ 849:
=={{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.
<syntaxhighlight lang="clojure">(defn accum [n]
(let [acc (atom n)]
(fn [m] (swap! acc + m))))</syntaxhighlight>
Similarly, a ''ref'' could be used.
<syntaxhighlight lang="clojure">(defn accum [n]
(let [acc (ref n)]
#(dosync (alter acc + %))))</syntaxhighlight>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="coffeescript">accumulator = (sum) ->
(n) -> sum += n
Line 826 ⟶ 867:
=={{header|Common Lisp}}==
{{trans|TXR}}
<syntaxhighlight lang="lisp">(defun accumulator (sum)
(lambda (n)
(incf sum n)))</syntaxhighlight>
Example usage:
<syntaxhighlight lang="lisp">(defvar x (accumulator 1))
(funcall x 5)
(accumulator 3)
Line 843 ⟶ 884:
 
=={{header|Crystal}}==
<syntaxhighlight lang="crystal">
# Make types a bit easier with an alias
alias Num = Int32 | Int64 | Float32 | Float64
Line 860 ⟶ 901:
=={{header|D}}==
 
<syntaxhighlight lang="d">import std.stdio;
 
void main() {
Line 881 ⟶ 922:
 
Implementation with dynamic typing:
<syntaxhighlight lang="dart">makeAccumulator(s) => (n) => s += n;</syntaxhighlight>
 
Implementation with static typing (preferred in Dart 2):
<syntaxhighlight lang="dart">typedef Accumulator = num Function(num);
 
Accumulator makeAccumulator(num s) => (num n) => s += n;</syntaxhighlight>
 
Verbose version:
<syntaxhighlight lang="dart">typedef Accumulator = num Function(num);
 
Accumulator makeAccumulator(num initial) {
Line 901 ⟶ 942:
 
Usage example for any of above:
<syntaxhighlight lang="dart">void main() {
var x = makeAccumulator(1);
x(5);
Line 912 ⟶ 953:
 
Type checking:
<syntaxhighlight lang="dart">void main() {
var x = makeAccumulator(1);
print(x(5).runtimeType); // int
Line 920 ⟶ 961:
 
=={{header|Déjà Vu}}==
<syntaxhighlight lang="dejavu">accum n:
labda i:
set :n + n i
Line 932 ⟶ 973:
{{libheader| System.SysUtils}}
{{libheader| System.Variants}}
<syntaxhighlight lang=Delphi"delphi">
program Accumulator_factory;
 
Line 962 ⟶ 1,003:
end.</syntaxhighlight>
=={{header|E}}==
<syntaxhighlight lang="e">def foo(var x) {
return fn y { x += y }
}</syntaxhighlight>
 
=={{header|EchoLisp}}==
<syntaxhighlight lang="lisp">
(define-syntax-rule (inc x v) (set! x (+ x v)))
(define (accumulator (sum 0)) (lambda(x) (inc sum x) sum))
Line 981 ⟶ 1,022:
 
=={{header|Elena}}==
ELENA 46.x :
<syntaxhighlight lang="elena">function(acc)
= (n => acc.append:(n));
 
accumulator(n)
Line 1,005 ⟶ 1,046:
=={{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)
Line 1,014 ⟶ 1,055:
end</syntaxhighlight>
The passing test to exercise the Accumulator and show usage:
<syntaxhighlight lang="elixir">ExUnit.start
 
defmodule AccumulatorFactoryTest do
Line 1,036 ⟶ 1,077:
 
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.
<syntaxhighlight lang="erlang">
-module(acc_factory).
-export([loop/1,new/1]).
Line 1,061 ⟶ 1,165:
 
=={{header|ERRE}}==
<syntaxhighlight lang=ERRE"erre">PROGRAM ACCUMULATOR
 
PROCEDURE ACCUMULATOR(SUM,N,A->SUM)
Line 1,085 ⟶ 1,189:
=={{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
Line 1,107 ⟶ 1,211:
 
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 ->
Line 1,123 ⟶ 1,227:
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USE: locals
:: accumulator ( n! -- quot ) [ n + dup n! ] ;
 
Line 1,133 ⟶ 1,237:
=={{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.
<syntaxhighlight lang="fantom">class AccumulatorFactory
{
static |Num -> Num| accumulator (Num sum)
Line 1,186 ⟶ 1,290:
=={{header|Forth}}==
Forth is untyped; this works on integers.
<syntaxhighlight lang="forth">: accumulator
create ( n -- ) ,
does> ( n -- acc+n ) tuck +! @ ;
Line 1,198 ⟶ 1,302:
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:
 
<syntaxhighlight lang="forth">
: faccumulator ( r "name" -- )
create falign f,
Line 1,226 ⟶ 1,330:
in Fortran77 but was accepted by virtually all compilers.
 
<syntaxhighlight lang=Fortran"fortran">#define foo(type,g,nn) \
typex function g(i);\
typex i,s,n;\
Line 1,255 ⟶ 1,359:
Fortran2003 and later supports objects and overloading. The overloaded functions are encapsulated in an object.
 
<syntaxhighlight lang=Fortran"fortran">
module modAcc
implicit none
Line 1,349 ⟶ 1,453:
 
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)
Line 1,406 ⟶ 1,510:
=={{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.
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 1,444 ⟶ 1,548:
 
=={{header|Golo}}==
<syntaxhighlight lang="golo">#!/usr/bin/env golosh
----
An accumulator factory example for Rosetta Code.
Line 1,466 ⟶ 1,570:
=={{header|Groovy}}==
Solution:
<syntaxhighlight lang="groovy">def accumulator = { Number n ->
def value = n;
{ it = 0 -> value += it}
}</syntaxhighlight>
Test:
<syntaxhighlight lang="groovy">def x = accumulator(1)
 
println x()
Line 1,505 ⟶ 1,609:
=={{header|Haskell}}==
{{trans|Ruby}}
<syntaxhighlight lang="haskell">import Control.Monad.ST
import Data.STRef
 
Line 1,526 ⟶ 1,630:
 
'''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>
 
Line 1,533 ⟶ 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.
<syntaxhighlight lang=Unicon"unicon">procedure main()
a := genAcc(3)
b := genAcc(5)
Line 1,560 ⟶ 1,664:
 
=={{header|Io}}==
<syntaxhighlight lang=Io"io">accumulator := method(sum,
block(x, sum = sum + x) setIsActivatable(true)
)
Line 1,569 ⟶ 1,673:
 
=={{header|J}}==
See http[[j://www.jsoftware.com/jwiki/Guides/Lexical_Closure]], including the [[j:Guides/Lexical%20Closure#dissent|dissent]] section.
<syntaxhighlight lang=J"j">oleg=:1 :0
a=. cocreate''
n__a=: m
Line 1,576 ⟶ 1,680:
)</syntaxhighlight>
Example use:
<syntaxhighlight lang="j"> F=: 10 oleg
F 11
21
Line 1,590 ⟶ 1,694:
 
{{works with|Java|5 and up}}
<syntaxhighlight lang="java">public class Accumulator
//implements java.util.function.UnaryOperator<Number> // Java 8
{
Line 1,628 ⟶ 1,732:
 
{{works with|Java|8 and up}}
<syntaxhighlight lang="java">import java.util.function.UnaryOperator;
 
public class AccumulatorFactory {
Line 1,658 ⟶ 1,762:
=={{header|JavaScript}}==
===ES5===
<syntaxhighlight lang="javascript">function accumulator(sum) {
return function(n) {
return sum += n;
Line 1,672 ⟶ 1,776:
 
===ES6===
<syntaxhighlight lang="javascript">let accumulator = sum => (n => sum += n);
let x = accumulator(1);
console.log(x(5));
Line 1,682 ⟶ 1,786:
 
===JavaScript 1.8 (SpiderMonkey Only)===
<syntaxhighlight lang="javascript">function accumulator(sum) function(n) sum += n;
var x = accumulator(1);
x(5);
Line 1,693 ⟶ 1,797:
=={{header|Jsish}}==
From Javascript ES5 entry.
<syntaxhighlight lang="javascript">/* Accumulator factory, in Jsish */
function accumulator(sum) {
return function(n) {
Line 1,745 ⟶ 1,849:
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">function accumulator(i)
f(n) = i += n
return f
Line 1,762 ⟶ 1,866:
=={{header|Kotlin}}==
Overloads would be needed for all six primitive numeric types but, in the interests of brevity, only two overloads of 'foo' have been coded:
<syntaxhighlight lang="scala">// version 1.1
 
fun foo(n: Double): (d: Double) -> Double {
Line 1,793 ⟶ 1,897:
=={{header|Lambdatalk}}==
Lambdatlk is a functional programming language without closures but with mutable arrays.
<syntaxhighlight lang="scheme">
{def acc
{lambda {:a :n}
Line 1,817 ⟶ 1,921:
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,824 ⟶ 1,964:
=== Traditional closure ===
 
<syntaxhighlight lang="lisp">
(defun accum (m)
(lambda (n)
Line 1,853 ⟶ 1,993:
We can creating a looping process which provides the same functionality as the self-calling function in the "traditional closure" approach:
 
<syntaxhighlight lang="lisp">
(defun loop (m)
(receive
Line 1,888 ⟶ 2,028:
=={{header|Lua}}==
A simple implementation:
<syntaxhighlight lang=Lua"lua">function acc(init)
init = init or 0
return function(delta)
Line 1,897 ⟶ 2,037:
An expanded example of similar but more complex functionality:
{{works with|Lua|5.1}}
<syntaxhighlight lang="lua">do
local accSum = 0; -- accumulator factory 'upvalue'
function acc(v) -- the accumulator factory
Line 1,911 ⟶ 2,051:
end--end of factory closure</syntaxhighlight>
Usage example:
<syntaxhighlight 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
Line 1,919 ⟶ 2,059:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang=M2000"m2000 Interpreterinterpreter">\\ M2000 Interpreter
\\ accumulator factory
foo=lambda acc=0 (n as double=0) -> {
Line 1,954 ⟶ 2,094:
=={{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.
<syntaxhighlight lang=Maple"maple">AccumulatorFactory := proc( initial := 0 )
local total := initial;
proc( val := 1 ) total := total + val end
end proc:</syntaxhighlight>
Running this, we get:
<syntaxhighlight lang=Maple"maple">> acc := AccumulatorFactory( 1 ):
> acc( 5 );
6
Line 1,977 ⟶ 2,117:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang=Mathematica"mathematica">accFactory[initial_] :=
Module[{total = initial},
Function[x, total += x]
Line 1,998 ⟶ 2,138:
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"mercury">:- module accum.
:- interface.
 
Line 2,031 ⟶ 2,171:
As used:
 
<syntaxhighlight lang=Mercury"mercury">:- module accumuser.
:- interface.
:- import_module io.
Line 2,071 ⟶ 2,211:
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"mercury">:- module accum2.
:- interface.
 
Line 2,103 ⟶ 2,243:
As used, with the same output:
 
<syntaxhighlight lang=Mercury"mercury">:- module accumuser2.
:- interface.
:- import_module io.
Line 2,131 ⟶ 2,271:
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.
<syntaxhighlight lang=Nemerle"nemerle">def Foo(n) {
mutable value : object = n;
fun (i : object) {
Line 2,161 ⟶ 2,339:
 
=={{header|NewLisp}}==
<syntaxhighlight lang=NewLisp"newlisp">(define (sum (x 0)) (inc 0 x))
</syntaxhighlight>
 
Line 2,184 ⟶ 2,362:
 
=={{header|NGS}}==
<syntaxhighlight lang=NGS"ngs">{
F Acc(start:Int) {
sum = start
Line 2,214 ⟶ 2,392:
Argument to the created accumulator function must be float.
Result is always float.
<syntaxhighlight lang=Nim"nim">
proc accumulator[T: SomeNumber](x: T): auto =
var sum = float(x)
Line 2,237 ⟶ 2,415:
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"nim">
proc accumulator[T: SomeNumber](x: T): auto =
var sum = x
Line 2,267 ⟶ 2,445:
 
This solution fulfills the requirements.
<syntaxhighlight lang=Nim"nim">
type
 
Line 2,345 ⟶ 2,523:
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.
Line 2,373 ⟶ 2,551:
=={{header|Objeck}}==
Uses objects instead of first class functions.
<syntaxhighlight lang="objeck">bundle Default {
class Accumulator {
@sum : Float;
Line 2,396 ⟶ 2,574:
=={{header|Objective-C}}==
{{works with|Mac OS X|10.6+}}
<syntaxhighlight lang="objc">#import <Foundation/Foundation.h>
 
typedef double (^Accumulator)(double);
Line 2,425 ⟶ 2,603:
{{trans|Ruby}}
Deviations: An accumulator instance can take ''either'' integers ''or'' floats, but not both mixed (due to lack of runtime polymorphism).
<syntaxhighlight lang="ocaml">let accumulator sum0 =
let sum = ref sum0 in
fun n ->
Line 2,442 ⟶ 2,620:
=={{header|Octave}}==
 
<syntaxhighlight lang="octave"># not a function file:
1;
function fun = foo(init)
Line 2,460 ⟶ 2,638:
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.
 
<syntaxhighlight lang=Oforth"oforth">: foo( n -- bl )
#[ n swap + dup ->n ] ;</syntaxhighlight>
 
Usage :
<syntaxhighlight lang=Oforth"oforth">: testfoo
| x y z |
1 foo ->x
Line 2,485 ⟶ 2,663:
=={{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"oorexx">
x = .accumulator~new(1) -- new accumulator with initial value of "1"
x~call(5)
Line 2,578 ⟶ 2,756:
=={{header|Oz}}==
A bit unwieldy because the '+' operator does not allow mixed type operands. The implementation is thread-safe (atomic Exchange operation).
<syntaxhighlight lang="oz">declare
fun {Acc Init}
State = {NewCell Init}
Line 2,609 ⟶ 2,787:
=={{header|PARI/GP}}==
 
<syntaxhighlight lang="parigp">stack = List([1]);
factory(b,c=0) = my(a=stack[1]++);listput(stack,c);(b)->stack[a]+=b;
 
Line 2,630 ⟶ 2,808:
 
{{trans|Ruby}}
<syntaxhighlight lang="perl">sub accumulator {
my $sum = shift;
sub { $sum += shift }
Line 2,664 ⟶ 2,842:
accumulator_factory() and return a pointer to that instead of an id/length.
 
<!--<syntaxhighlight lang=Phix"phix">-->
<span style="color: #004080;">sequence</span> <span style="color: #000000;">accumulators</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 2,708 ⟶ 2,886:
 
=={{header|PHP}}==
<syntaxhighlight lang=PHP"php"><?php
function accumulator($start){
return create_function('$x','static $v='.$start.';return $v+=$x;');
Line 2,717 ⟶ 2,895:
?></syntaxhighlight>
{{works with|PHP|5.3+}}
<syntaxhighlight lang="php"><?php
function accumulator($sum){
return function ($x) use (&$sum) { return $sum += $x; };
Line 2,727 ⟶ 2,905:
 
=={{header|PicoLisp}}==
<syntaxhighlight lang=PicoLisp"picolisp">(de accumulator (Sum)
(curry (Sum) (N)
(inc 'Sum N) ) )
Line 2,738 ⟶ 2,916:
=={{header|Pony}}==
 
<syntaxhighlight lang=Pony"pony">
use "assert"
class Accumulator
Line 2,776 ⟶ 2,954:
 
=={{header|PostScript}}==
<syntaxhighlight lang=PostScript"postscript">/mk-acc { % accumulator generator
{0 add 0 0 2 index put}
7 array copy
Line 2,800 ⟶ 2,978:
 
The GetNewClosure method returns a ScriptBlock with captured variables.
<syntaxhighlight lang=PowerShell"powershell">
function Get-Accumulator ([double]$Start)
{
Line 2,806 ⟶ 2,984:
}
</syntaxhighlight>
<syntaxhighlight lang=PowerShell"powershell">
$total = Get-Accumulator -Start 1
& $total -Plus 5.0 | Out-Null
Line 2,819 ⟶ 2,997:
{{works with|SWI Prolog}}
Uses the module '''lambda''' written by '''Ulrich Neumerkel'''.
<syntaxhighlight lang=Prolog"prolog">:- use_module(library(lambda)).
 
define_g(N, G) :-
Line 2,843 ⟶ 3,021:
=={{header|Python}}==
{{works with|Python|2.x/3.x}}
<syntaxhighlight lang="python">>>> def accumulator(sum):
def f(n):
f.sum += n
Line 2,872 ⟶ 3,050:
{{trans|Ruby}}
{{works with|Python|3.x}}
<syntaxhighlight lang="python">def accumulator(sum):
def f(n):
nonlocal sum
Line 2,888 ⟶ 3,066:
 
{{works with|Python|2.5+}}
<syntaxhighlight lang="python">def accumulator(sum):
while True:
sum += yield sum
Line 2,907 ⟶ 3,085:
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"quackery"> [ tuck tally share ]this[ swap ] is accumulate ( n s --> [ n )
 
[ [ stack ] copy tuck put nested
Line 2,972 ⟶ 3,150:
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"quackery"> [ dip
[ -1 split dup [] = if
[ $ "accumulator needs a starting value."
Line 3,020 ⟶ 3,198:
 
=={{header|R}}==
<syntaxhighlight lang=R"r">accumulatorFactory <- function(init) {
currentSum <- init
function(add) {
Line 3,037 ⟶ 3,215:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">#lang racket
(define ((accumulator n) i)
(set! n (+ n i))
Line 3,046 ⟶ 3,224:
(formerly Perl 6)
{{works with|Rakudo|2018.03}}
<syntaxhighlight lang=perl6"raku" line>sub accum ($n is copy) { sub { $n += $^x } }
 
#Example use:
Line 3,060 ⟶ 3,238:
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">make-acc-gen: func [start-val] [
use [state] [
state: start-val
Line 3,079 ⟶ 3,257:
Retro only supports integers.
 
<syntaxhighlight lang=Retro"retro">:acc (ns-)
d:create , [ [ fetch ] [ v:inc ] bi ] does ;</syntaxhighlight>
{{out}}
Line 3,095 ⟶ 3,273:
This REXX program is partially modeled after the ooRexx example.
<br><br>This example will handle any kind of number: integer, floating point.
<syntaxhighlight lang="rexx">/*REXX program shows one method an accumulator factory could be implemented. */
x=.accumulator(1) /*initialize accumulator with a 1 value*/
x=call(5)
Line 3,115 ⟶ 3,293:
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">oGenerator = new Generator
 
Func main
Line 3,142 ⟶ 3,320:
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>
 
Line 3,147 ⟶ 3,367:
Ruby deviates from the task because methods and Proc objects have different syntax. 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).
 
<syntaxhighlight lang="ruby">def accumulator(sum)
lambda {|n| sum += n}
end
Line 3,166 ⟶ 3,386:
This accumulator also works with other types that have a <tt>+</tt> method.
 
<syntaxhighlight lang="ruby">require 'rational'
require 'complex'
y = accumulator(Rational(2, 3))
Line 3,184 ⟶ 3,404:
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.
 
<syntaxhighlight lang="ruby">def accumulator(sum)
lambda {|n| sum += n}
end
Line 3,199 ⟶ 3,419:
Changing "x = foo(1.)" to "x = foo(1)" in the code below should not change the output (it does).
 
<syntaxhighlight lang="rust">// rustc 1.26.0 or later
 
use std::ops::Add;
Line 3,225 ⟶ 3,445:
=== 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)]
 
Line 3,326 ⟶ 3,546:
=={{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.
<syntaxhighlight lang="scala">def AccumulatorFactory[N](n: N)(implicit num: Numeric[N]) = {
import num._
var acc = n
Line 3,351 ⟶ 3,571:
=={{header|Scheme}}==
{{trans|Ruby}}
<syntaxhighlight lang="scheme">(define (accumulator sum)
(lambda (n)
(set! sum (+ sum n))
Line 3,371 ⟶ 3,591:
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">class Accumulator(sum) {
method add(num) {
sum += num;
Line 3,384 ⟶ 3,604:
The same thing can be achieved by returning a closure from the '''Accumulator''' function.
 
<syntaxhighlight lang="ruby">func Accumulator(sum) {
func(num) { sum += num };
}
Line 3,394 ⟶ 3,614:
 
=={{header|Simula}}==
<syntaxhighlight lang="simula">BEGIN
 
! ABSTRACTION FOR SIMULA'S TWO NUMERIC TYPES ;
Line 3,473 ⟶ 3,693:
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<syntaxhighlight lang="smalltalk">Object subclass: AccumulatorFactory [
AccumulatorFactory class >> new: aNumber [
|r sum|
Line 3,495 ⟶ 3,715:
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}}
<syntaxhighlight lang="smalltalk">|factory accu1 accu2|
 
factory := [:initial |
Line 3,521 ⟶ 3,741:
{{trans|OCaml}}
Deviations: An accumulator instance can take ''either'' integers ''or'' reals, but not both mixed (due to lack of runtime polymorphism).
<syntaxhighlight lang="sml">fun accumulator (sum0:real) : real -> real = let
val sum = ref sum0
in
Line 3,540 ⟶ 3,760:
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">func makeAccumulator(var sum: Double) -> Double -> Double {
return {
sum += $0
Line 3,557 ⟶ 3,777:
{{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.
<syntaxhighlight lang="tcl">package require Tcl 8.6
 
# make the creation of coroutines without procedures simpler
Line 3,586 ⟶ 3,806:
}</syntaxhighlight>
Sample usage (extra characters over Paul's example to show more clearly what is going on):
<syntaxhighlight lang="tcl">% set x [accumulator 1]
::accumulator.1
% $x 5
Line 3,599 ⟶ 3,819:
===Verbose===
 
<syntaxhighlight lang="txrlisp">(defun accumulate (sum)
(lambda (n)
(inc sum n)))
Line 3,629 ⟶ 3,849:
===Sugared===
 
<syntaxhighlight lang="txrlisp">(let ((f (let ((sum 0)) (do inc sum @1))))
(mapdo (do put-line `@1 -> @[f @1]`) (gun (iread : : nil))))</syntaxhighlight>
{{out}}
Line 3,642 ⟶ 3,862:
Using the <code>obtain</code>/<code>yield</code> interface to delimited continuations, we can turn an imperative for loop into an accumulation function:
 
<syntaxhighlight lang="txrlisp">(defun accum ()
(for ((sum (yield-from accum)))
()
Line 3,660 ⟶ 3,880:
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:
 
<syntaxhighlight lang="txrlisp">(defstruct (accum count) nil
(count 0))
 
Line 3,673 ⟶ 3,893:
=={{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"unicon">procedure main()
a := genAcc(3)
b := genAcc(5)
Line 3,704 ⟶ 3,924:
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}}
<syntaxhighlight lang="bash">#!/bin/sh
accumulator() {
# Define a global function named $1
Line 3,729 ⟶ 3,949:
==={{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>.
<syntaxhighlight lang="es">fn accumulator n {
result @ i {
n = `{echo $n + $i | bc}
Line 3,741 ⟶ 3,961:
echo <={x 2.3}
echo <={y -3000}</syntaxhighlight>
 
== {{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
<syntaxhighlight lang="vb">class accumulator
dim A
public default function acc(x)
Line 3,756 ⟶ 3,990:
end class</syntaxhighlight>
;Invocation
<syntaxhighlight lang="vb">dim a
set a = new accumulator
x = a( 1 )
Line 3,770 ⟶ 4,004:
 
=={{header|Wart}}==
<syntaxhighlight lang="python">def (accumulator n)
(fn() ++n)</syntaxhighlight>
 
Line 3,786 ⟶ 4,020:
 
=={{header|Wren}}==
<syntaxhighlight lang=ecmascript"wren">var accumulator = Fn.new { |acc| Fn.new { |n| acc = acc + n } }
 
var x = accumulator.call(1)
Line 3,808 ⟶ 4,042:
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
Line 3,972 ⟶ 4,206:
=={{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))
Line 3,994 ⟶ 4,228:
 
=={{header|Yabasic}}==
<syntaxhighlight lang=Yabasic"yabasic">sub foo$(n)
local f$
Line 4,011 ⟶ 4,245:
=={{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.
<syntaxhighlight lang="yorick">func accum(data, n) {
if(!is_obj(data))
return closure(accum, save(total=data));
Line 4,028 ⟶ 4,262:
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn foo(n){ fcn(n,acc){ acc.set(n+acc.value).value }.fp1(Ref(n)) }</syntaxhighlight>
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 4,042 ⟶ 4,276:
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|Scratch|cannot generate functions nor pass them as arguments or values}}
{{omit from|Commodore BASIC}}
1,150

edits