3

We have a number of clauses (condition body) which we want to give to cond, like so:

(cond (condition1 body1)
      (condition2 body2)
      (condition3 body3))

But imagine that the clauses were first generated via mapcar, which gave the following list:

((condition1 body1)
 (condition2 body2)    
 (condition3 body3))

Let's say that the above list is the content of variable clauses. Now, we would like to pass it to cond, but if we do the following:

`(cond ,clauses)

it results in:

(cond ((condition1 body1)
       (condition2 body2)
       (condition3 body3)))

which does not work, instead of:

(cond (condition1 body1)
      (condition2 body2)
      (condition3 body3))

Is there a way around this problem ?

  • How about just mapcar-ing down the list of clauses and test each condition during that process (you can use a catch and throw done once a condition tests positive to stop the mapcar dead in its tracks), instead of trying to force it into a particular format of (cond (. . .? – lawlist Jul 20 '15 at 0:58
  • How about using apply? – Dan Jul 20 '15 at 1:42
  • Are you inside a macro? Can you give some example code here that shows what you're trying to do on a slightly higher level? – zck Jul 20 '15 at 4:10
  • @Dan, you cannot apply special form, only functions. – Mark Karpov Jul 20 '15 at 4:48
6

You want to splice the list into the new form:

`(cond ,@clauses)

See C-hig (elisp) Backquote RET

You can also "splice" an evaluated value into the resulting list, using the special marker ,@. The elements of the spliced list become elements at the same level as the other elements of the resulting list. The equivalent code without using ` is often unreadable. Here are some examples:

     (setq some-list '(2 3))
          ⇒ (2 3)
     (cons 1 (append some-list '(4) some-list))
          ⇒ (1 2 3 4 2 3)
     `(1 ,@some-list 4 ,@some-list)
          ⇒ (1 2 3 4 2 3)

     (setq list '(hack foo bar))
          ⇒ (hack foo bar)
     (cons 'use
       (cons 'the
         (cons 'words (append (cdr list) '(as elements)))))
          ⇒ (use the words foo bar as elements)
     `(use the words ,@(cdr list) as elements)
          ⇒ (use the words foo bar as elements)
  • 3
    I'd also add the equivalent code without backquote, namely (cons 'cond clauses) – YoungFrog Jul 20 '15 at 5:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.