I'm having trouble with the output of my code, I think it's when I'm checking conditions for the null of my lists.
The question I am trying to complete is: Write a function vecmul
that will take as inputs two simple lists of numbers. vecmul should multiply these lists coordinate-wise as one would multiply vectors. Assume the two lists are the same length. [For example, (vecmul '(2 3 4 5) '(1 4 5 2))
returns (2*1 3*4 4*5 5*2)
or (2 12 20 10)
. You are not allowed to use mapcar
for this function]
So far I have
(defun vecmul (list list2)
(cond ((null list) 0)
(t (cons (* (car list) (car list2))
(vecmul (cdr list) (cdr list2))))))
[170]> (setq l '(2 4 6))
(2 4 6)
[171]> (setq r '(1 3 5))
(1 3 5)
[172]> (vecmul l r)
(2 12 30 . 0)
I'm getting the correct numbers, it's just that the list is adding the "." and the "0" at the end of the list. I'm pretty sure it's because i'm not stopping the recursion right or not working the cond right. I'm just not entirely sure how to correct it.
You've got it almost right. However, you're terminating your list with 0
, when the correct termination is nil
. This code works:
(defun vecmul (list list2)
(cond ((null list) nil)
(t (cons (* (car list) (car list2)) (vecmul (cdr list) (cdr list2))))))
When you call (cons 1 2)
, the cons cell you get is written (1 . 2)
. the notation (1 2 3 4 5)
is just shorthand for (1 . (2 . (3 . (4 . (5 . nil)))))
. If the cdr
of the last cons cell is 6
, not nil
, then you get (1 . (2 . (3 . (4 . (5 . 6)))))
, which shortens to (1 2 3 4 5 . 6)
.