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

时间:2019-05-07 18:58:01

标签: lisp common-lisp

简单线性搜索输入参数,不能使用诸如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)

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

1 个答案:

答案 0 :(得分:8)

(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已声明
  • 您需要在DO的迭代形式之前写一个LOOP
  • 调用=的括号内是错误的
  • 调用/=的括号内是错误的
  • 向量可以很容易地写为#(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