on master help sign in
Move `average` to the automaton library.
commitfc37907bc12913a7f4f132c541d7699f06dacb38 authorevancz <info@elm-lang.org> dateWed 3 Apr 2013, 10:15 (14 years ago) parentd27ab15
2 files changed+20−12
libraries/Automaton.elm+20 libraries/Signal.elm−12
libraries/Automaton.elm+20
@@ -55,6 +55,26 @@ init' s f = Step (\x -> let (s',out) = f x s
5555count : Automaton a Int
5656count = init 0 (\_ c -> c + 1)
5757
58+type Queue t = ([t],[t])
59+empty = ([],[])
60+enqueue x (en,de) = (x:en, de)
61+dequeue q = case q of
62+ ([],[]) -> Nothing
63+ (en,[]) -> enqueue ([], reverse en)
64+ (en,hd::tl) -> Just (hd, (en,tl))
65+
66+-- Computes the running average of the last `n` inputs.
67+average : Int -> Automaton Float Float
68+average k =
69+ let step n (ns,len,sum) =
70+ if len == k then stepFull n (ns,len,sum)
71+ else ((enqueue n ns, len+1, sum+n), (sum+n) / (len+1))
72+ stepFull n (ns,len,sum) =
73+ case dequeue ns of
74+ Nothing -> ((ns,len,sum), 0)
75+ Just (m,ns') -> let sum' = sum + n - m
76+ in ((enqueue n ns', len, sum'), sum' / len)
77+ in init' (empty,0,0) step
5878
5979{-- TODO(evancz): move this code to the Form library so people can find it.
6080
libraries/Signal.elm−12
@@ -110,15 +110,3 @@ delay : Time -> Signal a -> Signal a
110110-- scene <~ Mouse.x ~ Mouse.y
111111-- lift2 scene Mouse.x Mouse.y
112112(~) : Signal (a -> b) -> Signal a -> Signal b
113−
114−
115−{-- TODO: only found in docs
116− , ("average", "Int -> Signal Number -> Signal Float", [markdown|
117−
118−Takes an integer `n` and a signal of numbers. Computes the running
119−average of the signal over the last `n` events.
120−
121−So `(average 20 (fps 40))` would be the average time between the frames for
122−the last 20 frames.|])
123−--}
124−