[Haskell-cafe] creating tree with level subnodes and incrementing number?

Marc Weber marco-oweber at gmx.de
Tue Aug 8 08:30:39 EDT 2006


Hi

I've tried as an exercise to learn how to use the state monad to create
a tree this way:

module Main where
import Control.Monad.State
import Data.Tree
import Random

createTree :: Int -> Int -> (Tree Int, Int)
createTree 4 = runState $ State $ \s -> (Node s [] , s+1) -- stop at level 4
createTree level = runState (do item <- State $ (\s -> (s,s+1))
				forest <- State $ (\s -> foldr (\_ (for, n) -> let (l, n') = (createTree (level + 1) n) in (l:for,n')) 
							       ([], s) 
							       (replicate level ()) )
				return $ Node item (reverse forest) )


main = do
  putStrLn $ drawTree $ fmap show $ fst $ createTree 2 0

---- output ----------
0
|
+- 1    -- features: auto numbering and level n exists of n Nodes
|  |
|  +- 2
|  |
|  +- 3
|  |
|  `- 4
|
`- 5
   |
   +- 6
   |
   +- 7
   |
   `- 8

   |  |
   2  3  ... Nodes per level

I think this line is not very easy to understand.. the (replecate part is just a dummy to count the iterations)
forest <- State $ (\s -> foldr (\_ (for, n) -> let (l, n') = (createTree (level + 1) n) in (l:for,n')) 
				       ([], s) 
				       (replicate level ()) )

Is there a better way to do this?
This problem is similar to adding numbers to each tree item

Marc


More information about the Haskell-Cafe mailing list