v2 / vlib / v / tests / assign / assign_literal_with_closure_test.v
26 lines · 23 sloc · 577 bytes · 6488041a749df9762348d019c4223908c476f2e2
Raw
1fn sma(period int) fn (f64) f64 {
2 mut i := 0
3 mut sum := 0.0
4 mut storage := []f64{len: 0, cap: period}
5
6 return fn [mut storage, mut sum, mut i, period] (input f64) f64 {
7 if storage.len < period {
8 sum += input
9 storage << input
10 }
11
12 sum += input - storage[i]
13 storage[i], i = input, (i + 1) % period
14 return sum / f64(storage.len)
15 }
16}
17
18fn test_assign_literal_with_closure() {
19 sma3 := sma(3)
20 sma5 := sma(5)
21 println('x sma3 sma5')
22 for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] {
23 println('${x:5.3f} ${sma3(x):5.3f} ${sma5(x):5.3f}')
24 }
25 assert true
26}
27