domingo, 13 de diciembre de 2020

Primeros pasos con Clojure, parte 6

 


Seguimos con Clojure... 

Antes de empezar a hablar del Relp de Clojure, tenemos que saber un aspecto importante del Relp es que Clojure siempre compila la expresión antes de ejecutarla; Clojure siempre se compila en bytecode de JVM. No hay intérprete de Clojure.

El Relp de Clojure esta recopado, trae como unos trucos, que nos hacen la vida más fácil. Por ejemplo, algunos símbolos especiales recuerdan los resultados de evaluar las últimas tres expresiones:

  • * 1 (el último resultado)
  • * 2 (el resultado hace dos expresiones)
  • * 3 (el resultado hace tres expresiones)
Veamoslo en acción : 

user=> (+ 3 4)
7
user=> (+ 10 *1)
17
user=> (+ *1 *2)
24

Podemos llamar al espacio de nombres clojure.repl que se incluye en la biblioteca estándar de Clojure que proporciona una serie de funciones útiles. Para cargar esa biblioteca y hacer que sus funciones estén disponibles en nuestro contexto actual, debemos escribir :

user=> (require '[clojure.repl :refer :all])
nil

Ahora tenemos acceso a algunas funciones adicionales que son útiles en REPL: doc, find-doc, apropos, source y dir.

La función doc muestra la documentación de cualquier función. Veamos un ejemplo :

user=> (doc +)
-------------------------
clojure.core/+
([] [x] [x y] [x y & more])
  Returns the sum of nums. (+) returns 0. Does not auto-promote
  longs, will throw on overflow. See also: +'
nil

La función doc imprime la documentación para +, incluidas las firmas válidas.

La función doc imprime la documentación, luego devuelve nil como resultado; verá ambos en la salida de evaluación.

También podemos invocar doc sobre sí mismo:

user=> (doc doc)

-------------------------

clojure.repl/doc

([name])

Macro

  Prints documentation for a var or special form given its name,

   or for a spec if given a keyword

nil

Si no estamos seguros de cómo se llama algo podemos usar el comando apropos para buscar funciones que coincidan con una cadena o expresión regular en particular.

user=> (apropos "+")
(clj-stacktrace.repl/pst+ clojure.core/+ clojure.core/+' clojure.core/read+string clojure.spec.alpha/+ clojure.spec.alpha/rep+impl net.cgrand.parsley.grammar/->Repeat+ net.cgrand.parsley.grammar/map->Repeat+ net.cgrand.regex/+ net.cgrand.regex.charset/+)

También puede ampliar la búsqueda para incluir las cadenas de documentos en sí mismas con find-doc:

user=> (find-doc "trim")
-------------------------
clojure.pprint/ltrim
([s c])
  Trim all instances of c from the beginning of sequence s
-------------------------
clojure.pprint/rtrim
([s c])
  Trim all instances of c from the end of sequence s
-------------------------
clj-stacktrace.core/parse-cause-exception
([causer-e caused-parsed-elems])
  Like parse-exception, but for causing exceptions. The returned map has all
  of the same keys as the map returned by parse-exception, and one added one:
  :trimmed-elems  A subset of :trace-elems representing the portion of the
                  top of the stacktrace not shared with that of the caused
                  exception.
-------------------------
clj-stacktrace.core/trim-redundant
([causer-parsed-elems caused-parsed-elems])
  Returns the portion of the tail of causer-elems that is not duplicated in
  the tail of caused-elems. This corresponds to the "...26 more" that you
  see at the bottom of regular trace dumps.
-------------------------
leiningen.core.utils/git-file-contents
([git-dir ref-path])
  Returns the (trimmed) contents by the given git path, or nil if it is
  inacessible or nonexisting. If it exists and is not readable, a warning is
  printed.
-------------------------
clojure.string/trim
([s])
  Removes whitespace from both ends of string.
-------------------------
clojure.string/trim-newline
([s])
  Removes all trailing newline \n or return \r characters from
  string.  Similar to Perl's chomp.
-------------------------
clojure.string/triml
([s])
  Removes whitespace from the left side of string.
-------------------------
clojure.string/trimr
([s])
  Removes whitespace from the right side of string.
-------------------------
clojure.core/read+string
([] [stream] [stream eof-error? eof-value] [stream eof-error? eof-value recursive?] [opts stream])
  Like read, and taking the same args. stream must be a LineNumberingPushbackReader.
  Returns a vector containing the object read and the (whitespace-trimmed) string read.
-------------------------
clojure.core/subvec
([v start] [v start end])
  Returns a persistent vector of the items in vector from
  start (inclusive) to end (exclusive).  If end is not supplied,
  defaults to (count vector). This operation is O(1) and very fast, as
  the resulting vector shares structure with the original and no
  trimming is done.
nil

Si desea ver lla lista completa de las funciones en un espacio de nombres en particular, puede usar la función dir. Aquí podemos usarlo en el espacio de nombres clojure.repl:

user=> (dir clojure.repl)
apropos
demunge
dir
dir-fn
doc
find-doc
pst
root-cause
set-break-handler!
source
source-fn
stack-element-str
thread-stopper
nil

Y finalmente, podemos ver no solo la documentación sino el código fuente subyacente de cualquier función accesible por el tiempo de ejecución:

user=> (source dir)
(defmacro dir
  "Prints a sorted directory of public vars in a namespace"
  [nsname]
  `(doseq [v# (dir-fn '~nsname)]
     (println v#)))
nil


No hay comentarios.:

Publicar un comentario