Computer science: Concatenate two lists recursive definition

322 Views Asked by At

concatenate two lists recursive definition.

This is the exercise:

$concatenate(L1, L2)$ , returns concatenation of $L1$ with $L2$.

I guessed the Base Case is:

$concatenate ([],[])$ $[]$ being empty lists, the concatenation is $[]$.

Now, I don't know how do I get the recursive Case, can you please help me ?

1

There are 1 best solutions below

1
On BEST ANSWER

To tackle this problem, you need a way to convey information throughout recursive calls. The way I would do this is probably overloading, but that's a little computer science-y so I'll skip that.

Our function would be $concatenate(L_1,L_2,L)$ =

$$\hspace{4.75cm}L \text{ if } L_1 =[] \text{ and } L_2 =[]$$ $$concatenate([],L_2,L+L_1) \text{ if } L_1 \neq[] \text{ and } L_2 =[]$$ $$concatenate(L_1,[],L+L_2) \text{ if } L_1=[] \text{ and } L_2\neq[]$$ $$concatenate([],L_2,L+L_1) \text{ if } L_1\neq[] \text{ and } L_2\neq[]$$

This formula is the same as $concatenate(L_1,L_2,L)=concatenate([],[],L_1+L_2) = L_1+L_2$

If you already have a defined concatenation, there's literally no use for recursion, as you're gaining no new functionality, just wasting stack memory. The only thing recursion does here is handle edge cases that don't even raise issue.

Even in the situation you describe in the comments, where you add one element at a time to the beginning of $L_2$ until $L_1$ is empty, can be achieved by looping the same instruction until $L_1$ is empty.

Sorry if I sound rude, but there's no reason to define concatenation recursively.