Question

I'm using Scheme (Racket) for the first time, and I am having some problems. I want to know how I can manipulate lists within lists (specifically print the head of each sublist)

I know how to print the head of the superlist (which is a list itself)

eg:

 (define (concatenate list-a)
   (car list-a)) 

Now if I input:

(concatenate '(("one" "two") ("three" "four") ("five" "six")))

Then I get

'("one" "two")

But what I want to get is: "one" "three" "five"

How do I do this?

Was it helpful?

Solution

You need to apply car to every element (sublist) of the main list, using map:

(define (concatenate lst)
  (map car lst))

(concatenate '(("one" "two") ("three" "four") ("five" "six")))
=> '("one" "three" "five")

To print these values each on its own line, use for-each:

(for-each displayln (concatenate '(("one" "two") ("three" "four") ("five" "six"))))
=> 
one
three
five

You could also use map instead of for-each, but then you'd get

one
three
five
'(#<void> #<void> #<void>)

The trailing '(#<void> #<void> #<void>) is the result of applying displayln to each value (displayln always returns void). So use map if you care about the result, for-each if you don't.

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