If I have a `flatMap`

-compatible function `f:A->List[B]`

and a `List[A]`

I can use `flatMap`

to produce the `List[B]`

. I suppose that this list concatenation is done efficiently. I.e., I hope the `flatMap`

implementation does not keep searching the list for the end on each iteration, but rather somehow keeps a pointer to “almost” the end.

I’d like to build a list in sort of the same way. I have a recursive function which takes two lists, and on each iteration (depending on program logic) either advances one list or the other list or both, and on each iteration I want to “contribute” another (possibly empty) list of elements which get appended.

Currently I’m using `accumlatedList ++ listOfNewLements`

each time. I could rewrite this to just `cons`

up the lists in reverse order and finally do a reverse and flatten. But is there a better way?

What I envision is a cousin of `flatMap`

where the client function both returns the new list to efficiently append, but also returns the `List`

for the next iteration. The iteration would continue until `List()`

is returned as that component. This is more or less the pattern of tail-recursion.

```
def flatMapDIY[M[_],N[_],A,B](in:M[A],zero:M[A],f:M[A]=>(M[A],N[B])):N[B] = {...}
```

Here is an implementation for `Seq`

to sort of show what I mean.

```
def flatMapDIY[A,B](in:Seq[A],zero:Seq[A],f:M[A]=>(Seq[A],Seq[B])):Seq[B] = {
def again(in:Seq[A],acc:Seq[B]):Seq[B] = {
val (next,incremental) = f(in)
if (next == zero)
acc ++ incremental
else
// I would like to do this as flatMap does,
// rather than searching for the end of the sequence each time.
again(next,acc++incremental)
}
again(in,Seq[B]())
}
```