Reputation: 7
I'm new to Scheme, and I am trying to manipulate a list and return the cdr of a pair in the list.
So far here is my code:
(define get-userid (lambda (ls)
(if (pair? ls)
(cdar ls)
(get-userid (cdar ls)))))
The list I wish to manipulate is:
(define *rider-preferences4*
'((userid . anna)
(role . rider)
(origin . "southampton")
(destination . "glasgow")
(time . "15:15")
(capacity . 2)
(smoking . no)))
Input and outputs:
> get-userid *rider-preferences4*
#<procedure:get-userid>
((userid . anna) (role . rider) (origin . "southampton") (destination . "glasgow") (time . "15:15") (capacity . 2) (smoking . no))
> get-userid (get-userid *rider-preferences4*)
#<procedure:get-userid>
**anna**
I want the result of just anna
, and to be able to do it just by calling get-userid
. How would this be possible? Even though I assume it's trivial.
Upvotes: 0
Views: 103
Reputation: 18917
Since *rider-preferences4*
is an association list you can use the specific procedures (assoc
, assq
, assv
) to retrieve any key:
> (cdr (assq 'userid *rider-preferences4*))
'anna
> (cdr (assq 'destination *rider-preferences4*))
"glasgow"
so the code is
(define (get-userid alst)
(cdr (assq 'userid alst)))
Besides being usable for any key, it is also independent of the position, so
> (get-userid '((role . rider) (userid . anna)))
'anna
will also work.
Upvotes: 1
Reputation: 236004
I think you're a bit confused with the way list operations work in Scheme, I suggest you take a look at the relevant section in the documentation. For this problem, the solution is as simple as this:
(define get-userid ; even simpler: (define get-userid cdar)
(lambda (ls)
(cdar ls)))
Explanation: the input list is a list of pairs, and we're interested in the cdr
part of the first element (which holds the user id). So we take the cdr
of the car
, or abbreviated: the cdar
. It works as expected:
(get-userid *rider-preferences4*)
=> 'anna
Upvotes: 1