lisp - 在 lisp 中乘以 2 个向量

标签 lisp

我正在尝试用 lisp 将两个向量相乘。 我的代码是:

(defun produs(x y)
  (cond
    ((or (null x) (null y))
     nil)
    ((eq (cdr x) nil)
     (cons (* (car x) (car y))
           (cdr y))) 
    ((eq (cdr y) nil)
     (cons (* (car x) (car y))
           (cdr x)))
    (t
     (cons (* (car x) (car y))
           (produs (cdr x) (cdr y))))))

当我验证

(produs '(7) '(1 2))

它给了我 (7 2)。

第 4 行代码没有指定如果 x 主体的其余部分为 nil,则将其与 y 的所有元素相乘?

最佳答案

如果我正确地理解了你想要实现的目标,那么这段代码应该可以工作:

(defun produs(x y)
(cond
((or (null x) (null y)) nil)
((eq (cdr x) nil) ( cons (* (car x)(car y))(produs (cdr y) x )))
((eq (cdr y) nil) ( cons (* (car x)(car y)) (produs (cdr x) y)))
(t (cons (*(car x)(car y)) (produs (cdr x)(cdr y))))
)
)

问题是您不是“说”将所有元素与头部 x 相乘,而是只是将 y 中的所有剩余元素添加到结果列表中。

(produs '(7) '(1 2)) => (7 14)

关于lisp - 在 lisp 中乘以 2 个向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34055155/

相关文章:

emacs - 如何在 Common Lisp 中隐藏(读取)输出

lisp - 尝试返回当前列表中偶数位置的值列表

list - 如何在 Lisp 中获取点对?

lisp - CUDA 的任何 Lisp 扩展?

Lisp排序查询

haskell - 惰性求值与宏

functional-programming - 如何让我的大脑在 "lisp mode?"中移动

lisp - Scheme中 `define`的返回值是多少?

scheme - 在解释器中确定Scheme函数的定义和参数?/函数如何存储在Scheme中?

functional-programming - LISP - 破坏性和非破坏性结构