2013-07-28 21 views
1

我想要得到一個表達式並將其轉換爲標準形式。爲了更好地闡明我的目的,假設你定義一個通用樣式你的表情是這樣的:用Haskell定義一個正常形式

Σ(A * B)//產品

現在總和,如果你給出的輸入這是不是在格式如:(a + b)*(c + d),你需要先對它進行標準化(其實它只是一個簡單的例子而不是我的例子) 現在我有一個已經寫在ML中的代碼,它的也是長。在這裏你可以看到一些snipets:

rew(p_choice(x,p_nil)) = rew(x) | 
rew(p_choice(p_nil,x)) = rew(x) | 
rew(p_sum(d,p_nil)) = p_nil | 
rew(p_sum(d,p_choice(x,y))) = rew(p_choice(rew(p_sum(d,x)),rew(p_sum(d,y)))) 
rew(p_cond(b,p_nil,p_nil)) = p_nil | 
rew(p_cond(b,p_choice(x,y),p_nil)) =rew(p_choice(rew(p_cond(b,x,p_nil)),rew(p_cond(b,y,p_nil)))) | 
rew(p_cond(b,p_sum(x,y),p_nil)) = rew(p_sum(x,rew(p_cond(b,y,p_nil)))) | 
rew(p_cond(b1,p_cond(b2,x,p_nil),p_nil)) = rew(p_cond(b1 andalso b2, x,p_nil)) | 
rew(p_cond(b,x,p_nil)) = p_cond(b,x,p_nil) | 
rew(p_cond(b,x,y)) = 
    rew(p_choice(rew(p_cond(b,x,p_nil)),rew(p_cond(not(b),y,p_nil)))) 

我的問題是,是否哈斯克爾介紹,可以幫助此代碼更加整齊完成的功能?

+4

如果你有1000個案件處理,你必須處理1000個的情況下,沒有語言可以幫助你在 – Ankur

+1

我認爲你所說的「風格」或「標準形式」通常被稱爲「範式」。 – Toxaris

+1

Haskell需要較少的逗號和括號:-) – yatima2975

回答

3

Haskell中的模式匹配設施非常相似,我不認爲最大的Haskell排他性(類型類,懶惰等)可以幫助您。也就是說,可能有辦法在ML中使事情變得更簡單。

需要考慮的一件事是分步處理。現在有一些重複,如果事情是左或右的論點。你可以嘗試轉換到一箇中間標準形式,爲事物選擇一個特定的順序。

另一個訣竅是將每個步驟的處理與遞歸分開,因此您不要將樹遍歷與節點處理混合在一起。您可以編寫函數來處理每個節點的stp,然後使用單獨的摺疊函數將所有內容綁定在一起。

data Tree = Leaf Int | Node Tree Tree 

directsum :: Tree -> Int 
directSum (Leaf n) = n 
directsum (Node a b) = (directsum a) + (directsum b) 

-- vs 

foldtree :: (Int -> r) -> (r -> r -> r) -> Tree -> b 
foldtree onLeaf onNode t = 
    go t 
    where 
    go (Leaf n) = onLeaf n 
    go (Tree a b) = onNode (go a) (go b) 

foldedSum :: Tree -> Int 
foldedsum t = 
    foldtree leafsum nodesum t 
    where 
    leafsum n = n 
    nodesum a b = a + b