Funciones anónimas en Clojure
Pasa funciones sin nombre a map y filter sobre una semana de lluvia medida.
(def rainfall-mm [4 0 12 7 0 21])
;; fn makes a function with no name, used right where it is written
(println (map (fn [mm] (/ mm 10.0)) rainfall-mm))
;; #(...) is reader shorthand for the same thing, and % is the argument
(println (filter #(pos? %) rainfall-mm))
;; %1 and %2 name the arguments when there is more than one
(def notes (map #(str %1 " mm on day " %2) rainfall-mm (range 1 7)))
(println (first notes) "/" (last notes))
;; give the shorthand a name once the body starts earning one
(def wet-day? #(>= % 10))
(println "wet days:" (count (filter wet-day? rainfall-mm)))
Cómo funciona
(fn [mm] (/ mm 10.0))convierte cada medición a centímetros dentro demap.#(pos? %)es la forma corta del lector para la misma idea, con%en lugar del argumento.#(str %1 " mm on day " %2)nombra dos argumentos, ywet-day?es la forma corta ya con nombre propio.
Palabras clave y builtins usados aquí
countdeffilterfirstfnlastmapprintlnrangestr
El intento, en números
- Líneas
- 15
- Caracteres a escribir
- 586
- Tokens
- 100
- Ritmo de tres estrellas
- 70 tpm
Al ritmo de tres estrellas de 70 tokens por minuto, este intento toma unos 86 segundos.
Paso 2 de 3 en Funciones; paso 8 de 27 en Fundamentos del lenguaje.