Jump to content

Averages/Simple moving average: Difference between revisions

no edit summary
m ({{out}})
No edit summary
Line 1,393:
printSMA n p = mapM_ (\(n,a) -> putStrLn $ "Next number: " ++ show n ++ " Average: " ++ show a)
. take n . sMA p $ [1..5]++[5,4..1]++[3..]</lang>
 
Stateful function using the state monad to keep track of state
 
{{works with|GHC|7.8.3}}
<lang Haskell>
import Control.Monad
import Control.Monad.State
 
period :: Int
period = 3
 
type SMAState = [Float]
 
computeSMA :: Float -> State SMAState Float
computeSMA x = do
previousValues <- get
let values = previousValues ++ [x]
let newAverage = if length values <= period then (sum values) / (fromIntegral $ length remainingValues :: Float)
else (sum remainingValues) / (fromIntegral $ length remainingValues :: Float)
where remainingValues = dropIf period values
put $ dropIf period values
return newAverage
 
dropIf :: Int -> [a] -> [a]
dropIf x xs = drop ((length xs) - x) xs
 
demostrateSMA :: State SMAState [Float]
demostrateSMA = mapM computeSMA [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]
 
main :: IO ()
main = putStrLn $ (show result)
where
(result, _) = runState demostrateSMA []
</lang>
 
outputs:
<pre>
[1.0,1.5,2.0,3.0,4.0,4.6666665,4.6666665,4.0,3.0,2.0]
</pre>
 
=={{header|HicEst}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.