给定地图坐标

Given Coordinates of Map

type Coordinate = (XCoord, YCoord)
type XCoord = Coord
type YCoord = Coord
type Coord = Integer

coordInBound :: Coordinate -> Bool

coordInBound (XCoord, YCoord) =

XCoord

        |x >= 0 && x <= 9 = True
        |otherwise = False
YCoord

        |y >= 0 && y <= 9 = True
        |otherwise = False

我正在尝试编写一个函数,如果坐标在 0,0 -> 9,9

的 10 x 10 网格中,则 returns 为真

由于 XCoordYCoord 只是整数,您可以简单地检查它们是否在 [0, 9]:

的范围内
type Coordinate = (XCoord, YCoord)
type XCoord = Coord
type YCoord = Coord
type Coord = Integer

coordInBound :: Coordinate -> Bool
coordInBound (x, y) =
  x >= 0 && x <= 9 && y >= 0 && y <= 9

main = print $ coordInBound (9, 0)

但是如果您希望 XCoordYCoord 是类型,那么您需要以下类型定义和用法:

data XCoord = XCoord Int
data YCoord = YCoord Int
type Coordinate = (XCoord, YCoord)

coordInBound :: Coordinate -> Bool
coordInBound (XCoord x, YCoord y) =
  x >= 0 && x <= 9 && y >= 0 && y <= 9

main = print $ coordInBound (XCoord 9, YCoord 0)

尝试将问题分成两部分:x 坐标是否在边界内? y 坐标在边界内吗?并将它们组合在一起以确定它们是否都在边界内。

xInBounds :: XCoord -> Bool
xInBounds x | x >= 0 && x <= 9 = True
            | otherwise = False

yInBounds :: YCoord -> Bool
???

你现在拥有的将无法编译,因为除其他外,模式 (XCoord, YCoord) 中的变量名称不能以大写字母开头。 haskell 中以大写字母开头的名称保留给 Coordinate 等类型和 True 等构造函数。变量的名称是小写的,例如 coordInBound.

使用 xInBoundsyInBounds 尝试使用小写变量名称完成 coordInBound

coordInBound :: Coordinate -> Bool
coordInBound (x, y) = ???