2016-05-16 7 views
0

私はデータ型ツリーとデータ型のオペアンプを作り、今私が運転して文字列を生成する関数を作成したいと思います:すべての私のコードのhaskell、データツリー関数、文字列出力?

まず:

data Op = Add | Sub | Mult | Div 
    deriving(Eq,Show) 
data Tree a b = Leaf a | Node (Tree a b) b (Tree a b) 
    deriving(Eq,Show) 

マイツリー出力はこの文字列のようになります。最後には

tree = Node (Node (Node (Leaf 20) Add (Leaf 20)) Sub (Leaf 2)) Mult (Node (Leaf 33) Div (Leaf 3)) 

--     Node _ Mult _ 
--     /   \ 
--     /   \ 
--     /    \ 
--    /    \ 
--    /     \ 
--    /     \ 
--    Node _ Sub _    Node _ Div _ 
--    / \     / \ 
--    /  \     /  \ 
--    / Leaf 2   Leaf 33 Leaf 3 
--   /   
--   /   
--   Node _ Add _     
--   /  \ 
--   /  \ 
--   /   \ 
--   Leaf 20  Leaf 30 

"(((20+30)-2)*(33 div 3))」

+1

ビット宿題のように聞こえる、あなたは何を試してみましたか?何がうまくいったのですか?小さな木(1葉、1節、2葉...)を手動で文字列に変換することで問題に近づけてみてください。すべてのツリーに対してこれを行う関数を再帰的に定義するために、それを使用できないかどうかを確認してください。 – jakubdaniel

答えて

1
treeToStr :: (Show a, Show b) => Tree a b -> String 
treeToStr (Leaf a) = show a 
treeToStr (Node a n b) = "(" ++ treeToStr a ++ show n ++ treeToStr b ++ ")" 

Showの暗黙の実装ではなく、シンボルを出力する演算子の変換を行うだけで済みます。そのためには、Opの手作業でShowをインスタンス化するか、新しいクラスを導入するか、treeToStrを特化してください。

data Op = Add | Sub | Mult | Div 
    deriving Eq 

-- Be careful about giving non-standard implementations of classes like show, in Haskell there are always laws and rules to follow: Show should output what Read would accept for example. 
instance Show Op where 
    show Add = ... 
    ... 

または

data Op = ... deriving Eq 
data Tree = ... deriving Eq 

class Stringifiable c where 
    toStr :: c -> String 

instance Stringifiable Op where 
    toStr Add = ... 

instance (Show a, Stringifiable b) => Stringifiable (Tree a b) where 
    toStr (Leaf a) = show a 
    toStr (Node a n b) = "(" ++ toStr a ++ toStr n ++ toStr b ++ ")" 

-- You can then stringify your tree: 
toStr tree 

または単に

opTreeToStr :: Show a => Tree a Op -> String 
opTreeToStr (Leaf a) = show a 
opTreeToStr (Node a n b) = "(" ++ toStr a ++ opToStr n ++ toStr b ++ ")" 

opToStr :: Op -> String 
opToStr Add = "+" 
... 

-- Stringify tree, assuming it has the correct type Tree a Op: 
opTreeToStr tree 
関連する問題