木
Haskellで木を書こう
というわけで。
数日前に、大学で課題で出た二分木を書いてみることに
まだ途中だけれども、掲載
data Tree a = Empty | Leaf a | Branch a (Tree a) (Tree a) deriving (Show , Eq) main = do cs <- getLine; print $ mkTree $ delChar ' ' cs delChar :: Char -> String -> String delChar _ [] = [] delChar x (c:cs) = if c == x then delChar x cs else c:delChar x cs mkTree :: String -> Tree Int mkTree (c:cs) | c == '(' = Branch (read [head cs]) (mkTree $ tail cs) (mkTree cs) | c >= '0' && c <= '9' = Leaf (read [c]) | c == '_' = Empty | otherwise = mkTree cs
delChar関数は、Spaceキーなどの読み飛ばしです。
実際の木を解析します
木の入力は
()
で括る、という制限を設けました
1
のような入力は不正です。そのようにする場合は、
(1 _ _)
として、子を持たない、という書き方をします。
すると、左部分木のうち左要素に関してのみ、正常に動作
右側の部分の処理を、再帰をうまいこと利用して書いてやればいいですね。
といっても、まだ思いつかないんですが笑