简体   繁体   English

Haskell 多重声明错误类型“形状”

[英]Haskell multiple declaration error type “Shape”

I trying to create an sum type named Shape and later on another sum type named PositionedShape with the property of Shape init我试图创建一个名为Shape的总和类型,然后创建另一个名为PositionedShape的总和类型,其属性为 Shape init

data Shape = Circle Float |
             Rectangle Float Float

area :: Shape -> Float
area (Circle r)      = pi * r * r
area (Rectangle h w) = h * w

data Point = Point Float Float
             deriving (Eq,Show )


data PositionedShape = Circle Point Float |
                       Rectangle Point Float Float
                       deriving (Eq,Show)

From me, it seem correct but it kept saying multiple declaration.在我看来,这似乎是正确的,但它一直在说多个声明。

Week7.hs:92:24: error:
    Multiple declarations of ‘Circle’
    Declared at: Week7.hs:26:14
                 Week7.hs:92:24

   |
92 | data PositionedShape = Circle Point Float |
   |                        ^^^^^^^^^^^^^^^^^^

Week7.hs:93:24: error:
    Multiple declarations of ‘Rectangle’
    Declared at: Week7.hs:27:14
                 Week7.hs:93:24
   |
93 |                        Rectangle Point Float Float
   |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^

As the error message says, you have declared Circle and Rectangle multiple times.如错误消息所述,您已多次声明CircleRectangle In Haskell, data constructors must have unique names, at least within the same module.在 Haskell 中,数据构造函数必须具有唯一的名称,至少在同一模块内。

You can resolve the issue by giving the data constructors unambiguous names, eg:您可以通过为数据构造函数提供明确的名称来解决此问题,例如:

data PositionedShape = PositionedCircle Point Float |
                       PositionedRectangle Point Float Float
                       deriving (Eq,Show)

The data constructors can also be used as functions.数据构造函数也可以用作函数。 For example, you can view PositionedCircle as a function:例如,您可以将PositionedCircle视为 function:

Prelude> :t PositionedCircle
PositionedCircle :: Point -> Float -> PositionedShape

You can call it with a Point and a Float value:您可以使用PointFloat值调用它:

Prelude> PositionedCircle (Point 1 2) 3
PositionedCircle (Point 1.0 2.0) 3.0

Function names must be unique, because otherwise the compiler don't know which one you mean. Function 名称必须是唯一的,否则编译器不知道您指的是哪一个。 That's the reason that data constructors must have unambiguous names.这就是数据构造函数必须具有明确名称的原因。


It seems that the problem that you're really trying to solve is how to associate a position with a shape, which might be better done like this:看来您真正要解决的问题是如何将 position 与形状相关联,这样做可能会更好:

data PositionedShape = PositionedShape Point Shape deriving (Eq, Show)

You could use this alternative like this:您可以像这样使用这种替代方法:

Prelude> PositionedShape (Point 1 2) (Circle 3)
PositionedShape (Point 1.0 2.0) (Circle 3.0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM