簡體   English   中英

構造函數模式匹配haskell

[英]constructor pattern matching haskell

我有這個數據類型

data Struct val =  Empty | Exec1 val
                         | Exec2 val 

和兩個虛擬功能

apply :: Struct -> String
apply (Empty) = "matched Empty"  
apply (exec struct) = "matched Exec1 or Exec2"              

apply' :: Struct val -> String
apply' (Empty)   = "matched Empty"  
apply' (Exec1 _) = "matched Exec1"
apply' (Exec2 _) = "matched Exec2"

第二個工作正常,但第一個導致錯誤:“在模式中解析錯誤:exec”。 您能否解釋一下為什么我不能以這種方式在構造函數上進行匹配:apply(exec struct)= ...?

當我的數據類型中有多個構造函數並且必須分別對它們進行模式匹配時,這會導致很多樣板代碼。

通常,如果您有多個共享數據的構造函數,那么通常最好將數據聲明重構為類似

data Struct val = Empty | NonEmpty StructType val
data StructType = Exec1 | Exec2

現在您可以像這樣在模式匹配中apply

apply :: Struct -> String
apply (Empty) = "matched Empty"  
apply (NonEmpty exec struct) = "matched Exec1 or Exec2"

而且您仍然可以將模式匹配到特定的Exec類型

apply' :: Struct val -> String
apply' (Empty)   = "matched Empty"  
apply' (NonEmpty Exec1 _) = "matched Exec1"
apply' (NonEmpty Exec2 _) = "matched Exec2"

“ exec”不是類型構造函數,您只能在模式匹配中使用它們。

你能做的是

data Struct val =  Empty | Exec Int val

apply :: Struct -> String
apply (Empty) = "matched Empty"  
apply (Exec _ _) = "matched Exec1 or Exec2"              

apply' :: Struct val -> String
apply' (Empty)   = "matched Empty"  
apply' (Exec 1 _) = "matched Exec1"
apply' (Exec 2 _) = "matched Exec2"

為什么? 因為您只能匹配構造函數,所以exec是一個新變量。 造成這種情況的原因之一如下:

data Struct2 =  Empty | Exec1 String
                      | Exec2 Int

apply :: Struct2 -> String
apply Empty = "matched Empty"  
apply (exec struct) = ??

誰能知道您要匹配的Exec1Exec2 您無法在此處應用函數,因為無法確定struct的實際類型。

如果要減少模式匹配,可以使用多種方法,從使用case到不同的data實現(如建議的@Karolis)和helper函數,再到具有更復雜類型的更高級別的構造。 但這是一個無休止的話題。

在您的特定情況下,您可以執行以下操作:

apply :: Struct -> String
apply Empty = "matched Empty"  
apply _     = "matched Exec1 or Exec2"

但是,這將無法很好地擴展到更復雜的結果。

apply Empty = "matched empty"
apply (Exec1 _) = notEmpty
apply (Exec2 _) = notEmpty

notEmpty  = "matched Exec1 or Exec2"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM