我一直在 Lisp 中到处寻找以下功能,但一无所获:

  1. 查找列表中某些内容的索引。例子:

    (index-of item InThisList)
    
  2. 替换列表中特定位置的某些内容。例子:

    (replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
    
  3. 返回特定索引处的项目。例子:

    (return InThisList ItemAtThisIndex)
    

到目前为止,我一直用我自己的函数来伪造它。我想知道我是否只是在为自己创造更多的工作。

这就是我伪造第一名的方式:

(defun my-index (findMe mylist)
  (let ((counter 0) (found 1))
    (dolist (item mylist)
      (cond
        ((eq item findMe) ;this works because 'eq' checks place in memory, 
                  ;and as long as 'findMe' was from the original list, this will work.
         (setq found nil)
        (found (incf counter))))
  counter))
有帮助吗?

解决方案

您可以使用 setfnth 通过索引替换和检索值。

(let ((myList '(1 2 3 4 5 6)))
     (setf (nth 4 myList) 101); <----
     myList)

(1 2 3 4 101 6)

要按索引查找,您可以使用 position 功能.

(let ((myList '(1 2 3 4 5 6)))
     (setf (nth 4 myList) 101)
     (list myList (position 101 myList)))

((1 2 3 4 101 6) 4)

我找到了这些 在这个函数索引中.

其他提示

  1. 查找列表中某些内容的索引。

在 Emacs Lisp 和 Common Lisp 中,您有 position 功能:

> (setq numbers (list 1 2 3 4))
(1 2 3 4)
> (position 3 numbers)
2

在Scheme中,这是一个尾递归实现 博士计划的文档:

(define list-position 
  (lambda (o l)
    (let loop ((i 0) (l l))
      (if (null? l) #f
          (if (eqv? (car l) o) i
              (loop (+ i 1) (cdr l)))))))

----------------------------------------------------

> (define numbers (list 1 2 3 4))
> (list-position 3 numbers)
2
> 

但是如果您使用列表作为槽的集合来存储结构化数据,也许您应该看看 defstruct 甚至是某种 Lisp 对象系统,例如 CLOS。

如果您正在学习 Lisp,请务必查看 实用 Common Lisp 和/或 小阴谋家.

干杯!

答案:

  1. (位置项顺序&key from-end(start 0) end key test test-not)
    http://lispdoc.com/?q=position&search=Basic+search

  2. (setf(elt序列索引)值)

  3. (elt序列索引)
    http://lispdoc.com/?q=elt&search=Basic+search
    笔记:elt 比 nth 更好,因为 elt 适用于任何序列,而不仅仅是列表

杰里米的答案应该有效;但话虽如此,如果您发现自己编写了类似的代码

(setf(我的列表中的第 n 个)新 elt)

您可能使用了错误的数据结构。列表只是链接列表,因此通过索引访问它们的时间复杂度为 O(N)。使用数组可能会更好。

或者也许您正在使用列表作为元组。那样的话,他们应该没问题。但是您可能想要命名访问器,这样阅读您代码的人就不必记住“nth 4”的含义。就像是

(defun my-attr (list)
  (nth 4 list))

(defun (setf my-attr) (new list)
  (setf (nth 4 list) new))

+2 “实用 Common Lisp”。它是一本 Common Lisp Cookbook 和一本高质量的 Teach Yourself Lisp 书的混合体。

还有“成功的 Common Lisp”(http://www.psg.com/~dlamkins/sl/cover.htmlhttp://www.psg.com/~dlamkins/sl/contents.html)这似乎填补了“实用 Common Lisp”中的一些空白/扩展了内容。

我还读过 Paul Graham 的“ANSI Common Lisp”,它更多地介绍了该语言的基础知识,但更多的是一本参考手册。

我必须同意托马斯的观点。如果您使用像数组这样的列表,那么速度会很慢(而且可能很尴尬)。因此,您应该使用数组,或者坚持使用您编写的函数,但以某种方式将它们“向上”移动,以便稍后可以轻松地用数组替换慢速列表。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top