Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lisp: How to write an if statement with multiple conditions?

I understand how to write an if statement with an individual condition. For example:

(if (> a 20))

However, after researching online, I found no resources explaining how to write an if statement with multiple conditions (for example, checking if a > 20 or a < 10). How do I write an if statement with multiple conditions in Lisp?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The if special form is the same no matter what:

(if test-expression 
    true-expression
    false-expression)

If you want something to happen if both a is above 20 or below 10 you just do:

(if (not (<= 10 a 20)) ; same as (or (> 20 a) (< 10 a))
    true-expression
    false-expression)

But I get it. What if you have two expressions where one of them true should trigger, then you can use or:

(if (or (> 20 a) (< 10 a))
    true-expression
    false-expression)

Now and and or are macros for nexted ifs. Eg. The expression above can be done like this:

(if (> 20 a)
    true-expression
    (if (< 10 a)
        true-expression
        false-expression)))

Where true-expression is the same expression both places.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading