I just started studying lisp and it became a problem, I went through a bunch of options, I don't even know which one to attach. It sounds like this : write a function that combines 2 lists in such a way that Log in (1 2 3 4 5) (4 5 6 7 8) Exit (1 2 3 4 5 6 7 8) . Only basic functionality can be used. I.e., loop operators, direct access functions to list elements, etc. are not allowed. You can only use "eql", "member". Here is my code, but there is an error in it
Thank you in advance
(defun lsp(x y)
((null x)y)
((null y)x)
((member(car x)y)x)
(t(lsp(cdr x) y ))))
The main problem I see is the third clause:
((member (car x) y) x)
You check if the first element of x
belongs to y
, and then you return the whole list x
. For example:
(lsp '(1 3 4) '(1 2 7 8 9))
In this case you just return the first list, (1 3 4)
, which is wrong.
You might be missing a recursive call here.
I think it should be helpful to clarify the intent of your function to have a clear understanding of what should be implemented. For example, your first test works if you assume that y
already doesn't contain duplicates. But if you call the function as follows:
(lsp () '(1 2 1 2))
Then maybe you should have the following result (order does not matter):
(2 1)
Or, maybe you are supposed to assume that x
and y
do not contain duplicates and then your first tests in the cond
are sufficient.
I'm going to assume that x
and y
already have unique elements.
Let's say you already have a function that iterates over each element i
of x
, and you are trying to check if i
is part of the result. You would write a function like this:
(defun maybe-add (i y)
(if (member i y)
...
...))
There are two cases, i
belongs to y
or not.
In the first case, you should simply return y
.
In the second case, you build a new list from y
where i
is present. You probably can use cons
so I guess it is easy to write at this point.
Then, you can try to use maybe-add
from your main function: maybe-add
always returns a list if you give an item from x
. You have to recurse over x
to get each element i
, give it to maybe-add
, and use the result for your next recursive call.
(defun lsp (x y)
(if (null x)
...
(lsp ... ...)))
Test often your code, then later if this works you will be able to use an additional argument to lsp
so that your function is tail-recursive.
In order to test your code, you can write (trace lsp)
or (trace maybe-add)
to see additional output where each function is called and what it returns.