Haskell检查棋盘对角线运动是对还是错 [英] Haskell check if chess board diagonal movement is True or False
问题描述
我正在尝试编写4x5棋盘游戏,我想做一个简单的true false Bool函数,说明基于x,y坐标的移动是否为对角线.我想放置4个坐标2 x和2 y.我应该使用&&函数,例如我想放(1,1)和(2,2)吗?
I am trying to write a board game function of 4x5 board and I want to do a simple true false Bool function stating if the movement based on x,y coordinates is diagonal or not. I want to put 4 coordinates 2 x and 2 y. should I use the && function if for example I want to put (1,1) and (2,2)?
isDiagonal x
if x == 1 && y == 1 then True
else False
isDiagonal x
if x == 2 && y == 2 then True
else False
推荐答案
如果要检查点(x,y)
是否与Haskell中的点(x',y')
在同一对角线上,那么最好的起点是类型.
If you want to check if a point (x,y)
is on the same diagonal as a point (x',y')
in Haskell, a good place to start is with a type.
isDiagonal :: (Int, Int) -> (Int, Int) -> Bool
尽管在技术上是可选的,但最好的做法是为每个顶级函数都指定一个显式类型.
Whilst technically optional, it's good practice to give every top level function an explicit type.
现在,我们需要一个用于此功能的主体.
Now, we need a body for this function.
isDiagonal (x, y) (x', y') = ...
如果它们在相同的对角线上,则x
和x'
彼此之间的距离必须与y
和y'
一样远.这样我们就可以检查差异是否相等.即
If they're on the same diagonal, then x
and x'
must be as far apart from each other as y
and y'
are. So we can just check if the differences are equal. i.e
abs (x - x') == abs (y - y')
将它们放在一起,我们(希望)达到了所需的功能
Putting it all together, we (hopefully) arrive at the desired function
isDiagonal :: (Int, Int) -> (Int, Int) -> Bool
isDiagonal (x, y) (x', y') = abs (x - x') == abs (y - y')
这里完全不需要&&
.但是我们可以使用它,例如,如果我们想施加一个额外的条件,例如新点必须位于4x5板上(假设使用1分索引)
There's no need for &&
here, at all. But we could use it, if for example we wanted to impose an extra condition, like the new points must be on the 4x5 board (assuming 1-indexing)
isDiagonal :: (Int, Int) -> (Int, Int) -> Bool
isDiagonal (x, y) (x', y') = x' >= 1 && x' <= 4 &&
y' >= 1 && y' <= 5 &&
abs (x - x') == abs (y - y')
这篇关于Haskell检查棋盘对角线运动是对还是错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!