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

本文介绍了一个使用Haskell解决骑士在棋盘上三步内能否到达指定位置的问题。定义了骑士当前位置的数据类型,并实现了一个计算骑士一步后所有可能位置的方法。通过组合三次移动,找出所有可能到达的位置,并判断目标位置是否可达。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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  

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值