2013年1月17日木曜日

Haskell Tree Forest!

まず、Data.Treeの中身をのぞいてみます。
data Tree a = Node {rootLabel :: a, subForest :: Forest a}
instance [safe] Eq a => Eq (Tree a)
instance [safe] Monad Tree
instance [safe] Functor Tree
instance [safe] Read a => Read (Tree a)
instance [safe] Show a => Show (Tree a) 
Prelude Data.Tree> :t unfoldTree
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
Prelude Data.Tree> :browse
type Forest a = [Tree a]
data Tree a = Node {rootLabel :: a, subForest :: Forest a}
drawForest :: Forest String -> String
drawTree :: Tree String -> String
flatten :: Tree a -> [a]
levels :: Tree a -> [[a]]
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForestM ::
  Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF ::
  Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
目標は二三分間でTreeを作って出してみたいですから、
drawTreeかdrawForestを使いたいな・・・
ただし、drawTreeはTree Stringしか描画できないです。
ということは、aのところで、Stringを入れ替える必要がありますね。

あともう一つ、どうやって枝のない葉っぱをつくるの問題が残ってます・・・
よく見たら、Node中のsubForestのtype、実際は [ ] Tree a !
Listです!!
[ ]をすれば、葉っぱができるはず!

早速作りました!あの人が何年もかけて作った会社を
import Data.Tree

type Human = Forest String
type Occupation = Tree String

boss,worker,newbie::Occupation
newbie = Node "Baby Door" []
worker = Node "Bill Door" [newbie, newbie,newbie]
boss = Node "Bill Gate" [worker, worker]

guys::Human
guys = [newbie,worker,boss]

main::IO()
main = do
    putStr "\n <------------------------ Microsoft !\n"
    putStr $ drawTree boss
    putStr "\n <------------------------ All the guys !\n"
    putStr $ drawForest guys

0 件のコメント:

コメントを投稿