문제

Hi everyone I am new to programming and I have to work with association list like this

((course (john .math) (jim .english) (carl .biology) )
 (year (john .2) (jim. 1) (carl .3))
 (age (john .22) (jim .20) (carl .27))
)

I am supposed to use the matcher to work like that with a function lookup

(lookup 'john 'course data) and return math

Now I am new to programming and completely new to Lisp and need to do this for the school. Now I do not need a complete solution necessary but some ideas or instructions.

This is what I have though so far but took me a lot of time

If someone can help it will be much appreciated!!!!

(defun lookup (name course data)

(matches '(name course data) '(first course  )) 

)
도움이 되었습니까?

해결책

First let's put the data into a list called data. Pay attention that the list needs to be quoted by ', and that the . dot signs need to be surrounded by spaces because they have a signification of their own:

(defparameter *data* '((course (john . math) (jim . english) (carl . biology))
                       (year   (john . 2)    (jim . 1)       (carl . 3))
                       (age    (john . 22)   (jim . 20)      (carl . 27))))

Now let's try using procedure assoc:

? *data*
((COURSE (JOHN . MATH) (JIM . ENGLISH) (CARL . BIOLOGY)) (YEAR (JOHN . 2) (JIM . 1) (CARL . 3)) (AGE (JOHN . 22) (JIM . 20) (CARL . 27)))
? (assoc 'course *data*)
(COURSE (JOHN . MATH) (JIM . ENGLISH) (CARL . BIOLOGY))
? (cdr (assoc 'course *data*))
((JOHN . MATH) (JIM . ENGLISH) (CARL . BIOLOGY))
? (assoc 'john (cdr (assoc 'course *data*)))
(JOHN . MATH)
? (cdr (assoc 'john (cdr (assoc 'course *data*))))
MATH

so the function becomes

(defun lookup (name attr data)
  (cdr (assoc name (cdr (assoc attr data)))))

(lookup 'john 'course *data*) 
=> MATH

(lookup 'carl 'age *data*) 
=> 27
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top