Advertisement
NLinker

Generate and prettyprint binary trees

Sep 13th, 2016
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- small experiment with enumerating binary trees
  2.  
  3. data T = B T T | L deriving (Eq)
  4.  
  5. instance Show T where
  6.   show L = "."
  7.   show (B l r) = "(" ++ show l ++ show r ++ ")"
  8.  
  9. buildTs :: Int -> [T]
  10. buildTs 0 = [L]
  11. buildTs n = [B l r | i <- [0..n-1],
  12.                      l <- buildTs i,
  13.                      r <- buildTs (n-1-i) ]
  14.  
  15. randomT :: (MonadRandom m) => Int -> m T
  16. randomT 0 = return L
  17. randomT n = do
  18.   i <- getRandomR (0, n-1)
  19.   l <- randomT i
  20.   r <- randomT (n-1-i)
  21.   return $ B l r
  22.  
  23. main :: IO ()
  24. main = do
  25.   let gen = mkStdGen 42
  26.   let t = evalRand (randomT 4) gen
  27.   print t
  28.  
  29. -- prints ((..)((..).))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement