[英]how can i show a derivation tree in haskell?
我正在做一個練習,它構建了一段時間的語言的派生樹。 我對while語言的實現由“ Aexp”(算術表達式)“ Bexp”(布爾表達式)和“ Stm”(語句)等代數數據類型組成:
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
在這些代數數據類型之后,我創建了更多的代數數據類型來表示while語言程序的派生樹。
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'''
每個構造函數的期望值如下所示:
這是一個使用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'''
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.