首页 > 解决方案 > 无法将预期类型 '(a0, b0, c0, Geometry -> b)' 与实际类型 'Geometry -> (Int, Int, Int, Int) 匹配

问题描述

我有以下代码:

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]

Wherebbox计算给定形状的边界框。

但我得到以下错误:

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]
   |                                  ^^^^

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

标签: haskell

解决方案


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

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

这里fst适用于bbox。因此,它需要一个 2 元组,但您将它传递给一个 function 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)它将始终是 a 的边界框的一部分Group?不管 te 组中有哪些元素?您可能希望使用 aNonEmpty来确保Group包含至少一个元素。


推荐阅读