Pergunta

I'm supposed to write a function that will take in a list, extract the ID number from the list, and then return it as an integer (not a list).

My first function was pretty simple:

(defun idReturn2 (l) (if (eq (car l) '(ID)) (cadr l) (idReturn list)))

Which I called with the function:

 (idReturn2 '((name (light bulb)) (mfgr ge) (watts 60) (id 357) (quantity 6)))

The method is supposed to return 357, but instead returns (357). It's the right number to return, but it's part of a list, which my professor outright told us not to do.

I noticed that my quadratic equation function only returned an integer without the parentheses, so I thought I could parse the integer using parse-integer:

(defun idReturn2 (l) (if (eq (car l) '(ID)) (parse-integer (cadr l)) (idReturn list)))

Still returns (357). I've gone over my lisp notes a dozen times, as well as the slides, and I can see absolutely no way to pull the data out of the list. Could anyone offer me some guidance?

Foi útil?

Solução

So you have a list ((property-name1 value1) (property-name2 value2) ...) if that list is given as argument l then (car l) isn't (property-name1) but (property-name1 value1). Luckily you see that the symbol you should check is in the results first element and that means you should use (car (car l)) or (caar l) for short. (eq (caar l) 'property-name1) ; ==> t

Notice that when you don't find it in the first iteration you call a totally different function IdReturn, not with the rest of l but a different variable list (whatever that is). You haven't supplied it so I cannot tell how you get (357) but it's not from functions supplied in your question.

PS: Any list (a) (a b) or (a b c) you pull the first value with car. (car '(357)) ;==> 357

Outras dicas

Maybe it's less confusing if you use the first, second and rest functions:

(defun idReturn (l) 
  (when l
    (let ((c (first l)))
      (if (eq (first c) 'id)
        (second c) 
        (idReturn (rest l))))))

which is the same as

(defun idReturn (l) 
  (when l
    (let ((c (car l)))
      (if (eq (car c) 'id)
        (cadr c) 
        (idReturn (cdr l))))))

then

? (idReturn '((name (light bulb)) (mfgr ge) (watts 60) (id 357) (quantity 6)))
357
? (idReturn '((name (light bulb)) (mfgr ge) (watts 60) (idx 357) (quantity 6)))
NIL

Note that, using assoc, you can simplify the function to

(defun idReturn (l)
  (second (assoc 'id l)))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top