Anonymous user
Averages/Simple moving average: Difference between revisions
→{{header|Haskell}}: reformulated mean calculation with foldl' and strict pair in first example
(→{{header|Lua}}: variable period, f renamed to sum and simplified) |
(→{{header|Haskell}}: reformulated mean calculation with foldl' and strict pair in first example) |
||
Line 1,572:
Conform version to the requirement, function SMA called multiple times with just a number:
{{works with|GHC|6.10.4}}
<lang Haskell>
import Control.Monad
import Data.List
import Data.IORef
data Pair a b = Pair !a !b
mean :: Fractional a => [a] -> a
mean = divl . foldl' (\(Pair s l) x -> Pair (s+x) (l+1)) (Pair 0.0 0)
where divl (_,0) = 0.0
divl (s,l) = s / fromIntegral l
series = [1,2,3,4,5,5,4,3,2,1]
mkSMA :: Int -> IO (Double -> IO Double)
mkSMA period
where avgr nsref x = readIORef nsref >>= (\ns ->
main = mkSMA 3 >>= (\sma3 -> mkSMA 5 >>= (\sma5 ->
mapM_ (str <$> pure n <*> sma3 <*> sma5) series))
where str n mm3 mm5 =
concat
▲ putStrLn $ "Next number = " ++ (show n) ++ ", SMA_3 = " ++ (show mm3) ++ ", SMA_5 = " ++ (show mm5)
{{out}}
<pre>Next number = 1.0, SMA_3 = 1.0, SMA_5 = 1.0
Line 1,652 ⟶ 1,651:
main :: IO ()
main =
</lang>
|