[Haskell-cafe] Re: Am I doing it right?

Achim Schneider barsoap at web.de
Wed Sep 24 18:39:42 EDT 2008

"Creighton Hogg" <wchogg at gmail.com> wrote:

> So as another step in my education, I wanted to ask if the following
> code at least feels 'morally' correct as a find/replace function,
> replacing each occurrence of the sub-list before with after in the
> list.  
Besides not using head, tail and isPrefixOf I would write it the same,
except that I'd write it like this:


import Data.ByteString.Lazy.Char8 as B
import Prelude as P

cut = 
    let f _ s [] = [s]
        f n s (x:xs) = 
            let (h,t) = B.splitAt (x - n) s
            in h:f x t xs
    in f 0

replace before@(b:_) after this = 
        before' = B.pack before
        after' = B.pack after
        f s | B.tail before' `B.isPrefixOf` B.tail s = 
                B.append after' $ B.drop (B.length before') s
            | otherwise = s
    in B.concat $ P.map f $ cut this $ B.elemIndices b this

main =
    B.interact $ replace "th" "s"


As we all love benchmarks so dearly, here are the times:

./replace < /usr/share/dict/words > /dev/null  1.29s user 0.02s system
87% cpu 1.498 total

./replace < /usr/share/dict/words > /dev/null  0.25s user 0.02s system
84% cpu 0.313 total

(c) this sig last receiving data processing entity. Inspect headers
for copyright history. All rights reserved. Copying, hiring, renting,
performance and/or broadcasting of this signature prohibited.

More information about the Haskell-Cafe mailing list