typestar

Qué cuenta como verdadero y nil en Clojure

Solo nil y false cuentan como falso; or y and lo vuelven valores por defecto.

;; only nil and false are falsey: 0, "" and [] are all truthy
(defn truthy? [x] (if x true false))
(println (truthy? 0) (truthy? "") (truthy? []) (truthy? nil))

;; or returns its first truthy value; and returns the last one
(def jar {:label "cumin" :grams 0})
(def shelf-name (or (:name jar) (:label jar) "unlabeled"))
(println shelf-name (and (:grams jar) (:label jar)) (and nil :skipped))

;; if-let binds and tests in one step; the else branch sees no binding
(defn jar-note [rack spice]
  (if-let [grams (get rack spice)]
    (str spice " holds " grams " g")
    (str spice " is missing")))

;; when-let skips its body entirely when the binding comes up nil
(when-let [low (seq (filter #(< (val %) 5) {:mace 2 :dill 40}))]
  (println "low jars:" (map key low)))
(println (jar-note {"mace" 2} "mace") (jar-note {} "anise"))

Cómo funciona

  1. truthy? informa que 0, "" y [] cuentan todos como verdadero.
  2. or toma el primer valor verdadero para shelf-name, y and devuelve el último cuando todos se cumplen.
  3. if-let vincula grams solo si la búsqueda acierta, y when-let salta su cuerpo cuando seq da nil.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
19
Caracteres a escribir
815
Tokens
167
Ritmo de tres estrellas
70 tpm

Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 143 segundos.

Escribe este fragmento

Paso 2 de 3 en Flujo y qué cuenta como verdadero; paso 11 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →