Reputation: 215
I've searched google and other places for a while but I can't find out how to generate or create dotted pairs. I ask this because, I need to turn a list that looks like this:
(X Y Z)
To a list that is in this format:
((X . 1) (Y . 2) (Z . 3))
Where the numbers represent the index. I have a function that turns the list into the format of
(X 1 Y 2 Z 3)
Here is that function:
(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))
But I'm not sure how to get dotted pairs. Thanks in advance
Upvotes: 1
Views: 2857
Reputation: 118
And by the way, for the question itself, this code will do:
(defun listFormat (lst)
(loop for idx from 1
for item in lst
collect (cons item idx)))
Upvotes: 1
Reputation: 139411
Your code has a very basic mistake:
(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))
Don't nest DEFUN. That's just wrong. DEFUN defines a global function. Whenever you run listFormat, it redefines the GLOBAL function PLACE-INDEX. You may have seen similarly nested functions in SCHEME using DEFINE. In Common Lisp you should not use DEFUN for a nested local function.
In Lisp local functions are defined with FLET or LABELS (for recursive functions).
(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)))
Also Stackoverflow is the wrong place to solve your homework. Google searches is also the wrong way to learn Lisp programming.
I propose to use the good old way of reading an introductory book and using a reference.
Here is a basic introductory Lisp book for download: Common Lisp: A Gentle Introduction to Symbolic Computation.
Reference sheets: a small Common Lisp Quick Reference (PDF) and a more detailed Common Lisp Quick Reference.
Dotted pairs are called conses in Lisp.
See the real online reference for Common Lisp, the Common Lisp HyperSpec.
Upvotes: 11
Reputation: 5218
You want the else-branch to read:
(cons (cons (first l) idx) (place-index (+ idx 1) (rest l)))
Upvotes: 6