2015-12-04 101 views
3

讓我們說我有兩個類型別名:如何 「投」 聯合類型榆樹

type alias A = {...} 
type alias B = {...} 

和聯合類型

type Content = A | B 

和模型類型

type alias Model= {cont : Content, ...} 

init : Content -> Model 
init cont = {cont = cont, ...} 

怎麼辦我將類型A的記錄傳遞給init。

a : A 
a = {...} 
init a 

引發以下錯誤:

Detected errors in 1 module. 
## ERRORS in Main.elm ########################################################## 

-- TYPE MISMATCH ------------------------------------------------------ Main.elm 

The 1st argument to function `init` has an unexpected type. 

78|    init e 
        ^
As I infer the type of values flowing through your program, I see a conflict 
between these two types: 

    Content 

    A 

我會想象A是一種內容的 「亞型」 的。我不能只是寫

a:Content 
a = {...} 
init a 

因爲一些邏輯上的內容做案例分析

+0

是類型別名A和B,以及對內容的定義:

a : A a = { ... } init (TagA a) 

init您可以通過區分這兩種類型相同的模塊?無法編譯重複定義錯誤。 –

+0

它們不在同一模塊中,但我引用了'type Content = modulename.A | modulename.B'。問題是這些類型不能真正引入到模塊中。我可以做出某種代理類型,我想。你怎麼看? –

回答

6

榆木的聯合類型的所謂歧視工會(或標籤聯合)。鑑別部分是標籤或構造函數。在這種情況下,我想你想:

type Content = TagA A | TagB B 

注意第一個大寫的名字是標籤,和其他任何爲其他類型或類型變量。

現在你可以這樣做:

init content = 
    case content of 
    TagA a -> ... 
    TagB b -> ...