📜  LISP 中的列表

📅  最后修改于: 2022-05-13 01:55:27.495000             🧑  作者: Mango

LISP 中的列表

公共 LISP 中的列表只是一个单链表。在 LISP 中,列表被设计为记录链。在谈论 LISP 中的记录结构时,Cons 的概念至关重要。 LISP 中的缺点是具有 2 个主要组件的记录结构。 cons函数接受 2 个参数并返回一个带有 car 和 dir 的新 cons 单元格。

  1. car:用于访问 cons函数的第一个值。
  2. cdr:用于访问 cons函数的第二个值。

注意:如果第二个值不是 nil 或者只是另一个 cons 单元格,那么这些值将打印为用括号括起来的点对。

例子:

Lisp
; cons with 2 string object reference
(write (cons 'Geeksforgeeks 'Is_Best))
(terpri)
  
; cons with 1 nil value as argument
(write (cons 999 nil))
(terpri)
  
;cons with anoher cons as argument
(write (cons 'A (cons 'B nil)))
(terpri)
  
;cons with otyhen nested cons as argument
(write (cons 'A (cons 'B (cons 'C nil))))


Lisp
(write (list 1 2))
(terpri)
(write (list 'g 'e 'e'k's))
(terpri)
(write (list 'Geeksforgeeks' nil))
(terpri)
  
;list with a cons as an argument
(write (list 3 4 'geeks (car '(G . F)) (* 99  +78)))
(terpri)
  
; list with another list as an argument
(write (list (list 'Geeksforgeeks 'is) (list 'the 'best 'resource 'for 'DSA)))


Lisp
; here we will extract the string Best
(write (cadadr '(Geeksforgeeks (is best) (for Data Structures))))
(terpri)
  
; here we will extract the string Geeks
(write (caar (list (list 'Geeks 'for) 'geeks)))   
(terpri)
  
; here we will use the abbv. cadr
(write (cadr (list (list 'A 'B) (list 'C'D))))


输出:



(GEEKSFORGEEKS . IS_BEST)
(999)
(A B)
(A B C)

LISP 中的列表:

LISP 中的列表函数可用于在 LISP 中创建列表。

句法:

write( list value1 value 2 ...)

注意: list函数可以取任何编号。论据。

例子:

Lisp

(write (list 1 2))
(terpri)
(write (list 'g 'e 'e'k's))
(terpri)
(write (list 'Geeksforgeeks' nil))
(terpri)
  
;list with a cons as an argument
(write (list 3 4 'geeks (car '(G . F)) (* 99  +78)))
(terpri)
  
; list with another list as an argument
(write (list (list 'Geeksforgeeks 'is) (list 'the 'best 'resource 'for 'DSA)))

输出:

(1 2)
(G E E K S)
(GEEKSFORGEEKS NIL)
(3 4 GEEKS G 7722)
((GEEKSFORGEEKS IS) (THE BEST RESOURCE FOR DSA))

访问列表的元素:

通用 LISP 中carcdr函数的组合可用于从列表中提取元素。 carr和cdr的组合可以简写为cadadr/caar/cadr等。

例子:

Lisp

; here we will extract the string Best
(write (cadadr '(Geeksforgeeks (is best) (for Data Structures))))
(terpri)
  
; here we will extract the string Geeks
(write (caar (list (list 'Geeks 'for) 'geeks)))   
(terpri)
  
; here we will use the abbv. cadr
(write (cadr (list (list 'A 'B) (list 'C'D))))

输出:

BEST
GEEKS
(C D)