Professional Documents
Culture Documents
** Numbers
**** Arithmetic
**** Compare
****Test
****TEST
****Random
** Strings
**** Create
;;
It is a
java.util.Formatter$Fo
;; 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))
java.util.Formatter$FormatS
;; 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.
The main
**** Use
(count "string")
;;=> 6
(count '(1 2 3 3 1))
;;=> 5
;; and as a koan
(= (count '(1 2 3 3 1)) 5)
;;=> true
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."
{\< "<", \> ">", \ & "&"})
"I want 1 < 2 as HTML, & other good things."
")
Splits s en \ no \ r \ n.
user=> (clojure.string/split-lines "test \n string")
["test " " string"]
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)
")
* Collections
** Collections
**** Generic ops:
()
[]
{}
#{}
[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]]
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
Devuelve false si (x pred) es lgico cierto para cualquier x en coll, cosa verdad
era.
**** Capabilities
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 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
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
;;=> (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 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)
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"]
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 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}
****Examine
[:a
[:a
"f"
"f"
:b :c] :b)
:b :c] 2)
0)
1)
;=>
;=>
;=>
;=>
false
true
true
false
;=> false
****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 { }
clojure.lang.PersistentArrayMap.cr
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}
(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"])
{:seconds 57, :date 13, :class java.util.Date, :minutes 55, :hours 17, :year 110,
:timezoneOffset -330, :month 6, :day 2, :time 1279023957492}
;; 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}}
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
:name])
:address :city])
:address :zip-code])
:address :zip-code] "no zip code!")
associative:
3]
6]
9]])
2])
1])
;;=> 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
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,
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}