Skip to content

Instantly share code, notes, and snippets.

@sebfisch
Created July 30, 2009 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebfisch/158634 to your computer and use it in GitHub Desktop.
Save sebfisch/158634 to your computer and use it in GitHub Desktop.
Simple solver for the n-queens problem in Curry
-- Simple solver for the n-queens problem in Curry.
--
-- A placement is represented as permutation of [1..n], each list
-- element represents the placement of a queen in the column
-- corresponding to its index.
import Integer ( abs )
-- Solutions are computed using a lazy generate-and-test approach:
-- candidate solutions are created lazily and admissible solutions
-- filtered out using a guard.
--
queens :: Int -> [Int]
queens n | safe qs = qs
where qs = permute [1..n]
-- As queens are placed in different rows and columns automatically,
-- we only check that they don't capture each other diagonally.
--
safe :: [Int] -> Bool
safe qs = and [ j-i /= abs (q_j-q_i) | (i,q_i) <- iqs, (j,q_j) <- iqs, i < j ]
where iqs = zip [1..] qs
-- Candidate solutions are computed using a non-deterministic
-- operation to permute a list.
--
permute :: [a] -> [a]
permute [] = []
permute (x:xs) = insert x (permute xs)
insert :: a -> [a] -> [a]
insert x l = x : l
insert x (y:ys) = y : insert x ys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment