[英]How to get dotted pairs in Lisp?
我已經在Google和其他地方搜索了一段時間,但無法找到如何生成或創建點對的方法。 我問這個問題是因為,我需要打開一個看起來像這樣的列表:
(X Y Z)
要使用以下格式的列表:
((X . 1) (Y . 2) (Z . 3))
數字代表索引。 我有一個功能,可以將列表轉換為以下格式
(X 1 Y 2 Z 3)
這是該函數:
(defun listFormat (l)
(defun place-index (idx l)
(if (null l)
nil
(append (list (first l)) (list idx)
(place-index (+ idx 1) (rest l)))))
(place-index 1 l))
但是我不確定如何獲得虛線對。 提前致謝
您的代碼有一個非常基本的錯誤:
(defun listFormat (l)
(defun place-index (idx l) ; <<<---- This DEFUN is wrong
(if (null l)
nil
(append (list (first l)) (list idx)
(place-index (+ idx 1) (rest l)))))
(place-index 1 l))
不要嵌套DEFUN。 那是錯誤的 。 DEFUN定義一個全局函數。 每當您運行listFormat時,它都會重新定義GLOBAL函數PLACE-INDEX。 您可能已經在使用DEFINE的SCHEME中看到了類似的嵌套函數。 在Common Lisp中,不應將DEFUN用於嵌套的局部函數。
在Lisp中,局部函數用FLET或LABELS定義(用於遞歸函數)。
(defun listFormat (l)
(labels ((place-index (idx l)
(if (null l)
nil
(append (list (first l)) (list idx)
(place-index (+ idx 1) (rest l))))))
(place-index 1 l)))
另外,Stackoverflow是解決作業的錯誤位置。 Google搜索也是學習Lisp編程的錯誤方法。
我建議使用閱讀入門和參考書的良好舊方法。
以下是基本的Lisp入門書籍可供下載: Common Lisp:符號計算的溫和介紹 。
參考表 :小型Common Lisp快速參考 (PDF)和更詳細的Common Lisp快速參考 。
虛線對在Lisp中稱為cons 。
請參閱Common Lisp的實際在線參考, Common Lisp HyperSpec 。
您希望else分支讀取:
(cons (cons (first l) idx) (place-index (+ idx 1) (rest l)))
順便說一下,對於問題本身,此代碼將執行以下操作:
(defun listFormat (lst)
(loop for idx from 1
for item in lst
collect (cons item idx)))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.