Emil
Emil

Reputation: 2167

Why is >>= faster than concatMap when they ought to be the same thing?

Last night, I was writing some recreational code, and at some point I replaced a concatMap with >>= and saw a ~10% speedup in my code.

I was under the impression the definition of >>= for [] was exactly concatMap, so I am a little confused.

Upvotes: 11

Views: 203

Answers (1)

erdeszt
erdeszt

Reputation: 791

In base 4.8 (>>=) is implemented (see here) as:

xs >>= f = [y | x <- xs, y <- f x]

and concatMap is using a more complicated builder(source here)

concatMap :: Foldable t => (a -> [b]) -> t a -> [b]
concatMap f xs = build (\c n -> foldr (\x b -> foldr c b (f x)) n xs)

Upvotes: 8

Related Questions