Functional programming 在Lisp中列出操作
我一直在到处搜索Lisp中的以下功能,但一无所获:Functional programming 在Lisp中列出操作,functional-programming,lisp,list,Functional Programming,Lisp,List,我一直在到处搜索Lisp中的以下功能,但一无所获: 在列表中查找某物的索引。例如: (index-of item InThisList) (replace item InThisList AtThisIndex) ;i think this can be done with 'setf'? (return InThisList ItemAtThisIndex) 在列表中的特定位置替换某物。例如: (index-of item InThisList) (replace item InTh
(index-of item InThisList)
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
(return InThisList ItemAtThisIndex)
(index-of item InThisList)
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
(return InThisList ItemAtThisIndex)
(index-of item InThisList)
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
(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))
您可以使用
setf
和nth
按索引替换和检索值
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101); <----
myList)
(1 2 3 4 101 6)
我都找到了。杰里米的答案应该有用;但也就是说,如果您发现自己编写的代码 (setf(我的第N份名单)新英语教学) 您可能使用了错误的数据结构。列表是简单的链表,所以它们是O(N)的索引访问。您最好使用数组 或者你可能正在使用列表作为元组。那样的话,他们应该没问题。但您可能希望命名访问器,以便阅读您的代码的人不必记住“nth4”的含义。差不多
(defun my-attr (list)
(nth 4 list))
(defun (setf my-attr) (new list)
(setf (nth 4 list) new))
我不得不同意托马斯的观点。如果您使用数组之类的列表,那么这只会很慢(而且可能会很尴尬)。因此,您应该要么使用数组,要么坚持使用您编写的函数,但要以某种方式将它们“向上”移动,以便以后可以轻松地用数组替换慢速列表
位置
功能:
> (setq numbers (list 1 2 3 4))
(1 2 3 4)
> (position 3 numbers)
2
在Scheme中,以下是来自的文档的尾部递归实现:
但是如果您使用一个列表作为存储结构化数据的插槽集合,那么您可能应该看看defstruct
,甚至是类似CLOS的Lisp对象系统
如果您正在学习Lisp,请确保查看和/或
干杯 答案:
注:elt优于nth,因为elt适用于任何序列,而不仅仅是列表
我还读过Paul Graham的“ANSI Common Lisp”,这本书更多地介绍了该语言的基础知识,但更像是一本参考手册。此外,我们没有“替换”列表中的元素。我们复制第一个(r-1)元素并将新值放入r中,其中cdr连接到(r+1)元素——因为我们处理的是持久性。