Question

I am new to lisp and I am trying to code a function that will turn a list with sub-lists such as (1 2 (3 (4)) 5) in to a list like this (1 2 3 4 5). The thing is, I have no idea how to put 2 orders in one condition. For example here is my code

(defun Func1 (x y)
(cond
((null x) y)
((listp (CAR x)) (Func1 (CDR x) (append y (CAR x) )) )
(T (Func1 (CDR x) (CONS (CAR x) y) ) ) ) )

Well, I know that I need to change the second condition, so if the first element of x is a list, then i will call the same function like (Func1 (CAR x) y) but if I do that i will only get the items of the sub-list and I am going to lose the other part of the list. So basiclly, my question is, how do I tell LISP that after it finishes with this line

 ((listp (CAR x)) (Func1 (CDR x) (append y (CAR x) )) )

it should continue executing the other line

(T (Func1 (CDR x) (CONS (CAR x) y) ) ) ) )
Was it helpful?

Solution

I don't understand why your function takes 2 arguments when it's going to rearrange one list.

Your t case is almost correct, but you've practically turned it inside out - it should be

(cons (car x) (Func1 (cdr x)))

That is, a list where the car is the same as in the input, and the cdr is the result of flattening the cdr of the input.

The listp case looks like it's suffering from a similar form of "inside-out-ness".
Apart from the inexplicable y you have all the right bits but in the wrong order, except that it needs two Func1 calls - one for the car and one for the cdr.

I'll leave the rearrangement of the bits in that case as an exercise.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top