haskell - Monads - problem solving : A knight's quest

阅读更多

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)