Accumulator factory: Difference between revisions

(signal task not to arm assembly)
Line 832:
=={{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 accumulatormakeAccumulator(var ns) => (var in) => ns += in;</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;
var b =num accumulator(4.2num n); {
s += n;
return s;
}
var a =return accumulator(42);
}</lang>
 
Usage example for any of above:
<lang dart>void main() {
var x = makeAccumulator(1);
x(5);
makeAccumulator(3);
print(x(2.3));
}</lang>
 
{{out}}
<pre>42, 43, 53, 1538.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}}==
Anonymous user