gpt4 book ai didi

lisp - Lisp 中的线性搜索,数组错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:46 25 4
gpt4 key购买 nike

输入参数的简单线性搜索,不能使用 find 等内置函数

不幸的是,我找不到很多合适的文档,因为它们要么已经过时,要么大多数都没有涵盖这么简单的问题。

非常感谢有关理解 lisp 的提示。

(defun search(numray x) 
(defvar i 0)
(loop for i in numray
(cond
((= x (aref numray i) "Element is present in array")
((/= x (aref numray i) "Element is not present in array")
(t "iddunno")))))
)

(setf numray (make-array '(10)
:initial-contents '(0 11 2 33 44 55 66 7 88 99)))
(defvar x (read))
(search arr x)

检查输入变量的定义数组。说明是否存在。

最佳答案

(defun search(numray x) 
(defvar i 0)
(loop for i in numray
(cond
((= x (aref numray i) "Element is present in array")
((/= x (aref numray i) "Element is not present in array")
(t "iddunno")))))
)

(setf numray (make-array '(10)
:initial-contents '(0 11 2 33 44 55 66 7 88 99)))
(defvar x (read))
(search arr x)

学习 Lisp 的第一件事是根据列表结构缩进代码:

(defun search (numray x) 
(defvar i 0)
(loop for i in numray
(cond
((= x (aref numray i) "Element is present in array")
((/= x (aref numray i) "Element is not present in array")
(t "iddunno")))))
)

(setf numray (make-array '(10)
:initial-contents '(0 11 2 33 44 55 66 7 88 99)))
(defvar x (read))
(search arr x)

下一步:

  • DEFVAR 用于全局变量,而不是局部变量
  • 你不需要声明i,因为LOOP声明了它
  • 您需要在 LOOP 中的迭代形式之前编写一个 DO
  • 调用 = 的括号是错误的
  • 调用 /= 的括号是错误的
  • 向量可以很容易地写成#(1 2 3 4 5)
  • *放在一个全局变量中
  • 不要将您的函数命名为search,因为该函数已经内置
  • IN 适用于列表,ACROSS 适用于向量

例子:

CL-USER 3 > (defun note-num-in-array (vector number) 
(loop for item across vector do
(print (if (= number item)
"Element is present in array"
"Element is not present in array"))))
NOTE-NUM-IN-ARRAY

CL-USER 4 > (note-num-in-array #(1 2 3 1 2 4 5 4 3 2) 2)

"Element is not present in array"
"Element is present in array"
"Element is not present in array"
"Element is not present in array"
"Element is present in array"
"Element is not present in array"
"Element is not present in array"
"Element is not present in array"
"Element is not present in array"
"Element is present in array"
NIL

关于lisp - Lisp 中的线性搜索,数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com