Search code examples
lispcommon-lisp

Getting values from a list of length-2 lists


There is a defconstant statement:

(defconstant *contant2* '((Allan 4) (Zols 5) (Milo 2) (Judh 0)))

I want to take separated from this constant the name and the value associated with the name. How can I do that?

I need to achieve this goal:

Give taste scores: ((name-1 score-1) ... (name-n score-n)) as an argument, LISP functions which avare score and other which generate word scores (9-10 is VeryGood, 7-8 is Good).

I appreciate any help! Thanks.


Solution

  • To answer your direct question:

    ? (mapcar #'car *cookie-scores*)
    (JOHN MARY MIKE JANE)
    ? (mapcar #'cadr *cookie-scores*)
    (8 9 1 0)
    

    In a loop, you can use loop's destructuring:

    for (name val) in
    

    Other options are available; here's 2 example implementations of the required functions that I will leave uncommented; please ask questions, or show us your code.

    (defun average-score (lst)
      (/ (reduce #'+ lst :key #'cadr) (length lst))))
    
    ? (average-score *cookie-scores*)
    9/2
    

    and

    (defun word-scores (lst)
      (loop 
        for (name val) in lst
        collect (list name
                      (cond
                       ((> val 8) 'Excellent)
                       ((> val 6) 'Tasty)
                       ((> val 0) 'Terrible)
                       (t         'Garbage)))))
    
    ? (word-scores *cookie-scores*)
    ((JOHN TASTY) (MARY EXCELLENT) (MIKE TERRIBLE) (JANE GARBAGE))