Scheme / Racket : transposing lists with map and lambda
Asked Answered
L

1

1

I'm currently trying to code a procedure which gets a list of lists and returns a list of lists, which contains each first item of the input lists. For example I'll provide you with a Input and Output.

Input:

(list (list 1 5) (list 2 6) (list 3 7) (list 4 8)))

Output:

(list (list 1 2 3 4) (list 5 6 7 8))

My idea was to build a somewhat map procedure using lambda for function. I'm currently struggling on mapping any function on combined list elements, since map only processes a single item on the list (to my understanding).

Could anyone provide me with helpful insights?

Thank you so much in advance.

Louisalouisburg answered 9/11, 2018 at 16:21 Comment(3)
Are you talking about lists or tuples... parentheses are syntax for tuples in python but you have the word list so not to sure what the input looks likeSwanskin
@DrewNicolette in Scheme parens are for lists, so it's OK.Eth
@DrewNicolette Thanks for answering, but Will Ness is totally right about Scheme syntax. If you want to, feel free to take a look on his answer in this thread. It made clear to me, how to handle the recursive map function and lambda for several listsLouisalouisburg
E
2

This can be done in Scheme / Racket with

(apply map list (list (list 1 5) (list 2 6) (list 3 7) (list 4 8)))

which in DrRacket returns

'((1 2 3 4) (5 6 7 8))

Basically, calling (apply map list [a b c ... n]) (in pseudocode), is the same as calling

(map list a b c ... n)

The argument list is "opened up", so to speak.

(lambda x x) could be used instead of list, too:

(apply map (lambda x x) (list ....... ))

This is because map can be used with several lists as its inputs, not just one. In such a case the number of arguments to the lambda function must match the number of input lists.

A special case is (lambda x ...) where x is not enclosed in parentheses. This means such a lambda function can be applied to any number of arguments, which will all be collected and passed in as a list. So (lambda x x) will act just the same as the built-in list does, and can be seen as its implementation.

And by the way, this isn't "merging", it is "transposition".

Eth answered 9/11, 2018 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.