Search code examples
schemelispracketevaluatefunction-call

Scheme help - how to call a function


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.


Solution

  • 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.