[英]Haskell - Combining datatypes?
我是Haskell的新手,我一直在尋找以下內容的答案,但沒有運氣。
為什么此代碼無法編譯?
newtype Name = Name String deriving (Show, Read)
newtype Age = Age Int deriving (Show, Read)
newtype Height = Height Int deriving (Show, Read)
data User = Person Name Age Height deriving (Show, Read)
data Characteristics a b c = Characteristics a b c
exampleFunction :: Characteristics a b c -> User
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c))
錯誤:
"Couldn't match expected type ‘String’ with actual type ‘a’,‘a’ is a rigid type, variable bound by the type signature"
但是,這樣編譯就可以了:
exampleFunction :: String -> Int -> Int -> User
exampleFunction a b c = (Person (Name a) (Age b) (Height c))
我意識到可以采用更簡單的方法來進行上述操作,但是我只是在測試自定義數據類型的不同用法。
更新:
我的傾向是編譯器不喜歡'exampleFunction :: Characteristics abc',因為它的類型不安全。 即我不提供以下保證:a ==名稱字符串,b ==年齡整數,c ==高度整數。
exampleFunction
太籠統了。 您聲稱它可以為a
, b
和c
任何類型a
Characteristics abc
值。 但是,類型a
的值傳遞給Name
,后者只能采用String
類型的值。 解決方案是具體說明特征實際上可以是什么類型。
exampleFunction :: Characteristics String Int Int -> User
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c))
但是,請考慮一下,在這里甚至可能不需要newtype
。 簡單類型別名就足夠了。
type Name = String
type Age = Int
type Height = Int
type Characteristics = (,,)
exampleFunction :: Characteristics Name Age Height -> User
exampleFunction (Charatersics n a h) = Person n a h
嘗試這個:
exampleFunction :: Characteristics String Int Int -> User
exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c))
之所以起作用,而您卻不起作用,是因為Name,Age和Height需要特定類型,您的示例函數使用了完全通用的參數。
示例行中的a,b和c定義了參數的類型,而不是參數的名稱。
exampleFunction :: Characteristics a b c
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.