Permalink
Browse files

Lazier intersperse

A lazier implementation of intersperse, and consequentially intercalate, to
avoid space leaks.
  • Loading branch information...
Daniel Fischer
Daniel Fischer committed Oct 2, 2010
1 parent 11a832d commit 2b17b2a58087c438ebd5a7de91b2e9f69e09a17f
Showing with 10 additions and 2 deletions.
  1. +10 −2 Data/List.hs
View
@@ -422,8 +422,16 @@ intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
intersperse :: a -> [a] -> [a]
intersperse _ [] = []
-intersperse _ [x] = [x]
-intersperse sep (x:xs) = x : sep : intersperse sep xs
+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
-- | 'intercalate' @xs xss@ is equivalent to @('concat' ('intersperse' xs xss))@.
-- It inserts the list @xs@ in between the lists in @xss@ and concatenates the

0 comments on commit 2b17b2a

Please sign in to comment.