Quick and Small Haskell Question

by Mithrandir

Which of the following is better to use?

List comprehesions

test1 :: Int -> [Int]
test1 k = [x+y | x <-l, x==1, y <-l]
  where
    l = [1..k]

with the following result

mihai@keldon:~/tmp$ time ./test 1e7 > /dev/null

real    0m9.057s
user    0m8.549s
sys     0m0.308s

or some monads?

test2 :: Int -> [Int]
test2 k = do
  x <- l
  guard (x == 1)
  y <- l
  return (x+y)
  where
    l = [1..k]

resulting in

mihai@keldon:~/tmp$ time ./test 1e7 > /dev/null

real    0m24.057s
user    0m23.309s
sys     0m0.596s

Both times the main function was:

main = do
  [d] <- map read `fmap` getArgs
  let l = test1 d
  putStrLn $ show l

I’m mainly interested in a quick to code and fast to execute method for a dirty backtracking implementation. (Over 100 variables to be bounded to and over 1500 restrictions). Yet, I’m mainly interested in the aspects behind the scenes which will make one solution better than the other. I want to find out why the list implementation technique is faster that the monadic counterpart. Things like that.

About these ads