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))

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.