Averages/Simple moving average: Difference between revisions

→‎{{header|zkl}}: re-write to match task description
(Added Kotlin)
(→‎{{header|zkl}}: re-write to match task description)
Line 4,212:
 
=={{header|zkl}}==
<lang zkl>class [static] SMA{var P=3,ns=L(); // only one instance of this class
fcn init(n){
if(P<ns.append(n.toFloat()).len()) ns.del(0);
returnClass(ns.sum(0.0)/ns.len()); // return average, not Class
}
fcn reset(p){P=p;ns=L();} // to make examples easier
}</lang>
<lang zkl>zkl: T(1,2,3,4,5,5,4,3,2,1).apply(SMA)
L(1,1.5,2,3,4,4.66667,4.66667,4,3,2)
 
zkl: SMA.reset(5)
zkl: T(1,2,3,4,5,5,4,3,2,1).apply(SMA)
L(1,1.5,2,2.5,3,3.8,4.2,4.2,3.8,3)</lang>
Using a closure and creating a function
<lang zkl>fcn SMA(P){
fcn(n,ns,P){ if(P<ns.append(n.toFloat()).len()) ns.del(0);
sz:=ns.sumappend(0n.0toFloat())/ns.len();
}.fp1 if(L(),P>sz) return(0);
if(P<ns.append(n.toFloat()).len()sz) ns.del(0);
ns.sum(0.0)/P;
}.fp1(List.createLong(P+1),P) // pre-allocate a list of length P+1
}</lang>
fp1 creates a partial application fixing the (in this case) the second and third
<lang zkl>zkl: T(1,2,3,4,5,5,4,3,2,1).apply(SMA(3))
parameters
L(1,1.5,2,3,4,4.66667,4.66667,4,3,2)
<lang zkl>zkl: T(1,2,3,4,5,5,4,3,2,1).apply(SMA(3)).println();
 
zkl: T(1,2,3,4,5,5,4,3,2,1).apply(SMA(5)).println();</lang>
{{out}}
L(1,1.5,2,2.5,3,3.8,4.2,4.2,3.8,3)</lang>
<pre>
L(10,1.50,2,3,4,4.66667,4.66667,4,3,2)
L(10,1.50,20,2.50,3,3.8,4.2,4.2,3.8,3)</lang>
</pre>
Anonymous user