Knight's tour: Difference between revisions

Content added Content deleted
(→‎{{header|Haskell}}: Slight disaggregation, pruned out some surplus magic from a list.)
Line 3,202: Line 3,202:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang Haskell>import Data.List (minimumBy, (\\), intercalate, sort)
<lang Haskell>{-# LANGUAGE TupleSections #-}

import Data.List (minimumBy, (\\), intercalate, sort)
import Data.Ord (comparing)
import Data.Ord (comparing)
import Data.Char (ord, chr)
import Data.Char (ord, chr)
Line 3,216: Line 3,218:
newSquare = minimumBy (comparing (length . findMoves)) possibilities
newSquare = minimumBy (comparing (length . findMoves)) possibilities
possibilities = findMoves $ head moves
possibilities = findMoves $ head moves
findMoves = (\\ moves) . knightMoves
findMoves = (\\ moves) . knightOptions


knightMoves :: Square -> [Square]
knightOptions :: Square -> [Square]
knightMoves (x, y) =
knightOptions (x, y) =
knightMoves >>=
[(1, 2), (1, -2), (-1, 2), (-1, -2), (2, 1), (2, -1), (-2, 1), (-2, -1)] >>=
(\(i, j) ->
(\(i, j) ->
let a = x + i
let a = x + i
b = y + j
b = y + j
in bool [] [(a, b)] (onBoard a && onBoard b))
in bool [] [(a, b)] (onBoard a && onBoard b))

knightMoves :: [(Int, Int)]
knightMoves =
let deltas = (<$> [1, 2]) =<< [id, negate]
in deltas >>=
(\i -> deltas >>= (bool [] . return . (i, )) <*> ((abs i /=) . abs))


onBoard :: Int -> Bool
onBoard :: Int -> Bool