从一个列表中获取两个列表

时间:2016-11-12 21:04:51

标签: racket

假设我有以下列表:

(list '("a" 2) '("b" 1) '("c" 'end))

我想从第一个列表中获取两个列表,输出:

(list "a" "b" "c") and (list 2 1 'end)

我如何在Racket中做到这一点?

我想出了类似的东西:

(define first (mlist))
(define second (mlist))
(define (get-two-lists l)
  (for ([i t])
    (mappend! first (list-ref i 0))
    (mappend! second (list-ref i 1))))

输出给我空列表..

2 个答案:

答案 0 :(得分:2)

#lang racket
(define l (list '("a" 2) '("b" 1) '("c" 'end)))

(values (map first l)
        (map second l))

答案 1 :(得分:1)

对于手动循环功能:

(define (f l)
  (let loop ((l l)
             (l1 '())
             (l2 '()))
    (if (empty? l)
        (values (reverse l1)
                (reverse l2))
        (loop (rest l)
              (cons (first (first l)) l1)
              (cons (second (first l)) l2) ))))

测试:

(f (list '("a" 2) '("b" 1) '("c" 'end)))

输出:

'("a" "b" "c")
'(2 1 'end)
相关问题