Difference between revisions of "SCL Examples"
Jump to navigation
Jump to search
(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) ...") |
|||
(One intermediate revision by the same user not shown) | |||
Line 1: | Line 1: | ||
== Eight queens puzzle == | == Eight queens puzzle == | ||
+ | |||
+ | Copy the following commands to the SCL console: | ||
<pre> | <pre> | ||
Line 9: | Line 11: | ||
lq = [l!i - (m-i) | i <- [0..m-1]] | lq = [l!i - (m-i) | i <- [0..m-1]] | ||
uq = [l!i + (m-i) | i <- [0..m-1]] | uq = [l!i + (m-i) | i <- [0..m-1]] | ||
− | > expandSolution l = | + | > expandSolution l = do |
x <- possibleNextPositions l | x <- possibleNextPositions l | ||
return (l + [x]) | return (l + [x]) | ||
Line 19: | Line 21: | ||
> repeatString k (s :: String) = sum [s | x <- [1..k]] | > repeatString k (s :: String) = sum [s | x <- [1..k]] | ||
> rowText k = repeatString k "." + "X" + repeatString (n-k-1) "." | > rowText k = repeatString k "." + "X" + repeatString (n-k-1) "." | ||
− | > printSolution (l :: [Integer]) = | + | > printSolution (l :: [Integer]) = do |
printString (repeatString n "-") | printString (repeatString n "-") | ||
mapM (printString . rowText) l | mapM (printString . rowText) l | ||
> mapM printSolution solutions | > mapM printSolution solutions | ||
</pre> | </pre> |
Latest revision as of 14:34, 22 August 2012
Eight queens puzzle
Copy the following commands to the SCL console:
> 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 = do 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]) = do printString (repeatString n "-") mapM (printString . rowText) l > mapM printSolution solutions