Just another update

This commit is contained in:
Ingy döt Net 2015-02-20 00:35:01 -05:00
parent a25938f123
commit 00a190b0a6
6591 changed files with 94363 additions and 23227 deletions

View file

@ -0,0 +1,26 @@
import Control.Monad
import Data.List
import Data.IORef
mean :: Fractional a => [a] -> a
mean xs = sum xs / (genericLength xs)
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
)
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)
)

View file

@ -0,0 +1,28 @@
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 []