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到10的10乘10网格,则返回True。 9,9-
答案 0 :(得分:1)
由于XCoord
和YCoord
只是整数,因此您只需检查两者是否都在[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)
但如果您希望XCoord
和YCoord
是类型,那么您需要以下类型定义和用法:
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)
答案 1 :(得分:1)
尝试将问题分成两部分:x坐标是否在边界内? y坐标是否在边界内?并将这些结合在一起,以确定它们是否都在界限内。
xInBounds :: XCoord -> Bool
xInBounds x | x >= 0 && x <= 9 = True
| otherwise = False
yInBounds :: YCoord -> Bool
???
你现在所拥有的东西不会被编译,因为除了其他方面,模式(XCoord, YCoord)
中的变量名称不能以大写字母开头。在haskell中以大写字母开头的名称保留用于Coordinate
之类的类型和True
之类的构造函数。变量具有小写名称,如coordInBound
。
xInBounds
和yInBounds
尝试使用小写变量名完成coordInBound
coordInBound :: Coordinate -> Bool
coordInBound (x, y) = ???