let's use the monad to solve some problems. here is a famous question,
Say you have a chess board and only one knight piece on it. We want to find out if the knight can reach a certain position in three moves. We'll just use a pair of numbers to represent the knight's position on the chess board. The first number will determine the column he's in and the second number will determine the row.
let's make the type synonyms for the knight currrent position on the chess board:
type KnightPos = (Int,Int)
so let's make a method that can calculate the position after one move after the knight moves.
we can write this :
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = do
(c',r') <- [(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1)
,(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)
]
guard (c' `elem` [1..8] && r' `elem` [1..8])
return (c',r')
this can also be written as this, if you writre with "filter"
moveKnight :: KnightPos -> [KnightPos]
moveKnight (c,r) = filter onBoard
[(c+2,r-1),(c+2,r+1),(c-2,r-1),(c-2,r+1)
,(c+1,r-2),(c+1,r+2),(c-1,r-2),(c-1,r+2)
]
where onBoard (c,r) = c `elem` [1..8] && r `elem` [1..8]
with that , we can do in3 which get the all the possible location as such :
in3 :: KnightPos -> [KnightPos]
in3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second
and then you can chain that by cropping up in several times, the above code can be wite as this withou tthe do notation.
in3 start = return start >>= moveKnight >>= moveKnight >>= moveKnight
now, let's take a function takes two positions and tell if we can reach that is like this:
canReachIn3 :: KnightPos -> KnightPos -> Bool canReachIn3 start end = end `elem` in3 start
now, let's test it .
ghci> (6,2) `canReachIn3` (7,3) False
本文介绍了一个使用Haskell解决骑士在棋盘上三步内能否到达指定位置的问题。定义了骑士当前位置的数据类型,并实现了一个计算骑士一步后所有可能位置的方法。通过组合三次移动,找出所有可能到达的位置,并判断目标位置是否可达。
1658

被折叠的 条评论
为什么被折叠?



