2

我正在做一個練習,建立一種語言的派生樹。我雖然語言的實現是由代數數據類型,如「AEXP」(算術表達式)「Bexp」(布爾表達式)和「STM」(報表)組成:我如何顯示haskell中的派生樹?

type Var = String 
data Aexp = N Integer 
     | V Var 
     | Add Aexp Aexp 
     | Mult Aexp Aexp 
     | Sub Aexp Aexp 
     deriving (Show, Eq) 

data Bexp = TRUE 
     | FALSE 
     | Eq Aexp Aexp 
     | Le Aexp Aexp 
     | Neg Bexp 
     | And Bexp Bexp 
     deriving (Show, Eq) 

data Stm = Ass Var Aexp 
     | Skip 
     | Comp Stm Stm 
     | If Bexp Stm Stm 
     | While Bexp Stm 
     | Repeat Stm Bexp 
     deriving Show 

這些代數數據類型後,我創造了更多的代數數據類型來表示程序的派生樹

type State = Var -> Z 

data Config = Inter Stm State -- <S, s> 
     | Final State  -- s 

data Transition = Config :-->: State 

data DerivTree = AssNS  Transition 
      | SkipNS Transition 
      | CompNS Transition DerivTree DerivTree 
      | IfTTNS Transition DerivTree 
      | IfFFNS Transition DerivTree 
      | WhileTTNS Transition DerivTree DerivTree 
      | WhileFFNS Transition 
      | RepeatTTNS Transition 
      | RepeatFFNS Transition DerivTree DerivTree 

如何顯示這種派生樹?

<z:=x, s> -> s' <x:=,s1> -> s'' 
---------------------------------- 
    <z:=x; x:=y,s> -> s''    <y:=z,s''> -> s''' 
    ------------------------------------------------------ 
      <z:=x; x:=y; y:=z, s> -> s''' 

每一個構造函數的預期值如下:

enter image description here

+0

只是遞歸地做。你想如何渲染樹,文本,膠乳,別的東西? – Bergi

+0

什麼是「配置」和「狀態」? – Bergi

+0

您嘗試了什麼,遇到了什麼問題? 「Aexpr」,「Bexpr」和「Stm」確實與顯示DerivTree的問題有關嗎? – Cirdec

回答

3

下面是使用boxes包生產的東西派生樹樣的一個簡單的例子。您應該能夠適應您的需求,而不會產生太多麻煩 - 通過生成Tree String或使用pp中的想法直接從您的派生樹生成Box。 (我選擇在這裏使用Tree String,而不是你的類型主要是爲了避免不得不計算出所有數據類型的漂亮印花的細節有很多的構造函數)

import Data.Tree 
import Text.PrettyPrint.Boxes 

pp :: Tree String -> Box 
pp (Node here []  ) = text here 
pp (Node here children) = vcat center1 [premises, separator, conclusion] 
    where 
    premises = hsep 4 bottom (map pp children) 
    conclusion = text here 
    width  = max (cols premises) (cols conclusion) 
    separator = text (replicate width '-') 

sampleTree :: Tree String 
sampleTree = Node "<z:=x; x:=y; y:=z, s> -> s'''" 
    [Node "<z:=x; x:=y,s> -> s''" 
     [Node "<z:=x, s> -> s'" [] 
     ,Node "<x:=,s1> -> s''" [] 
     ] 
    ,Node "<y:=z, s''> -> s'''" [] 
    ] 

下面是ghci中運行示例:

*Main> printBox (pp sampleTree) 
<z:=x, s> -> s' <x:=,s1> -> s''      
----------------------------------      
     <z:=x; x:=y,s> -> s''   <y:=z, s''> -> s''' 
--------------------------------------------------------- 
       <z:=x; x:=y; y:=z, s> -> s'''    
+0

謝謝你!這很好! – Eduen