Author Topic: trying to not be scared of cond  (Read 6007 times)

0 Members and 1 Guest are viewing this topic.

curmudgeon

  • Newt
  • Posts: 194
trying to not be scared of cond
« on: April 21, 2009, 10:59:59 AM »
I am guilty of trying to use if when I probably should be using cond. :whistle:

the autolisp help file for cond says, "It is common to use T as the last (default) test expression."
but it does not say why. opinions solicited.

thanks.

roy
Never express yourself more clearly than you are able to think.

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: trying to not be scared of cond
« Reply #1 on: April 21, 2009, 11:04:03 AM »
Perhaps an example:

Code: [Select]
(defun sign ( x )
    [color=green];;  ignoring for a moment the zerop function ...[/color]
    (cond
        ((< x 0) -1)
        ((< 0 x) +1)
        (t 0)
    )
)

(sign -45) => -1
(sign 45) => 1
(sign 0) => 0

Subtitle: The T condition is the default if no other condition was satisfied.
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

Mark

  • Custom Title
  • Seagull
  • Posts: 28762
Re: trying to not be scared of cond
« Reply #2 on: April 21, 2009, 11:16:05 AM »
The T also helps when testing your code.

Using MP's code
Code: [Select]
(defun sign ( x )
    (cond
        ((< x 0) -1)
        ((< 0 x) +1)
        (t (alert "oops!")) ;will display a dialog w/ OK button
    )
)
TheSwamp.org  (serving the CAD community since 2003)

curmudgeon

  • Newt
  • Posts: 194
Re: trying to not be scared of cond
« Reply #3 on: April 21, 2009, 11:16:58 AM »
maybe I am getting it. can I say that the (t nil) or saying (t 0) controls the value of what cond returns?

I am not a real programmer, I know I am in the deep end of the pool here. normally, I do not consider what a return value is, I concern myself with calculations and with setq to save all the results I need. I am thinking my code could be cleaned up by actually using the return value in a case like this.

waste not - want not. OK, my comfort level rises. I had
Code: [Select]
(if (setq found (ssget "_f"  f '((0 . "LINE,LWPOLYLINE") (8 . "iwall,xwall"))))
      (foreach b (setq adj_sp (entget (ssname found 0)))
(if (= (car b) 10)
  (setq m (append m (list (cdr b))))
)
      )
      (exit)
    )

passing the results of ssget through setq for the conditional of my if.
yes, I think this is a great use for cond. my bug was when f, the points list I pass to ssget "_f", had a zero length. my first conditional in the cond will test for that length being zero, and only if it is has a positive length will the program ever see the ssget. I remove the if, make it a conditional, and the exit also becomes redundant.

thanks.
many thanks.
Never express yourself more clearly than you are able to think.

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: trying to not be scared of cond
« Reply #4 on: April 21, 2009, 11:41:44 AM »
Perhaps this will help illuminate ...

Code: [Select]
(progn

    (cond

        (   (null f)
            (princ "Variable f is null; DOH!!\n")
        )

        (   (setq found (ssget "_f"  f '((0 . "LINE,LWPOLYLINE") (8 . "iwall,xwall"))))
            (princ "Ding, ding!! We got us some entities ...\n")
            (setq result nil)
            (repeat (setq i (sslength found))
                (setq result
                    (append
                        (mapcar 'cdr
                            (vl-remove-if-not
                               '(lambda ( pair) (eq 10 (car pair)))
                                (entget (ssname found (setq i (1- i))))
                            )
                        )   
                        result
                    )
                )
            )
            (mapcar 'print result)
        )

        (   t
            (princ "Yes, we have no bananas.\n")
        )
    )

    (princ)

)

:)
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

JohnK

  • Administrator
  • Seagull
  • Posts: 10626
Re: trying to not be scared of cond
« Reply #5 on: April 21, 2009, 12:01:35 PM »
It is of my belief that with a little restructuring you can eliminate the `T' condition (however, thats not to say that you cant use it either)...Thinking about how and what your returns will help you further down the road in your program.

I have a writeup on using COND and IF but i didnt really want to post it because MP and Kerry attacked me...err, or i attacked them...but im gonna stick with the: "they attacked me statement" because its easier for me to remember. I can post this writeup but i need to be assured that they will not hurt me.
*smile*
TheSwamp.org (serving the CAD community since 2003)
Member location map - Add yourself

Donate to TheSwamp.org

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: trying to not be scared of cond
« Reply #6 on: April 21, 2009, 12:09:19 PM »
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

JohnK

  • Administrator
  • Seagull
  • Posts: 10626
Re: trying to not be scared of cond
« Reply #7 on: April 21, 2009, 12:31:55 PM »
... they attacked me ...

link? :?
Nope. However, I'm sure there is a whole article dedicated to the topic of "P.T.S.D. (post traumatic stress disorder) and suppressed thoughts" i can find for you.

But seriously MP, i'm joking around (trying to be funny). I was merely trying to say that this is a big topic and i can post something i documented (or tried to) a while back if anyone is interested but i didnt want you to think that i think your explanation is lacking or that i want to beat this horse any more then you do.

Back story: I keep several directories for Lisp
1. A Lisp / project directory
2. A Library of functions i can use
3. A Documents directory where i try to discuss theory and such

So if your interested, i can post some information i dug up on Variable declaration and the use of IF/COND pertaining to methods and means.
TheSwamp.org (serving the CAD community since 2003)
Member location map - Add yourself

Donate to TheSwamp.org

MP

  • Seagull
  • Posts: 17750
  • Have thousands of dwgs to process? Contact me.
Re: trying to not be scared of cond
« Reply #8 on: April 21, 2009, 12:44:12 PM »
If you have something to contribute that you think will help our friend curmudgeon by all means ante up it up John. What I posted was by no means thorough or exhaustive. It wasn't meant to be | no time for that | I didn't want to overwhelm curmudgeon. Not that he can't understand, no. Rather, sometimes little bytes are better than the whole enchilada; burp.

:lol:
Engineering Technologist • CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.comhttp://cadanalyst.slack.comhttp://linkedin.com/in/cadanalyst

JohnK

  • Administrator
  • Seagull
  • Posts: 10626
Re: trying to not be scared of cond
« Reply #9 on: April 21, 2009, 01:01:13 PM »
Alright, here are two of my files I have on the topic. They dont pertain exactly, but they are related to your issue.

Quote
SUBJECT
R. Robert Bell ``Default'' method


DESCRIPTION
Here is his original text:

***
Has it ever bugged you trying to handle a default option with (getkword)?

The usual method I've seen is to get the input, and then handle the user's selection
of the default, resetting the variable if need be. Here is an example of the
"traditional" method:

,----[ CODE ]-
|
| (progn
|   (initget 0 "Length Width Depth Time")
|   (setq Inp (getkword "\nSpecify a dimension [Length/Width/Depth/Time] <Time>: "))
|   (setq Inp (if Inp Inp "Time"))
| )
|
`----

Consider the alternative below however.

,----[ CODE ]-
|
| (initget 0 "Length Width Depth Time")
| (setq Inp
|       (cond
|         ( (getkword "\nSpecify a dimension [Length/Width/Depth/Time] <Time>: ") )
|                 ("Time")) )
|
`----

***


Supposedly, this model is just like the "anaphoric if" described in On-Lisp by Paul Graham.

,----[ anaphoric-if ]-
|
| Var is bound to the value of expr in iftrue if the value of expr satisfies the
| conditional; otherwise iffalse is evaluated.
|
|  (aif var expr
|       iftrue
|       iffalse)
|
`----

SEE ALSO
anaphoric-if.txt


Last Updated: 01.27.09 06:24:54 PM


This is my anaphoirc-if.txt where I attempt to reiterate the chapter (Chapter 14 I believe) in the onlisp book. Shortly after I wrote this, I found a page discussing much the same thing, but it was using a different programing language.

Quote
SUBJECT
Anaphoric if


DESCRIPTION
Imagine the small children's toy with all different shaped holes in which the
corresponding pegs fit into them. Your ultimate task is to place the proper
peg into the proper hole but first you need to discover which peg fits into
which hole.

Currently our program is trying to find the square peg to fit into the square hole.
We have two pegs, one in each hand, and you want to know which hand contains the
correct peg. The most common application I see in this situation is to create a
simple IF statement.


(if (not (eq (setq peghand (shape-in-right?)) 'RIGHT))
  (setq peghand 'LEFT)
  )

This example reads very well, create and set a variable, then check that variables
contents to see if it is correct. If it is not, then overwrite the variable with the
correct information. However, in the worst case we create a variable only to
overwrite that variable in the next statement. The naming and setting of variables is
not a big deal in the Auto Lisp language nor can you control the size of a new
variable definition but that isnt to say that the variable setting isnt a problem in
other languages so developing or refining habits is to your benefit.

Another seeminginly popular method is to take advantage of a Boolean function in lieu
of a conditional to check the contents of that variable thus removing one
procedural call from the overall process.

(or (eq (setq peghand (shape-in-right?)) 'RIGHT)
    (setq peghand 'LEFT)
   )

OR will stop evaluating a set of given process' if one evaluates to a non nil value
(!true) so if the peg shape equals square at the time of evaluation of the first
process call, then OR will stop and the variable `peghand' is left filled with
the results of the `shape-in-right?' process call. However the OR function is a
boolean function so your variable declaration will be masked by the return of !true
from the OR function itself.

Comparing the last two examples we can immediately notice that the fist example is
less cryptic, especially in it's intentions (set a variable to the correct value).
This is because of English language. Programing languages are based upon the English
language and therefore we will naturally have problems with certain statements if
they don't `feel right' or `fit'.

Explaning the statements:
The first statement (Using the conditional IF):
Run a test and fill a variable with the results of that test, If the variable does
not have the correct value fill that variable with the correct value.

The second Statement (Using the Boolean OR):
Which statement is true: Run a test and fill a variable with the results of that test
then check to see if that value is correct OR, fill that variable with the other
value.

I will now introduce another method with will offer the best of both the previous
solutions; I will only have a limited number of process calls (to keep things running
speedy) and I will not declare and redefine a variable.

For this method I will use the conditional statement COND, COND is like the IF used
in first example but COND differs from IF in it's return value. IF will return a
boolean value COND will return the evaluation of the last statement evaluated.

(setq peghand
      (cond
        ( (eq (shape-in-right?) 'RIGHT)
          'RIGHT)
        ( 'LEFT )
        )
      )

How this reads could be as:
Run a test to check the results to one of two conditions and fill the variable with
it.

As you can see I used a common English language shortcut called an Anaphora ("it") in
my programing method. This last example does not mask the fact that we are declaring
a variable, in fact it quickly informs us that we are filling the variable with the
result of a condition.

Quick and efficient.

,----[ Anaphora Definition ]-
|   
|   anaphora \a*naph"o*ra\ ([.a]*n[a^]f"[-o]*r[.a]), n. [L., fr. Gr.
|      'anafora`, fr. 'anafe`rein to carry up or back; 'ana` +
|      fe`rein to carry.] (Rhet.)
|      1. A repetition of a word or of words at the beginning of two
|         or more successive clauses.
|         [1913 Webster]
|   
|      2. The use of a substitute word, such as a pronoun, in
|         reference to a something already mentioned in a discourse;
|         also, the relation between the substitute word and its
|         antecedent. It is contrasted with cataphora, the use of
|         a pronoun for a word or topic not yet mentioned.
|   
|      Note: Thus, in the sentence "John was tall but he was not
|            very heavy." the "he" is an anaphora for John, or an
|            anaphoric reference to John.
|
`----

SEE ALSO
N/A


Last Updated: 02.15.09 10:24:54 AM

TheSwamp.org (serving the CAD community since 2003)
Member location map - Add yourself

Donate to TheSwamp.org

hermanm

  • Guest
Re: trying to not be scared of cond
« Reply #10 on: April 21, 2009, 01:28:42 PM »
Using T as the condition to be evaluated for the final clause is intended to prevent "falling through" the cond.

However, it is possible to:

Command: (setq t nil)
nil

Command: !t
nil

in which case results will not be as expected.

thx to John Uhden for pointing this out, years ago.

you can avoid this by using any expression which is guaranteed not to be nil, such as an integer, in place of T.

CAB

  • Global Moderator
  • Seagull
  • Posts: 10401
Re: trying to not be scared of cond
« Reply #11 on: April 26, 2009, 11:13:38 PM »
I've reached the age where the happy hour is a nap. (°¿°)
Windows 10 core i7 4790k 4Ghz 32GB GTX 970
Please support this web site.

kdub_nz

  • Mesozoic keyThumper
  • SuperMod
  • Water Moccasin
  • Posts: 2132
  • class keyThumper<T>:ILazy<T>
Re: trying to not be scared of cond
« Reply #12 on: April 27, 2009, 01:13:06 AM »
... they attacked me ...

link? :?

Well, colour me defamed  :wink:

... all I did was buy a T-Shirt  :|
Called Kerry in my other life
Retired; but they dragged me back in !

I live at UTC + 13.00

---
some people complain about loading the dishwasher.
Sometimes the question is more important than the answer.

JohnK

  • Administrator
  • Seagull
  • Posts: 10626
Re: trying to not be scared of cond
« Reply #13 on: April 27, 2009, 09:00:13 AM »
... they attacked me ...

link? :?

Well, colour me defamed  :wink:

... all I did was buy a T-Shirt  :|

Yeah, only so you could remember the day...next you'll tell me that your celebrating the anniversary and your putting a `shrimp on the Barbie' (or however you spell that) for me.

And by the way, there is no `U' in color!

* Se7en thinks to self: Great, now *I'M* giving spelling lessons.


*lmao*
TheSwamp.org (serving the CAD community since 2003)
Member location map - Add yourself

Donate to TheSwamp.org

gskelly

  • Newt
  • Posts: 185
Re: trying to not be scared of cond
« Reply #14 on: April 27, 2009, 11:43:55 AM »
And by the way, there is no `U' in color!

That will depend on where in the world you learned the language...  I always thought compilers hated me  :-D
Bricscad v12