Monday, January 4, 2016

Riding the knight in haskell

Caluclate possible moves of a knight on a chess board:

import Control.Monad as M

type KnightPos = (Int, Int)

moveKnight :: KnightPos -> [KnightPos]
moveKnight (c, r) = do
  (c', r') <- possibleMoves
  M.guard (c' `elem` [1..8] && r' `elem` [1..8])
  return (c', r')
    where
      possibleMoves = [
        \(a, b) (c, d) -> (c + a, d + b),
        \(a, b) (c, d) -> (c + a, d - b),
        \(a, b) (c, d) -> (c - a, d + b),
        \(a, b) (c, d) -> (c - a, d - b)
        ] <*> [(1, 2), (2, 1)] <*> [(c, r)]

0 comments: