Reputation: 47
how do I get the keys from an association list? I.E (
define lst1 (list(list 2 "three")(list 2 "two")(list 1 "one")))
(get-keys lst1) => (list 2 2 1)
the below is what I wrote:
(define(get-keys alst)
(cond
[(empty? alst) empty]
[(number?(first(first alst)))(cons(first(first alst))(get-keys (rest alst)))]
[else(get-keys (rest alst))]))
however this is highly inneficient when I try and use get-keys as a helper function..What I am really trying to do is write a program that consumes two association lists and returns only the keys that do not repeat.
Upvotes: 0
Views: 2063
Reputation: 236004
Here's a really simple solution, using built-in higher-order procedures (don't reinvent the wheel!):
(define (get-keys alst)
(map first alst))
The above procedure maps the first
procedure over the input list, that is: it takes the first element from each association. If at some point you need to delete duplicate keys, then use remove-duplicates
, for example:
(define lst1 (list (list 2 "three") (list 2 "two") (list 1 "one")))
(remove-duplicates (get-keys lst1))
=> '(2 1)
Alternatively, if you're note allowed to use map
we can always write a procedure from scratch using only primitive operations, like this:
(define (get-keys alst)
(cond
[(empty? alst) empty]
[else (cons (first (first alst))
(get-keys (rest alst)))]))
Upvotes: 4