无法将预期类型"(a0、b0、c0、几何图形 -> b)"与实际类型"几何图形 ->(整数、整数、整数、国际))"匹配



我有以下代码:

data Geometry = Point Int Int | Circle Int Int Int | Rectangle Int Int Int Int | Triangle Int Int Int Int Int Int | Group [Geometry]
bbox :: Geometry -> (Int, Int, Int, Int)
bbox (Point x y) = (x, y, x, y)
bbox (Circle x y r) = (x - r, y - r, x + r, y + r)
bbox (Rectangle x1 y1 x2 y2) = (x1, y1, x2, y2)
bbox (Triangle x1 y1 x2 y2 x3 y3) = (mx1, my1, mx2, my2)
where mx1 = min x1 (min x2 x3)
my1 = min y1 (min y2 y3)
mx2 = max x1 (max x2 x3)
my2 = max y1 (max y2 y3)
bbox (Group shape) = (x1, y1, x2, y2)
where x1 = foldr min 0 [fst bbox s | s <- shape]
y1 = foldr min 0 [snd bbox s | s <- shape]
x2 = foldr max 0 [third bbox s | s <- shape]
y2 = foldr max 0 [fourth bbox s | s <- shape]

其中bbox计算给定形状的边界框。

但是我遇到了以下错误:

2.hs:37:34: error:
• Couldn't match expected type ‘(a0, b0, c0, Geometry -> b)’
with actual type ‘Geometry -> (Int, Int, Int, Int)’
• Probable cause: ‘bbox’ is applied to too few arguments
In the first argument of ‘fourth’, namely ‘bbox’
In the expression: fourth bbox s
In the third argument of ‘foldr’, namely
‘[fourth bbox s | s <- shape]’
• Relevant bindings include y2 :: b (bound at 2.hs:37:9)
|
37 |         y2 = foldr max 0 [fourth bbox s | s <- shape]
|                                  ^^^^

我不明白为什么会出现此错误。

您在此处的列表推导包含错误:

foldr min 0 [fst bbox s| s <- shape]

这里fst应用于bbox。因此,它需要一个 2 元组,但你bbox :: Geometry -> (Int, Int, Int, Int)传递给它一个函数。请注意,fst仅适用于 2 元组,不适用于 4 元组。

例如,您可以使用let表达式来"解压缩"4元组:

foldr min 0 [x| s <- shape, let(x,_,_,_)= bbox s]

您应该以类似的方式修复其他表达式。

请注意,您可以在此处使用minimum,并将其实现为:

minimum(0:[x | s <- shape, let (x,_,_,_) = bbox s])

或者,如果您实现了自己的函数来对 4 元组进行操作,则可以将其编写为:

-- …
bbox (Group shapes) = (x1, y1, x2, y2)
where x1 = minimum (0:map myfirst bbs)
y1 = minimum (0:map mysecond bbs)
x2 = maximum (0:map mythird bbs)
y2 = maximum (0:map myfourth bbs)
bbs = map bbox shapes

但是,我不确定以零开头是一个好主意。这意味着(0,0)将永远是Group边界框的一部分?不管 te 组中有哪些元素?您可能希望使用NonEmpty来确保Group至少包含一个元素。

最新更新