【问题标题】:Haskell - Combining datatypes?Haskell - 组合数据类型?
【发布时间】:2016-09-22 23:06:35
【问题描述】:

我是 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 a b c',因为它不是类型安全的。即我不保证:a == Name String, b == Age Int, c == Height Int.

【问题讨论】:

    标签: haskell types


    【解决方案1】:

    exampleFunction 太笼统了。您声称它可以为 any 类型 abc 采用 Characteristics a b c 值。但是,a 类型的值被传递给Name,它只能采用String 类型的值。解决方案是具体说明特征实际上可以是什么类型。

    exampleFunction :: Characteristics String Int Int -> User
    exampleFunction (Characteristics a b c) = (Person (Name a) (Age b) (Height c))
    

    但请考虑,您甚至可能不需要newtypes;简单的类型别名就足够了。

    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
    

    【讨论】:

    • 谢谢,我刚刚同时更新了我的问题:p
    【解决方案2】:

    试试这个:

    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 
    

    【讨论】:

    • 这并不能解释错误,只是拍打编译器:-)
    • 添加了一些解释
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2018-11-29
    • 2011-02-22
    • 1970-01-01
    • 2013-05-10
    • 2021-03-11
    相关资源
    最近更新 更多