Anonymous user
Accumulator factory: Difference between revisions
Reintroduced solution with float accumulator.
m (→{{header|Nim}}) |
(Reintroduced solution with float accumulator.) |
||
Line 2,127:
:– give the accumulator type the type of the initial value provided at the creation;
:– use a customized type.
We provide the code for the
=== Using float accumulator ===
<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
</lang>
{{out}}
<pre>
6.0
8.300000000000001
</pre>
=== Fixed accumulator type ===
Line 2,138 ⟶ 2,158:
let x = accumulator(1)
echo x(5)
echo x(2)
let y = accumulator(3.5)
echo y(2) # 5.5
echo y(3) # 8.5
</lang>
{{out}}
|