Skip to content

Commit

Permalink
Monad Knight's quest exercise.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gabi Volpe committed Aug 22, 2016
1 parent 11935ac commit 1280866
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions category-theory/monad-knight-quest.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Control.Monad

type KnightPos = (Int,Int)

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')

-- same function defined using list's filter
moveKnightFilter :: KnightPos -> [KnightPos]
moveKnightFilter (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]

a1 = moveKnight (6,2)
a2 = moveKnight (8,1)

-- all the positions that can be reached in 3 moves
in3 :: KnightPos -> [KnightPos]
in3 start = do
first <- moveKnight start
second <- moveKnight first
moveKnight second

b1 = in3 (6,2)

-- defined without do notation
--in3 start = return start >>= moveKnight >>= moveKnight >>= moveKnight

canReachIn3 :: KnightPos -> KnightPos -> Bool
canReachIn3 start end = end `elem` in3 start

c1 = (6,2) `canReachIn3` (6,1)
c2 = (6,2) `canReachIn3` (7,3)

0 comments on commit 1280866

Please sign in to comment.