[Haskell-beginners] what space leak could happen here?
Dimitri DeFigueiredo
defigueiredo at ucdavis.edu
Sun Sep 21 17:05:43 UTC 2014
Hi All,
I was looking at the definition of intersperse on
http://hackage.haskell.org/package/base-4.7.0.1/docs/src/Data-List.html#intersperse
And found this
-- | The 'intersperse' function takes an element and a list and
-- \`intersperses\' that element between the elements of the list.
-- For example,
--
-- > intersperse ',' "abcde" == "a,b,c,d,e"
intersperse :: a -> [a] -> [a]
intersperse _ [] = []
intersperse sep (x:xs) = x : prependToAll sep xs
-- Not exported:
-- We want to make every element in the 'intersperse'd list available
-- as soon as possible to avoid space leaks. Experiments suggested that
-- a separate top-level helper is more efficient than a local worker.
prependToAll :: a -> [a] -> [a]
prependToAll _ [] = []
prependToAll sep (x:xs) = sep : x : prependToAll sep xs
I don't understand why we need to "make every element in the
'intersperse'd list available as soon as possible to avoid space leaks."
Could somebody shed some light on what could cause a space leak here? In
particular, would this simpler version cause problems?
intersperse :: a -> [a] -> [a]
intersperse _ [] = []
intersperse _ [x] = [x]
intersperse a (x: xs@(y:ys)) = x : a : intersperse a xs
Thanks,
Dimitri
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140921/2f4d7959/attachment.html>
More information about the Beginners
mailing list