如何将列表转换为其元素

时间:2015-02-10 18:01:14

标签: scheme racket

这一定很容易实现,但我是新手,不知道如何:

我有一个清单(1 2 3 4)并希望将其转换为(1)(2)(3)(4)

或者有没有办法将其构建为(1)(2)(3)(4)。我正在使用

 cons '(element) call-function

在函数内部(递归地)构建它

2 个答案:

答案 0 :(得分:5)

试试这个:

(map list '(1 2 3 4))

答案 1 :(得分:2)

从您的文字中,我看到您'(element)。问题在于所引用的一切都不是你所看到的。因此,如果element恰好是变量,则由于报价而无法扩展。

获取包含一个元素的列表的正确方法是使用list。例如。 (list element)将变量element作为列表中的一个元素。但是,您不会在自己的滚动递归过程中需要这个:

(define (listify lst)
  (if (null? lst)                  ; if lst is null we are done
      '()                          ; evaluate to the empty list
      (cons (list (car lst))       ; else we make a list with the first element
            (listify (cdr lst))))) ; and listify the rest of the list too

现在大多数程序都在促进通过论证,但由于它是常见的事情,我们可以使用带有foldr的高阶程序,这样你只关注这个元素会发生什么。链与其他过程相对应:

(define (listify lst)
  (foldr (lambda (e acc)
           (cons (list e) ; chain this element wrapped in a list 
                 acc))    ; with the result from the rest of the list
         '()              ; initiate with an empty list
         lst))            ; go through lst

当然,由于我们对列表中的每个元素执行某些操作并且使用map没有任何想象力,我们只需要提供如何处理每个元素,而不是告诉如何将列表中的链连接在一起。

(define (listify lst)
  (map list lst))      ; make a new list by applying a list of each element

它实际上是zip的单个参数版本:

(require srfi/1)
(zip '(1 2 3 4))        ; ==> ((1) (2) (3) (4))
(zip '(1 2 3) '(a b c)) ; ==> ((1 a) (2 b) (3 c))

你去吧。尽可能简单。

相关问题