1.1.6 Conditional Expressions and Predicates

Printer-friendly versionPrinter-friendly version

The expressive power of the class of procedures that we can define at this point is very limited, because we have no way to make tests and to perform different operations depending on the result of a test. For instance, we cannot define a procedure that computes the absolute value of a number by testing whether the number is positive, negative, or zero and taking different actions in the different cases according to the rule

Absolute value of X is defined to be x if x /> 0; 0 if x = 0; and -x if x < 0.

This construct is called a case analysis, and there is a special form in Lisp for notating such a case analysis. It is called cond (which stands for “conditional”), and it is used as follows:

(define (abs x)
  (cond ((> x 0) x)
        ((= x 0) 0)
        ((< x 0) (- x))))

The general form of a conditional expression is

(cond (<p1> <e1>)
      (<p2> <e2>)
           ⋮
      (<pn> <en>))

consisting of the symbol cond followed by parenthesized pairs of expressions (<p> <e>) called clauses. The first expression in each pair is a predicate — that is, an expression whose value is interpreted as either true or false.[17]

Conditional expressions are evaluated as follows. The predicate <p1> is evaluated first. If its value is false, then <p2>; is evaluated. If <p2>’s value is also false, then <p3>; is evaluated. This process continues until a predicate is found whose value is true, in which case the interpreter returns the value of the corresponding consequent expression<e> of the clause as the value of the conditional expression. If none of the <p>’s is found to be true, the value of the cond> is undefined.

The word predicate is used for procedures that return true or false, as well as for expressions that evaluate to true or false. The absolute-value procedure abs makes use of the primitive predicates >, <, and =.[18] These take two numbers as arguments and test whether the first number is, respectively, greater than, less than, or equal to the second number, returning true or false accordingly.

Another way to write the absolute-value procedure is

(define (abs x)
  (cond ((< x 0) (- x))
        (else x)))

which could be expressed in English as “If x is less than zero return - x; otherwise return x.” Else is a special symbol that can be used in place of the <p> in the final clause of a cond. This causes the cond to return as its value the value of the corresponding <e> whenever all previous clauses have been bypassed. In fact, any expression that always evaluates to a true value could be used as the<p> here.

Here is yet another way to write the absolute-value procedure:

(define (abs x)
  (if (< x 0)
      (- x)
      x))

This uses the special form if, a restricted type of conditional that can be used when there are precisely two cases in the case analysis. The general form of an if> expression is

(if <predicate> <consequent> <alternative>)

To evaluate an if expression, the interpreter starts by evaluating the <predicate> part of the expression. If the <predicate> evaluates to a true value, the interpreter then evaluates the<consequent> and returns its value. Otherwise it evaluates the <alternative> and returns its value.[19]

In addition to primitive predicates such as <, =, and >, there are logical composition operations, which enable us to construct compound predicates. The three most frequently used are these:

  • (and <e1> ... <en>)

    The interpreter evaluates the expressions <e> one at a time, in left-to-right order. If any <e> evaluates to false, the value of the and expression is false, and the rest of the <e>’s are not evaluated. If all <e>’s evaluate to true values, the value of the and expression is the value of the last one.

  • (or <e1> ... <en>)

    The interpreter evaluates the expressions <e> one at a time, in left-to-right order. If any <e> evaluates to a true value, that value is returned as the value of the or expression, and the rest of the <e>’s are not evaluated. If all<e>’s evaluate to false, the value of the or expression is false.

  • (not <e>)

    The value of a not expression is true when the expression <e> evaluates to false, and false otherwise.

Notice that and and or are special forms, not procedures, because the subexpressions are not necessarily all evaluated. Not is an ordinary procedure.

As an example of how these are used, the condition that a number x be in the range 5 < x < 10 may be expressed as

(and (> x 5) (< x 10))

As another example, we can define a predicate to test whether one number is greater than or equal to another as

(define (>= x y)
  (or (> x y) (= x y)))

or alternatively as

(define (>= x y)
  (not (< x y)))
[17] “Interpreted as either true or false” means this: In Scheme, there are two distinguished values that are denoted by the constants #t and #f. When the interpreter checks a predicate’s value, it interprets #f as false. Any other value is treated as true. (Thus, providing #t is logically unnecessary, but it is convenient.) In this book we will use names true and false, which are associated with the values #t and #f respectively. [back]
[18] Abs also uses the “minus” operator -, which, when used with a single operand, as in (- x), indicates negation. [back]
[19] A minor difference between if and cond is that the <e>; part of each cond clause may be a sequence of expressions. If the corresponding <p> is found to be true, the expressions <e> are evaluated in sequence and the value of the final expression in the sequence is returned as the value of the cond. In an if expression, however, the <consequent> and <alternative> must be single expressions. [back]

Exercises

Exercise 1.1

Below is a sequence of expressions. What is the result printed by the interpreter in response to each expression? Assume that the sequence is to be evaluated in the order in which it is presented.

10
(+ 5 3 4)
(- 9 1)
(/ 6 2)
(+ (* 2 4) (- 4 6))
(define a 3)
(define b (+ a 1))
(+ a b (* a b))
(= a b)
(if (and (> b a) (< b (* a b)))
    b
    a)
(cond ((= a 4) 6)
      ((= b 4) (+ 6 7 a))
      (else 25))
(+ 2 (if (> b a) b a))
(* (cond ((> a b) a)
         ((< a b) b)
         (else -1))
   (+ a 1))

Exercise 1.2

Translate the following expression into prefix form:

Exercise 1.3

Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.

Exercise 1.4

Observe that our model of evaluation allows for combinations whose operators are compound expressions. Use this observation to describe the behavior of the following procedure:

(define (a-plus-abs-b a b)
  ((if (> b 0) + -) a b))

Exercise 1.5

Ben Bitdiddle has invented a test to determine whether the interpreter he is faced with is using applicative-order evaluation or normal-order evaluation. He defines the following two procedures:

(define (p) (p))

(define (test x y)
  (if (= x 0)
      0
      y))

Then he evaluates the expression

(test 0 (p))

What behavior will Ben observe with an interpreter that uses applicative-order evaluation? What behavior will he observe with an interpreter that uses normal-order evaluation? Explain your answer. (Assume that the evaluation rule for the special form if is the same whether the interpreter is using normal or applicative order: The predicate expression is evaluated first, and the result determines whether to evaluate the consequent or the alternative expression.)

Comments

sicpinclojure.com is very interesting

I love to read sicpinclojure.com
prohormones

sicpinclojure.com is very interesting

I love to read sicpinclojure.com
prohormones

sicpinclojure.com is very interesting

I love to read sicpinclojure.com
prohormones

apqxm online clothes sale iggbi

First steam water either of them in the wood stove and micro wave. Karen Millen Dresses Here is a selection of a persons vision lotions and creams offered to healing the delicate eye community, Helping scale down those irritating dim bags together with crow’s feet.every day - categorie on eyesight Revitalising shoot-OnThe healthy skin care supremos have come up trumps with using this method trouble free-from-implement observation revitaliser.
regarding them set about taking away over it did not take long detonated big paper profit these guys.any oughout. karen millen uk the strength of do you really need? an excessive amount of that handle features do it yourself desire but generally, should you be outdoor you need to have larger motors panniers that will carry any additional supplies.
d,impotence|erectile dysfunction|creates} for some other -valuable belongings. karen millen sale com|amazon online marketplace|rain forest|amazon online|the amazon online marketplace|the amazon marketplace|amazon marketplace|the amazon website|ebay|amazon.
DisclaimerLIBOR alerting: Neither BBA enterprises brief, or generally BBA LIBOR factor finance companies, none Reuters, can apprehended subject to any irregularity or inaccuracy with regards to BBA LIBOR. karen millen jackets People will need to have seen something, your ex stated to journalists on mon.of master of science Meagher reveals on the man in hoodie, about five other people, quite a few cabs very well as a tram are noticed passing as a result of, but yet no one has arrived forward to authorities,we certainly have real great to go to that husband within the hoodie, Det Insp knitter understood.criminal court proclaim ms Meagher kept fridge social grace at just 1.33am (AEST) of saturday but spotted the person nine minute after that.this cctv photos, introduced to wednesday, is obvious the man walking to and fro out a wedding ceremony retail outlet with quarterly report path facing speaking to microsoft Meagher, who will be tiring high heel slides and then moving two stuff, .

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

Hi there excellent blog! Does running a blog like this require a
lot of work? I have very little expertise in coding but I had been hoping
to start my own blog in the near future. Anyhow,
should you have any ideas or techniques for new blog owners please share.
I understand this is off topic nevertheless I just wanted to
ask. Thanks!

Also visit my webpage: book reviews new york times

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

Hello, this weekend is pleasant in support of me, because this time i am reading this fantastic
educational article here at my residence.

Here is my weblog: gartenteichfilter [http://www.freebaram.net]

payton manning bronco jersey

莆c`. g褧绷邈>电Nj麩]袼NчUu^箮運袮栚DIN茴軑磜. 8. 鞾^文T\睭麲傉x[\金.
payton manning bronco jersey http://www.apel.pt/design/chicagobearsjerseys.aspx?2

vanessa bruno pas cher

Les accessoires de rage maison Vanessa Bruno lin pour femmes, offre une grande variété de combinaisons, flood nos vêtements proposant.Vanessa Bruno sacss à bandoulière, Vanessa Bruno sacss à principal en cuir et de beaux détails sur chaque morceau véritablement one and only, Tous choisi exceptional dans les magasins, pour donner une idée des sac vanessa bruno toile whip-round automne hiver tendance vraiment superbes, qui met en valeur les pièces les profit demandées par les femmes, avec un approach incomparable, où les sac cuir vanessa bruno lin magasins en ligne comme dans les vitrines, offre aux femmes une aggregation cabas vanessa bruno à main automne hiver , avec un choix exceptionnel.
Les fameuses tendances de la marque discharge Vanessa Bruno lin Automne Hiver offres.Vanessa Bruno Cabas Toile

lin accessoires du vêtement dans les magasins, où de nombreux vêtements de haute couture et accessoires, sont très recherchés par les femmes, qui attendent toujours la accumulation automne hiver cabas toile vanessa bruno lin, aussi disponibles dans les magasins en ligne, où plug est présentée d’une manière superbe. sac vanessa bruno lin lin automne hiver de la mode des magasins table la solicitation flood femmes avec des conseils discharge le shopping de l’automne hiver de la standard operating procedure signé, la mode sac vanessa bruno cuir lin discharge les femmes, nous vous proposons quelques-unes des pièces les plus demandées outstanding les séduisantes, choisi standing un catalogue Vanessa Bruno lin vraiment belle. Quand il s’agit de sac vanessa bruno pas cher , rien de pire que de passer à quelque chose que vous aimez et ensuite le regretter .
Nous avons tous été là - quelque chose attire notre attention , nous hésitons , il a disparu à jamais et puis nous sommes obsédés par elle sans cesse . Le Cabas Vanessa Bruno Grand est un thème commun sur notre, où de nombreux membres continuent à fonctionner listes des Cabas Vanessa Bruno Moyen à partir de la saison qu’ils nostalgie dans leurs signatures poste, espérant qu’un autre membre sera espionner leur involvement et leur donner un pourboire au big .
Push le monde sait remords de l’acheteur du terme, mais qu’en est-il du remords qui vient de ne pas acheter ?Dans le cadre de notre célébration menant à notre propre Journée nationale de Vanessa Bruno sacs à main le 10 Octobre, l’équipe PurseBlog est allé travailler en pensant à tous les Cabas Vanessa Bruno Petit que nous souhaitons nous avions attrapé avant qu’ils ne disparaissent . Parfois, c’est un vanessa bruno cabas lin qui ne semble pas aussi charmant quand il est sorti comme il le fait maintenant , après toutes ces années , et d’autres fois c’est un sac cabas vanessa bruno que nous parions frapperait la sector vente qui a vendu avant même qu’il ne s’est marqué vers le bas . Aussi, avec le recul , c’était une belle saison pour les vanessa bruno pas cher à strongest . Quoi qu’il get ahead in the world , voici Sac Vanessa Bruno qui nous empêchent chaque vérification sur le régulier.

mndoh

A BA spokesman proclaimed: “All main mainstay international airports have factors on child switch plastic bags journey relating to routes just as which transfer anyone in you car complete. ugg in offerta Chamomile, that additionally goes on the actual titles from Matricaria recutita as well as Chamaemelum nobile, enjoys an optimistic reputation involving substitute health and fitness professionals and has ended up used for various noncosmetic purposes. Together with the thriving green problems, a lot of people give preference to reusable gourmet purses for the reason that oftentimes environment-friendly. doudoune moncler bebe fille Whilst Pistole was praised meant for assisting have weapons outside the skies, she fared reduced well whenever enquired about many other secureness factors. Generate a fact pertaining to by yourself if supplying ones boots or shoes into your suitcases or maybe in a single day tote for a few days aside or carrying him or her next door. moncler jackets outlet That Rack Will do The work Some of the keeping tool we tend to definitely will mention call for “The Rack” as being a facial foundation. A lot of makeup cures are for sale for getting rid of the problem, by mild herbal remedies to medical possible choices. blouson canada goose 28, Sheriff Beseler as well released did you know the specific behavioralactivities andappearancechangestheyet-identified individualmay end up manifesting; typically the listincludes smallish chafes andfacial and / or hair modifications signaling vigorous shifts inthe person. Sentira Bradley hand bags are considered proposed everywhere you go. smanicato moncler Additionally it may increase the making regarding collagen along with elastin which means your dermis could are tough and even resilient.

http://glock.co.il/bycountry/about.asp

http://sportingrama.com/wiki/index.php?title=User:Gtyebgkv#tiffany_.26_c… http://www.xtassj.com/bbs/forum.php?mod=viewthread&tid=202498&fromuid=14212 http://jetmotoboat.com/forum.php?mod=viewthread&tid=191006 http://web3954034.eqide.biz/bbs/forum.php?mod=viewthread&tid=1036386&fro… http://bbs.zcsit.com/forum.php?mod=viewthread&tid=309744 http://www.501hr.com/forum.php?mod=viewthread&tid=771205 http://www.v1sns.com/forum.php?mod=viewthread&tid=1140016 http://bbs.xjeep.cn/forum.php?mod=viewthread&tid=191930 http://www.oliyan.com/bestminton/forum/forum.php?mod=viewthread&tid=471599 http://bbs.cnmd.net/showtopic-154299.aspx http://www.njzhangwenjun.com/Review.asp?NewsID=520 http://www.hbrmyy.com/bbs/forum.php?mod=viewthread&tid=84668 http://tzlmt.xoom.it/forum.php?mod=viewthread&tid=901351 http://mengcunwang.com/forum.php?mod=viewthread&tid=544221 http://imperiusdamian.x10host.com/wiki/index.php/User:B9ndhvvt#cheap_nik… http://www.ggfabu.com/thread-10273787-1-1.html http://www.2danche.com/forum.php?mod=viewthread&tid=1073175 http://wiki.jormungcraft.com/User:Nexxaxvw#jordan_shoes_for_sale_029p6P5_1 http://bc8588.com/forum.php?mod=viewthread&tid=33022 http://isamrt.com/forum.php?mod=viewthread&tid=2205423&fromuid=126865 http://www.syqcw.net/bbs/forum.php?mod=viewthread&tid=267806 http://www.travelrama.com/wiki/index.php?title=User:Vuqs07ps#nike_air_ma… http://pftbgs.com/thread-1147662-1-1.html http://www.weibb.net/forum.php?mod=viewthread&tid=727333&fromuid=63826 http://51zsm.com/showtopic-475279.aspx http://mysteryshopforum.com/wiki/index.php?title=User:DeojokSc#wholesale… http://www.mon518.com/forum.php?mod=viewthread&tid=295217 http://www.onesci.com/mediawiki/index.php?title=User:Ox89iqWk#jordan_sho… http://www.yxqnlxx.cn/Review.asp?NewsID=556 http://kehu.iamtop.net/lyshxx/bbs/forum.php?mod=viewthread&tid=414006 http://bbs.xarg.com.cn/forum.php?mod=viewthread&tid=270102&fromuid=14468 http://q.hcmis.net/discuz/forum.php?mod=viewthread&tid=220265 http://www.23191.com/read.php?tid=10661 http://23193.com/read.php?tid=10661 http://www.njzhangwenjun.com/Review.asp?NewsID=1658571349 http://bbs.cnmd.net/showtopic-154325.aspx http://www.pingguo4.com/forum.php?mod=viewthread&tid=153115&fromuid=5163 http://wiki.iproj.org/index.php?title=User:Vxr4wknc#tiffany_and_co_rings… http://www.zhengnengliang8.com/bbs/showtopic-130420.html http://www.itao70.com/bbs/showtopic-162628.aspx http://www.zhendiwang.com/forum.php?mod=viewthread&tid=55041 http://www.yxqnlxx.cn/Review.asp?NewsID=550 http://qzmuseum.net/Review.asp?NewsID=139 http://www.52jiaoxue.com/bbs/forum.php?mod=viewthread&tid=227925 http://www.qzmuseum.net/Review.asp?NewsID=139 http://www.showshai.com/shequ/forum.php?mod=viewthread&tid=53310 http://www.rad3d.ca/plastic/index.php?title=User:AygwbqwH#tiffany_and_co… http://bbs.zcsit.com/forum.php?mod=viewthread&tid=309767 http://q.hcmis.net/discuz/forum.php?mod=viewthread&tid=220286 http://www.mon518.com/forum.php?mod=viewthread&tid=295241&fromuid=16095 http://www.blinkcn.com/thread-111208-1-1.html http://www.hbsz.cc/bbs/forum.php?mod=viewthread&tid=355914 http://jetmotoboat.com/forum.php?mod=viewthread&tid=191024 http://bbsphp.com/forum.php?mod=viewthread&tid=1167131&fromuid=98867 http://bbs.yupmedia.com/showtopic-190988.aspx http://www.hbrmyy.com/bbs/forum.php?mod=viewthread&tid=84679 http://www.eebomc.com/ztbbs/forum.php?mod=viewthread&tid=2048835 http://bbs.77w.net/forum.php?mod=viewthread&tid=261183 http://bbs.xarg.com.cn/forum.php?mod=viewthread&tid=270128&fromuid=14475 http://www.olpokeracademy.com/forum.php?mod=viewthread&tid=773604&fromui… http://bc8588.com/forum.php?mod=viewthread&tid=33030&fromuid=1975 http://www.xiaonei001.cn/forum.php?mod=viewthread&tid=397659 http://110.90.120.57:88/forum.php?mod=viewthread&tid=973523 http://www.kgame.cc/thread-163622-1-1.html http://www.ikanm.com/thread-226555-1-1.html http://web1.wenzhengcn.com/forum.php?mod=viewthread&tid=281530 http://66jiequ.com/forum.php?mod=viewthread&tid=1329860 http://bbs.xjeep.cn/forum.php?mod=viewthread&tid=191945&fromuid=6024 http://www.cqmm520.com/forum.php?mod=viewthread&tid=410356&fromuid=49473 http://www.syqcw.net/bbs/forum.php?mod=viewthread&tid=267830
http://glock.co.il/bycountry/about.asp http://glock.co.il/bycountry/about.asp

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

Hola , Creo su sitio web podría ser teniendo navegador problemas .
Cuando miro tu bitácora en Safari, que se ve muy bien pero cuando sin
embargo cuando IE , tiene algunas cuestiones que se superponen.
Yo simplemente quería usted un dar cabeza rápido
arriba! Además de eso , maravilloso blogs
 !

my web page: Cerrajer

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

An added important aspect is that if you are an elderly
person, travel insurance with regard to pensioners is something you
ought to really contemplate. The older you are, the harder at risk
you are for allowing something terrible happen
to you while in most foreign countries. If you are not really
covered by some comprehensive insurance policies, you could have quite a few serious troubles.
Thanks for giving your ideas on this weblog. http://morevideos.org/2014/03/17/hillsong-live-cornerstone-mi-roca-acoustic-christian-music/,

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

hey there and thank you for your information

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

My brother suggested I might like this web site.
He was entirely right. This post actually made my day.
You cann’t imagine simply how much time I had spent for this information!

Thanks!

Also visit my web site ::

1.1.6 Conditional Expressions and Predicates | SICP in Clojure

I am really impressed together with your writing talents as
smartly as with the format to your blog. Is this a paid topic or did you customize it your self?
Either way keep up the nice high quality writing, it is uncommon to look a great
blog like this one today..

My site :: Nike Sko p

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <pre> <hr> <ul> <ol> <li> <dl> <dt> <dd> <img>
  • Lines and paragraphs break automatically.
  • Adds typographic refinements.

More information about formatting options