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
truthy?informa que0,""y[]cuentan todos como verdadero.ortoma el primer valor verdadero parashelf-name, yanddevuelve el último cuando todos se cumplen.if-letvinculagramssolo si la búsqueda acierta, ywhen-letsalta su cuerpo cuandoseqda nil.
Palabras clave y builtins usados aquí
anddefdefnfiltergetifkeymaporprintlnseqstrval
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.
Paso 2 de 3 en Flujo y qué cuenta como verdadero; paso 11 de 27 en Fundamentos del lenguaje.