9. Conditionals

In Common Lisp, conditional structures allow you to run code based on conditions. The most basic one is if:

(if (> 5 3)
    "5 es mayor que 3"
    "5 no es mayor que 3")

The structure is (if condition then else). If the condition is true (any value other than nil), the then expression is executed. If it is false (nil), the else expression is executed.

* (if (> 10 20)
      "Esto no se ejecutará"
      "Esto sí se ejecutará")
"Esto sí se ejecutará"

If you need to run multiple expressions in one of the branches, you can use progn:

(if (> x 0)
    (progn
      (print "El número es positivo")
      (print "Continuamos con el programa")
      x)
    (print "El número no es positivo"))

For cases where you only care about running code when the condition is true, use when:

(when (> x 0)
  (print "El número es positivo")
  (print "Haciendo más cosas...")
  x)

And for the opposite case, when you only care about running code if the condition is false, use unless:

(unless (zerop x)
  (print "El número no es cero")
  (/ 100 x))

For multiple chained conditions, the most common structure is cond:

(cond
  ((> x 0) 'positivo)
  ((< x 0) 'negativo)
  (t 'cero))

Each line inside cond is a clause with the format (condition result). They are evaluated in order until a true condition is found. The letter t (true) in the last clause acts as the default case, similar to else in other languages.

You can have multiple expressions in each clause:

(cond
  ((> x 100)
   (print "Número muy grande")
   'grande)
  ((> x 0)
   (print "Número positivo")
   'positivo)
  (t
   (print "Número no positivo")
   'otro))

Another alternative is case, useful when you compare a value against multiple constants:

(case (day-of-week)
  (monday 'inicio-semana)
  (friday 'fin-semana)
  ((saturday sunday) 'fin-de-semana)
  (otherwise 'entre-semana))
Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

Building SPAs with Django and HTML Over the Wire: Learn to build real-time single page applications with Python

The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.

Buy the book

Help me keep writing

Every coffee gives me a push toward the next article.

Comments

There are no comments yet.