hel*_*dre 7 lisp functional-programming list
我一直在寻找Lisp中的以下功能,并且无处可寻:
找到列表中某些内容的索引.例:
(index-of item InThisList)
Run Code Online (Sandbox Code Playgroud)替换列表中特定位置的内容.例:
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
Run Code Online (Sandbox Code Playgroud)返回特定索引处的项目.例:
(return InThisList ItemAtThisIndex)
Run Code Online (Sandbox Code Playgroud)到目前为止,我一直在用自己的功能伪装它.我想知道我是否只为自己创造更多的工作.
这就是我伪造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))
Run Code Online (Sandbox Code Playgroud)
小智 23
您可以使用setf和nth按索引替换和检索值.
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101); <----
myList)
(1 2 3 4 101 6)
Run Code Online (Sandbox Code Playgroud)
要通过索引查找,您可以使用该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)
Run Code Online (Sandbox Code Playgroud)
我在这个函数索引中找到了所有这些.
Séb*_*rra 11
- 找到列表中某些内容的索引.
在Emacs Lisp和Common Lisp中,您有以下position功能:
> (setq numbers (list 1 2 3 4))
(1 2 3 4)
> (position 3 numbers)
2
Run Code Online (Sandbox Code Playgroud)
在Scheme中,这是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
>
Run Code Online (Sandbox Code Playgroud)
但是如果你使用列表作为存储结构化数据的插槽集合,也许你应该看看defstruct甚至某种像CLOS这样的Lisp对象系统.
如果你正在学习Lisp,请确保你看看Practical Common Lisp和/或The Little Schemer.
干杯!
回答:
(位置项序列和键从头(开始0)结束键测试 - 不)
http://lispdoc.com/?q=position&search=Basic+search
(setf(elt序列索引)值)
(elt序列索引)
http://lispdoc.com/?q=elt&search=Basic+search
注意:elt优于nth,因为elt适用于任何序列,而不仅仅是列表