29 Jan 2013 10:25
list comprehansion performance has hug different
Junior White <efiish <at> gmail.com>
2013-01-29 09:25:49 GMT
2013-01-29 09:25:49 GMT
Hi Cafe,
I have two programs for the same problem "Eight queens problem",
My two grograms only has little difference, but the performance, this is my solution:
-- solution 1------------------------------------------------------------
queens1 :: Int -> [[Int]]
queens1 n = map reverse $ queens' n
where queens' 0 = [[]]
queens' k = [q:qs | q <- [1..n], qs <- queens' (k-1), isSafe q qs]
isSafe try qs = not (try `elem` qs || sameDiag try qs)
sameDiag try qs = any (λ(colDist, q) -> abs (try - q) == colDist) $ zip [1..] qs
-- solution 2--------------------------------------------------------------
queens2 :: Int -> [[Int]]
queens2 n = map reverse $ queens' n
where queens' 0 = [[]]
queens' k = [q:qs | qs <- queens' (k-1), q <- [1..n], isSafe q qs]
isSafe try qs = not (try `elem` qs || sameDiag try qs)
sameDiag try qs = any (λ(colDist,q) -> abs (try - q) == colDist) $ zip [1..] qs
the performance difference is: (set :set +s in ghci)
*Main> length (queens1 8)
92
(287.85 secs, 66177031160 bytes)
*Main> length (queens2 8)
92
(0.07 secs, 17047968 bytes)
*Main>
The only different in the two program is in the first is "q <- [1..n], qs <- queens' (k-1)," and the second is "qs <- queens' (k-1), q <- [1..n]".
Does sequence in list comprehansion matter? And why?
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe <at> haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe
RSS Feed