Reputation: 3137
Let say I have the following list:
(list '("a" 2) '("b" 1) '("c" 'end))
I want to get two lists out of the first list, output:
(list "a" "b" "c") and (list 2 1 'end)
How would I do this in Racket?
I came up with something like this:
(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))))
The output gives me empty list..
Upvotes: 1
Views: 65
Reputation: 52344
Another way, iterating over the list of lists using a list comprehension - specifically, for/lists
, which builds and returns multiple lists as individual values. Also demonstrates pattern matching to bind the elements of the sublists to variables instead of using functions like first
and second
:
#lang racket/base
(require racket/match)
(define (get-two-lists lol)
(for/lists (l1 l2)
([sublist (in-list lol)])
; Could also use (apply values sublist) here
(match-let ([(list a b) sublist])
(values a b))))
(define-values (first-list second-list)
(get-two-lists '(("a" 2) ("b" 1) ("c" end))))
(println first-list) ; '("a" "b" "c")
(println second-list) ; '(2 1 end)
Upvotes: 0
Reputation: 24535
For a manual loop function:
(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) ))))
Testing:
(f (list '("a" 2) '("b" 1) '("c" 'end)))
Output:
'("a" "b" "c")
'(2 1 'end)
Upvotes: 1
Reputation: 31147
#lang racket
(define l (list '("a" 2) '("b" 1) '("c" 'end)))
(values (map first l)
(map second l))
Upvotes: 2