You are on page 1of 57

* Primitives

** Numbers
**** Arithmetic

**** Compare
****Test

****TEST

****Random

** Strings
**** Create

;;

====== Clojure format/printf and large integers =====

;; This big number doesn't fit in a Long.

It is a

;; clojure.lang.BigInt, which format cannot handle directly.


user=> (format "%5d" 12345678901234567890)
IllegalFormatConversionException d != clojure.lang.BigInt
rmatSpecifier.failConversion (Formatter.java:3999)

java.util.Formatter$Fo

;; You can convert it to a java.math.BigInteger, which format does handle.


user=> (format "%5d" (biginteger 12345678901234567890))
"12345678901234567890"

;; If you do this very often, you might want to use something like
;; format-plus to avoid sprinkling your code with calls to biginteger.
(defn coerce-unformattable-types [args]
(map (fn [x]
(cond (instance? clojure.lang.BigInt x) (biginteger x)
(instance? clojure.lang.Ratio x) (double x)
:else x))
args))

(defn format-plus [fmt & args]


(apply format fmt (coerce-unformattable-types args)))

;; Now this works:


user=> (format-plus "%5d" 12345678901234567890)
"12345678901234567890"
;;

==== Clojure format/printf and floating-point formats ====

user=> (format "%.3f" 2.0)


"2.000"

;; format doesn't handle integers or ratios with %e, %f, %g, or %a


user=> (format "%.3f" 2)
IllegalFormatConversionException f != java.lang.Long
pecifier.failConversion (Formatter.java:3999)

java.util.Formatter$FormatS

;; In general, if you want to use floating-point formats %e, %f, %g,


;; or %a with format or printf, and you don't know whether the values
;; you want to format are floats or doubles, you should convert them:
user=> (format "%.3f" (double 2))
"2.000"

user=> (format "%.3f" (double (/ 5 2)))


"2.500"

;; One could make a function that parses the format string to look for
;; %f and other floating-point formats and automatically coerces the
;; corresponding arguments to doubles, but such a function probably
;; wouldn't fit into a short example.

You could also consider using

;; cl-format which does handle these kinds of things for you.

The main

;; disadvantage to doing so is that you have to learn a different syntax


;; for format specifiers.

**** Use

Devuelve el nmero de elementos de la coleccin. (Nil recuento) regresa


0. Tambin funciona con cadenas, matrices y colecciones de Java y Mapas
(count nil)
;;=> 0
(count [])
;;=> 0
(count [1 2 3])
;;=> 3
(count {:one 1 :two 2})
;;=> 2
(count [1 \a "string" [1 2] {:foo :bar}])
;;=> 5

(count "string")
;;=> 6
(count '(1 2 3 3 1))
;;=> 5
;; and as a koan
(= (count '(1 2 3 3 1)) 5)
;;=> true

Devuelve el valor asignado a la tecla, no encontrado o nulo si la clave no est p


resente.
(get [1 2 3] 1)
;;=> 2
(get [1 2 3] 5)
;;=> nil
(get {:a 1 :b 2} :b)
;;=> 2
(get {:a 1 :b 2} :z "missing")
;;=> "missing"

Devuelve la subcadena de s que comienza en el arranque inclusiva, y terminando


al final (por defecto es la longitud de la cadena), exclusivo.
user=> (subs "Clojure" 1)
"lojure"
user=> (subs "Clojure" 1 3)
"lo"
;; String indexes have to be between 0 and (.length s)
user=> (subs "Clojure" 1 20)
java.lang.StringIndexOutOfBoundsException: String index out of range: 20 (NO_SOUR
CE_FILE:0)

Devuelve una cadena de todos los elementos en el coll, devuelto por (coll ss),
separados por un separador opcional.
user=> (clojure.string/join ", " [1 2 3])
"1, 2, 3"
;; Splits a string on space character and joins
;; the resulting collection with a line feed character
(use '[clojure.string :only (join split)])
user=> (println
(join "\n"
(split "The Quick Brown Fox" #"\s")))
The
Quick
Brown
Fox
nil

Devuelve una nueva cadena, utilizando CMAP para escapar de cada carcter ch
s de la siguiente manera:
Si (ch CMAP) es nula, aada ch a la nueva cadena.
Si (ch CMAP) es no nulo, append (str (CMAP ch)) en su lugar.
;; There should be no space between the \ and the &, but I don't know how
;; to create that in an example yet.
;; No debe haber ningn espacio entre el \ y la Y, pero no s cmo
;; para crear que en un ejemplo todava.

user=> (clojure.string/escape "I want 1 < 2 as HTML, & other good things."
{\< "&lt;", \> "&gt;", \ & "&amp;"})
"I want 1 &lt; 2 as HTML, &amp; other good things."

Divide la cadena en una expresin regular. Lmite argumento opcional es


el nmero mximo de divisiones. No perezoso. Devuelve vector de las divisiones.
user=> (require '[clojure.string :as str])
user=> (str/split "Clojure is awesome!" #" ")
["Clojure" "is" "awesome!"]
user=> (str/split "q1w2e3r4t5y6u7i8o9p0" #"\d+")
["q" "w" "e" "r" "t" "y" "u" "i" "o" "p"]
user=> (str/split "q1w2e3r4t5y6u7i8o9p0" #"\d+" 5)
["q" "w" "e" "r" "t5y6u7i8o9p0"]
(use '[clojure.string :only (split triml)])
;; Splitting on whitespace is a common desire.
user=> (split "Some words to split" #"\s+")
["Some" "words" "to" "split"]
;; By using the pattern #"\s+", we split on all occurrences of one or
;; more consecutive whitespace characters.
user=> (split "Some
words
with\tother whitespace
\n" #"\s+")
["Some" "words" "with" "other" "whitespace"]
;; If you are used to Perl's special behavior of split(' ', $str),
;; where it ignores leading whitespace in the string to be split, this
;; does not quite do it.
user=> (split "
Leading whitespace causes empty first string" #"\s+")
["" "Leading" "whitespace" "causes" "empty" "first" "string"]
;; This will do it.
user=> (defn perl-split-on-space [s]
(split (triml s) #"\s+"))
#'user/perl-split-on-space
user=> (perl-split-on-space "
This is often what you want
["This" "is" "often" "what" "you" "want"]

")

;; There might be cases where you want this instead.


user=> (split "Some
words
with\tother whitespace
\n" #"\s")
["Some" "" "" "" "words" "" "" "with" "other" "whitespace"]

Splits s en \ no \ r \ n.
user=> (clojure.string/split-lines "test \n string")
["test " " string"]

Reemplaza todas las instancias del partido con sustitucin en s.


partido / el reemplazo puede ser:
cadena / cuerda
char / carbn
patrn / (cadena o funcin del partido).
Ver tambin sustituir-primero.
La sustitucin es literal (es decir, ninguno de sus personajes son tratados
especialmente) para todos los casos por encima excepto patrn / cadena.
Para el patrn / cadena, $ 1, $ 2, etc., en la cadena de reemplazo son
sustituido por la cadena que haca juego con la correspondiente
grupo entre parntesis en el patrn. Si desea que su reemplazo
cadena r para ser utilizado literalmente, utilice (re-quote-reemplazo r) como el
argumento reemplazo. Ver tambin la documentacin para
mtodo appendReplacement de java.util.regex.Matcher.
Ejemplo:
(Clojure.string / reemplazar "Casi Pig Latin" # "\ b (\ w) (\ w +) \ b" "$ 2 $ 1
AY")
-> "LmostAay Igpay Atinlay"
user=> (clojure.string/replace "The color is red" #"red" "blue")
"The color is blue"
user=> (clojure.string/replace "The color is red." #"[aeiou]" #(str %1 %1))
"Thee cooloor iis reed."

user=> (use '[clojure.string :only (replace-first)])


Sustituye la primera instancia del partido con sustitucin en s.
partido / el reemplazo puede ser:
char / carbn
cadena / cuerda
patrn / (cadena o funcin del partido).
Ver tambin sustituir.

La sustitucin es literal (es decir, ninguno de sus personajes son tratados


especialmente) para todos los casos por encima excepto patrn / cadena.
Para el patrn / cadena, $ 1, $ 2, etc., en la cadena de reemplazo son
sustituido por la cadena que haca juego con la correspondiente
grupo entre parntesis en el patrn. Si desea que su reemplazo
cadena r para ser utilizado literalmente, utilice (re-quote-reemplazo r) como el
argumento reemplazo. Ver tambin la documentacin para
mtodo appendReplacement de java.util.regex.Matcher.
Ejemplo:
(clojure.string / reemplazar-primero "swaps primeros dos palabras"
# "(\ W +) (\ s +) (\ w +)" "$ 3 $ 2 $ 1")
-> "Primera intercambiar dos palabras"
;; Only replace the first match.
user=> (replace-first "A good day to you, sir.
"A good night to you, sir. Good day."

Good day." #"day" "night")

;; If there are no matches, return the original string.


user=> (replace-first "A good day to you, sir." #"madam" "master")
"A good day to you, sir."
;; (?i) at the beginning of a pattern makes the entire thing match
;; case-insensitively, at least for US ASCII characters. (?u) does
;; the corresponding thing for Unicode.
user=> (replace-first "Day need not be SHOUTED." #"(?i)day" "night")
"night need not be SHOUTED."
;; See here for many details on regex patterns:
;; http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html
;; Also the book "Mastering Regular Expressions" by Jeffrey Friedl.
user=> (use '[clojure.string :only (replace-first)])
;; Pattern matches from beginning of string (signified by ^) up to the
;; last occurrence of /, because by default * is greedy, i.e. it
;; matches as much as possible.
user=> (replace-first "/path/to/file/name" #"^.*/" "")
"name"
;; Use *? to match as little as possible.
user=> (replace-first "/path/to/file/name" #"^.*?/" "")
"path/to/file/name"

Devoluciones s con sus caracteres invertidos.


user> (reverse "foo")
"oof"

Dada una cadena de reemplazo que usted desea ser un literal reemplazo para una co
incidencia de patrn en sustituir o reemplazar-primera, haga lo necesario escape
de caracteres especiales en el reemplazo.

**** Test

Coaccionar a char
;; can coerce an int (or similar)
user=> (char 97)
\a
;; a byte can be coerced to a char
user=> (let [bytes-array (.getBytes "abc")]
(char (first bytes-array)))
\a
;; char is just a function
user=> (map char [65 66 67 68])
(\A \B \C \D)

Devuelve verdadero si x es un caracter


user=> (char? \a)
true
user=> (char? 22)
false
user=> (char? "a")
false
user=> (char? (first "abc"))
true

Devuelve verdadero si x es una cadena


user=> (string? "abc")
true
user=> (string? "")
true
user=> (string? \a)
false
user=> (string? 1)
false
user=> (string? ["a" "b" "c"])
false
user=> (string? nil)
false

True si s es nula, vaca, o contiene slo espacios en blanco.


user> (clojure.string/blank? nil)
true
user> (clojure.string/blank? false)
true
user> (clojure.string/blank? "
true

")

user> (clojure.string/blank? " a ")


false

* Collections
** Collections
**** Generic ops:

Devuelve una coleccin vaca de la misma categora que coll, o nil


(empty '(1 2)) ;; =>
(empty [1 2]) ;; =>
(empty {1 2}) ;; =>
(empty #{1 2}) ;; =>

()
[]
{}
#{}

Si la coleccion est vaca, devuelve nil, sino devuelve la coleccion


user=> (not-empty
[1]
user=> (not-empty
[1 3 5]
user=> (not-empty
nil
user=> (not-empty
nil
user=> (not-empty
nil

[1])
[1 3 5])
[])
'())
nil)

Devuelve una nuevo coleccion consistente a la coleccion con todos los elementos d
e de-coll unidos.
; Maps can be constructed from a sequence of 2-vectors or a sequence
; of maps
user=> (into (sorted-map) [ [:a 1] [:c 3] [:b 2] ] )
{:a 1, :b 2, :c 3}
user=> (into (sorted-map) [ {:a 1} {:c 3} {:b 2} ] )
{:a 1, :b 2, :c 3}
; When maps are the input source, they convert into an unordered sequence
; of key-value pairs, encoded as 2-vectors
user=> (into [] {1 2, 3 4})
[[1 2] [3 4]]

conj [oin]. Devuelve una nueva coleccin con los xs


'Aadido'. (Punto cero conj) devuelve (artculo). La "adicin" puede
suceder en diferentes "lugares" en funcin del tipo de hormign.
;; notice that conjoining to a vector is done at the end
(conj [1 2 3] 4)
;;=> [1 2 3 4]
;; notice conjoining to a list is done at the beginning
(conj '(1 2 3) 4)
;;=> (4 1 2 3)
(conj ["a" "b" "c"] "d")
;;=> ["a" "b" "c" "d"]
;; conjoining multiple items is done in order
(conj [1 2] 3 4)
;;=> [1 2 3 4]
(conj '(1 2) 3 4)
;;=> (4 3 1 2)
(conj [[1 2] [3 4]] [5 6])
;;=> [[1 2] [3 4] [5 6]]
;; conjoining to maps only take items as vectors of length exactly 2
(conj {1 2, 3 4} [5 6])
;;=> {5 6, 1 2, 3 4}
(conj {:firstname "John" :lastname "Doe"} {:age 25 :nationality "Chinese"})
;;=> {:nationality "Chinese", :age 25, :firstname "John", :lastname "Doe"}
;; conj on a set
(conj #{1 3 4} 2)
;;=> #{1 2 3 4}

**** Content tests

Devuelve verdadero si no hay dos de los argumentos son =

user=> (distinct? 1 2 3)
true
user=> (distinct? 1 2 3 3)
false

Devuelve true si coll no tiene partidas - iguales que (no (coll ss)).
Utilice el lenguaje (ss x) en lugar de (no (vaco? X))
user=> (empty? ())
true
user=> (empty? '(1))
false
user=> (every? empty? ["" [] () '() {} #{} nil])
true
;example of recommended idiom for testing if not empty
user=> (every? seq ["1" [1] '(1) {:1 1} #{1}])
true

Devuelve true si (x pred) es lgico cierto para toda x en coll, otro falsa.
user=> (every? even? '(2 4 6))
true
user=> (every? even? '(1 2 3))
false
;; you can use every? with a set as the predicate to return true if
;; every member of a collection is in the set
user=> (every? #{1 2} [1 2 3])
false
user=> (every? #{1 2} [1 2])
true
;; or use a hash-map as
;; if every member of a
user=> (every? {1 "one"
true
user=> (every? {1 "one"
false

the predicate with every? to return true


collection is a key within the map
2 "two"} [1 2])
2 "two"} [1 2 3])

Devuelve false si (x pred) es lgico cierto para toda x en coll, de lo verdadero.


user=> (not-every? odd? '(1 2 3))
true
user=> (not-every? odd? '(1 3))
false

Devuelve el primer valor de la verdadera lgica de (x pred) para cualquier x en c


oll, otro nulo. Un idioma comn es el uso de un conjunto como pred, por ejemplo
Esto devolver: fred si: fred est en la secuencia, si no nula:
(Algunos # {: fred} coll)
;; 2 is even, so `some` stops there, 3 and 4 are never tested
(some even? '(1 2 3 4))
;;=> true
;; they are all odd, so not true, i.e. nil
(some even? '(1 3 5 7))
;;=> nil
(some true? [false false false])
;;=> nil
(some true? [false true false])
;;=> true
(some true? [true true true])
;;=> true

Devuelve false si (x pred) es lgico cierto para cualquier x en coll, cosa verdad
era.

user=> (not-any? odd? '(2 4 6))


true
user=> (not-any? odd? '(1 2 3))
false

**** Capabilities

Devuelve true si la coleccin implementada es secuencial


user=>
true
user=>
true
user=>
true
user=>
true
user=>
true
user=>
false
user=>
false
user=>
false
user=>
false

(sequential? '(1 2 3))


(sequential? [1 2 3])
(sequential? (range 1 5))
(sequential? '())
(sequential? [])
(sequential? nil)
(sequential? 1)
(sequential? {:a 2 :b 1})
(sequential? #{1 2 3})

Devuelve true si la collecion implementada es Asociativo


user=> (associative? [1 2 3]) ; vector
true
user=> (associative? '(1 2 3)) ; list
false
user=> (associative? {:a 1 :b 2}) ; map
true

user=> (associative? #{:a :b :c}) ; set


false
user=> (associative? "fred") ; string
false

Devuelve true si la coleccion implementa es Ordenada


user=> (sorted? (sorted-set 5 3 1 2 4))
true
user=> (sorted? (sorted-map :a 1 :c 3 :b 2))
true
;; Note you can't just pass in a collection that happens to be sorted.
user=> (sorted? [1 2 3 4 5])
false

Devuelve true si cuentan implementos coll en tiempo constante


user=>
true
user=>
true
user=>
true
user=>
true
user=>
false
user=>
false

(counted? [:a :b :c])


(counted? '(:a :b :c))
(counted? {:a 1 :b 2 :c 3})
(counted? #{:a :b :c})
(counted? "asdf")
(counted? (into-array Integer/TYPE [1 2 3]))

Devuelve true si coll implementa Reversible

user=>
true
user=>
true
user=>
true
user=>
false
user=>
false
user=>
false

(reversible? [])
(reversible? (sorted-map))
(reversible? (sorted-set))
(reversible? '())
(reversible? {})
(reversible? #{})

** Lists
****Create ()

Crea una nueva lista que contiene los artculos.


user=> (list 'a 'b 'c 'd 'e 'f 'g)
(a b c d e f g)
user=> (list 1 2 3)
(1 2 3)
user=> (let [m {:1 1 :2 2 :3 3 :4 4}] (map list (keys m) (vals m)))
((:1 1) (:2 2) (:3 3) (:4 4))

Crea una nueva lista que contiene los elementos antepondr al resto, la ltimo de
los cuales se tratar como una secuencia.
;; `list*` function:
user=> (list* 1 [2 3])
(1 2 3)
user=> (list* 1 2 [3 4])
(1 2 3 4)
;; compared to regular `list` function:
user=> (list 1 [2 3])
(1 [2 3])
user=> (list 1 2 [3 4])

(1 2 [3 4])
;; Corner cases:
user=> (list* nil [1 2])
(nil 1 2)
user=> (list* 1 nil)
(1)
user=> (list* () [1 2])
(() 1 2)
user=> (list* 1 ())
(1)

****Examine

Devuelve el primer elemento de la coleccin. Las llamadas siguientes en su


argumento. Si coll es nulo, devuelve nil.
(first '(:alpha :bravo :charlie))
;;=> :alpha

Devuelve el valor en el ndice. Consiguen devuelve nil si el ndice de lmites, e


nsima lanza una excepcin a menos que no se encuentra, se suministra. Nth tambi
n trabaja para cadenas, matrices Java, Matchers expresiones regulares y listas, y
, en O (n) el tiempo, para las secuencias.
user=> (nth ["a" "b" "c" "d"] 0)
"a"
user=> (nth ["a" "b" "c" "d"] 1)
"b"
user=> (nth [] 0)
IndexOutOfBoundsException ...
user=> (nth [] 0 "nothing found")
"nothing found"
user=> (nth [0 1 2] 77 1337)
1337

Para obtener una lista o cola, igual que en primer lugar, para un vector, al igua
l que, pero mucho ms eficiente que, pasado. Si la coleccin est vaca, devuelve
nil.
user=> (def large-vec (vec (range 0 10000)))
#'user/large-vec
user=> (time (last large-vec))
"Elapsed time: 1.279841 msecs"
9999
user=> (time (peek large-vec))
"Elapsed time: 0.049238 msecs"
9999

****Change

Devuelve una nueva SEQ donde x es el primer elemento y SEC es el resto.


;; prepend 1 to a list
(cons 1 '(2 3 4 5 6))
;;=> (1 2 3 4 5 6)
;; notice that the first item is not expanded
(cons [1 2] [4 5 6])
;;=> ([1 2] 4 5 6)

Devuelve una ss posiblemente vaca de los artculos despus de la primera. Las ll


amadas siguientes en su argumento.
(rest [1 2 3 4 5])
(rest ["a" "b" "c" "d" "e"])

;;=> (2 3 4 5)
;;=> ("b" "c" "d" "e")

Para obtener una lista o cola, devuelve una nueva lista / cola sin la primera ele
mento, por un vector, devuelve un nuevo vector sin el ltimo elemento. Por Si la
coleccin est vaca, se produce una excepcin. Nota - No es lo mismo como siguie
nte / butlast.
user=>
3
user=>
[1 2]
user=>
1
user=>
(2 3)

(peek [1 2 3])
(pop [1 2 3])
(peek '(1 2 3))
(pop '(1 2 3))

**Vectors
****Create [ ]

Crea un nuevo vector que contiene los argumentos.


;; create an empty vector the long way
user=> (vector)
[]
;; create an empty vector the short way
user=> []
[]
;; you can even create vectors with nil values
user=> (vector nil)
[nil]
;; create a vector the long way
user=> (vector 1 2 3)
[1 2 3]
;; create a vector the short way
user=> [1 2 3]
[1 2 3]
;; checking for the 2 results above
user=> (class (vector 1 2 3))
clojure.lang.PersistentVector
user=> (class [1 2 3])
clojure.lang.PersistentVector
user=> (= (vector 1 2 3) [1 2 3])
true

Crea un nuevo vector que contiene el contenido de coll. Arrays de Java ser alias
y no debe ser modificado.
user=> (vec
[1 2 3]
user=> (vec
[1 2 3]
user=> (vec
[1 3 2]
user=> (vec
[[:c 3] [:b
user=> (vec
[]
user=> (vec
[]

'(1 2 3))
[1 2 3])
#{1 2 3})
{:a 1 :b 2 :c 3})
2] [:a 1]]
'())
nil)

Crea un nuevo vector de un


float: doble: byte: corto:
la interfaz de vectores en
e. Opcionalmente toma uno

tipo primitivo nico t, donde t es un de: int: largo:


char o: boolean. Los Las vector resultante cumple con
general, pero almacena los valores UNBOXED internament
o ms elementos para poblar el vector.

user=> (conj (vector-of :int) 1 2 3)


[1 2 3] ; <-- note, these are unboxed internally
user=> (vector-of :int 1 2 3)
[1 2 3] ; same here
user=> (type (conj (vector-of :int) 1 2 3))
clojure.core.Vec

Devuelve un vector que consiste en el resultado de aplicar f a la un conjunto de


primeros elementos de cada coll, seguido de la aplicacin f al conjunto de segund
os elementos de cada Coll, hasta que uno cualquiera de los Colls es agotado. Cual

quier artculo que queda en otros Colls se ignoran. Funcin f debe aceptar nmero
de Colls-argumentos.
(mapv inc [1 2 3 4 5])
;;=> [2 3 4 5 6]
;; map can be used with multiple collections. Collections will be consumed
;; and passed to the mapping function in parallel:
(mapv + [1 2 3] [4 5 6])
;;=> [5 7 9]
;; When map is passed more than one collection, the mapping function will
;; be applied until one of the collections runs out:
(mapv + [1 2 3] (iterate inc 1))
;;=> [2 4 6]
;; map is often used in conjunction with the # reader macro:
(mapv #(str "Hello " % "!" ) ["Ford" "Arthur" "Tricia"])
;;=> ["Hello Ford!" "Hello Arthur!" "Hello Tricia!"]
;; A useful idiom to pull "columns" out of a collection of collections.
;; Note, it is equivalent to:
;; (mapv vector [:a :b :c] [:d :e :f] [:g :h :i])
(apply mapv vector [[:a
[:d
[:g
;;=> [[:a :d :g] [:b :e

:b :c]
:e :f]
:h :i]])
:h] [:c :f :i]]

Devuelve un vector de los elementos de coll para los que (Punto pred) devuelve tr
ue. pred debe estar libre de efectos secundarios.
;; very similar to filter but returns a vector
(filterv even? (range 10))
;;=> [0 2 4 6 8]
(filter (fn [x]
(= (count x) 1))
["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ["a" "b" "n" "f" "q"]
(filter #(= (count %) 1)
["a" "aa" "b" "n" "f" "lisp" "clojure" "q" ""])
;;=> ["a" "b" "n" "f" "q"]

****Examine --get peek


****Change --pop conj

Assoc [IATE]. Cuando se aplica a un mapa, devuelve un nuevo mapa de la


mismo (hash / ordenados) tipo, que contiene el mapeo de clave (s) a
val (s). Cuando se aplica a un vector, devuelve un nuevo vector que
contiene val en el ndice. Nota - ndice debe ser <= (contar vector).
(assoc {} :key1 "value" :key2 "another value")
;;=> {:key2 "another value", :key1 "value"}
;; Here we see an overwrite by a second entry with the same key
(assoc {:key1 "old value1" :key2 "value2"}
:key1 "value1" :key3 "value3")
;;=> {:key3 "value3", :key2 "value2", :key1 "value1"}
;; We see a nil being treated as an empty map
(assoc nil :key1 4)
;;=> {:key1 4}
;; 'assoc' being used on an array, the key is the index.
(assoc [1 2 3] 0 10)
;;=> [10 2 3]
(assoc [1 2 3] 3 10)
;;=> [1 2 3 10]
;; but if the index does not exist, it is not added automagically
(assoc [1 2 3] 4 10)
;; java.lang.IndexOutOfBoundsException (NO_SOURCE_FILE:0)

Devuelve un vector persistente de los elementos del vector de


Inicio (inclusive) a fin (exclusivo). Si no se suministra final, por defecto (vec
tor de recuento). Esta operacin es O (1) y muy rpido, como la estructura de acc
iones vector resultante con el original y no recorte se hace.
;; not supplying 'end' returns vector from 'start' to (count vector)
user=> (subvec [1 2 3 4 5 6 7] 2)
[3 4 5 6 7]
;; supplying 'end' returns vector from 'start' to element (- end 1)
user=> (subvec [1 2 3 4 5 6 7] 2 4)
[3 4]

Dado un mapa de pares de recambio y un vector / coleccin, devuelve un vector / s


s con cualquier elemento = una clave en SMAP reemplazado con el val correspondien
te en SMAP
user=> (replace [:zeroth :first :second :third :fourth] [0 2 4 0])
[:zeroth :second :fourth :zeroth]
user=> (replace [10 9 8 7 6] [0 2 4])
[10 8 6]
user=> (replace {2 :two, 4 :four} [4 2 3 4 5 6 2])
[:four :two 3 :four 5 6 :two]
user=> (replace '{0 ZERO, 1 ONE, 2 TWO} '(This is the code 0 1 2 0))
(This is the code ZERO ONE TWO ZERO)

Devoluciones, en tiempo constante, una ss de los artculos en rev (que puede ser
un vector o clasificado-mapa), en orden inverso. Si rev est vaca devuelve nil
user=> (vec (range 10))
[0 1 2 3 4 5 6 7 8 9]
user=> (rseq (vec (range 10)))
(9 8 7 6 5 4 3 2 1 0)
(rseq (into (sorted-map) {:a 1 :b 2}))
;; => ([:b 2] [:a 1])

**Sets
****Create #{ }

Devuelve un conjunto de los distintos elementos de coll.


;; returns distinct elements
user=> (set '(1 1 2 3 2 4 5 5))
#{1 2 3 4 5}

;; returns distinct elements (different nomenclature)


user=> (set [1 1 2 3 2 4 5 5])
#{1 2 3 4 5}
user=> (set [1 2 3 4 5])
#{1 2 3 4 5}
user=> (set "abcd")
#{\a \b \c \d}
user=> (set '("a" "b" "c" "d"))
#{"a" "b" "c" "d"}
user=> (set {:one 1 :two 2 :three 3})
#{[:two 2] [:three 3] [:one 1]}
user=> (set nil)
#{}

Devuelve un nuevo conjunto hash con llaves suministradas. Todas las teclas son ig
uales manejado como por usos repetidos de conj.
user=> (hash-set 1 2 1 3 1 4 1 5)
#{1 4 3 2 5}
user=> (= (hash-set :c :a :b) #{:b :a :c})
true
user=> (apply hash-set (seq "Lorem ipsum dolor sit amet"))
#{\space \a \d \e \i \L \l \m \o \p \r \s \t \u}

Devuelve un nuevo conjunto ordenado con claves suministrados. Todas las teclas so
n iguales manejado como por usos repetidos de conj.
user=> (sorted-set 3 2 1)
#{1 2 3}
user=> (sorted-set 3 2 1 1)
#{1 2 3}
user=> #{2 1 3}
#{1 3 2}
user=> (apply sorted-set #{2 1 3})

#{1 2 3}

Devuelve un nuevo conjunto ordenado con claves suministrados, mediante el softwar


e comparador. Cualquier claves iguales se manejan como si por usos repetidos de
conj.
user> (sorted-set-by > 3 5 8 2 1)
#{8 5 3 2 1}
;; Be cautious about comparison functions that only compare part of
;; the objects:
user=> (defn second-< [x y]
(< (second x) (second y)))
user=> (sorted-set-by second-< [:a 1] [:b 1] [:c 1])
#{[:a 1]}
;; Where did the other elements go?
;; Replacing < with <= might look like a fix, but doesn't work,
;; either:
user=> (defn second-<= [x y]
(<= (second x) (second y)))
user=> (def s2 (sorted-set-by second-<= [:a 1] [:b 1] [:c 1]))
#'user/s2
user=> s2
#{[:c 1] [:b 1] [:a 1]}
;; So far, so good, but set membership tests can't find the elements.
user=> (contains? s2 [:b 1])
false
user=> (s2 [:c 1])
nil
;; Here is one way to write a good comparison function. When the two
;; objects are equal in the parts we care about, use the tie-breaker
;; 'compare' on the whole values to give them a consistent order that
;; is only equal if the entire values are equal.
user=> (defn second-<-with-tie-break [x y]
(let [c (compare (second x) (second y))]
(if (not= c 0)
c
;; Otherwise we don't care as long as ties are broken
;; consistently.
(compare x y))))
user=> (def s3 (sorted-set-by second-<-with-tie-break [:a 1] [:b 1] [:c 1]))
#'user/s3
user=> s3
#{[:a 1] [:b 1] [:c 1]}
user=> (contains? s3 [:b 1])
true

user=> (s3 [:c 1])


[:c 1]
;; All good now!

****Examine

Devuelve true si la clave est presente en la coleccin dada, de lo contrario dev


uelve false. Tenga en cuenta que para las colecciones numricamente indexados com
o vectores y matrices Java, esta prueba si la tecla numrica est dentro de la ga
ma de ndices. Contiene? ' opera la constante de tiempo o logartmica; no va a r
ealizar una bsqueda lineal de un valor. Vase tambin "algunos".
;; `contains?`
(contains? {:a
(contains? {:a
(contains? {:a

is straightforward for maps:


1} :a)
;=> true
nil} :a) ;=> true
1} :b)
;=> false

;; It's likely to surprise you for other sequences because it's


;; about *indices* or *keys*, not *contents*:
(contains?
(contains?
(contains?
(contains?

[:a
[:a
"f"
"f"

:b :c] :b)
:b :c] 2)
0)
1)

;=>
;=>
;=>
;=>

false
true
true
false

;; It can be applied to non-sequences:


(contains? 5 3)

;=> false

;; Although lists are sequences, they are not keyed sequences.


;; `contains` should not be used for lists.
(contains? '(1 2 3) 1)
;;=> false
(Clojure = 1.1)
;; IllegalArgumentException (Clojure >=1.5)

****Change --Conj

disj [oin]. Devuelve un nuevo juego de la misma (hash / ordenados) tipo, que no c
ontiene clave (s).
user=> (disj #{1 2 3}) ; disjoin nothing
#{1 2 3}
user=> (disj #{1 2 3} 2) ; disjoin 2
#{1 3}
user=> (disj #{1 2 3} 4) ; disjoin not existed item
#{1 2 3}
user=> (disj #{1 2 3} 1 3) ; disjoin several items at once
#{2}

**Maps:
****Create { }

keyval => val clave


Devuelve un nuevo mapa hash con asignaciones suministrados. Si todas las claves s
on iguales, stos son manejados como si por usos repetidos de asoc.
;; create hash map the long way
user=> (hash-map)
{}
;; create hash map the short way
user=> {}
{}
;; sending a key more times, will remap it to the last value
user=> (hash-map :key1 1, :key1 2)
{:key1 2}
user=> {:key1 1, :key1 2}
IllegalArgumentException Duplicate key: :key1
eateWithCheck (PersistentArrayMap.java:70)

clojure.lang.PersistentArrayMap.cr

user=> (hash-map :key1 'val1, 'key2 :val2, [:compound :key] nil)


{[:compound :key] nil, :key1 val1, key2 :val2}

Construye una matriz de mapa. Si todas las claves son iguales, que son manejados
como Si por usos repetidos de Assoc.
user=> (array-map [1 2] [3 4 5])
{[1 2] [3 4 5]}
user=> (array-map :a 10)
{:a 10}
user=> (array-map :a 10 :b 20)
{:a 10 :b 20}
user=> (apply array-map [:a 10 :b 20 :c 30])
{:a 10 :b 20 :c 30}
user=> (apply assoc {} [:a 10 :b 20 :c 30]) ;same result using assoc
{:a 10 :b 20 :c 30}

Devuelve un mapa con las teclas asignadas a los intervalos correspondientes.


user=> (zipmap [:a :b :c :d :e] [1 2 3 4 5])
{:e 5, :d 4, :c 3, :b 2, :a 1}
;; 4 is not included in the result
user=> (zipmap [:a :b :c] [1 2 3 4])
{:c 3, :b 2, :a 1}
;; :c is not included in the result
user=> (zipmap [:a :b :c] [1 2])
{:b 2, :a 1}

keyval => val clave


Devuelve un nuevo mapa ordenados con asignaciones suministrados. Si todas las cla
ves son iguales, stos son manejados como si por usos repetidos de asoc.

(sorted-map :z 1, :b 2, :a 3)
;;=> {:a 3, :b 2, :z 1}
(into (sorted-map) {:b 2 :a 1}) ;;=> {:a 1, :b 2}
; 'seq' can be used to turn a map into a list of vectors
; notice how the list is built in the sorted order as with vectors.
(seq (into (sorted-map) {:key1 "value1" :key2 "value2"}))
;;=> ([:key1 "value1"] [:key2 "value2"])

keyval => val clave


Devuelve un nuevo mapa ordenados con asignaciones suministrados, mediante el soft
ware comparador. Si todas las claves son iguales, se manejan como si por usos rep
etidos de Assoc.
; The basic function requires discrete elements, and cannot accept a
; pre-existing map:
user=> (sorted-map-by > 1 "a", 2 "b", 3 "c")
{3 "c", 2 "b", 1 "a"}
; We can use the syntax "(sorted-map >)" to create an empty sorted map that sorts
; in reverse order (i.e. the opposite of "(sorted-map)").
; it using (into ...) with a pre-existing map:
user=> (into (sorted-map-by >) {1 :a 2 :b 3 :c} )
{3 :c, 2 :b, 1 :a}
; This
user=>
{1 :a,
user=>
{1 :a,

It we can then fill

two are the same


(into (sorted-map-by <) {1 :a 2 :b 3 :c} )
2 :b, 3 :c}
(into (sorted-map) {1 :a 2 :b 3 :c} )
2 :b, 3 :c}

Toma un objeto Java y devuelve una implementacin de slo lectura de la


mapa abstraccin basada en sus propiedades JavaBean.
user=> (import java.util.Date)
java.util.Date
user=> (def *now* (Date.))
#'user/*now*
user=> (bean *now*)

{:seconds 57, :date 13, :class java.util.Date, :minutes 55, :hours 17, :year 110,
:timezoneOffset -330, :month 6, :day 2, :time 1279023957492}

Devuelve un mapa de artculos distintos en coll para el nmero de veces aparecen.


user=> (frequencies ['a 'b 'a 'a])
{a 3, b 1}

Devuelve un mapa de los elementos de coll introducido por el resultado de f en ca


da elemento. El valor de cada clave ser un vector de los elementos correspondien
tes, en el orden en que aparecen en el coll.
;; group strings by their length
(group-by count ["a" "as" "asd" "aa" "asdf" "qwer"])
;;=> {1 ["a"], 2 ["as" "aa"], 3 ["asd"], 4 ["asdf" "qwer"]}
;; group integers by a predicate
(group-by odd? (range 10))
;;=> {false [0 2 4 6 8], true [1 3 5 7 9]}
;; group by a primary key
(group-by :user-id [{:user-id 1 :uri "/"}
{:user-id 2 :uri "/foo"}
{:user-id 1 :uri "/account"}])
;;=> {1 [{:user-id 1, :uri "/"}
;;
{:user-id 1, :uri "/account"}],
;;
2 [{:user-id 2, :uri "/foo"}]}

Devuelve un mapa de los distintos valores de ks en el xrel asignado a un conjunto


de los mapas en xrel con los correspondientes valores de ks.
(use '[clojure.set :only (index)])
;; Suppose you have a set of descriptions of the weights of animals:
user=> (def weights #{ {:name 'betsy :weight 1000}

{:name 'jake :weight 756}


{:name 'shyq :weight 1000} })

;; You want the names of all the animals that weight 1000. One way to do
;; that uses `index`. First, you can group the set elements (the maps) so
;; that those with the same weights are in the same group.
user=> (def by-weight (index weights [:weight]))
#'user/by-weight
;; index returns a map. The keys are maps themselves, where {:weight 756} and {:
weight 1000} are taken from the maps in the weights set. The values in the map r
eturned by index are sets that contain map entries from the above weights set.
user=> by-weight
{{:weight 756} #{{:name jake, :weight 756}},
{:weight 1000} #{{:name shyq, :weight 1000}
{:name betsy, :weight 1000}}}

;; To better visualize the by-weight map that is returned by index, you can query
it using get, using {:weight 756} as the key. This will return all the maps (an
imals) that contain a weight of 756. In this case, there is only one result, whi
ch is a set containing a single map.
user=> (get by-weight {:weight 756})
#{{:name jake, :weight 756}}

;; To see that there are two animals with a weight of 1000, you can query by-weig
ht with the key {:weight 1000}. This returns a set containing two maps.
user=> (get by-weight {:weight 1000})
#{{:name shyq, :weight 1000} {:name betsy :weight 1000}}

;; You can verify by using count


user=> (count (get by-weight {:weight 1000}))
2
;; To get the names of those two animals we can map a name-extracting function
;; over the set of two maps. Since a keyword in a map is also a function that
;; returns its corresponding value, we can just use `:name` as our function:
user=> (map :name (get by-weight {:weight 1000}))
(shyq betsy)

ORDERED
Ordenado proporciona conjuntos y mapas que mantienen el orden de insercin de sus
contenidos.

Sets
(use 'flatland.ordered.set)
(ordered-set 4 3 1 8 2)
=> #ordered/set (4 3 1 8 2)
(conj (ordered-set 9 10) 1 2 3)
=> #ordered/set (9 10 1 2 3)
(into (ordered-set) [7 6 1 5 6])
=> #ordered/set (7 6 1 5)
(disj (ordered-set 8 1 7 2 6) 7)
=> #ordered/set (8 1 2 6)

Maps
(use 'flatland.ordered.map)
(ordered-map :b 2 :a 1 :d 4)
=> #ordered/map ([:b 2] [:a 1] [:d 4])
(assoc (ordered-map :b 2 :a 1 :d 4) :c 3)
=> #ordered/map ([:b 2] [:a 1] [:d 4] [:c 3])
(into (ordered-map) [[:c 3] [:a 1] [:d 4]])
=> #ordered/map ([:c 3] [:a 1] [:d 4])
(dissoc (ordered-map :c 3 :a 1 :d 4) :a)
=> #ordered/map ([:c 3] [:d 4])

data.priority-map
Un mapa de prioridades es muy similar a un mapa ordenado, pero mientras que un
mapa ordenado produce una secuencia de las entradas ordenadas por clave, un mapa
de prioridades produce las entradas ordenadas por valor.
Adems de apoyar a todas las funciones de un mapa ordenado apoya, un mapa de
prioridades tambin se puede considerar como una cola de pares [prioritarios
artculo]. Para apoyar el uso como una cola de prioridad verstil, mapas
prioritarios tambin soportan operaciones conj / peek / pop.

****Examine --get

Devuelve el valor en una estructura asociativa anidada, donde KS es una secuencia


de teclas. Devuelve nil si la clave no est presente, o el valor no se encuentra
, si se suministra.
;; We can use get-in for reaching into nested maps:
user=> (def m {:username "sally"
:profile {:name "Sally Clojurian"
:address {:city "Austin" :state "TX"}}})
#'user/m
user=> (get-in m [:profile
"Sally Clojurian"
user=> (get-in m [:profile
"Austin"
user=> (get-in m [:profile
nil
user=> (get-in m [:profile
"no zip code!"

;; Vectors are also


user=> (def v [[1 2
[4 5
[7 8
#'user/v
user=> (get-in v [0
3
user=> (get-in v [2
8

:name])
:address :city])
:address :zip-code])
:address :zip-code] "no zip code!")

associative:
3]
6]
9]])
2])
1])

;; We can mix associative types:


user=> (def mv {:username "jimmy"
:pets [{:name "Rex"
:type :dog}
{:name "Sniffles"
:type :hamster}]})
#'user/mv
user=> (get-in mv [:pets 1 :type])
:hamster

Devuelve la entrada de mapa para la llave, o nulo si la clave no est presente.


(find {:a 1 :b 2 :c 3} :a)
;;=> [:a 1]
(find {:a 1 :b 2 :c 3} :d)

;;=> nil

Devuelve una secuencia de teclas del mapa, en el mismo orden como (mapa SEC).
(keys {:keys :and, :some :values})
;;=> (:keys :some)
(keys {})
;;=> nil
(keys nil)
;;=> nil

Devuelve una secuencia de valores del mapa, en el mismo orden como (mapa SEC).
(vals {:a "foo", :b "bar"})
;;=> ("foo" "bar")
(vals {})
;;=> nil
(vals nil)
;;=> nil

****Change--assoc

Asocia un valor en una estructura asociativa anidada, donde ks es un


secuencia de teclas y v es el nuevo valor y devuelve una nueva estructura anidada
.
Si no existen niveles, se crearn hash mapas.
(def users [{:name "James" :age 26}

{:name "John" :age 43}])

;; update the age of the second (index 1) user


(assoc-in users [1 :age] 44)
;;=> [{:name "James", :age 26} {:name "John", :age 44}]

;; insert the password of the second (index 1) user


(assoc-in users [1 :password] "nhoJ")
;;=> [{:name "James", :age 26} {:password "nhoJ", :name "John", :age 43}]
;; create a third (index 2) user
;; Also (assoc m 2 {...}) or (conj m {...})
(assoc-in users [2] {:name "Jack" :age 19})
;;=> [{:name "James", :age 26} {:name "John", :age 43} {:name "Jack", :age 19}]
;; From http://clojure-examples.appspot.com/clojure.core/assoc-in

dissoc [IATE]. Devuelve un nuevo mapa de la misma (hash / ordenada) tipo,


que no contiene una asignacin para la clave (s).

<pre>user=&gt; (dissoc {:a 1 :b 2 :c 3}) ; dissoc nothing


{:a 1, :b 2, :c 3}
user=&gt; (dissoc {:a 1 :b 2 :c 3} :b) ; dissoc key :b
{:a 1, :c 3}
user=&gt; (dissoc {:a 1 :b 2 :c 3} :d) ; dissoc not existed key
{:a 1, :b 2, :c 3}
user=&gt; (dissoc {:a 1 :b 2 :c 3} :c :b) ; several keys at once
{:a 1}
</pre>

Devuelve un mapa que consiste en el resto de los mapas conj-ed hacia


el primero. Si una tecla se produce en ms de un mapa, el mapeo de
este ltimo (de izquierda a derecha) ser el mapeo en el resultado.
(merge {:a 1 :b 2 :c
;;=> {:d 4, :a 1, :b
(merge {:a 1} nil)
(merge nil {:a 1})
(merge nil nil)

3} {:b 9 :d 4})
9, :c 3}
;=> {:a 1}
;=> {:a 1}
;=> nil

Devuelve un mapa que consiste en el resto de los mapas conj-ed hacia el primero.
Si una tecla se produce en ms de un mapa, el mapeo (s) de este ltimo (de izquie
rda a derecha) se combinar con la asignacin en el resultado llamando al (f valen-val-resultado-en este ltimo).
merge-with concat
{"Lisp" ["Common Lisp" "Clojure"]
"ML" ["Caml" "Objective Caml"]}
{"Lisp" ["Scheme"]
"ML" ["Standard ML"]})
;;=> {"Lisp" ("Common Lisp" "Clojure" "Scheme"), "ML" ("Caml" "Objective Caml" "S
tandard ML")}
(clojure.pprint/pp)
;; {"Lisp" ("Common Lisp" "Clojure" "Scheme"), "ML" ("Caml" "Objective Caml" "Sta
ndard ML")}
;;=> nil
;; merge two maps using the addition function
(merge-with +
{:a 1 :b 2}
{:a 9 :b 98 :c 0})
;;=> {:c 0, :a 10, :b 100}

Devuelve un mapa que contiene slo aquellas entradas en un mapa cuya clave est e
n las teclas
user=>
{:a 1}
user=>
{:a 1}
user=>
{:c 3,

(select-keys {:a 1 :b 2} [:a])


(select-keys {:a 1 :b 2} [:a :c])
(select-keys {:a 1 :b 2 :c 3} [:a :c])
:a 1}

'Actualizaciones' un valor en una estructura asociativa anidada, donde ks es un s


ecuencia de teclas y f es una funcin que tendr el valor antiguo y cualquier sum
inistran argumentos y devuelven el nuevo valor y devuelve un nuevo estructura ani
dada. Si no existen niveles, hash mapas sern creado.
(def users [{:name "James" :age 26}
#'user/users

{:name "John" :age 43}])

;; similar to assoc-in but does not simply replace the item.


;; the specified function is performed on the matching item.
;; here the age of the second (index 1) user is incremented.
(update-in users [1 :age] inc)
;;=> [{:name "James", :age 26} {:name "John", :age 44}]

Devuelve el mapa con las llaves en kmap renombrados para el vals en kmap
user=> (rename-keys {:a 1, :b 2} {:a :new-a, :b :new-b})
{:new-a 1, :new-b 2}
;; The behavior when the second map contains a key not in the first is interestin
g.
;; I suspect you shouldn't depend on it. (Clojure 1.1 - no longer happens in 1.2.
1)
user=> (rename-keys {:a 1} {:b :new-b})
{ :a 1, :new-b nil}

Devuelve el mapa con el vals asignadas a las teclas.


;; Despite being in clojure.set, this has nothing to do with sets.
user=> (map-invert {:a 1, :b 2})
{2 :b, 1 :a}
;; If there are duplicate keys, one is chosen:
user=> (map-invert {:a 1, :b 1})
{1 :b}
;; I suspect it'd be unwise to depend on which key survives the clash.

You might also like