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

1 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)

Run Code Online (Sandbox Code Playgroud)

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

Rai*_*wig 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)
Run Code Online (Sandbox Code Playgroud)

了解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)
Run Code Online (Sandbox Code Playgroud)

下一个:

  • 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
Run Code Online (Sandbox Code Playgroud)