2011-01-31 37 views
1

我搜索了谷歌和其他地方一段時間,但我無法找到如何生成或創建虛線對。我問這個是因爲,我需要把看起來像這樣的列表:如何在Lisp中獲得虛線對?

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

但我不知道怎麼去點對。 在此先感謝

回答

11

你的代碼中有一個很基本的錯誤:

(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,它都會重新定義函數PLACE-INDEX的GLOBAL。您可能已經在使用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是錯誤的地方來解決你的功課。谷歌搜索也是學習Lisp編程的錯誤方式。

我建議使用閱讀介紹性書籍和使用參考書的好老方法。

這是一個基本的介紹性的Lisp書供下載:Common Lisp: A Gentle Introduction to Symbolic Computation

參考表:小Common Lisp Quick Reference(PDF)和更詳細的Common Lisp Quick Reference

虛線對在Lisp中被稱爲conses

請參閱Common Lisp的真實在線參考,Common Lisp HyperSpec

6

你想要的其他分支閱讀:

(cons (cons (first l) idx) (place-index (+ idx 1) (rest l))) 
1

順便說一下,對於問題本身,這個代碼就可以了:

(defun listFormat (lst) 
    (loop for idx from 1 
     for item in lst 
     collect (cons item idx)))