4 ms·
But if you try it on ghci you will see that it breaks. (ghc 8.0.1). So it dependes on how you "interpret" the code. `ghc -O` is sophisticated enough to make the
by WmyEE0UsWAwC2i 10y ago
But if you try it on ghci you will see that it breaks. (ghc 8.0.1). So it dependes on how you "interpret" the code. `ghc -O` is sophisticated enough to make the right decisions when compiling your code. You probably don't want a space leak, so it doesn't generate one.
GHC will have more trouble making the right choice in more involved computations. It will revert to "just do what the coder says".
Consider this C code for example:
unsigned int sum = 0;
const unsigned int n = 1000;
for(int i = 0; i<n; i++) {
sum += 0;
}
If you look at it, you can tell this is O(1) in space for any valid `n`. A spohisticated enough compiler may replace it by
unsigned int sum = 0;
and be done with it. But even an unsophisticated(but correct) compiler will produce O(1) space wise code.
EDIT: format
EDIT: What I was trying to say in my original comment is that, in haskell, space leaks my appear even in the most innocent looking code. And that it may require a bit of experience to identify and avoid them.
- k_bx 10y agoWell, sure, running code in interpreter does less optimizations than doing full compilation. I can write an interpreter for your C code which runs out of memory if you want :) So your "you can tell" depends on particular compiler or interpreter implementation, and no, you can't tell what my compiler will do.
- WmyEE0UsWAwC2i 10y agoI'll have to agree with that. But then I would also say that I had to make some assumptions, right? :) I think GHCi is helpful in this situation, however. It clearly distinguishes between leaky and non-leaky code. This leak is a product of "just doing what the coder says" (go to "Data.Monoid.sum" and do what it says there with such and such...). I'm assuming that, for this code, GHCi is bug-free. I think sum (replicate n 0) is as dangerous as foldl (+) 0 (replicate n 0) or foldr (+) 0 (replicate n 0) . `sum (replicate n 0)` may be the right thing to do in some cases unknown to me. There is `{-# LANGUAGE Strict #-}`, as you mention, and BangPatterns for strict arguments. But I would assume, those are used only by coders already familiar with haskell and its leaky pitfalls.