ConcatMap in haskell without ++

Here's a way that makes the state of the computation explicit:

concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = go []
  where
    -- We have b values; use one.
    go (b:bs) as = b : go bs as
    -- No bs left; get some more.
    go [] (a:as) = go (f a) as
    -- Nothing left; we're done.
    go [] [] = []

This maintains the current list of bs, filling it up whenever it's empty.


This might be cheating, but how about:

myConcatMap f s = concat (map f s)

The concat function uses some sort of ++ in its source code, so that is why you might not like it. You can try to use an alternative concat that does list comprehensions, it has a more "from scratch" feeling.

myconcat ll = [y | x <- ll, y <- x]

Tags:

Haskell