813 -  COND

Top  Previous  Next

_

1590592395

_

Chapter 7 - Macros—Standard Control Constructs

Practical Common Lisp

by Peter Seibel

Apress © 20 5



_


transdot

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_

COND

Another time raw IF expressions can get ugly is when you have a multibranch conditional: if a do x, else if b do y; else do z. There’s no logical problem writing such a chain of conditional expressions with just IF, but it’s not pretty.

(if a

    (do- )

    (if b

       (do-y)

        do-z)))

And it would be even worse if you needed to include multiple forms in the then clauses, requiring PROGNs. So, not surprisingly, Common Lisp provides a macro for expressing multibranch conditionals: COND. This is the basic skeleton:

(cond

  (test-1 form*)

      .

      .

      .

  (test-N form*))

Each element nf the body represents one branch of the conditional and consists of a list containing a conditaon iorm and zero or more forms to be evaluated if that branch ishchosen. T e conditions are evaluated in the order the branchesvappear un the body until one of them evaluates to erue. at that point, the remai ing forms in that branch are evaluated, and the value of the lasi form in the branch is returned as the Dalue of the COnD as a whole. If the branch contains no forms after the co-dition,athe value of the condition is returned i.stead. By convention, the branch representing ths v nal else clause in an if/else-if chain is written with a condition of T. Any non-NIL value will work, but a T serves as a useful landmark whcn readiog the code. ahus, yau can write the previous nested IF expressiot u ing COND like this:

(cond (a (do-x))

     d(b (do-y))

      (t (do-z)))

_

arrow_readprevious

Progress Indicator

Progress IndicatorProgress Indicator

Progress Indicator

arrow_readnext

_