[Haskell-cafe] Dropping trailing nulls from a list of list

Neil Mitchell ndmitchell at gmail.com
Wed Mar 8 12:22:16 EST 2006


> dropTrailNulls list = reverse (dropWhile null (reverse list))

Or more succinctly:

dropTrailNulls = reverse . dropWhile null . reverse

> Or, is there a more efficient idiom for addressing these problems?

The "bad thing" about this definition is that it is tail strict. Consider

["hello","everyone","","","","",... <forever>]

With your definition  you will get nothing back (since reverse is tail
strict). However, there is an alternative definition that will give
the first two elements back:

dropTrailNulls x = f 0 x
   where
      f n [] = []
      f n ([]:xs) = f (n+1) xs
      f n (x:xs) = replicate n [] ++ (x : f 0 xs)

-- note: untested, may not work

The reason is because it is significantly more lazy. It is also more
space efficient, and probably faster.

However, despite all this, I love the reverse . something . reverse
example, and I think its totally beautiful in terms of simplicity.

The general programming advice holds here as for everywhere else -
write beautifully, if performance demands, profile then write to
obtain speed.

Thanks

Neil


More information about the Haskell-Cafe mailing list