SCL Examples

From Developer Documents
Revision as of 13:37, 20 June 2012 by Hannu Niemisto (talk | contribs) (Created page with "== Eight queens puzzle == <pre> > n = 8 > allPositions = [0..n-1] > possibleNextPositions l = allPositions \\ (l + lq + uq) where m = length l lq = [l!i - (m-i) ...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Eight queens puzzle

> n = 8
> allPositions = [0..n-1]
> possibleNextPositions l = allPositions \\ (l + lq + uq)
    where
      m = length l
      lq = [l!i - (m-i) | i <- [0..m-1]]
      uq = [l!i + (m-i) | i <- [0..m-1]]
> expandSolution l =
      x <- possibleNextPositions l
      return (l + [x])
> solve k cur = if k == n
                then return cur
                else expandSolution cur >>= solve (k+1)
> solutions = solve 0 []
> length solutions
> repeatString k (s :: String) = sum [s | x <- [1..k]]
> rowText k = repeatString k "." + "X" + repeatString (n-k-1) "."
> printSolution (l :: [Integer]) = 
      printString (repeatString n "-")
      mapM (printString . rowText) l
> mapM printSolution solutions