Anonymous user
Accumulator factory: Difference between revisions
→{{header|Dart}}
(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>.
Implementation with dynamic typing:
<lang dart>
Implementation with static typing (preferred in Dart 2):
void main() {▼
<lang dart>typedef Accumulator = num Function(num);
var a = accumulator(42);▼
Accumulator makeAccumulator(num s) => (num n) => s += n;</lang>
var b = accumulator(4.2);▼
Verbose version:
<lang dart>typedef Accumulator = num Function(num);
Accumulator makeAccumulator(num initial) {
num s = initial;
s += n;
return s;
}
}</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>
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}}==
|