2012-09-30 51 views
16

裝飾樹我想在樹上的每一個元素標記不同的值(智力,例如緣故)。我成功地做到這一點,但代碼是醜陋的野獸,我不知道如何與單子還沒有工作。如何在Haskell

我的看法:

data Tree a = Tree (a, [Tree a]) 

tag (Tree (x, l)) n = ((m, x), l') 
where (m,l') = foldl g (n,[]) l 
     where g (n,r) x = let ff = tag x n in ((fst $ fst ff) +1, (Tree ff):r) 

你知道一些更好的辦法?

編輯: 我剛剛意識到,上述foldl真的是mapAccumL。所以,這裏是以上清理版本:

import Data.List (mapAccumL) 

data Tree a = Tree (a, [Tree a]) 

tag (Tree (x, l)) n = ((m,x),l') 
    where (m,l') = mapAccumL g n l 
     g n x = let [email protected]((f,_),_) = tag x n in (f+1,ff) 
+2

注意mapAccumL是一樣的MAPM爲國家單子,如果刪除了newtypes。所以每當你使用mapAccumL,考慮使用狀態單子。 –

回答

11

我已經稍微修改了您的類型。仔細研究這段代碼:

import Control.Monad.State 

-- It's better not to use a pair as the argument of the constructor  
data Tree a = Tree a [Tree a] deriving Show 

-- We typically want to put the Tree argument last; it makes it 
-- easier to compose tree functions. 
-- 
-- Also, the Enum class is what you want here instead of numbers; 
-- you want a "give me the next tag" operation, which is the succ 
-- method from Enum. (For Int, succ is (+1).) 
tag :: Enum t => t -> Tree a -> Tree (a, t) 
tag init tree = 
    -- tagStep is where the action happens. This just gets the ball 
    -- rolling. 
    evalState (tagStep tree) init 

-- This is one monadic "step" of the calculation. It assumes that 
-- it has access to the current tag value implicitcly. I'll 
-- annotate it in the comments. 
tagStep :: Enum t => Tree a -> State t (Tree (a, t)) 
tagStep (Tree a subtrees) = 
    do -- First, recurse into the subtrees. mapM is a utility function 
     -- for executing a monadic action (like tagStep) on a list of 
     -- elements, and producing the list of results. 
     subtrees' <- mapM tagStep subtrees 

     -- The monadic action "get" accesses the implicit state parameter 
     -- in the State monad. The variable tag gets the value. 
     tag <- get 

     -- The monadic action `put` sets the implicit state parameter in 
     -- the State monad. The next get will see the value of succ tag 
     -- (assuming no other puts in between). 
     -- 
     -- Note that when we did mapM tagStep subtrees above, this will 
     -- have executed a get and a put (succ tag) for each subtree.   
     put (succ tag) 

     return $ Tree (a, tag) subtrees' 

編輯:相同的溶液上面,而是通過一輪重構爲可重複使用的塊地說:

-- This function is not part of the solution, but it will help you 
-- understand mapTreeM below. 
mapTree :: (a -> b) -> Tree a -> Tree b 
mapTree fn (Tree a subtrees) = 
    let subtrees' = map (mapTree fn) subtrees 
     a' = fn a 
    in Tree a' subtrees' 

-- Normally you'd write that function like this: 
mapTree' fn (Tree a subtrees) = Tree (fn a) $ map (mapTree' fn) subtrees 

-- But I wrote it out the long way to bring out the similarity to the 
-- following, which extracts the structure of the tagStep definition from 
-- the first solution above.  
mapTreeM :: Monad m => (a -> m b) -> Tree a -> m (Tree b) 
mapTreeM action (Tree a subtrees) = 
    do subtrees' <- mapM (mapTreeM action) subtrees 
     a' <- action a 
     return $ Tree a' subtrees' 

-- That whole business with getting the state and putting the successor 
-- in as the replacement can be abstracted out. This action is like a 
-- post-increment operator.  
postIncrement :: Enum s => State s s 
postIncrement = do val <- get 
        put (succ val) 
        return val 

-- Now tag can be easily written in terms of those. 
tag init tree = evalState (mapTreeM step tree) init 
    where step a = do tag <- postIncrement 
         return (a, tag) 

您可以mapTreeM過程中的局部值在子樹之前如果你想:

mapTreeM action (Tree a subtrees) = 
    do a' <- action a 
     subtrees' <- mapM (mapTreeM action) subtrees 
     return $ Tree a' subtrees' 

並採用Control.Monad,你可以把它變成一個班輪:

mapTreeM action (Tree a subtrees) = 
    -- Apply the Tree constructor to the results of the two actions 
    liftM2 Tree (action a) (mapM (mapTreeM action) subtrees) 

-- in the children-first order: 
mapTreeM' action (Tree a subtrees) = 
    liftM2 (flip Tree) (mapM (mapTreeM action) subtrees) (action a) 
+0

有人告訴我,當我們做必要的事情時,Monads真的很有幫助,但我從來沒有想過它會在眼睛上如此輕鬆。感謝一個涉及單子的最全面的答案。 (我需要首先研究它們以瞭解它們的理性和用途) – Tomot

16

考慮的Data.Traversable和一些有用的GHC擴展的優勢,我們可以進一步重構sacundim's solution

{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} 

import Control.Monad.State 
import Data.Foldable 
import Data.Traversable 

data Tree a = Tree a [Tree a] 
    deriving (Show, Functor, Foldable, Traversable) 

postIncrement :: Enum s => State s s 
postIncrement = do val <- get 
        put (succ val) 
        return val 

-- Works for any Traversable, not just trees! 
tag :: (Enum s, Traversable t) => s -> t a -> t (a, s) 
tag init tree = evalState (traverse step tree) init 
    where step a = do tag <- postIncrement 
         return (a, tag)