
On Thursday 19 May 2011 16:05:29, jianqiuchi@gmail.com wrote:
Hi,
I have a question about the cost of list comprehension and map function.
For example, I have a list of Double and I want to do lots of calculation on it. There are two ways to do that: 1. [x ** 3 | x <- list] 2. map (flip (**) 3) list I am wondering if the cost of using them could be very different and why.
As Felipe said, they should compile to the same code. However, since you're asking about cost, which indicates that you care for performance, the above would be better written as [x*x*x | x <- list] unless you depend on the small differences in the outcome [I'm not quite sure how many bits may be affected, not many, typically none or one]. Functions like (**), exp, log, sin, cos, ... are slow, very slow. If the exponent is a small (positive) integer, specifically giving a sequence of multiplication steps is much faster, also using (^) instead of (**) is faster for small exponents (but slower than an explicit multiplication sequence). Of course, if the exponent may be a non-integer, you have to use (**), if it is an integer but not a fixed one, use (**) if the integer may be large¹, (^) or (^^) if it is sure to be small (in absolute modulus). [¹] (**) doesn't care how large the exponent is, (^) resp (^^) do.