0

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) ) ) ) )
Dimitar Spasovski
  • 2,023
  • 9
  • 29
  • 45
  • This is typically called flattening a list, and there are [lots of questions on Stack Overflow about flattening lists](http://stackoverflow.com/search?q=%5Blisp%5D+flatten+is%3Aquestion). If you browse through their code, you'll probably find the construction that you need. The formatting of code in this question, though, makes it hard to tell what you've tried to write, and it's not quite clear what you're asking. – Joshua Taylor Mar 18 '14 at 15:04
  • A function that accepts `(1 2 (3 (4)) 5)` and returns `(1 2 3 4 5)` is almost certainly a function of _one_ argument (the list to flatten), but you're writing a function of two arguments, `x` and `y`. What are `x` and `y` supposed to be (the naming doesn't make it clear)? Is `y` supposed to be a sort of accumulator, so that you'd initially call something like `(func1 (1 2 (3 (4)) 5))`. If that's the case, we really need more description of what you're trying to write, and what's not working about it. – Joshua Taylor Mar 18 '14 at 15:08
  • I was using y as an empty list from which I am going to return the result. – Dimitar Spasovski Mar 18 '14 at 15:27

1 Answers1

1

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.

molbdnilo
  • 64,751
  • 3
  • 43
  • 82