title: Reactive programming: how to get a moving average using Reactive.jl
body: <p>I am wanting to have a signal / function that outputs the moving average of <em>x</em> periods. I have come up with two approaches, both of which work, but I believe the second is more properly reactive. Does anyone know of a better method?</p>
  
  <p><strong>Method 1</strong></p>
  
  <pre><code>@time (
  x = Signal(100);
  
  col = foldp(Int[], x) do acc, val
      push!(acc, val)
  end;
  
  for i in rand(90:110, 100)
      push!(x, i)
  end;
  )
  </code></pre>
  
  <p>This code executes for me in <strong><em>0.102663 seconds</em></strong> and can easily yield an average over the last 100 signals: <code>mean(value(col))</code></p>
  
  <p><strong>Method 2</strong></p>
  
  <pre><code>@time (
  a = Signal(100);
  
  sar = Vector{Signal}(101);
  
  sar[1] = a;
  
  for i in 1:100
      sar[i+1] = previous(sar[i])
  end;
  
  for i in rand(90:110, 100)
      push!(a, i)
  end;
  )
  </code></pre>
  
  <p>This code executes for me in <strong><em>0.034911 seconds</em></strong> and can also easily yeild an average of the last 100 signals: </p>
  
  <pre><code>sarval = map(value, sar)
  mean(sarval[2:end])`
  </code></pre>
  
  <p>Neither method above directly provides an output signal; here is Method 1 applied to create a moving average of specified length as a continuing signal:</p>
  
  <p><strong>Method 1 Applied</strong></p>
  
  <pre><code>x = Signal(initial_value)
  
  col = foldp(Float64[], x) do acc, elem
      push!(acc, elem)
  end
  
  macro moving_average(per, collec)
      quote
          map($collec) do arr
              length(arr) &lt; $per ? mean(arr) : mean(arr[(end-$per+1):end])
          end
      end
  end
  
  ma_period = @moving_average(period_length, col)
  </code></pre>
  
  <p>This code uses the first method to generate a signal of arrays of all past signals, the length of which  increases linearly with the number of signals. For signals that update thousands of times, this seems unwieldy (at best). This does not seem ideal, and I am looking for some ideas for a better approach. Not sure how to take Method 2 and turn it into a signal output, and not sure if it is the best approach I could take.</p>
  
  <p>Also related question: there is a nice built in function <code>previous(signal)</code> that provides a signal lagging 1 update behind <em>signal</em>. Is there a way to specify a signsl that legs a specified, arbitrary number of updates behind <em>signal</em>?</p>