I’ve the below Python
code:
def initial_trend(series, slen):
sum = 0.0
for i in range(slen):
sum += float(series[i+slen] - series[i]) / slen
return sum / slen
That is converted to the below Rust
code:
fn initial_trend(series: &[i32], slen: usize) -> f32 {
series[..slen].iter().zip(&series[slen..])
.map(|(&a, &b)| (b as f32 - a as f32) / slen as f32).sum::<f32>() / slen as f32
}
Or can be re-written as:
fn initial_trend(series: &[i32], slen: usize) -> f32 {
let x = series[..slen].iter().zip(&series[slen..]);
let y = x.map(|(&a, &b)| (b as f32 - a as f32) / slen as f32);
let z = y.sum::<f32>();
z / slen as f32
}
for the input, with slen = 12
:
series = [30,21,29,31,40,48,53,47,37,39,31,29,17,9,20,24,27,35,41,38,
27,31,27,26,21,13,21,18,33,35,40,36,22,24,21,20,17,14,17,19,
26,29,40,31,20,24,18,26,17,9,17,21,28,32,46,33,23,28,22,27,
18,8,17,21,31,34,44,38,31,30,26,32];
I’ve the below output in Rust
code above
x = Zip { a: Iter([30, 21, 29, 31, 40, 48, 53, 47, 37, 39, 31, 29]), b: Iter([17, 9, 20, 24, 27, 35, 41, 38, 27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36, 22, 24, 21, 20, 17, 14, 17, 19, 26, 29, 40, 31, 20, 24, 18, 26, 17, 9, 17, 21, 28, 32, 46, 33, 23, 28, 22, 27, 18, 8, 17, 21, 31, 34, 44, 38, 31, 30, 26, 32]), index: 0, len: 12 }
y = Map { iter: Zip { a: Iter([30, 21, 29, 31, 40, 48, 53, 47, 37, 39, 31, 29]), b: Iter([17, 9, 20, 24, 27, 35, 41, 38, 27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36, 22, 24, 21, 20, 17, 14, 17, 19, 26, 29, 40, 31, 20, 24, 18, 26, 17, 9, 17, 21, 28, 32, 46, 33, 23, 28, 22, 27, 18, 8, 17, 21, 31, 34, 44, 38, 31, 30, 26, 32]), index: 0, len: 12 } }
z = -9.416667
w = -0.78472227
I want to write the equivalent Julia
code, so I wrote the below:
function initial_trend(series, slen)
x = zip(series[1:slen], series[slen+1:end])
y = map((a, b) -> (b - a) / 2, x)
z = sum(y) / slen
end
With this x
looks to be correct as it generates:
Base.Iterators.Zip{Tuple{Array{Int64,1},Array{Int64,1}}}(([30, 21, 29, 31, 40, 48, 53, 47, 37, 39, 31, 29], [29, 17, 9, 20, 24, 27, 35, 41, 38, 27, 31, 27, 26, 21, 13, 21, 18, 33, 35, 40, 36, 22, 24, 21, 20, 17, 14, 17, 19, 26, 29, 40, 31, 20, 24, 18, 26, 17, 9, 17, 21, 28, 32, 46, 33, 23, 28, 22, 27, 18, 8, 17, 21, 31, 34, 44, 38, 31, 30, 26, 32]))
But y
is wrong, not working, it gave me:
MethodError: no method matching (::getfield(Main, Symbol("##17#18")))(::Tuple{Int64,Int64})
Closest candidates are:
#17(::Any, !Matched::Any) at In[38]:1
it looks I do not understand working with tuples in arrays with map!
And not sure if I’ve to d something before x
, and if there is a way to make all of them in single line like the one in Rust