fizruk

Pointer problem

May 8th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. {-# LANGUAGE TemplateHaskell #-}
  2. module Main where
  3.  
  4. import Control.Lens
  5. import Control.Monad.State
  6. import Control.Applicative ((<$>))
  7.  
  8. data Node a = Node
  9.     { _val   :: a
  10.     , _left  :: Maybe (Node a)
  11.     , _right :: Maybe (Node a)
  12.     }
  13.     deriving (Show)
  14. makeLenses ''Node
  15.  
  16. leaf :: a -> Node a
  17. leaf x = Node x Nothing Nothing
  18.  
  19. -- helper for children manipulations
  20. h :: r -> State (Node a) r -> State (Maybe (Node a)) r
  21. h def m = do
  22.     s <- get
  23.     case s of
  24.         Nothing   -> return def
  25.         Just node -> do
  26.             let (ret, node') = runState m node
  27.            put $ Just node'
  28.             return ret
  29.  
  30. test :: (Num t) => State (Node t) t
  31. test = do
  32.     -- right->val = 10
  33.     zoom right $ h () $ do
  34.         val .= 10
  35.     -- left->right->left = 100
  36.     zoom left $ h () $ do
  37.         zoom right $ h () $ do
  38.             zoom left $ h () $ do
  39.                 val .= 10
  40.     -- right->left->val = left->val
  41.     v <- zoom left $ h 0 $ use val
  42.     zoom right $ h () $ do
  43.         zoom left $ h () $ do
  44.             val .= v
  45.     -- right->left->val + right->val
  46.     x <- zoom right $ h 0 $ do
  47.             zoom left $ h 0 $ do
  48.                 use val
  49.     y <- zoom right $ h 0 $ use val
  50.     return (x + y)
  51.  
  52. sample :: (Num t) => Node t
  53. sample =
  54.     Node 1
  55.         (Just $ Node 2
  56.             Nothing
  57.             (Just $ leaf 3))
  58.         (Just $ Node 4
  59.             (Just $ leaf 5)
  60.             (Just $ leaf 6))
  61.  
  62. main :: IO ()
  63. main = print . evalState test $ sample
Advertisement
Add Comment
Please, Sign In to add comment