2016 Update
This commit is contained in:
parent
948b86eafa
commit
dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions
|
|
@ -1,26 +1,25 @@
|
|||
{-# LANGUAGE BangPatterns #-}
|
||||
|
||||
import Control.Monad
|
||||
import Data.List
|
||||
import Data.IORef
|
||||
|
||||
data Pair a b = Pair !a !b
|
||||
|
||||
mean :: Fractional a => [a] -> a
|
||||
mean xs = sum xs / (genericLength xs)
|
||||
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]
|
||||
|
||||
simple_moving_averager period = do
|
||||
numsRef <- newIORef []
|
||||
return (\x -> do
|
||||
nums <- readIORef numsRef
|
||||
let xs = take period (x:nums)
|
||||
writeIORef numsRef xs
|
||||
return $ mean xs
|
||||
)
|
||||
mkSMA :: Int -> IO (Double -> IO Double)
|
||||
mkSMA period = avgr <$> newIORef []
|
||||
where avgr nsref x = readIORef nsref >>= (\ns ->
|
||||
let xs = take period (x:ns)
|
||||
in writeIORef nsref xs $> mean xs)
|
||||
|
||||
main = do
|
||||
sma3 <- simple_moving_averager 3
|
||||
sma5 <- simple_moving_averager 5
|
||||
forM_ series (\n -> do
|
||||
mm3 <- sma3 n
|
||||
mm5 <- sma5 n
|
||||
putStrLn $ "Next number = " ++ (show n) ++ ", SMA_3 = " ++ (show mm3) ++ ", SMA_5 = " ++ (show mm5)
|
||||
)
|
||||
main = mkSMA 3 >>= (\sma3 -> mkSMA 5 >>= (\sma5 ->
|
||||
mapM_ (str <$> pure n <*> sma3 <*> sma5) series))
|
||||
where str n mm3 mm5 =
|
||||
concat ["Next number = ",show n,", SMA_3 = ",show mm3,", SMA_5 = ",show mm5]
|
||||
|
|
|
|||
|
|
@ -23,6 +23,4 @@ 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 []
|
||||
main = print $ evalState demostrateSMA []
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue