{-# LANGUAGE NoImplicitPrelude #-} import Prelude (print) import Set nqueens n = (nqueens' empty zero (range n)) where compatible xa ya b = xa + ya /= xb + yb && xa + yb /= xb + ya where xb = fst b yb = snd b nqueens' sol y xs = iif (y == n) sol ( any (\x -> nqueens' (sol << pair x y) (succ y) (xs >> x)) (filter (\x -> all (compatible x y) sol) xs) ) nqueensAll n = (nqueensAll' empty zero (range n)) where compatible xa ya b = xa + ya /= xb + yb && xa + yb /= xb + ya where xb = fst b yb = snd b nqueensAll' sol y xs = iif (y == n) (singleton sol) ( flatmap (\x -> nqueensAll' (sol << pair x y) (succ y) (xs >> x)) (filter (\x -> all (compatible x y) sol) xs) ) -- verify there are 14,200 solutions for n = 12 main = print (size (nqueensAll twelve) == (ten * ten + six * seven) * ten * ten)