Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Show tree1 = Branch (Branch (Leaf 'A') (Branch (Leaf 'B') (Leaf 'C'))) (Branch (Leaf 'D') (Leaf 'E')) labelTree1 = fst . lab 0 where lab c (Leaf x) = (Leaf c, c+1) lab c (Branch t1 t2) = let (t1',c1) = lab c t1 (t2',c2) = lab c1 t2 in (Branch t1' t2', c2) type IntSt a = Int -> (a,Int) unit :: a -> IntSt a unit x = \s -> (x,s) bind :: IntSt a -> (a -> IntSt b) -> IntSt b m `bind` f = \s -> let (x1,s1) = m s (x2,s2) = f x1 s1 in (x2,s2) getInt :: IntSt Int getInt = \s -> (s,s) putInt :: Int -> IntSt () putInt x = \s -> ((),x) runIntSt :: IntSt a -> Int -> a runIntSt f s = fst (f s) inc :: IntSt Int inc = getInt `bind` \i -> putInt (i+1) `bind` \_ -> unit i labelTree2 t = runIntSt (lab t) 0 where lab (Leaf x) = inc `bind` \i -> unit (Leaf i) lab (Branch t1 t2) = lab t1 `bind` \t1' -> lab t2 `bind` \t2' -> unit (Branch t1' t2') newtype IntStM a = ISt (Int -> (a,Int)) instance Monad IntStM where return x = ISt (\s -> (x,s)) k >>= f = ISt (\s -> let ISt k' = k (x,s') = k' s ISt f' = f x in f' s') getIntM :: IntStM Int getIntM = ISt (\s -> (s,s)) putIntM :: Int -> IntStM () putIntM x = ISt (\s -> ((),x)) runIntStM :: IntStM a -> Int -> a runIntStM f s = let ISt f' = f in fst (f' s) incM :: IntStM Int incM = getIntM >>= \i -> putIntM (i+1) >> return i labelTree3 t = runIntStM (lab t) 0 where lab (Leaf x) = incM >>= \i -> return (Leaf i) lab (Branch t1 t2) = lab t1 >>= \t1' -> lab t2 >>= \t2' -> return (Branch t1' t2') labelTree4 t = runIntStM (lab t) 0 where lab (Leaf x) = do i <- incM return (Leaf i) lab (Branch t1 t2) = do t1' <- lab t1 t2' <- lab t2 return (Branch t1' t2')