Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {-# LANGUAGE TemplateHaskell #-}
- module Main where
- import Control.Lens
- import Control.Monad.State
- import Control.Applicative ((<$>))
- data Node a = Node
- { _val :: a
- , _left :: Maybe (Node a)
- , _right :: Maybe (Node a)
- }
- deriving (Show)
- makeLenses ''Node
- leaf :: a -> Node a
- leaf x = Node x Nothing Nothing
- -- helper for children manipulations
- h :: r -> State (Node a) r -> State (Maybe (Node a)) r
- h def m = do
- s <- get
- case s of
- Nothing -> return def
- Just node -> do
- let (ret, node') = runState m node
- put $ Just node'
- return ret
- test :: (Num t) => State (Node t) t
- test = do
- -- right->val = 10
- zoom right $ h () $ do
- val .= 10
- -- left->right->left = 100
- zoom left $ h () $ do
- zoom right $ h () $ do
- zoom left $ h () $ do
- val .= 10
- -- right->left->val = left->val
- v <- zoom left $ h 0 $ use val
- zoom right $ h () $ do
- zoom left $ h () $ do
- val .= v
- -- right->left->val + right->val
- x <- zoom right $ h 0 $ do
- zoom left $ h 0 $ do
- use val
- y <- zoom right $ h 0 $ use val
- return (x + y)
- sample :: (Num t) => Node t
- sample =
- Node 1
- (Just $ Node 2
- Nothing
- (Just $ leaf 3))
- (Just $ Node 4
- (Just $ leaf 5)
- (Just $ leaf 6))
- main :: IO ()
- main = print . evalState test $ sample
Advertisement
Add Comment
Please, Sign In to add comment