Accumulator factory: Difference between revisions

Content added Content deleted
(signal task not to arm assembly)
Line 832: Line 832:
=={{header|Dart}}==
=={{header|Dart}}==


The => 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.
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;
<lang dart>makeAccumulator(s) => (n) => s += n;</lang>


Implementation with static typing (preferred in Dart 2):
void main() {
<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;</lang>
var b = accumulator(4.2);

print("${b(0)}, ${b(1)}, ${b(10.0)}, ${b(100.4)}");
Verbose version:
<lang dart>typedef Accumulator = num Function(num);

Accumulator makeAccumulator(num initial) {
num s = initial;
num accumulator(num n) {
s += n;
return s;
}
return accumulator;
}</lang>

Usage example for any of above:
<lang dart>void main() {
var x = makeAccumulator(1);
x(5);
makeAccumulator(3);
print(x(2.3));
}</lang>
}</lang>


{{out}}
{{out}}
<pre>42, 43, 53, 153
<pre>8.3</pre>

4.2, 5.2, 15.2, 115.60000000000001</pre>
Type checking:
<lang dart>void main() {
var x = makeAccumulator(1);
print(x(5).runtimeType); // int
print(x(2.3).runtimeType); // double
print(x(4).runtimeType); // double
}</lang>


=={{header|Déjà Vu}}==
=={{header|Déjà Vu}}==