我在Haskell和代数类型一起工作,做一些练习题。我有以下练习:
我的本练习代码:
data Point = Point Float Float
deriving (Show)先前定义的形状数据:
data Shape = Circle Float |
Rectangle Float Float
deriving (Show)我的本练习代码:
data PositionedShape = PositionedShape Shape Point
deriving (Show)现在我的问题出现在下面一个:
定义一个函数:
haskell move :: PositionedShape -> Float -> Float -> PositionedShape,它以给定的x和y距离移动形状。
--我的实现如下:
move :: PositionedShape -> Float -> Float -> PositionedShape
move (Shape (Point x y)) newX newY = Shape (Point newX newY)这是在返回错误:
周8.hs:103:7:错误:不在作用域:数据构造函数“形状”失败,模块加载:无。
有人能解释一下为什么会出现这个错误吗?如何解决呢?我有点搞不懂代数类型,我尝试了很多东西,但似乎我无法得到一个解。
发布于 2019-04-23 01:49:27
您需要对数据构造函数(如Circle和Rectangle)进行模式匹配,而不是像现在所做的那样在类型构造函数上进行模式匹配(比如Shape)。对于PositionedShape,它们碰巧有相同的名称,尽管您完全忘记了这一次的匹配(实际上,除了复制它之外,您根本不需要关心内部Shape )。另外,move是指按给定的距离移动形状,而不是将其移动到一个新的给定位置;
发布于 2019-04-23 04:17:34
您需要使用PositionedShape构造函数来分解已使用Shape构造函数的PositionedShape。
试着从以下几点开始:
移动(PositionedShape shape (点old_x old_y))
发布于 2019-04-23 06:58:50
怎么样
move (PointedShape s (Point x y)) dx dy = PointedShape s (Point (x+dx) (y+dy))https://stackoverflow.com/questions/55803072
复制相似问题