[英]Haskell - Tuples of custom types
我希望能夠代表自定義類型的元組。 我介紹的內容如下:
type Name = String
data DataType a = DataType a deriving Show
data Val a = Single (DataType a) | List [(DataType a)] deriving Show
data State a = State [(Name,(Val a))] deriving Show
append :: (Name, (Val a)) -> State a -> State a
append nv (State st) = State (st ++ [nv])
現在的問題是State不能為[(“ NUM1”,Single(DataType 1)),(“ STR1”,Single(DataType“ Hello”))]]。 我希望能夠執行以下操作:
*Main> num1 = Single (DataType 1)
*Main> num1
Single (DataType 1)
*Main> str1 = Single (DataType "str1")
*Main> str1
Single (DataType "str1")
*Main> st1 = append ("NUM1",num1) (State [])
*Main> st1
State [("NUM1",Single (DataType 1))]
*Main> st2 = append ("STR1",str1) st1
<interactive>:8:28: error:
• No instance for (Num [Char]) arising from a use of ‘st1’
• In the second argument of ‘append’, namely ‘st1’
In the expression: append ("STR1", str1) st1
In an equation for ‘st2’: st2 = append ("STR1", str1) st1
當我嘗試附加(Name, Val String)
時,Haskell抱怨(Name, Val String)
因為它已經將State
解釋為State [(Name, (Val Int)]
,這並不是我真正的意圖。
如何實現State
作為DataType Int或DataType String的字典?
PS:這種功能的一種可能用途是在生成的代碼中,其中將不止一種類型的代碼生成為代碼,並且還使用上述功能來表示狀態。 例如,用戶可以使用UI定義某些類型,然后系統為這些類型以及上面定義的state
生成Haskell代碼。
Haskell並不真正支持混合類型列表,但是https://stackoverflow.com/a/7787429/3953988提供了一些好的解決方案。
從該答案中,或者:
data DataType = X Int | Y String...
) data DataType = forall a. Show a => Datatype a
)(顯示為可選約束,我想您希望它與DataType一樣可顯示)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.