Mike Manilone
Mike Manilone

Reputation: 590

Create a list of pairs from a list

I'm new to Lisp and have no idea how to write this...

You give: ("Test" "TEST" "third" "the last")
You get:  (("A" . "Test") ("B" . "TEST") ("C" . "third") ("D" . "the last"))
Function: (defun choices (&rest choices))

In C, I can just write a for for this, but Lisp can't +1 to string and loop doesn't have a counter, either... Could someone please give me a sample?

Upvotes: 1

Views: 147

Answers (2)

Michał Kwiatkowski
Michał Kwiatkowski

Reputation: 9764

You can concatenate two lists in the way you described by simply doing mapcar+cons:

(mapcar #'cons '("A" "B" "C" "D") '("Test" "TEST" "third" "the last"))
; => (("A" . "Test") ("B" . "TEST") ("C" . "third") ("D" . "the last"))

Since the second list is given, now the problem is only in generating the ABCD list. That can be achieved with loop and code-char:

(loop for i from 65 to 68 collect (string (code-char i)))
; => ("A" "B" "C" "D")

Combining those two into an answer and tailoring it to your specific problem should be easy now.

Upvotes: 1

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

I would write something like this:

(defun  choices (&rest choices)
  (loop for i from 1 to 26
        and item in choices
        collect (cons (string (digit-char (+ 9 i) 36))
                      item)))

The above code has no error checking for more than 26 choices (and you didn't specify how to handle them if it's not an error).

You could use CHAR-CODE and CODE-CHAR to "increment a character", but the encoding they provide is not standardized (only some properties of it are guaranteed). With DIGIT-CHAR in radix 36, we're guaranteed to get the English alphabet (uppercase) for weights 10 to 35.

And of course, LOOP has a lot of things, including whatever counters you want.

Upvotes: 2

Related Questions