typestar

Conjuntos y pertenencia en Clojure

Compara dos listas de avistamiento de aves con literales de conjunto y clojure.set.

(require '[clojure.set :as set])

;; a set literal keeps one copy of each value
(def spring-list #{"heron" "kite" "wren" "swift"})

;; conj adds and disj removes; both return new sets
(def autumn-list (disj (conj spring-list "brant") "swift"))

;; a set is a function that answers with the value or with nil
(println (spring-list "wren") (spring-list "puffin"))

;; union gathers every bird, intersection keeps the overlap
(println (sort (set/union spring-list autumn-list)))
(println (sort (set/intersection spring-list autumn-list)))

;; difference keeps what the first set has and the second does not
(println (set/difference spring-list autumn-list))

Cómo funciona

  1. spring-list es un literal de conjunto, y disj y conj derivan de él autumn-list.
  2. (spring-list "wren") llama al conjunto como función, que responde con el valor o con nil.
  3. set/union, set/intersection y set/difference combinan las dos listas de tres maneras.

Palabras clave y builtins usados aquí

El intento, en números

Líneas
17
Caracteres a escribir
654
Tokens
79
Ritmo de tres estrellas
75 tpm

Al ritmo de tres estrellas de 75 tokens por minuto, este intento toma unos 63 segundos.

Escribe este fragmento

Paso 3 de 3 en Colecciones; paso 6 de 27 en Fundamentos del lenguaje.

← Anterior Siguiente →