/* Simple moving average (Rosetta code) in Picat. http://rosettacode.org/wiki/Averages/Simple_moving_average """ Computing the simple moving average of a series of numbers. Task Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. Description A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period. It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA(). The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it: The period, P An ordered container of at least the last P numbers from each of its individual calls. Stateful also means that successive calls to I(), the initializer, should return separate routines that do not share saved state so they could be used on two independent streams of data. """ This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ main => go. % Using a map for the states (p and stream) go ?=> L=[1, 2, 3, 4, 5, 5, 4, 3, 2, 1], Map3 = new_map([p=3]), Map5 = new_map([p=5]), foreach(N in L) printf("n: %-2d sma3: %-17w sma5: %-17w\n",N, sma(N,Map3), sma(N,Map5)) end, nl. sma(N,Map) = Average => Stream = Map.get(stream,[]) ++ [N], if Stream.len > Map.get(p) then Stream := Stream.tail end, Average = cond(Stream.len == 0, 0, sum(Stream) / Stream.len), Map.put(stream,Stream).