comp y partial en Clojure
Lecturas de una estación meteorológica convertidas por funciones de comp y partial.
;; comp glues functions right to left: the rightmost one runs first
(def celsius->f #(+ 32 (* 1.8 %)))
(def tenths #(/ (Math/round (* 10.0 %)) 10.0))
(def station-reading (comp tenths celsius->f))
(println (station-reading 21.5) (station-reading -3.0))
;; partial pre-fills the leftmost arguments and returns a new fn
(def scale-by (partial * 100))
(def prefix (partial str "station "))
(println (scale-by 0.42) (prefix "KB7"))
(def readings [21.5 -3.0 14.25 30.0])
;; both compose cleanly with map, which is where they earn their keep
(println (map station-reading readings))
(println (map (comp prefix str) [1 2 3]))
(println (map (partial max 0) [-4 7 -1 12]))
Cómo funciona
(comp tenths celsius->f)corre primerocelsius->fy redondea lo que vuelve.(partial * 100)y(partial str "station ")rellenan de antemano los argumentos de la izquierda.- Ambas entran directo en
map, como en(map (comp prefix str) [1 2 3])y(map (partial max 0) [-4 7 -1 12]).
Palabras clave y builtins usados aquí
compdefmapmaxpartialprintlnstr
El intento, en números
- Líneas
- 17
- Caracteres a escribir
- 666
- Tokens
- 134
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 115 segundos.
Paso 3 de 3 en Herramientas de seq; paso 18 de 27 en Fundamentos del lenguaje.