Reputation: 33
For example, If the input is: (list (list 1) (list 2) (list 3)) Output will be: (list 1 2 3)
Why doesn't this code work?
(define (listoutput mylist)
(cond
[(empty? mylist) empty]
[(cons? mylist) (append (list (first list)) (listoutput (rest mylist)))]))
(check-expect (listoutput (list (list 1) (list 2) (list 3)))
(list 1 2 3)
Upvotes: 1
Views: 170
Reputation: 236004
You're asking for the flatten
procedure, try this:
(define (flatten lst)
(cond ((empty? lst) null)
((not (list? lst)) (list lst))
(else (append (flatten (first lst))
(flatten (rest lst))))))
You can test it:
(flatten (list (list 1) (list 2) (list 3)))
> (1 2 3)
(flatten '(1 (2 (3)) (4)))
> (1 2 3 4)
Upvotes: 0
Reputation: 5668
[(cons? mylist) (append (list (first list)) (listoutput (rest mylist)))]))
That line has two errors. The most obvious is that it should be (first mylist)
rather than (first list)
(although I expect that you actually know that and mistyped it). The second is that (first mylist)
returns a list (since you are getting a list of lists), but then you wrap it with the list
function before passing it to append. As a result, in your example, you're not passing (list 1)
to append
the first time you call it, but rather (list (list 1))
. You should simply remove the list
function from that expression.
Upvotes: 0
Reputation: 10643
You're actually fairly close. Here are some questions that might help:
What's the contract/signature of listoutput
?
What's the contract/signature of append
?
Also, I recommend building your examples simplest first, each example building on the previous ones. For example,
(check-expect (listoutput empty)) ???)
(check-expect (listoutput (cons (list 1) empty)) ???)
If the first test passes but the second one fails, what does that imply about where the problem is, given the structure of the function?
Upvotes: 2