[Haskell-cafe] efficient chop

Kazu Yamamoto ( 山本和彦 ) kazu at iij.ad.jp
Wed Sep 14 05:03:05 CEST 2011

Hello Cafe,

I would like to have an efficient implementation of the chop function.
As you guess, the chop function drops spaces in the tail of a list.

   chop " foo  bar baz   "
   ->   " foo  bar baz"

A naive implementation is as follows:

    chopReverse :: String -> String
    chopReverse = reverse . dropWhile isSpace . reverse

But this is not elegant. foldr version is as follows:

    chopFoldr :: String -> String
    chopFoldr = foldr f []
        f c []
          | isSpace c = []
          | otherwise = c:[]
        f c cs = c:cs

But this code is slower than chopReverse in some cases.

Are there any more efficient implementations of chop? Any suggestions?


More information about the Haskell-Cafe mailing list