Lisp的列表操作

问题描述 投票:7回答:6

我一直在到处寻找在Lisp的以下功能,并且已经得到了无处:

  1. 找到的东西在列表中的索引。例: (index-of item InThisList)
  2. 在列表中的特定点取代的东西。例: (replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
  3. 在一个特定的指数回报的项目。例: (return InThisList ItemAtThisIndex)

直到此时,我已经用我自己的功能作假。我想知道如果我只是创造更多的工作,为自己。

这是我如何被伪造数1:

(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))
functional-programming lisp list
6个回答
23
投票

您可以使用setfnth通过指数更换和检索值。

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

(1 2 3 4 101 6)

要通过您可以使用the position function索引找到。

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

我发现这些所有in this index of functions


11
投票
  1. 找到的东西在列表中的索引。

在Emacs Lisp和Common Lisp的,你有position功能:

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

在方案中,这里是从DrScheme的doc尾递归实现:

(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甚至某种像CLOS Lisp的对象系统。

如果你正在学习的Lisp,确保你看看Practical Common Lisp和/或The Little Schemer

干杯!


7
投票

回答:

  1. (位置项目序列从停止键(开始0)结束键测试测试未) http://lispdoc.com/?q=position&search=Basic+search
  2. (SETF(ELT序列索引)值)
  3. (ELT序列索引) http://lispdoc.com/?q=elt&search=Basic+search 注:ELT最好第n因为ELT适用于任何序列,而不仅仅是列表

4
投票

杰里米的答案应该工作;但表示,如果你发现自己写的代码像

(SETF(第n我我的列表)新-ELT)

你可能使用了错误的数据结构。列表是简单链表,所以他们是O(N)通过索引访问。你可能会使用数组会更好。

或者,也许你正在使用列表元组。在这种情况下,他们应该被罚款。但是,你可能想这样的人读你的代码并没有记住什么“第n 4”的解释是:以名字访问。就像是

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

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

4
投票

+2为 “实用的Common Lisp”。这是一个Common Lisp的食谱的混合物和质量自学Lisp的书。

还有“成功的Common Lisp”(http://www.psg.com/~dlamkins/sl/cover.htmlhttp://www.psg.com/~dlamkins/sl/contents.html),这似乎填补某些空白/在“实用的Common Lisp”扩展的东西。

我也看到了保罗·格雷厄姆的“ANSI Common Lisp的”,这是更多关于语言的基础知识,但更多的是参考手册的位。


0
投票

我与托马斯同意。如果你使用像数组列表,然后这只是将是缓慢的(也可能是尴尬)。所以,你要么使用数组或坚持你写的功能,但它们在某种程度上动“起来”,让你可以轻松地与阵列更换慢名单后。

© www.soinside.com 2019 - 2024. All rights reserved.