方案/球拍:使用map和lambda转换列表 [英] Scheme / Racket : transposing lists with map and lambda
问题描述
我当前正在尝试编写一个程序,该程序获取一个列表列表并返回一个列表列表,其中包含输入列表的每个第一项.例如,我将为您提供输入和输出.
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.
输入:
(list (list 1 5) (list 2 6) (list 3 7) (list 4 8)))
输出:
(list (list 1 2 3 4) (list 5 6 7 8))
我的想法是使用lambda构建函数来构建某种程度的映射过程.我目前正在努力将任何函数映射到组合列表元素上,因为 map 只处理列表中的一个项目(据我所知).
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?
非常感谢您.
推荐答案
这可以在Scheme/Racket中使用
This can be done in Scheme / Racket with
(apply map list (list (list 1 5) (list 2 6) (list 3 7) (list 4 8)))
在DrRacket中返回的
which in DrRacket returns
'((1 2 3 4) (5 6 7 8))
基本上,调用(应用地图列表 [abc ... n] )
(在 pseudocode 中)与调用
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)
代替 list
:
(apply map (lambda x x) (list ....... ))
这是因为 map
可以与多个列表一起用作其输入,而不仅仅是一个.在这种情况下,lambda函数的参数数量必须与输入列表的数量匹配.
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.
特殊情况是(lambda x ...)
,其中 x
不在括号内.这意味着这样的lambda函数可以应用于任意个参数,这些参数将全部收集并作为列表传递给.因此,(lambda x x)
的行为与内置的 list
相同,并且可以视为其实现.
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".
这篇关于方案/球拍:使用map和lambda转换列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!