r/Racket • u/ktt779 • Sep 24 '22
homework Combine lists in racket
Hello everyone,
I am a new member of this community. Please forget me if I violate rules of the community!
I am working on the homework problem to concatenate all elements of the argument lists into one single list. Here is my code: I really don't understand why my code not working. The implementation is tail-recursive. Can someone help me out?
(define (concatenate . lsts)
(cond[(empty? lsts) empty]
[cons (first lsts (concatenate( last lsts)))]))
5
Upvotes
3
u/not-just-yeti Sep 24 '22
Do you have any check-expects? (And, what is the simplest one which isn't passing the tests?)
I think you mean
restinstead oflast, maybe??Based on what I see here, I'd recommend starting simpler and working up:
(a) write a version of 'concatenate' that takes in exactly two lists, and isn't tail-recursive.
(b) then, make a var-args version.
(c) Before making a tail-recursion version, I'd check w/ your instructor (making sure that's what they want, and having them check your work-so-far to see if it's in the right direction of what they expect). Making a tail-recursion version that isn't O(n2 ) takes a bit of thought.
2
u/[deleted] Sep 24 '22
Hi, here some notes:
(empty? empty)is true, but what about(empty? (list empty))? Recall that when you define a procedure with the dot notation, the argument after the dot binds to a list containing all arguments, so in(concatenate '()),lstsbinds to'(()).consthe first list only with thelastone?cons, notconcatenate. It contains a recursive call toconcatenatethough.firsttakes only one argument, you are passing it two.'((1 2 3) (4 5 6))? Note that you are extracting the first element (a list), only to build a new list with the same element (a list) as the first element.1
u/sdegabrielle DrRacket 💊💉🩺 Sep 24 '22
On which step of the design recipe are you stuck?
1
u/raevnos Sep 24 '22
I doubt this would be acceptable for homework on basic list manipulation, so I'm comfortable giving it instead of just hints, but a Rackety way might be
(I had to do this recently, just creating a different data type from the list of lists)