summaryrefslogtreecommitdiff
path: root/examples/vector-map.hs
diff options
context:
space:
mode:
authorVivian McPhail <haskell.vivian.mcphail@gmail.com>2010-08-28 11:29:57 +0000
committerVivian McPhail <haskell.vivian.mcphail@gmail.com>2010-08-28 11:29:57 +0000
commit693cae17c1e4ae3570f35324119f47ca6103f3cf (patch)
tree52cd26440025575a2e339fb542593325a3668df4 /examples/vector-map.hs
parent5e60b08d76e666643c795131bcbb18d196a39520 (diff)
add withIndex traversal
Diffstat (limited to 'examples/vector-map.hs')
-rw-r--r--examples/vector-map.hs33
1 files changed, 33 insertions, 0 deletions
diff --git a/examples/vector-map.hs b/examples/vector-map.hs
index f116946..7796cc0 100644
--- a/examples/vector-map.hs
+++ b/examples/vector-map.hs
@@ -30,12 +30,45 @@ addInitialM = mapVectorM_ (\x -> do
30 put $ x + i 30 put $ x + i
31 ) 31 )
32 32
33-- sum the values of the even indiced elements
34sumEvens :: Vector Int -> Int
35sumEvens = foldVectorWithIndex (\x a b -> if x `mod` 2 == 0 then a + b else b) 0
36
37-- sum and print running total of evens
38sumEvensAndPrint :: Vector Int -> VectorMonadT ()
39sumEvensAndPrint = mapVectorWithIndexM_ (\ i x -> do
40 when (i `mod` 2 == 0) (do
41 v <- get
42 put $ v + x
43 v' <- get
44 liftIO $ putStr $ (show v') ++ " "
45 return ())
46 return ()
47 )
48
49indexPlusSum :: Vector Int -> VectorMonadT ()
50indexPlusSum v' = do
51 v <- mapVectorWithIndexM (\i x -> do
52 s <- get
53 let inc = x+s
54 liftIO $ putStr $ show (i,inc) ++ " "
55 put inc
56 return inc) v'
57 liftIO $ do
58 putStrLn ""
59 putStrLn $ show v
60
33------------------------------------------- 61-------------------------------------------
62
34main = do 63main = do
35 v' <- test1 v 64 v' <- test1 v
36 putStrLn "" 65 putStrLn ""
37 putStrLn $ show v' 66 putStrLn $ show v'
38 evalStateT (addInitialM v) 0 67 evalStateT (addInitialM v) 0
39 putStrLn "" 68 putStrLn ""
69 putStrLn $ show (sumEvens v)
70 evalStateT (sumEvensAndPrint v) 0
71 putStrLn ""
72 evalStateT (indexPlusSum v) 0
40 return () 73 return ()
41 74