diff options
36 files changed, 2694 insertions, 504 deletions
diff --git a/bash.html.markdown b/bash.html.markdown index 15d1c068..57fb5c55 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] - ["Denis Arh", "https://github.com/darh"] - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] filename: LearnBash.sh --- @@ -72,15 +73,26 @@ echo Hello, $NAME! # use 'man test' for more info about conditionals if [ $NAME -ne $USER ] then - echo "Your name is your username" -else echo "Your name isn't your username" +else + echo "Your name is your username" fi # There is also conditional execution echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" +# To use && and || with if statements, you need multiple pairs of square brackets: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "This will run if $NAME is Steve AND $AGE is 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "This will run if $NAME is Daniya OR Zach." +fi + # Expressions are denoted with the following format: echo $(( 10 + 5 )) @@ -122,14 +134,28 @@ case "$VARIABLE" in esac # for loops iterate for as many arguments given: -# The contents of var $VARIABLE is printed three times. +# The contents of $VARIABLE is printed three times. for VARIABLE in {1..3} do echo "$VARIABLE" done +# They can also be used to act on files.. +# This will run the command 'cat' on file1 and file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ..or the output from a command +# This will cat the output from ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + # while loop: -while [true] +while [ true ] do echo "loop body here..." break diff --git a/c.html.markdown b/c.html.markdown index 8e170300..79b7aec7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -573,7 +573,7 @@ typedef void (*my_fnp_type)(char *); '\''; // single quote '\"'; // double quote '\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo'; // octal number. Example: '\013' = vertical tab character +'\0oo'; // octal number. Example: '\013' = vertical tab character //print formatting: "%d"; // integer diff --git a/compojure.html.markdown b/compojure.html.markdown new file mode 100644 index 00000000..56f43cb7 --- /dev/null +++ b/compojure.html.markdown @@ -0,0 +1,225 @@ +--- +category: tool +tool: compojure +contributors: + - ["Adam Bard", "http://adambard.com/"] +filename: learncompojure.clj +--- + +## Getting Started with Compojure + +Compojure is a DSL for *quickly* creating *performant* web applications +in Clojure with minimal effort: + +```clojure +(ns myapp.core + (:require [compojure.core :refer :all] + [org.httpkit.server :refer [run-server]])) ; httpkit is a server + +(defroutes myapp + (GET "/" [] "Hello World")) + +(defn -main [] + (run-server myapp {:port 5000})) +``` + +Create a project with [Leiningen](http://leiningen.org/): + +``` +lein new myapp +``` + +Add your dependencies: + +``` +[compojure "1.1.8"] +[http-kit "2.1.16"] +``` + +And run: + +``` +lein run -m myapp.core +``` + +View at: <http://localhost:5000/> + +Compojure apps will run on any ring-compatible server, but we recommend +[http-kit](http://http-kit.org/) for its performance and +[massive concurrency](http://http-kit.org/600k-concurrent-connection-http-kit.html). + +### Routes + +In compojure, each route is an HTTP method paired with a URL-matching pattern, +an argument list, and a body. + +```clojure +(defroutes myapp + (GET "/" [] "Show something") + (POST "/" [] "Create something") + (PUT "/" [] "Replace something") + (PATCH "/" [] "Modify Something") + (DELETE "/" [] "Annihilate something") + (OPTIONS "/" [] "Appease something") + (HEAD "/" [] "Preview something")) +``` + +Compojure route definitions are just functions which +[accept request maps and return response maps](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(myapp {:uri "/" :request-method :post}) +; => {:status 200 +; :headers {"Content-Type" "text/html; charset=utf-8} +; :body "Create Something"} +``` + +The body may be a function, which must accept the request as a parameter: + +```clojure +(defroutes myapp + (GET "/" [] (fn [req] "Do something with req"))) +``` + +Route patterns may include named parameters, + +```clojure +(defroutes myapp + (GET "/hello/:name" [name] (str "Hello " name))) +``` + +You can match entire paths with * + +```clojure +(defroutes myapp + (GET "/file/*.*" [*] (str *))) +``` + +Handlers may utilize query parameters: + +```clojure +(defroutes myapp + (GET "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + " Do something with title and author")))) +``` + +Or, for POST and PUT requests, form parameters + +```clojure +(defroutes myapp + (POST "/posts" [] + (fn [req] + (let [title (get (:params req) "title") + author (get (:params req) "title")] + "Do something with title and author")))) +``` + + +### Return values + +The return value of a route block determines at least the response body +passed on to the HTTP client, or at least the next middleware in the +ring stack. Most commonly, this is a string, as in the above examples. +But, you may also return a [response body](https://github.com/mmcgrana/ring/blob/master/SPEC): + +```clojure +(defroutes myapp + (GET "/" [] + {:status 200 :body "Hello World"}) + (GET "/is-403" [] + {:status 403 :body ""}) + (GET "/is-json" [] + {:status 200 :headers {"Content-Type" "application/json"} :body "{}"})) +``` + +### Static Files + +To serve up static files, use `compojure.route.resources`. +Resources will be served from your project's `resources/` folder. + +```clojure +(require '[compojure.route :as route]) + +(defroutes myapp + (GET "/") + (route/resources "/")) ; Serve static resources at the root path + +(myapp {:uri "/js/script.js" :request-method :get}) +; => Contents of resources/public/js/script.js +``` + +### Views / Templates + +To use templating with Compojure, you'll need a template library. Here are a few: + +#### [Stencil](https://github.com/davidsantiago/stencil) + +[Stencil](https://github.com/davidsantiago/stencil) is a [Mustache](http://mustache.github.com/) template library: + +```clojure +(require '[stencil.core :refer [render-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string "Hello {{name}}" {:name name}))) +``` + +You can easily read in templates from your resources directory. Here's a helper function + +```clojure +(require 'clojure.java.io) + +(defn read-template [filename] + (slurp (clojure.java.io/resource filename))) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-string (read-template "templates/hello.html") {:name name}))) +``` + +#### [Selmer](https://github.com/yogthos/Selmer) + +[Selmer](https://github.com/yogthos/Selmer) is a Django and Jinja2-inspired templating language: + +```clojure +(require '[selmer.parser :refer [render-file]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (render-file "templates/hello.html" {:name name}))) +``` + +#### [Hiccup](https://github.com/weavejester/hiccup) + +[Hiccup](https://github.com/weavejester/hiccup) is a library for representing HTML as Clojure code + +```clojure +(require '[hiccup.core :as hiccup]) + +(defroutes myapp + (GET "/hello/:name" [name] + (hiccup/html + [:html + [:body + [:h1 {:class "title"} + (str "Hello " name)]]]))) +``` + +#### [Markdown](https://github.com/yogthos/markdown-clj) + +[Markdown-clj](https://github.com/yogthos/markdown-clj) is a Markdown implementation. + +```clojure +(require '[markdown.core :refer [md-to-html-string]]) + +(defroutes myapp + (GET "/hello/:name" [name] + (md-to-html-string "## Hello, world"))) +``` + +Further reading: + +[Clojure for the Brave and True](http://www.braveclojure.com/) diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown new file mode 100644 index 00000000..98a452ba --- /dev/null +++ b/de-de/coffeescript-de.html.markdown @@ -0,0 +1,106 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Frederik Ring", "https://github.com/m90"] + - ["Philipp Fischbeck", "https://github.com/PFischbeck"] +filename: coffeescript-de.coffee +lang: de-de +--- + +CoffeeScript ist eine kleine Sprache, die eins zu eins nach JavaScript übersetzt wird - es findet keine Interpretation zur Laufzeit statt. +Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes, lesbaren, gut formatierten und sauber laufenden JavaScript-Code zu erzeugen, der in jeder JavaScript-Laufzeit einwandfrei funktioniert. + +Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführliches Tutorial. + +``` coffeescript +# CoffeeScript ist eine dieser Sprachen für "Hipster" +# und folgt daher vielen Trends und Einflüssen aus modernen Sprachen. +# Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet + +### +Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *'s und '* /'s +im erzeugten JavaScript umgewandelt. + +Vorweg: bevor du mit CoffeeScript anfängst, solltest du bereits einen guten +Überblick über die Sprache JavaScript haben. +### + +# Zuweisung: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Bedingungen: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Funktionen: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "Kaffee") -> + "#{container} wird mit #{liquid} gefüllt..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "Kaffee"; +# } +# return container + " wird mit " + liquid + " gefüllt..."; +#}; + +# "Ranges": +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objekte: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +#} + +# "Splats": +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +#}; + +# Existenz-Operator: +alert "Hab ich's nicht gesagt?" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); } + +# Listen-Abstraktion: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['Brokkoli', 'Spinat', 'Schokolade'] +eat food for food in foods when food isnt 'Schokolade' +#=>foods = ['Brokkoli', 'Spinat', 'Schokolade']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'Schokolade') { +# eat(food); +# } +#} +``` + +## Weiterführende Links + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 8c2f58dd..ca27fdc7 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -79,7 +79,7 @@ func learnTypes() { Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel. - g := 'Σ' // Ein Runen-Typ, alias uint32, gebraucht für unicode code points. + g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points. f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl c := 3 + 4i // complex128, besteht intern aus zwei float64-er diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 0418b2b6..38ce28e2 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -397,8 +397,8 @@ var myNumberObj = new Number(12); myNumber == myNumberObj; // = true
// Genau genommen: Sie sind nicht exakt äquivalent.
-typeof(myNumber); // = 'number'
-typeof(myNumberObj); // = 'object'
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
// Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
diff --git a/es-es/bash-es.html.markdown b/es-es/bash-es.html.markdown new file mode 100644 index 00000000..489fd39e --- /dev/null +++ b/es-es/bash-es.html.markdown @@ -0,0 +1,195 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] +translators: + - ["Daniel Zendejas", "https://github.com/danielzendejas"] +filename: LearnBash-es.sh +--- + +Tutorial de Shell en español. + +Bash es el nombre del shell de unix, el cual también es distribuido como +el shell del sistema operativo GNU. También es el shell +por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden +ser parte de un script shell o ser ejecutados directamente en la terminal. + +[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash + +# La primera línea del script es el [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) que le indica al sistema +# cómo ejecutar el script. +# Como te habrás dado cuenta, los comentarios en shell empiezan con #. +# El shebang también es un comentario. + +# Ejemplo sencillo de hola mundo: +echo ¡Hola mundo! + +# Cada comando empieza con una nueva línea, o después de un punto y coma: +echo 'Esta es la primera línea'; echo 'Esta es la segunda línea' + +# Para declarar una variable se hace lo siguiente: +VARIABLE="Mi string" + +# Pero no así: +VARIABLE = "Mi string" + +# Bash decidirá que VARIABLE es un comando a ejecutar, dando un error. + +# Usando la variable: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' + +# Cuando la variable es usada - o asignada, exportada, etcétera - se +# escribe su nombre sin $. Si se quiere saber el valor de la variables, +# entonces sí se usa $. Note que ' (comilla simple) no expandirá las +# variables. + +# Sustitución de strings en variables. +echo ${VARIABLE/Mi/Una} +# Esto sustituirá la primera cadena "Mi" con "Una". + +# Substring de una variable. +echo ${VARIABLE:0:7} +# Esto va a regresar sólo los primeros 7 caracteres del valor. + +# Valor por defecto de una variable +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# Esto trabaja para null (VARIABLE=), string vacío (VARIABLE=""), } +# cero (VARIABLE=0) regresa 0 + +# Variables del sistema: +# Aquí hay algunas variables incluídas en el sistema: +echo "El valor de regreso del último programa: $?" +echo "PID del sistema: $$" +echo "Número de argumentos: $#" +echo "Argumentos del script: $@" +echo "Argumentos del script separados en variables: $1 $2..." + +# Para leer un valor del input: +echo "¿Cuál es tu nombre?" +read NOMBRE # Note que no necesitamos declarar una variable +echo ¡Hola, $NOMBRE! + +# Tenemos la estructura 'if' usual: +# use 'man test' para más información sobre condicionales +if [ $NOMBRE -ne $USER ] +then + echo "Tu nombre es tu usuario." +else + echo "Tu nombre no es tu usuario." +fi + +# También hay ejecuciones condicionadas. +echo "Siempre ejecutado" || echo "Sólo ejecutado si el primer comando falla" +echo "Siempre ejecutado" && echo "Sólo ejecutado si el primer comando NO falla" + +# Para usar && y || con condicionales, se necesitan +# múltiples pares de corchetes: +if [ $NOMBRE == "Steve" ] && [ $EDAD -eq 15 ] +then + echo "Esto correrá si $NOMBRE es Steve Y $EDAD es 15." +fi + +if [ $NOMBRE == "Daniya" ] || [ $NOMBRE == "Zach" ] +then + echo "Esto correrá si $NOMBRE es Daniya O Zach." +fi + +# Las expresiones se denotan con el siguiente formato: +echo $(( 10 + 5 )) + +# A diferencia de otros lenguajes de programación, bash es shell , así que +# funciona en un contexto de directorio actual. Puedes listar archivos y +# directorios en un directorio actual con el comando 'ls': +ls + +# Estos comandos tienen opciones que controlan su ejecución: +ls -l # Lista todos los archivos y directorios en líneas distintas. + +# Los resultados del comando anterior pueden ser pasados al siguiente +# como input. El comando 'grep' filtra el input con los comandos provistos. +# Así es como podemos listar archivos .txt en el directorio actual: +ls -l | grep "\.txt" + +# Puedes también redireccionar el input y el error lanzado de algún comando. +python2 hello.py < "input.in" +python2 hello.py > "output.out" +python2 hello.py 2> "error.err" + +# El error lanzado eliminará el contenido del archivo si es que existe, +# para después escribir el error. Para que se concatene (en lugar de eliminar) +# use el comando ">>". + +# Los comandos pueden ser sustituidos dentro de otros comandos usando $(): +# El siguiente ejemplo despliega el número de archivos y directorios en el +# directorio actual. +echo "Hay $(ls | wc -l) elementos aquí." + +# Lo mismo puede ser hecho usando comillas invertidas `` pero no pueden ser +# anidadas. El método preferido es $(). +echo "Hay `ls | wc -l` elementos aquí." + +# Bash usa una estructura de casos similar al switch de Java o C++: +case "$VARIABLE" in + # Lista de patrones que las condiciones deben cumplir: + 0) echo "Hay un cero.";; + 1) echo "Hay un uno.";; + *) echo "No es null.";; +esac + +# Para los ciclos, se usa la estructura 'for'. Cicla para cada argumento dado: +# El contenido de $VARIABLE se imprime tres veces. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# ciclos while: +while [true] +do + echo "cuerpo del ciclo..." + break +done + +# También se pueden definir sub-rutinas (funciones) +# Definición: +function miFuncion () +{ + echo "Los argumentos trabajan igual que argumentos de script: $@" + echo "Y: $1 $2..." + echo "Esto es una función" + return 0 +} + +# O simplemente: +miOtraFuncion () +{ + echo "¡Otra forma de declarar funciones!" + return 0 +} + +# Para llamar a tu función +foo "Mi nombre es:" $NOMBRE + +# Hay muchos comandos útiles que puedes aprender: +# imprime las últimas 10 líneas del archivo file.txt +tail -n 10 file.txt +# imprime las primeras 10 líneas del archivo file.txt +head -n 10 file.txt +# ordena las líneas del archivo file.txt +sort file.txt +# identifica u omite las líneas repetidas, con -d las reporta +uniq -d file.txt +# imprime sólo la primera columna antes de cada ',' en el archivo| +cut -d ',' -f 1 file.txt +``` diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown new file mode 100644 index 00000000..e33d672d --- /dev/null +++ b/es-es/brainfuck-es.html.markdown @@ -0,0 +1,87 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- + +Brainfuck (con mayúscula sólo al inicio de una oración) es un +lenguaje de programación mínimo, computacionalmente universal +en tamaño con sólo 8 comandos. + +``` + +Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) +será ignorado. + +Brainfuck es representado por un arreglo de 30,000 celdas inicializadas +en cero y un apuntador en la celda actual. + +Existen ocho comandos: + ++ : Incrementa 1 al valor de la celda actual. +- : Decrementa 1 al valor de la celda actual. +> : Mueve el apuntador a la siguiente celda. (a la derecha) +< : Mueve el apuntador a la celda anterior. (a la izquierda) +. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A') +, : Lee un caracter como input y lo escribe en la celda actual. +[ : Si el valor en la celda actual es cero mueve el apuntador + hasta el primer ']' que encuentre. Si no es cero sigue a la + siguiente instrucción. +] : Si el valor en la celda actual es cero, entonces sigue con + la siguiente instrucción. Si no entonces mueve el apuntador + hacia atrás hasta encontrar el primer '['. + +[ y ] forman un while. Obviamente, deben estar balanceados. + +Ahora unos ejemplos de programas escritos con brainfuck. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a +6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo +([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces, +y se regresa a la celda #1 (<), para después decrementarla en 1 (-). +Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0), +cuando esto pasa se salta a (]) y continúa. + +En este punto estamos en la celda #1, que tiene un valor de 0, mientras +que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>), +la incrementamos 5 veces para tener un valor de 65 y luego imprimimos +el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A' +se imprime. + +, [ > + < - ] > . + +Este programa lee un caracter del input y lo copia en la celda #2 (,). +Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su +valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-). +Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un +cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre +terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). + +Ten en mente que los espacios son sólo para fines de legibilidad. +Es lo mismo escribir el ejemplo de arriba que esto: +,[>+<-]>. + +Intenta descrifrar lo que hace este programa: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa toma dos números como input y los multiplica. + +Primero recibe dos números del usuario. Luego empieza el ciclo externo, +condicionado en la celda #1. Luego se mueve a la celda #2, comenzando +el ciclo interno condicionado en la celda #2 incrementando la celda #3. +Sin embargo viene un problema: El ciclo interior no funcionará nuevamente +hasta la próxima vez. Para resolver este problema también incrementamos la +celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene +el resultado. +``` +Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir +tu propio intérprete de brainfuck o tu propio programa en brainfuck. El +intérprete es relativamente sencillo de hacer, pero si eres masoquista, +intenta construir tu proprio intérprete de brainfuck... en brainfuck. diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index e788e810..86de33ec 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -77,7 +77,7 @@ func learnTypes() { saltos de línea.` // mismo tipo cadena // Literal no ASCII. Los fuentes de Go son UTF-8. - g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode. + g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode. f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. c := 3 + 4i // complex128, representado internamente por dos float64. // Sintaxis Var con inicializadores. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 9b412f6e..a1348508 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -471,8 +471,8 @@ var miNumeroObjeto = new Number(12); miNumero == miNumeroObjeto; // = true // No son exactamente iguales. -typeof(miNumero); // = 'number' -typeof(miNumeroObjeto); // = 'object' +typeof miNumero; // = 'number' +typeof miNumeroObjeto; // = 'object' miNumero === miNumeroObjeyo; // = false if (0){ // Este código no se ejecutara porque 0 es false. diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index 4f0c26c1..644182ff 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -7,23 +7,24 @@ contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] translators: - ["Francisco Gomez", "http://github.com/frncscgmz"] + - ["Joaquín Ferrero", "http://github.com/joaquinferrero"] lang: es-es --- -Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo. +Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo. -Perl 5 corre en mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala. +Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala. ```perl -# Comentarios de una sola linea con un carácter hash. +# Comentarios de una sola línea con un carácter hash #### Tipos de variables en Perl -# Las variables comienzan con el símbolo $. -# Un nombre de variable valido empieza con una letra o un guión bajo, -# seguido por cualquier numero de letras, números o guiones bajos. +# Las variables comienzan con el símbolo $ +# Un nombre de variable válido empieza con una letra o un guión bajo, +# seguido por cualquier número de letras, números o guiones bajos -### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes. +### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes ## Escalares # Un escalar representa un solo valor: @@ -31,99 +32,98 @@ my $animal = "camello"; my $respuesta = 42; # Los valores escalares pueden ser cadenas de caracteres, números enteros o -# de punto flotante, Perl automáticamente los convertirá como sea requerido. +# de punto flotante; Perl automáticamente los convertirá como sea requerido ## Arreglos # Un arreglo representa una lista de valores: -my @animales = {"camello","llama","buho"}; -my @numeros = {23,42,69}; -my @mixto = {"camello",42,1.23}; - - +my @animales = ("camello","llama","buho"}; +my @numeros = (23, 42, 69); +my @mixto = ("camello", 42, 1.23); ## Hashes -# Un hash representa un conjunto de pares llave/valor: - -my %color_fruta = {"manzana","rojo","banana","amarillo"}; - -# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas -# fácilmente. +# Un hash representa un conjunto de pares llave/valor: +my %color_fruta = ("manzana","rojo","banana","amarillo"); +# Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente my %color_fruta = ( manzana => "rojo", banana => "amarillo", - ); -# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata). +); -# Los tipos de datos mas complejos pueden ser construidos utilizando -# referencias, las cuales te permiten construir listas y hashes dentro -# de listas y hashes. +# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata) -#### Estructuras condicionales y de ciclos +# Los tipos de datos más complejos se pueden construir utilizando +# referencias, las cuales le permiten construir listas y hashes dentro +# de listas y hashes -# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes. +#### Estructuras condicionales y de ciclos +# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes if ( $var ) { - ... + ...; } elsif ( $var eq 'bar' ) { - ... + ...; } else { - ... + ...; } unless ( condicion ) { - ... - } -# Esto es proporcionado como una version mas fácil de leer que "if (!condición)" + ...; +} -# La post condición al modo Perl +# Esto se ofrece como una versión más fácil de leer que "if (!condición)" + +# La postcondición al modo Perl: print "Yow!" if $zippy; print "No tenemos bananas" unless $bananas; # while - while ( condicion ) { - ... - } - +while ( condicion ) { + ...; +} # for y foreach for ($i = 0; $i <= $max; $i++) { - ... - } + ...; +} + +for $i (0 .. $max) { + ...; +} foreach (@array) { - print "Este elemento es $_\n"; - } + print "Este elemento es $_\n"; +} #### Expresiones regulares -# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es -# sujeto a una extensa documentación en perlrequick, perlretut, entre otros. +# El soporte de expresiones regulares en Perl es muy amplio y profundo, y +# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros. # Sin embargo, resumiendo: -# Pareo simple +# Coincidencia simple if (/foo/) { ... } # verdadero si $_ contiene "foo" if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo" # Substitución simple -$a =~ s/foo/bar/; # remplaza foo con bar en $a -$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a +$a =~ s/foo/bar/; # remplaza "foo" con "bar" en $a +$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en $a -#### Archivos e I/O +#### Archivos y E/S -# Puedes abrir un archivo para obtener datos o escribirlos utilizando la -# función "open()". +# Puede abrir un archivo para obtener datos o escribirlos utilizando la +# función "open()" open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!"; open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!"; open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!"; -# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>" -# operador. En contexto escalar leer una sola linea desde el gestor de -# archivo, y en contexto de lista leer el archivo completo en donde, asigna -# cada linea a un elemento de la lista. +# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>". +# En contexto escalar, leer una sola línea desde el gestor de archivo, y +# en contexto de lista, leer el archivo completo en donde asigna +# cada línea a un elemento de la lista my $linea = <$entrada>; my @lineas = <$entrada>; @@ -131,30 +131,26 @@ my @lineas = <$entrada>; #### Escribiendo subrutinas # Escribir subrutinas es fácil: - sub logger { my $mensajelog = shift; open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!"; print $archivolog $mensajelog; } -# Ahora podemos utilizar la subrutina al igual que cualquier otra función -# incorporada: - +# Ahora podemos utilizar la subrutina al igual que cualquier otra función incorporada: logger("Tenemos una subrutina logger!"); - ``` #### Utilizando módulos Perl -Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl. +Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl. -perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar. +perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar. #### Material de Lectura - [perl-tutorial](http://perl-tutorial.org/) - - [Aprende en www.perl.com](http://www.perl.org/learn.html) + - [Learn Perl](http://www.perl.org/learn.html) - [perldoc](http://perldoc.perl.org/) - - y perl incorporado: `perldoc perlintro` + - y en su propio perl: `perldoc perlintro` diff --git a/es-es/whip-es.html.markdown b/es-es/whip-es.html.markdown new file mode 100644 index 00000000..7c2f4bd2 --- /dev/null +++ b/es-es/whip-es.html.markdown @@ -0,0 +1,255 @@ +--- +language: whip +contributors: + - ["Tenor Biel", "http://github.com/L8D"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +author: Tenor Biel +author_url: http://github.com/L8D +filename: whip-es.lisp +lang: es-es +--- +Tutorial de Whip en español. + +Whip es un dialecto de LISP hecho para escribir código y conceptos +simples. Ha tomado prestado bastante de la sintaxis de Haskell +(un lenguaje no relacionado). + +Esta documentación fue escrita por el creador del lenguaje + +```scheme +; Los comentarios son como en LISP, con punto y coma... + +; La mayoría de las sentencias de primer nivel están dentro de +; "formas". Una forma no es más que cosas dentro de paréntesis +no_en_la_forma +(en_la_form) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 1. Números, Strings y Operadores + +;Whip tiene un tipo para números (es el estándar 64-bit IEEE 754 double, de JS) +3 ; => 3 +1.5 ; => 1.5 + +; Las funciones son llamadas si son el primer elemento de una forma +(funcion_llamada argumentos) + +; La mayoría de los operadores se hacen con funciones +; Toda la aritmética básica es bastante estándar +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 +; incluso el módulo +(% 9 4) ; => 1 +; división impar al estilo de JavaScript. +(/ 5 2) ; => 2.5 + +; Las formas anidadas funcionan como se espera. +(* 2 (+ 1 3)) ; => 8 + +; Hay un tipo booleano. +true +false + +; Los Strings son creados con comillas dobles ". +"Hola mundo" + +; Los caracteres solos se declaran con comillas simples '. +'a' + +; La negación usa la función 'not'. +(not true) ; => false +(not false) ; => true + +; La mayoría de las funcions que no vienen de Haskell tienen +; atajos. La función 'not' también se puede declarar con '!'. +(! (! true)) ; => true + +; La igualdad es `equal` o `=`. +(= 1 1) ; => true +(equal 2 1) ; => false + +; Por ejemplo, la desigualdad sería combinar la función 'not' con +; la función de igualdad +(! (= 2 1)) ; => true + +; Más comparaciones +(< 1 10) ; => true +(> 1 10) ; => false +; y su contraparte textual. +(lesser 1 10) ; => true +(greater 1 10) ; => false + +; Los Strings pueden concatenarse con la función +. +(+ "Hola " "mundo!") ; => "Hello world!" + +; También puedes usar las comparativas de JavaScript +(< 'a' 'b') ; => true +; ...y la coerción de tipos +(= '5' 5) + +; La función 'at' o @ accesa a los caracteres dentro de los strings, +; empezando en 0. +(at 0 'a') ; => 'a' +(@ 3 "foobar") ; => 'b' + +; También están las variables `null` and `undefined`. +null; usado para indicar una falta de valor deliberada. +undefined; usado para indicar un valor que aún no está definido. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 2. Variables, Listas y Diccionarios + +; Las variables son declaradas con las funciones `def` o `let`. +; Las variables que aún no son asignadas tendrán el valor `undefined`. +(def mi_variable 5) +; `def` asignará la variable al contexto global. +; `let` asignará la variable al contexto local, +; y tiene una sintaxis distinta. +(let ((mi_variable 5)) (+ mi_variable 5)) ; => 10 +(+ mi_variable 5) ; = undefined + 5 => undefined + +; Las listas son arreglos de valores de cualquier tipo. +; Básicamente, son formas sin funciones al inicio. +(1 2 3) ; => [1, 2, 3] (sintaxis JavaScript) + +; Los diccionarios son el equivalente en Whip de los 'objetos' de JavaScript, +; los 'dicts' de Python o los 'hashes' de Ruby: una colección desordenada +; de pares llave-valor +{"llave1" "valor1" "llave2" 2 3 3} + +; Las llaves son sólo valores, identificadores, números o strings. +(def mi_diccionario {mi_llave "mi_valor" "mi otra llave" 4}) +; Pero con Whip, los diccionarios son leidos así: +; "llave" "espacio en blanco" "valor" "espacio en blanco" +{"llave" "valor" +"otra llave" +1234 +} + +; Las definiciones de los diccionarios pueden accesarse con la función @ +; (como los strings y las listas) +(@ "mi otra llave" mi_diccionario) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; 3. Logica y secuencias de control + +; La funcion `if` es bastante simple, aunque distinta que en otros lenguajes. +(if true "regresa esto si es true" "regresa esto si es false") +; => "regresa esto si es true" + +; Y para el operador ternario `?` +(? false true false) ; => false + +? `both` es un 'y' lógico, mientras que la función `either` es un 'o'. +(both true true) ; => true +(both true false) ; => false +(either true false) ; => true +(either false false) ; => false +; Y sus atajos son '&' y '^' respectivamente +; & => both +; ^ => either +(& true true) ; => true +(^ false true) ; => true + +;;;;;;;;; +; Lambdas + +; Las Lambdas en Whip son declaradas con las funciones `lambda` o `->`. +; Las funciones regulares en realidad sólo son lambdas con nombre. +(def mi_funcion (-> (x y) (+ (+ x y) 10))) +; | | | | +; | | | valor regresado(estas son las variables argumentos) +; | | argumentos +; | declaración de lambda +; | +; nombre de la lambda + +(mi_funcion 10 10) ; = (+ (+ 10 10) 10) => 30 + +; Obviamente, todas las lambdas por definición son anónimas y +; técnicamente siempre usadas anónimamente. Redundancia. +((lambda (x) x) 10) ; => 10 + +;;;;;;;;;;;;;;;; +; Comprensiones + +; `range` o `..` genera una lista de números que comprende +; cada entero dentro de los argumentos. +(range 1 5) ; => (1 2 3 4 5) +(.. 0 2) ; => (0 1 2) + +; `map` aplica su primer argumento (que debe ser una función) +; al siguiente argumento (que es una lista). +(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) + +; Reducir +(reduce + (.. 1 5)) +; equivale a +((+ (+ (+ 1 2) 3) 4) 5) + +; Nota: map y reduce no tienen atajos. + +; `slice` o `\` es idéntico a la función .slice() de JavaScript +; Pero toma la lista del primer argumento, no del último. +(slice (.. 1 5) 2) ; => (3 4 5) +(\ (.. 0 100) -5) ; => (96 97 98 99 100) + +; `append` o `<<` se explica solo. +(append 4 (1 2 3)) ; => (1 2 3 4) +(<< "bar" ("foo")) ; => ("foo" "bar") + +; Length se explica solo. +(length (1 2 3)) ; => 3 +(_ "foobar") ; => 6 + +;;;;;;;;;;;;;;; +; Elementos de Haskell + +; Primer elemento en una lista +(head (1 2 3)) ; => 1 + +; Lista del segundo elemento al último en una lista +(tail (1 2 3)) ; => (2 3) + +; Último elemento en una lista +(last (1 2 3)) ; => 3 + +; Contrario a `tail` +(init (1 2 3)) ; => (1 2) + +; Lista del primer elemento al argumento +(take 1 (1 2 3 4)) ; (1 2) + +; Contrario a `take` +(drop 1 (1 2 3 4)) ; (3 4) + +; Valor más pequeño de una lista +(min (1 2 3 4)) ; 1 + +; Valor más grande de una lista +(max (1 2 3 4)) ; 4 + +; Comprobar que el elemento está en la lista +(elem 1 (1 2 3)) ; true +(elem "foo" {"foo" "bar"}) ; true +(elem "bar" {"foo" "bar"}) ; false + +; Invertir el orden de la lista +(reverse (1 2 3 4)) ; => (4 3 2 1) + +; Comprobar si un elemento es par o impar +(even 1) ; => false +(odd 1) ; => true + +; Separar string en una lista de strings, separados por espacios +(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") +; Juntar lista de strings. +(unwords ("foo" "bar")) ; => "foobar" +(pred 21) ; => 20 +(succ 20) ; => 21 +``` + +Para más información, revisa el [repositorio](http://github.com/L8D/whip) diff --git a/es-es/xml-es.html.markdown b/es-es/xml-es.html.markdown new file mode 100644 index 00000000..2e9326cf --- /dev/null +++ b/es-es/xml-es.html.markdown @@ -0,0 +1,131 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Daniel Zendejas", "https://github.com/DanielZendejas"] +lang: es-es +--- +XML es un lenguaje diseñado para guardar y transportar datos + +A diferencia de HTML, XML no especifica cómo desplegar la información, +sólo la guarda. + +* Sintaxis XML + +```xml +<!-- Los comentarios en XML son de esta forma --> + +<?xml version="1.0" encoding="UTF-8"?> +<tiendaDeLibros> + <libro categoria="COCINA"> + <titulo lenguaje="en">Everyday Italian</titulo> + <autor>Giada De Laurentiis</autor> + <anio>2005</anio> + <precio>30.00</precio> + </libro> + <libro categoria="INFANTES"> + <titulo lenguaje="en">Harry Potter</titulo> + <autor>J K. Rowling</autor> + <anio>2005</anio> + <precio>29.99</precio> + </libro> + <libro categoria="WEB"> + <titulo lenguaje="en">Learning XML</titulo> + <autor>Erik T. Ray</autor> + <anio>2003</anio> + <precio>39.95</precio> + </libro> +</tiendaDeLibros> + +<!-- Este es un archivo típico de XML. + Empieza con una declaración de metadatos (opcional). + + XML usa una estructura de árbol. El nodo raíz es 'tiendaDeLibros', el cual + tiene tres nodos hijos, todos llamados 'libros'. + Esos nodos tienen más nodos hijos, y así continúa... + + Los nodos son creados usando tags que abren y cierran, y los hijos + son sólo nodos entre estas tags.--> + + +<!-- XML guarda dos tipos de datos: + 1 - Atributos -> Son los metadatos de un nodo. + Usualmente el parseador XML usa esta información para guardar los datos + apropiadamente. Aparecen con el formato (nombre="valor") dentro de la + tag que abre. + 2 - Elementos -> Ese es el dato puro. + Eso es lo que el parseador recuperará del archivo XML. + Los elementos aparecen entre las tags que abren y cierran.--> + + +<!-- Debajo, un elemento con dos atributos. --> +<archivo tipo="gif" id="4293">computer.gif</archivo> + + +``` + +* Documentos con buen formato x Validación + +Un documento XML está bien formado cuando es sintácticamente correcto. +Aún esto, es posible inyectar más restricciones en el documento, +usando definiciones de documento, así como DTD o XML Schemas. + +Un documento XML que sigue a una definición de documento (un esquema) es +válida. + +Con esta herramienta puedes validar datos XML fuera de la aplicación + +```xml + +<!-- Debajo puedes encontrar una versión simplificada del documento + tiendaDeLibros en adición a la definición DTD.--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "tiendaDeLibros.dtd"> +<tiendaDeLibros> + <libro categoriq="COCINA"> + <titulo>Everyday Italian</titulo> + <precio>30.00</precio> + </libro> +</tiendaDeLibros> + +<!-- El DTD de este documento podría verse algo así:--> + +<!DOCTYPE note +[ +<!ELEMENT tiendaDeLibros (libro+)> +<!ELEMENT libro (titulo,precio)> +<!ATTLIST libro categoria CDATA "Literatura"> +<!ELEMENT titulo (#PCDATA)> +<!ELEMENT precio (#PCDATA)> +]> + +<!--El DTD empieza con una declaración. + Después el nodo raíz es declarado, requiriendo 1 o más nodos 'libro' + Cada 'libro' debe contener exactamente un 'titulo' y un 'precio' y + un atributo llamado 'categoria', con "Literatura" como su valor + default. + Los nodos 'titulo' y 'precio' contienen datos de caracteres + parseados. + + El DTD puede ser declarado dentro del XML mismo.--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT tiendaDeLibros (libro+)> +<!ELEMENT libro (titulo,precio)> +<!ATTLIST libro categoria CDATA "Literatura"> +<!ELEMENT titulo (#PCDATA)> +<!ELEMENT precio (#PCDATA)> +]> +<tiendaDeLibros> + <libro categoriq="COCINA"> + <titulo>Everyday Italian</titulo> + <precio>30.00</precio> + </libro> +</tiendaDeLibros> +``` diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown new file mode 100644 index 00000000..a5157b5d --- /dev/null +++ b/es-es/yaml-es.html.markdown @@ -0,0 +1,151 @@ +--- +language: yaml +lang: es-es +filename: learnyaml-es.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Daniel Zendejas","https://github.com/DanielZendejas"] +--- +Tutorial de YAML en español. + +YAML es un lenguaje de serialización de datos diseñado para ser +leído y escrito por humanos. + +Basa su funcionalidad en JSON, con la adición de líneas nuevas +e indentación inspirada en Python. A diferencia de Python, YAML +no permite tabs literales. + +```yaml +# Los comentarios en YAML se ven así. + +################### +# TIPOS ESCALARES # +################### + +# Nuestro objeto raíz (el cual es el mismo a lo largo de todo el +# documento) será un mapa, equivalente a un diccionario, hash, +# u objeto en otros lenguajes. + +llave: valor +otra_llave: Otro valor +un_valor_numerico: 100 +notacion_cientifica: 1e+12 +booleano: true +valor_nulo: null +llave con espacios: valor +# Nótese que los strings no deben estar entre comillas, aunqué también es válido. +llave: "Un string, entre comillas." +"Las llaves tambien pueden estar entre comillas.": "valor entre comillas" + +# Los strings de líneas múltiples pueden ser escritos +# como un 'bloque literal' (usando pipes |) +# o como un 'bloque doblado' (usando >) + +bloque_literal: | + Este bloque completo de texto será preservado como el valor de la llave + 'bloque_literal', incluyendo los saltos de línea. + + Se continúa guardando la literal hasta que se cese la indentación. + Cualquier línea que tenga más indentación, mantendrá los espacios dados + (por ejemplo, estas líneas se guardarán con cuatro espacios) + +nloque_doblado: > + De la misma forma que el valor de 'bloque_literal', todas estas + líneas se guardarán como una sola literal, pero en esta ocasión todos los + saltos de línea serán reemplazados por espacio. + + Las líneas en blanco, como la anterior, son convertidos a un salto de línea. + + Las líneas con mayor indentación guardan sus saltos de línea. + Esta literal ocuparán dos líneas. + +######################## +# TIPOS DE COLECCIONES # +######################## + +# La indentación se usa para anidar. +un_mapa_indentado: + llave: valor + otra_llave: otro valor + otro_mapa_indentado: + llave_interna: valor_interno + +# Las llaves de los mapas no deben ser strings necesariamente +0.25: una llave numérica + +# Las llaves también pueden ser objetos de multi línea, usando ? para indicar +# el inicio de una llave +? | + Esto es una llave + que tiene múltiples líneas +: y este es su valor + +# YAML tambien permite colecciones como llaves, pero muchos lenguajes de +# programación se quejarán. + +# Las secuencias (equivalentes a listas o arreglos) se ven así: +una_secuencia: + - Item 1 + - Item 2 + - 0.5 # las secuencias pueden tener distintos tipos en su contenido. + - Item 4 + - llave: valor + otra_llave: otro_valor + - + - Esta es una secuencia + - ...dentro de otra secuencia + +# Dado que todo JSON está incluído dentro de YAML, también puedes escribir +# mapas con la sintaxis de JSON y secuencias: +mapa_de_json: {"llave": "valor"} +secuencia_de_json: [3, 2, 1, "despegue"] + +################################## +# CARACTERÍSTICAS EXTRAS DE YAML # +################################## + +# YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten +# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo +# a continuación, ambas llaves tendrán el mismo valor: +contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves +otra_ancla: *nombre_del_ancla + +# YAML también tiene tags, que puedes usar para declarar tipos explícitamente. +string_explícito: !!str 0.5 +# Algunos parseadores implementar tags específicas del lenguaje, como el +# que se muestra a continuación, encargado de manejar números complejos en +# Python: +numero_complejo_python: !!python/complex 1+2j + +######################## +# TIPOS EXTRAS EN YAML # +######################## + +# Stirngs y números no son los únicos escalares que YAML puede entener. +# YAML también puede parsear fechas en formato ISO . +fechaHora: 2001-12-15T02:59:43.1Z +fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5 +fecha: 2002-12-14 + +# La tag !!binary indica que un string es, en realidad, un blob +# representado en base-64. +archivo_gif: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML también tiene un tipo set, que se ve de la siguiente forma: +set: + ? item1 + ? item2 + ? item3 + +# Al igual que Python, los sets sólo son mapas con valores nulos. +# El ejemplo de arriba es equivalente a: +set2: + item1: null + item2: null + item3: null +``` diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown index 922fe416..5c64d24a 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript.html.markdown @@ -493,8 +493,8 @@ myNumber == myNumberObj; // = true <p dir='rtl'>به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.</p> ```js -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 3060bd75..75c8d0d3 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -336,8 +336,8 @@ class Humain puts "#{msg}" end - def species - @@species + def espece + @@espece end end diff --git a/go.html.markdown b/go.html.markdown index 5247ecf8..758c9ff4 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -12,7 +12,7 @@ contributors: - ["Alexej Friesen", "https://github.com/heyalexej"] --- -Go was created out of the need to get work done. It's not the latest trend +Go was created out of the need to get work done. It's not the latest trend in computer science, but it is the newest fastest way to solve real-world problems. @@ -26,7 +26,7 @@ Go comes with a great standard library and an enthusiastic community. ```go // Single line comment /* Multi- - line comment */ + line comment */ // A package clause starts every source file. // Main is a special name declaring an executable rather than a library. @@ -41,8 +41,8 @@ import ( "strconv" // String conversions. ) -// A function definition. Main is special. It is the entry point for the -// executable program. Love it or hate it, Go uses brace brackets. +// A function definition. Main is special. It is the entry point for the +// executable program. Love it or hate it, Go uses brace brackets. func main() { // Println outputs a line to stdout. // Qualify it with the package name, fmt. @@ -77,8 +77,8 @@ func learnTypes() { s2 := `A "raw" string literal can include line breaks.` // Same string type. - // Non-ASCII literal. Go source is UTF-8. - g := 'Σ' // rune type, an alias for uint32, holds a unicode code point. + // Non-ASCII literal. Go source is UTF-8. + g := 'Σ' // rune type, an alias for int32, holds a unicode code point. f := 3.14195 // float64, an IEEE-754 64-bit floating point number. c := 3 + 4i // complex128, represented internally with two float64's. @@ -95,15 +95,29 @@ can include line breaks.` // Same string type. a3 := [...]int{3, 1, 5} // An array initialzed with a fixed size of three // elements, with values 3, 1, and 5. - // Slices have dynamic size. Arrays and slices each have advantages + // Slices have dynamic size. Arrays and slices each have advantages // but use cases for slices are much more common. - s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. + s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here. s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0. var d2 [][]float64 // Declaration only, nothing allocated here. bs := []byte("a slice") // Type conversion syntax. + // Because they are dynamic, slices can be appended to on-demand. + // To append elements to a slice, built-in append() function is used. + // First argument is a slice to which we are appending. Commonly, + // the array variable is updated in place, as in example below. + s := []int{1, 2, 3} // Result is a slice of length 3. + s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can + // pass a reference to a slice or a slice literal like this, with a + // trailing elipsis, meaning take a slice and unpack its elements, + // appending them to slice s. + s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + p, q := learnMemory() // Declares p, q to be type pointer to int. - fmt.Println(*p, *q) // * follows a pointer. This prints two ints. + fmt.Println(*p, *q) // * follows a pointer. This prints two ints. // Maps are a dynamically growable associative array type, like the // hash or dictionary types of some other languages. @@ -129,7 +143,7 @@ func learnNamedReturns(x, y int) (z int) { return // z is implicit here, because we named it earlier. } -// Go is fully garbage collected. It has pointers but no pointer arithmetic. +// Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. @@ -178,6 +192,14 @@ func learnFlowControl() { break // Just kidding. continue // Unreached. } + + // You can use range to iterate over an array, a slice, a string, a map, or a channel. + // range returns one (channel) or two values (array, slice, string and map). + for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} { + // for each pair in the map, print key and value + fmt.Printf("key=%s, value=%d\n", key, value) + } + // As with for, := in an if statement means to declare and assign // y first, then test y > x. if y := expensiveComputation(); y > x { @@ -199,7 +221,7 @@ func learnFlowControl() { func(a, b int) int { return (a + b) * 2 }(10, 2)) // Called with args 10 and 2 - // => Add + double two numbers: 24 + // => Add + double two numbers: 24 // When you need it, you'll love it. goto love @@ -246,7 +268,7 @@ type pair struct { x, y int } -// Define a method on type pair. Pair now implements Stringer. +// Define a method on type pair. Pair now implements Stringer. func (p pair) String() string { // p is called the "receiver" // Sprintf is another public function in package fmt. // Dot syntax references fields of p. @@ -254,13 +276,13 @@ func (p pair) String() string { // p is called the "receiver" } func learnInterfaces() { - // Brace syntax is a "struct literal." It evaluates to an initialized - // struct. The := syntax declares and initializes p to this struct. + // Brace syntax is a "struct literal". It evaluates to an initialized + // struct. The := syntax declares and initializes p to this struct. p := pair{3, 4} fmt.Println(p.String()) // Call String method of p, of type pair. var i Stringer // Declare i of interface type Stringer. i = p // Valid because pair implements Stringer - // Call String method of i, of type Stringer. Output same as above. + // Call String method of i, of type Stringer. Output same as above. fmt.Println(i.String()) // Functions in the fmt package call the String method to ask an object @@ -298,7 +320,7 @@ func learnErrorHandling() { // prints 'strconv.ParseInt: parsing "non-int": invalid syntax' fmt.Println(err) } - // We'll revisit interfaces a little later. Meanwhile, + // We'll revisit interfaces a little later. Meanwhile, learnConcurrency() } @@ -309,12 +331,12 @@ func inc(i int, c chan int) { // We'll use inc to increment some numbers concurrently. func learnConcurrency() { - // Same make function used earlier to make a slice. Make allocates and + // Same make function used earlier to make a slice. Make allocates and // initializes slices, maps, and channels. c := make(chan int) - // Start three concurrent goroutines. Numbers will be incremented + // Start three concurrent goroutines. Numbers will be incremented // concurrently, perhaps in parallel if the machine is capable and - // properly configured. All three send to the same channel. + // properly configured. All three send to the same channel. go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) @@ -327,7 +349,7 @@ func learnConcurrency() { go func() { c <- 84 }() // Start a new goroutine just to send a value. go func() { cs <- "wordy" }() // Again, for cs this time. // Select has syntax like a switch statement but each case involves - // a channel operation. It selects a case at random out of the cases + // a channel operation. It selects a case at random out of the cases // that are ready to communicate. select { case i := <-c: // The value received can be assigned to a variable, @@ -337,7 +359,7 @@ func learnConcurrency() { case <-ccs: // Empty channel, not ready for communication. fmt.Println("didn't happen.") } - // At this point a value was taken from either c or cs. One of the two + // At this point a value was taken from either c or cs. One of the two // goroutines started above has completed, the other will remain blocked. learnWebProgramming() // Go does it. You want to do it too. @@ -376,13 +398,15 @@ func requestServer() { The root of all things Go is the [official Go web site](http://golang.org/). There you can follow the tutorial, play interactively, and read lots. -The language definition itself is highly recommended. It's easy to read +The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) +You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. + On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it +library](http://golang.org/src/pkg/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go -idioms. Or you can click on a function name in [the +idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). diff --git a/java.html.markdown b/java.html.markdown index 50875491..dffc3828 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -101,9 +101,9 @@ public class LearnJava { // Arrays //The array size must be decided upon instantiation - //The following formats work for declaring an arrow + //The following formats work for declaring an array //<datatype> [] <var name> = new <datatype>[<array size>]; - //<datetype> <var name>[] = new <datatype>[<array size>]; + //<datatype> <var name>[] = new <datatype>[<array size>]; int [] intArray = new int[10]; String [] stringArray = new String[1]; boolean boolArray [] = new boolean[100]; diff --git a/javascript.html.markdown b/javascript.html.markdown index c59a90c3..7c869b28 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -460,8 +460,8 @@ var myNumberObj = new Number(12); myNumber == myNumberObj; // = true // Except, they aren't exactly equivalent. -typeof(myNumber); // = 'number' -typeof(myNumberObj); // = 'object' +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index e4eaee56..3012c04f 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -79,7 +79,7 @@ func learnTypes() { 개행을 포함할 수 있다.` // 같은 string 타입 // non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다. - g := 'Σ' // 유니코드 코드 포인트를 담고 있고, uint32 타입의 가칭(alias)인 rune 타입 + g := 'Σ' // 유니코드 코드 포인트를 담고 있고, int32 타입의 가칭(alias)인 rune 타입 f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입 c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨 diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index f651fbe7..4ca3bb5c 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -381,8 +381,8 @@ var myNumberObj = new Number(12) myNumber == myNumberObj // = true // 하지만 정확히 같지는 않습니다. -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' +typeof myNumber // = 'number' +typeof myNumberObj // = 'object' myNumber === myNumberObj // = false if (0){ // 0은 거짓이라서 이 코드는 실행되지 않습니다. diff --git a/learntmux.html.markdown b/learntmux.html.markdown new file mode 100644 index 00000000..eaf3fd25 --- /dev/null +++ b/learntmux.html.markdown @@ -0,0 +1,71 @@ +--- +category: tool +tool: tmux +contributors: + - ["kaernyk", "http://github.com/kaernyk"] +filename: LearnTmux.txt +--- + + + tmux is a terminal multiplexer: it enables a number of terminals to be +created, accessed, and controlled from a single screen. tmux may be detached +from a screen and continue running in the background, then later reattached. + + Once you feel comfortable manipulating tmux to suit your needs, I strongly +suggest you read the man pages. + + + +``` +# Session Management + + tmux new Create new session + -s "Session" Create named session + -n "Window" Create named Window + -c "/dir" Start in target directory + + C^b $ Rename current session + C^b d Detach current session + C^b D Select session to detach + + tmux attach Attach last/available session + -t "#" Attach target session + -d Detach the session from other instances + + tmux ls List open sessions + C^b s Select new session for attached client interactively + + kill-session Kill current session + -t "#" Kill target session + -a Kill all sessions + -a -t "#" Kill all sessions but the target + + +# Window Management + + C^b c Create another window + C^b " Split Horizontally + C^b % Split Vertically + C^b M-(1-5) 1) Tile vertically + 2) Tile horizontally + 3) Tile Vertically /w large horizontal + 4) Tile horizontally /w large vertical + 5) Tile all windows evenly + + C^b q Briefly display pane indexes + C^# Choose current window by # + C^b w Choose current window interactively + C^b n Change to next window + C^b p Change to previous window + C^b Up, Right Change to pane in selected direction + Down, left + C^b { Swap current/previous window + C^b } Swap current/next window + + C^b C-Up, Right Resize in steps of one cell + Down, left + C^b M-Up, Right resize in steps of five cells + Down, left + + exit or C^b x Kill the current window +``` diff --git a/matlab.html.markdown b/matlab.html.markdown index d9a82890..9dae8ef2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas % Logicals can be applied to matrices: A > 5 % for each element, if condition is true, that element is 1 in returned matrix -A[ A > 5 ] +A( A > 5 ) % returns a vector containing the elements in A for which condition is true % Strings diff --git a/perl6.html.markdown b/perl6.html.markdown index 567c4629..fe5b197c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -7,48 +7,57 @@ contributors: - ["Nami-Doc", "http://github.com/Nami-Doc"] --- -Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for the +upcoming hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com). +Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM +and [the MoarVM](http://moarvm.com). + +Meta-note : the triple pound signs are here to denote headlines, +double paragraphs, and single notes. -Meta-note : the triple pound signs are here to denote headlines, double paragraphs, single notes. `#=>` represents the output of a command. ```perl # Single line comment start with a pound #`( - Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work. + Multiline comments use #` and a quoting construct. + (), [], {}, 「」, etc, will work. ) ### Variables # In Perl 6, you declare a lexical variable using `my` -a -# Perl 6 has 4 variable types : +my $variable; +# Perl 6 has 4 kinds of variables: ## * Scalars. They represent a single value. They start with a `$` my $str = 'String'; my $str2 = "String"; # double quotes allow for interpolation -# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores : +# variable names can contain but not end with simple quotes and dashes, +# and can contain (and end with) underscores : # my $weird'variable-name_ = 5; # works ! my $bool = True; # `True` and `False` are Perl 6's boolean my $inverse = !$bool; # You can invert a bool with the prefix `!` operator -my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool +my $forced-bool = so $str; # And you can use the prefix `so` operator + # which turns its operand into a Bool ## * Arrays. They represent multiple values. Their name start with `@`. my @array = 1, 2, 3; my @array = 'a', 'b', 'c'; # equivalent to : -my @array = <a b c>; # array of words, delimited by space. similar to perl5's qw, or Ruby's %w +my @array = <a b c>; # array of words, delimited by space. + # Similar to perl5's qw, or Ruby's %w. say @array[2]; # Array indices start at 0 -- This is the third element -say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c +say "Interpolate an array using [] : @array[]"; +#=> Interpolate an array using [] : a b c ## * Hashes. Key-Value Pairs. # Hashes are actually arrays of Pairs (`Key => Value`), @@ -58,10 +67,12 @@ my %hash = 1 => 2, my %hash = autoquoted => "key", # keys *can* get auto-quoted "some other" => "value", # trailing commas are okay ; -my %hash = <key1 value1 key2 value2>; # you can also create a hash from an even-numbered array +my %hash = <key1 value1 key2 value2>; # you can also create a hash + # from an even-numbered array my %hash = key1 => 'value1', key2 => 'value2'; # same as this -# You can also use the "colon pair" syntax: (especially handy for named parameters that you'll see later) +# You can also use the "colon pair" syntax: +# (especially handy for named parameters that you'll see later) my %hash = :w(1), # equivalent to `w => 1` # this is useful for the `True` shortcut: :truey, # equivalent to `:truey(True)`, or `truey => True` @@ -70,33 +81,37 @@ my %hash = :w(1), # equivalent to `w => 1` ; say %hash{'key1'}; # You can use {} to get the value from a key -say %hash<key2>; # if it's a string, you can actually use <> +say %hash<key2>; # If it's a string, you can actually use <> + # (`{key1}` doesn't work, as Perl6 doesn't have barewords) -## * Subs (subroutines, or functions in most other languages). Stored in variable, they use `&` +## * Subs (subroutines, or functions in most other languages). +# Stored in variable, they use `&`. sub say-hello { say "Hello, world" } -sub say-hello-to(Str $name) { # you can provide the type of an argument - # and it'll be checked at compile-time +sub say-hello-to(Str $name) { # You can provide the type of an argument + # and it'll be checked at compile-time. say "Hello, $name !"; } -# since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello` +# Since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to capture `say-hello`. my &s = &say-hello; -my &other-s = sub { say "anonymous function !" } +my &other-s = sub { say "Anonymous function !" } # A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # the `*@` slurpy will basically "take everything else". - # Note: you can have parameters *before* (like here) a slurpy one, - # but not *after*. +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". + # Note: you can have parameters *before* (like here) + # a slurpy one, but not *after*. say @rest.join(' / ') ~ " !"; } -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy Birthday ! - # Note that the splat did not consume the parameter before. +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! + # Note that the splat did not consume + # the parameter before. -## You can call a function with an array using the "argument list flattening" operator `|` -# (it's not actually the only feature of the operator, but it's one of them) +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) sub concat3($a, $b, $c) { say "$a, $b, $c"; } @@ -105,7 +120,8 @@ concat3(|@array); #=> a, b, c ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` if I don't have an argument passed, or I'll return my argument"; + say "I might return `(Any)` if I don't have an argument passed, + or I'll return my argument"; $arg; } with-optional; # returns Any @@ -127,19 +143,20 @@ sub with-named($normal-arg, :$named) { } with-named(1, named => 6); #=> 7 # There's one gotcha to be aware of, here: -# If you quote your key, Perl 6 won't be able to see it as compile time, +# If you quote your key, Perl 6 won't be able to see it at compile time, # and you'll have a single Pair object as a positional paramater. with-named(2, :named(5)); #=> 7 with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers, mainly useful for `:2nd` etc) + # (special colon pair syntax for numbers, + # to be used with s// and such, see later) with-named(3); # warns, because we tried to use the undefined $named in a `+`: # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { - say "$named !"; + say "$str !"; } with-mandatory-named(str => "My String"); #=> My String ! with-mandatory-named; # run time error: "Required named parameter not passed" @@ -171,10 +188,11 @@ named-def(def => 15); #=> 15 ### Containers # In Perl 6, values are actually stored in "containers". -# the assignment operator asks the container on the left to store the value on its right -# When passed around, containers are marked as immutable. Which means that, in a function, -# you'll get an error if you try to mutate one of your argument. -# If you really need to, you can ask for a mutable container using `is rw` : +# The assignment operator asks the container on the left to store the value on +# its right. When passed around, containers are marked as immutable. +# Which means that, in a function, you'll get an error if you try to +# mutate one of your arguments. +# If you really need to, you can ask for a mutable container using `is rw`: sub mutate($n is rw) { $n++; say "\$n is now $n !"; @@ -182,24 +200,26 @@ sub mutate($n is rw) { # If what you want is a copy instead, use `is copy`. -# A sub itself returns a container, which means it can be marked as rw : +# A sub itself returns a container, which means it can be marked as rw: my $x = 42; sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory (else Perl 6 thinks it's a "term") +mod() = 52; # in this case, the parentheses are mandatory + # (else Perl 6 thinks `mod` is a "term") say $x; #=> 52 ### Control Flow Structures # You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body : +# but that also means you always have to use brackets (`{ }`) for their body: ## Conditionals # - `if` -# Before talking about `if`, we need to know which values are "Truthy" (represent True), -# and which are "Falsey" (or "Falsy") -- meaning they represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type, and of course False itself. +# Before talking about `if`, we need to know which values are "Truthy" +# (represent True), and which are "Falsey" (or "Falsy") -- represent False. +# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# and of course False itself. # Every other value is Truthy. if True { say "It's true !"; @@ -217,18 +237,18 @@ say "Quite truthy" if True; # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; -# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching, -# and thanks to Perl 6's "topic variable", $_. +# - `given`-`when` looks like other languages `switch`, but much more +# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. # This variable contains the default argument of a block, # a loop's current iteration (unless explicitly named), etc. -# Given simply puts its argument into `$_` (like a block would do), -# and `when` uses it using the "smart matching" operator. -# Since other Perl 6 constructs use this variable (as said before, like `for`, blocks, etc), -# this means the powerful `when` is not only applicable along with a `given`, -# but instead anywhere a `$_` exists. +# `given` simply puts its argument into `$_` (like a block would do), +# and `when` compares it using the "smart matching" (`~~`) operator. +# Since other Perl 6 constructs use this variable (as said before, like `for`, +# blocks, etc), this means the powerful `when` is not only applicable along with +# a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it - # this is equivalent to `if $_ ~~ /foo/` + when /foo/ { # Don't worry about smart matching -- just know `when` uses it. + # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, @@ -242,15 +262,17 @@ given "foo bar" { ## Looping constructs -# - `loop` is an infinite loop if you don't pass it arguments, but can also be a c-style `for` : +# - `loop` is an infinite loop if you don't pass it arguments, +# but can also be a c-style `for`: loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages } loop (my $i = 0; $i < 5; $i++) { - next if $i == 3; # `next` skips to the next iteration, like `continue` in other languages. - # Notice that you can also use postfix conditionals, loops, etc. + next if $i == 3; # `next` skips to the next iteration, like `continue` + # in other languages. Note that you can also use postfix + # conditionals, loops, etc. say "This is a C-style for loop !"; } @@ -270,12 +292,13 @@ for @array { } for @array { - next if $_ == 3; # you can skip to the next iteration (like `continue` in C-like languages) - redo if $_ == 4; # you can re-do the iteration, keeping the same topic variable (`$_`) - last if $_ == 5; # you can also break out of a loop (like `break` in C-like languages) + # You can... + next if $_ == 3; # Skip to the next iteration (`continue` in C-like languages). + redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`). + last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } -# Note - the "lambda" `->` syntax isn't reserved to `for` : +# Note - the "lambda" `->` syntax isn't reserved to `for`: if long-computation() -> $result { say "The result is $result"; } @@ -283,15 +306,15 @@ if long-computation() -> $result { ### Operators ## Since Perl languages are very much operator-based languages -## Perl 6 operators are actually just funny-looking subroutines, in syntactic categories, -## like infix:<+> (addition) or prefix:<!> (bool not) +## Perl 6 operators are actually just funny-looking subroutines, in syntactic +## categories, like infix:<+> (addition) or prefix:<!> (bool not). -## The categories are : -# - "prefix" : before (like `!` in `!True`). -# - "postfix" : after (like `++` in `$a++`). -# - "infix" : in between (like `*` in `4 * 3`). -# - "circumfix" : around (like `[`-`]` in `[1, 2]`). -# - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`) +## The categories are: +# - "prefix": before (like `!` in `!True`). +# - "postfix": after (like `++` in `$a++`). +# - "infix": in between (like `*` in `4 * 3`). +# - "circumfix": around (like `[`-`]` in `[1, 2]`). +# - "post-circumfix": around, after another term (like `{`-`}` in `%hash{'key'}`) ## The associativity and precedence list are explained below. @@ -312,12 +335,15 @@ if long-computation() -> $result { (1, 2) eqv (1, 3); # - `~~` is smart matching -# for a complete combinations list, use this table : http://perlcabal.org/syn/S03.html#Smart_matching +# For a complete list of combinations, use this table: +# http://perlcabal.org/syn/S03.html#Smart_matching 'a' ~~ /a/; # true if matches regexp 'key' ~~ %hash; # true if key exists in hash -$arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an argument, returns True -1 ~~ Int; # "is of type" -1 ~~ True; # smart-matching against a boolean always returns that boolean (and will warn). +$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` + # as an argument, returns `True`. +1 ~~ Int; # "has type" (check superclasses and roles) +1 ~~ True; # smart-matching against a boolean always returns that boolean + # (and will warn). # - `===` is value identity and uses `.WHICH` on the objects to compare them # - `=:=` is container identity and uses `VAR()` on the objects to compare them @@ -330,38 +356,44 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar 3 .. 7; # 3 to 7, both included # `^` on either side them exclusive on that side : 3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`) -# this also works as a shortcut for `0..^N` +# This also works as a shortcut for `0..^N`: ^10; # means 0..^10 -# This also allows us to demonstrate that Perl 6 has lazy arrays, using the Whatever Star : +# This also allows us to demonstrate that Perl 6 has lazy arrays, +# using the Whatever Star: my @array = 1..*; # 1 to Infinite ! -say @array[^10]; # you can pass arrays as subscripts and it'll return an array of results - # this will print "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) -# Note : when reading an infinite list, Perl 6 will "reify" the elements it needs, then keep them in memory -# They won't be calculated more than once. +say @array[^10]; # you can pass arrays as subscripts and it'll return + # an array of results. This will print + # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) +# Note : when reading an infinite list, Perl 6 will "reify" the elements +# it needs, then keep them in memory. They won't be calculated more than once. -# Warning, though: if you try this example in the REPL and juste put `1..*`, -# Perl 6 will be forced to try and evaluate the whole array (to print it), -# so you'll end with an infinite loop. +# Warning, though: if you try this example in the REPL and just put `1..*`, +# Perl 6 will be forced to try and evaluate the whole array (to print it), +# so you'll end with an infinite loop. ## * And, Or 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. 0 || False; # False. Calls `.Bool` on `0` ## * Short-circuit (and tight) versions of the above -$a && $b && $c; # returns the first argument that evaluates to False, or the last argument +$a && $b && $c; # Returns the first argument that evaluates to False, + # or the last argument. $a || $b; -# And because you're going to want them, you also have composed assignment operators: +# And because you're going to want them, +# you also have composed assignment operators: $a *= 2; # multiply and assignment $b %%= 5; # divisible by and assignment -$c .= say; # method call and assignment +@array .= sort; # calls the `sort` method and assigns the result back ### More on subs ! -# As we said before, Perl 6 has *really* powerful subs. -# We're going to see a few more key concepts that make them better than in any other language :-). +# As we said before, Perl 6 has *really* powerful subs. We're going to see +# a few more key concepts that make them better than in any other language :-). -## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters. +## Unpacking ! +# It's the ability to "extract" arrays and keys. +# It'll work in `my`s and in parameter lists. my ($a, $b) = 1, 2; say $a; #=> 1 my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous @@ -374,17 +406,20 @@ sub foo(@array [$fst, $snd]) { say "My first is $fst, my second is $snd ! All in all, I'm @array[]."; # (^ remember the `[]` to interpolate the array) } -foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 1 2 +foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3 -# If you're not using the array itself, you can also keep it anonymous, much like a scalar: +# If you're not using the array itself, you can also keep it anonymous, +# much like a scalar: sub first-of-array(@ [$fst]) { $fst } first-of-array(@small); #=> 1 -first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big) +first-of-array(@tail); # Throws an error "Too many positional parameters passed" + # (which means the array is too big). # You can also use a slurp ... -sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous - say $fst + @rest.elems; +sub slurp-in-array(@ [$fst, *@rest]) { # You could keep `*@rest` anonymous + say $fst + @rest.elems; # `.elems` returns a list's length. + # Here, `@rest` is `(3,)`, since `$fst` holds the `2`. } slurp-in-array(@tail); #=> 3 @@ -403,18 +438,21 @@ sub key-of(% (:value($val), :qua($qua))) { } # Then call it with a hash: (you need to keep the brackets for it to be a hash) -key-of({value => 1}); +key-of({value => 'foo', qua => 1}); #key-of(%hash); # the same (for an equivalent `%hash`) -## The last expression of a sub is returned automatically (though you may use the `return` keyword, of course): +## The last expression of a sub is returned automatically +# (though you may use the `return` keyword, of course): sub next-index($n) { $n + 1; } my $new-n = next-index(3); # $new-n is now 4 -# This is true for everything, except for the looping constructs (due to performance reasons): -# there's no purpose in building a list if we're just going to discard all the results. -# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later) +# This is true for everything, except for the looping constructs +# (due to performance reasons): there's reason to build a list +# if we're just going to discard all the results. +# If you still want to build one, you can use the `do` statement prefix: +# (or the `gather` prefix, which we'll see later) sub list-of($n) { do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`) $_ # current loop iteration @@ -424,15 +462,16 @@ my @list3 = list-of(3); #=> (0, 1, 2) ## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block") my &lambda = -> $argument { "The argument passed to this lambda is $argument" } -# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments, -# and that the latter can be mistaken as a hash by the parser. +# `-> {}` and `{}` are pretty much the same thing, except that the former can +# take arguments, and that the latter can be mistaken as a hash by the parser. # We can, for example, add 3 to each value of an array using map: my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument -# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): -# a block doesn't have a "function context" (though it can have arguments), which means that if you -# return from it, you're going to return from the parent function, compare: +# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`): +# A block doesn't have a "function context" (though it can have arguments), +# which means that if you return from it, +# you're going to return from the parent function. Compare: sub is-in(@array, $elem) { # this will `return` out of the `is-in` sub # once the condition evaluated to True, the loop won't be run anymore @@ -441,28 +480,32 @@ sub is-in(@array, $elem) { sub truthy-array(@array) { # this will produce an array of `True` and `False`: # (you can also say `anon sub` for "anonymous subroutine") - map(sub { if $_ { return True } else { return False } }, @array); + map(sub ($i) { if $i { return True } else { return False } }, @array); # ^ the `return` only returns from the anonymous `sub` } # You can also use the "whatever star" to create an anonymous function # (it'll stop at the furthest operator in the current expression) my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` -my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }` +my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }` + # also `sub ($a, $b) { $a + $b + 3 }` say (*/2)(4); #=> 2 # Immediatly execute the function Whatever created. say ((*+3)/5)(5); #=> 1.6 # works even in parens ! -# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`), +# But if you need to have more than one argument (`$_`) +# in a block (without wanting to resort to `-> {}`), # you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above +map({ $^a + $^b + 3 }, @array); # equivalent to following: +map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) -# Note : those are sorted lexicographically. `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +# Note : those are sorted lexicographically. +# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` ## Multiple Dispatch -# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments, -# or on arbitrary preconditions, like with a type or a `where`: +# Perl 6 can decide which variant of a `sub` to call based on the type of the +# arguments, or on arbitrary preconditions, like with a type or a `where`: # with types multi sub sayit(Int $n) { # note the `multi` keyword here @@ -472,21 +515,25 @@ multi sayit(Str $s) } # the `sub` is the default say "String: $s"; } sayit("foo"); # prints "String: foo" -sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..." +sayit(True); # fails at *compile time* with + # "calling 'sayit' will never work with arguments of types ..." # with arbitrary precondition: multi is-big(Int $n where * > 50) { "Yes !" } # using a closure -multi is-big(Int $ where 10..50) { "Quite." } # this uses smart-matching (could use a regexp, etc) +multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching + # (could use a regexp, etc) multi is-big(Int $) { "No" } -# you can also name these checks, by creating "subsets": +# You can also name these checks, by creating "subsets": subset Even of Int where * %% 2; -multi odd-or-even(Even) { "Even" } # the main case using the type. We don't name the argument +multi odd-or-even(Even) { "Even" } # The main case using the type. + # We don't name the argument. multi odd-or-even($) { "Odd" } # "else" # You can even dispatch based on a positional's argument presence ! -multi with-or-without-you(:$with!) { # make it mandatory to be able to dispatch against it +multi with-or-without-you(:$with!) { # You need make it mandatory to + # be able to dispatch against it. say "I can live ! Actually, I can't."; } multi with-or-without-you { @@ -494,17 +541,21 @@ multi with-or-without-you { } # This is very, very useful for many purposes, like `MAIN` subs (covered later), # and even the language itself is using it in several places. -# `is`, for example, is actually a `multi sub` named `trait_mod:<is>`, and it works off that. -# `is rw`, for example, is a dispatch to a function with this signature: +# +# - `is`, for example, is actually a `multi sub` named `trait_mod:<is>`, +# and it works off that. +# - `is rw`, is simply a dispatch to a function with this signature: # sub trait_mod:<is>(Routine $r, :$rw!) {} -# (commented because running this would probably lead to some very surprising side-effects !) +# +# (commented because running this would be a terrible idea !) ### Scoping -# In Perl 6, contrarily to many scripting languages (Python, Ruby, PHP, for example), -# you are to declare your variables before using them. You already saw it, with `my`. -# (there are other declarator keywords, like `our`, `has` and `state`, but we'll talk about them later) -# This is called "lexical scoping", where in inner blocks, you can access variables from outer blocks. +# In Perl 6, contrarily to many scripting languages (like Python, Ruby, PHP), +# you are to declare your variables before using them. You know `my`. +# (there are other declarators, `our`, `state`, ..., which we'll see later). +# This is called "lexical scoping", where in inner blocks, +# you can access variables from outer blocks. my $foo = 'Foo'; sub foo { my $bar = 'Bar'; @@ -516,36 +567,40 @@ sub foo { foo()(); #=> 'Foo Bar' # As you can see, `$foo` and `$bar` were captured. -# But if we were to try and use `$bar` outside of `foo`, the variable would be undefined. -# (and you'd get a compile time error) +# But if we were to try and use `$bar` outside of `foo`, +# the variable would be undefined (and you'd get a compile time error). # Perl 6 has another kind of scope : dynamic scope. # They use the twigil (composed sigil) `*` to mark dynamically-scoped variables: my $*a = 1; -# Dyamically-scoped variables depend on the current call stack, instead of the current block stack. +# Dyamically-scoped variables depend on the current call stack, +# instead of the current block depth. sub foo { my $*foo = 1; bar(); # call `bar` in-place } sub bar { - say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`, - # even though the blocks aren't nested (they're call-nested). + say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, + # even though the blocks aren't nested (they're call-nested). #=> 1 } ### Object Model ## Perl 6 has a quite comprehensive object model -## You declare a class with the keyword `class`, fields with `has`, methods with `method`. -## In Perl 6, every field is private, and named `$!attr`, but if you declare it with `$.`, -## you get a public (immutable) accessor along with it. +# You declare a class with the keyword `class`, fields with `has`, +# methods with `method`. Every field to private, and is named `$!attr`, +# but you have `$.` to get a public (immutable) accessor along with it. +# (using `$.` is like using `$!` plus a `method` with the same name) -# (Perl 6's object model ("SixModel") is very flexible, and allows you to dynamically add methods, -# change semantics, etc -- This will not be covered here, and you should refer to the Synopsis) +# (Perl 6's object model ("SixModel") is very flexible, +# and allows you to dynamically add methods, change semantics, etc ... +# (this will not be covered here, and you should refer to the Synopsis). class A { - has $.field; # `$.field` is immutable. Use `$!field` from inside the class to modify it. - has $.other-field is rw; # You can, however, mark a public field as being read/write. + has $.field; # `$.field` is immutable. + # From inside the class, use `$!field` to modify it. + has $.other-field is rw; # You can obviously mark a public field `rw`. has Int $!private-field = 10; method get-value { @@ -556,7 +611,7 @@ class A { # $.field = $n; # As stated before, you can't use the `$.` immutable version. $!field = $n; # This works, because `$!` is always mutable. - $.other-field = 5; # This works, because `$.other-field` was declared `rw` (mutable). + $.other-field = 5; # This works, because `$.other-field` is `rw`. } method !private-method { @@ -565,13 +620,15 @@ class A { }; # Create a new instance of A with $.field set to 5 : -# note : you can't set private-field from here (more later on) +# Note: you can't set private-field from here (more later on). my $a = A.new(field => 5); $a.get-value; #=> 18 #$a.field = 5; # This fails, because the `has $.field` is immutable -$a.other-field = 10; # This, however, works, because the public field is mutable (`rw`). +$a.other-field = 10; # This, however, works, because the public field + # is mutable (`rw`). -## Perl 6 also has inheritance (along with multiple inheritance ... Considered a misfeature by many) +## Perl 6 also has inheritance (along with multiple inheritance) +# (though considered a misfeature by many) class A { has $.val; @@ -591,12 +648,14 @@ class B is A { # inheritance uses `is` method bar { $.val * 10 } # this shadows A's `bar` } -my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it, - # so you can call `new` on it. - # (`.=` is just the compound operator composed of the dot-call and of the assignment operator - # `$a .= b` is the same as `$a = $a.b`) - # Also note that `BUILD` (the method called inside `new`) will set parent properties too, - # so you can pass `val => 5` +# When you use `my T $var`, `$var` starts off with `T` itself in it, +# so you can call `new` on it. +# (`.=` is just the dot-call and the assignment operator: +# `$a .= b` is the same as `$a = $a.b`) +# Also note that `BUILD` (the method called inside `new`) +# will set parent properties too, so you can pass `val => 5`. +my B $b .= new(val => 5); + # $b.not-inherited; # This won't work, for reasons explained above $b.foo; # prints 5 $b.bar; #=> 50, since it calls B's `bar` @@ -613,27 +672,30 @@ role PrintableVal { class Item does PrintableVal { has $.val; - # When `does`-ed, a `role` literally "mixes in" the class : - # the methods and fields are put together, which means a class can access - # the private fields/methods of its roles (but not the inverse !) : + # When `does`-ed, a `role` literally "mixes in" the class: + # the methods and fields are put together, which means a class can access + # the private fields/methods of its roles (but not the inverse !): method access { say $!counter++; } - # However, this : + # However, this: # method print {} - # is an error, since the compiler wouldn't know which `print` to use : - # contrarily to inheritance, methods mixed in can't be shadowed - they're put at the same "level" + # is ONLY valid when `print` isn't a `multi` with the same dispatch. + # (this means a parent class can shadow a child class's `multi print() {}`, + # but it's an error if a role does) - # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed, - # since the compiler will consider `ROLE` to be a class + # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods + # will be shadowed, since the compiler will consider `ROLE` to be a class. } ### Exceptions -# Exceptions are built on top of classes, usually in the package `X` (like `X::IO`). -# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the block to `try`. -# By default, a `try` has a `CATCH` block that catches any exception (`CATCH { default {} }`). -# You can redefine it using `when`s (and `default`) to handle the exceptions you want: +# Exceptions are built on top of classes, in the package `X` (like `X::IO`). +# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the +# block to `try`. By default, a `try` has a `CATCH` block that catches +# any exception (`CATCH { default {} }`). +# You can redefine it using `when`s (and `default`) +# to handle the exceptions you want: try { open 'foo'; CATCH { @@ -649,20 +711,20 @@ die X::AdHoc.new(payload => 'Error !'); # TODO CONTROL ### Packages -# Packages are a way to reuse code. Packages are like "namespaces", and any element of the six model -# (`module`, `role`, `class`, `grammar`, `subset` and `enum`) are actually packages. -# (you can say that packages are the lowest common denomitor between them) -# Packages play a big part in a language, as Perl is well-known for CPAN, +# Packages are a way to reuse code. Packages are like "namespaces", and any +# element of the six model (`module`, `role`, `class`, `grammar`, `subset` +# and `enum`) are actually packages. (Packages are the lowest common denomitor) +# Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. -# You usually don't use packages directly : you use `class Package::Name::Here;`, or if you -# only want to export variables/subs, you can use `module`: -module Hello::World { # bracketed form - # if `Hello` doesn't exist yet, it'll just be created as an "empty package stub" - # that can be redeclared as something else later. - # declarations here +# You usually don't use packages directly: you use `class Package::Name::Here;`, +# or if you only want to export variables/subs, you can use `module`: +module Hello::World { # Bracketed form + # If `Hello` doesn't exist yet, it'll just be a "stub", + # that can be redeclared as something else later. + # ... declarations here ... } module Parse::Text; # file-scoped form -grammar Parse::Text::Grammar { # A grammar is a fine package, which you could `use` +grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } # NOTE for Perl 5 users: even though the `package` keyword exists, @@ -692,7 +754,8 @@ my $actions = JSON::Tiny::Actions.new; module Foo::Bar { our $n = 1; # note: you can't put a type constraint on an `our` variable our sub inc { - our sub available { # if you try to make scoped `sub`s `our` ... Better know what you're doing (Don't !). + our sub available { # If you try to make inner `sub`s `our`... + # Better know what you're doing (Don't !). say "Don't do that. Seriously. You'd get burned."; } my sub unavailable { # `my sub` is the default @@ -725,23 +788,24 @@ sub fixed-rand { fixed-rand for ^10; # will print the same number 10 times # Note, however, that they exist separately in different enclosing contexts. -# If you declare a function with a `state` within a loop, it'll re-create the variable -# for each iteration of loop. See: +# If you declare a function with a `state` within a loop, it'll re-create the +# variable for each iteration of the loop. See: for ^5 -> $a { sub foo { state $val = rand; # This will be a different value for every value of `$a` } for ^5 -> $b { - say foo; # This will print the same value 5 times, but only 5. Next iteration will re-run `rand` + say foo; # This will print the same value 5 times, but only 5. + # Next iteration will re-run `rand`. } } ### Phasers -# Phasers in Perl 6 are blocks that happen at determined points of time in your program -# When the program is compiled, when a for loop runs, when you leave a block, when -# an exception gets thrown ... (`CATCH` is actually a phaser !) +# Phasers in Perl 6 are blocks that happen at determined points of time in your +# program. When the program is compiled, when a for loop runs, when you leave a +# block, when an exception gets thrown ... (`CATCH` is actually a phaser !) # Some of them can be used for their return values, some of them can't # (those that can have a "[*]" in the beginning of their explanation text). # Let's have a look ! @@ -782,7 +846,7 @@ say "This code took " ~ (time - CHECK time) ~ "s to run"; # ... or clever organization: sub do-db-stuff { - ENTER $db.start-transaction; # create a new transaction everytime we enter the sub + ENTER $db.start-transaction; # New transaction everytime we enter the sub KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } @@ -791,7 +855,7 @@ sub do-db-stuff { # Those act a bit like phasers: they affect the behavior of the following code. # Though, they run in-line with the executable code, so they're in lowercase. # (`try` and `start` are theoretically in that list, but explained somewhere else) -# Note: all of these (except start) don't need explicit brackets (`{` and `}`) for their block. +# Note: all of these (except start) don't need explicit brackets `{` and `}`. # - `do` (that you already saw) - runs a block or a statement as a term # You can't normally use a statement as a value (or "term"): @@ -848,8 +912,9 @@ say nilthingie.perl; #=> Nil ## Everybody loves operators ! Let's get more of them -## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence -## But first, we need a little explanation about associativity : +# The precedence list can be found here: +# http://perlcabal.org/syn/S03.html#Operator_precedence +# But first, we need a little explanation about associativity: # * Binary operators: $a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c` @@ -864,8 +929,9 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>` !$a! # with non-associative `!`, this is illegal ## Create your own operators ! -# Okay, you've been reading all of that, so I guess I should try to show you something exciting. -# I'll tell you a little secret (actually not): +# Okay, you've been reading all of that, so I guess I should try +# to show you something exciting. +# I'll tell you a little secret (or not-so-secret): # In Perl 6, all operators are actually just funny-looking subroutines. # You can declare an operator just like you declare a sub: @@ -890,7 +956,7 @@ say 5!; #=> 120 sub infix:<times>(Int $n, Block $r) { # infix in the middle for ^$n { $r(); # You need the explicit parentheses to call the function in `$r`, - # else you'd be referring at the variable itself, kind of like with `&r`. + # else you'd be referring at the variable itself, like with `&r`. } } 3 times -> { say "hello" }; #=> hello @@ -906,36 +972,47 @@ sub circumfix:<[ ]>(Int $n) { say [5]; #=> 3125 # circumfix is around. Again, not whitespace. -sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is "after a term, around something" +sub postcircumfix:<{ }>(Str $s, Int $idx) { + # post-circumfix is + # "after a term, around something" $s.substr($idx, 1); } say "abc"{1}; #=> b # after the term `"abc"`, and around the index (1) # This really means a lot -- because everything in Perl 6 uses this. -# For example, to delete a key from a hash, you use the `:delete` adverb (named argument) +# For example, to delete a key from a hash, you use the `:delete` adverb +# (a simple named argument underneath): %h{$key}:delete; # equivalent to: -postcircumfix:<{ }>(%h, $key, :delete); -# It's *all* using the same building blocks! Syntactic categories (prefix infix ...), -# named arguments (adverbs), ..., used to build the language are available to you. +postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) +# It's *all* using the same building blocks! +# Syntactic categories (prefix infix ...), named arguments (adverbs), ..., +# - used to build the language - are available to you. -# (you are, obviously, recommended against making an operator out of *everything* -- -# with great power comes great responsibility) +# (you are, obviously, recommended against making an operator out of +# *everything* -- with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole, -# and you probably won't want to go back to other languages after reading that. +# Oh boy, get ready. Get ready, because we're dwelving deep +# into the rabbit's hole, and you probably won't want to go +# back to other languages after reading that. # (I'm guessing you don't want to already at that point). # Meta-operators, as their name suggests, are *composed* operators. # Basically, they're operators that apply another operator. ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and one or many lists. -# If it doesn't get passed any argument, it either return a "default value" for this operator -# (a value that'd be non-meaningful if contained in a list) or `Any` if there's none. -# Otherwise, it pops an element from the list(s) one at a time, and applies the binary function -# to the last result (or the list's first element) and the popped element. +# It's a prefix meta-operator that takes a binary functions and +# one or many lists. If it doesn't get passed any argument, +# it either return a "default value" for this operator +# (a value that wouldn't change the result if passed as one +# of the element of the list to be passed to the operator), +# or `Any` if there's none (examples below). +# +# Otherwise, it pops an element from the list(s) one at a time, and applies +# the binary function to the last result (or the list's first element) +# and the popped element. +# # To sum a list, you could use the reduce meta-operator with `+`, i.e.: say [+] 1, 2, 3; #=> 6 # equivalent to `(1+2)+3` @@ -943,18 +1020,20 @@ say [*] 1..5; #=> 120 # equivalent to `((((1*2)*3)*4)*5)`. # You can reduce with any operator, not just with mathematical ones. -# For example, you could reduce with `//` to get the first defined element of a list: +# For example, you could reduce with `//` to get +# the first defined element of a list: say [//] Nil, Any, False, 1, 5; #=> False # (Falsey, but still defined) # Default value examples: -say [*] (); #=> 1 -say [+] (); #=> 0 - # In both cases, they're results that, if they were contained in the lists, - # wouldn't have any impact on the final value (since N*1=N and N+0=N). +say [*] (); #=> 1 +say [+] (); #=> 0 + # In both cases, they're results that, were they in the lists, + # wouldn't have any impact on the final value + # (since N*1=N and N+0=N). say [//]; #=> (Any) - # There's no "default value" for `//` + # There's no "default value" for `//`. # You can also call it with a function you made up, using double brackets: sub add($a, $b) { $a + $b } @@ -980,23 +1059,36 @@ say [[&add]] 1, 2, 3; #=> 6 ## * Sequence operator # The sequence operator is one of Perl 6's most powerful features: -# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure), -# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list. +# it's composed of first, on the left, the list you want Perl 6 to deduce from +# (and might include a closure), and on the right, a value or the predicate +# that says when to stop (or Whatever for a lazy infinite list). my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end -my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches) -my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here) +#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, + # because Perl 6 can't figure out the end +my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element + # (the iteration when the predicate matches). +my @list = 1, 3, 9 ... * > 30; # you can use a predicate + # (with the Whatever Star, here). my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) -my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, computed using a closure ! + +my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, + # computed using a closure! my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) +my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above) +# $a and $b will always take the previous values, meaning here +# they'll start with $a = 1 and $b = 1 (values we set by hand). +# then $a = 1 and $b = 2 (result from previous $a+$b), and so on. + say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # (using a range as the index) # Note : as for ranges, once reified, elements aren't re-calculated. -# That's why `@primes[^100]` will take a long time the first time you print it, then be instant +# That's why `@primes[^100]` will take a long time the first time you print +# it, then be instant. ## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1). +# They return one value of the `Order` enum : `Less`, `Same` and `More` +# (which numerify to -1, 0 or +1). 1 <=> 4; # sort comparison for numerics 'a' leg 'b'; # sort comparison for string $obj eqv $obj2; # sort comparison using eqv semantics @@ -1014,14 +1106,17 @@ say Any // Nil // 0 // 5; #=> 5 say True ^^ False; #=> True ## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to Perl 5/Ruby's `..` and `...`). +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). # are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` by using `^` on either side. +# They are `False` until their left side returns `True`, then are `True` until +# their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +# by using `^` on either side. # Let's start with an example : for <well met young hero we shall meet later> { # by default, `ff`/`fff` smart-match (`~~`) against `$_`: - if 'met' ^ff 'meet' { # won't enter the if for "met" (explained in details below). + if 'met' ^ff 'meet' { # Won't enter the if for "met" + # (explained in details below). .say } @@ -1031,35 +1126,42 @@ for <well met young hero we shall meet later> { } # This will print "young hero we shall meet" (excluding "met"): # the flip-flop will start returning `True` when it first encounters "met" -# (but will still return `False` for "met" itself, due to the leading `^` on `ff`), -# until it sees "meet", which is when it'll start returning `False`. +# (but will still return `False` for "met" itself, due to the leading `^` +# on `ff`), until it sees "meet", which is when it'll start returning `False`. # The difference between `ff` (awk-style) and `fff` (sed-style) is that -# `ff` will test its right side just as its left side changes to `True`, -# and can get back to `False` right away (*except* it'll be `True` for the iteration that matched) -# while `fff` will wait for the next iteration to try its right side, once its left side changed: +# `ff` will test its right side right when its left side changes to `True`, +# and can get back to `False` right away +# (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +# try its right side, once its left side changed: .say if 'B' ff 'B' for <A B C B A>; #=> B B - # because the right-hand-side was tested directly (and returned `True`). - # "B"s are still printed since it matched that time - # (it just went back to `False` right away) + # because the right-hand-side was tested + # directly (and returned `True`). + # "B"s are printed since it matched that time + # (it just went back to `False` right away). .say if 'B' fff 'B' for <A B C B A>; #=> B C B - # because the right-hand-side wasn't tested until `$_` became "C" - # (and thus did not match directly). + # The right-hand-side wasn't tested until + # `$_` became "C" + # (and thus did not match instantly). # A flip-flop can change state as many times as needed: -for <test start print this stop you stopped printing start printing again stop not anymore> { +for <test start print it stop not printing start print again stop not anymore> { .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", #=> "print this printing again" } # you might also use a Whatever Star, # which is equivalent to `True` for the left side or `False` for the right: -for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here -- sometimes called "superstitious" - .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, it'll never go back to `False` +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here + # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, + # it'll never go back to `False` #=> 60 3 40 60 } -# You can also use this property to create an `If` that'll not execute the first time : +# You can also use this property to create an `If` +# that'll not go through the first time : for <a b c> { .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, # but the `^` makes it *not run* on the first iteration @@ -1072,37 +1174,42 @@ for <a b c> { # Well, now that you know a good deal of Perl 6 already, we can get started. # First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps). # -# IMPORTANT: You may feel like you already know these because you know PCRE. You'd be wrong. -# Some things are the same (like `?`, `+`, and `*`), but sometimes the semantics change (`|`). +# IMPORTANT: Don't skip them because you know PCRE. They're different. +# Some things are the same (like `?`, `+`, and `*`), +# but sometimes the semantics change (`|`). # Make sure you read carefully, because you might trip over a new behavior. # -# Perl 6 has a looot of features related to RegExps. After all, Rakudo parses itself. -# We're first going to look at the syntax itself, then talk about grammars (PEG-like), -# differences between the `token`, `regex` and `rule` keywords, and some more. +# Perl 6 has many features related to RegExps. After all, Rakudo parses itself. +# We're first going to look at the syntax itself, +# then talk about grammars (PEG-like), differences between +# `token`, `regex` and `rule` declarators, and some more. # Side note: you still have access to PCRE regexps using the `:P5` modifier. # (we won't be discussing this in this tutorial, however) # # In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars"). -# The pecking order for ambiguous parses is determined by a multi-level tie-breaking test: +# The pecking order for ambiguous parses is determined by a multi-level +# tie-breaking test: # - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions) # - Longest literal prefix. `food\w*` beats `foo\w*` (by 1) -# - Declaration from most-derived to less derived grammars (grammars are actually classes) +# - Declaration from most-derived to less derived grammars +# (grammars are actually classes) # - Earliest declaration wins say so 'a' ~~ /a/; #=> True say so 'a' ~~ / a /; # More readable with some spaces! -# In all our examples, we're going to use the smart-matching operator against a regexp. -# We're converting the result using `so`, but in fact, it's returning a `Match` object. -# They know how to respond to list indexing, hash indexing (and return the matched string). -# The results of the match are also available as `$/` (implicitly lexically-scoped). -# You can also use the capture variables (`$0`, `$1`, ... - starting at 0, not 1 !). +# In all our examples, we're going to use the smart-matching operator against +# a regexp. We're converting the result using `so`, but in fact, it's +# returning a `Match` object. They know how to respond to list indexing, +# hash indexing, and return the matched string. +# The results of the match are available as `$/` (implicitly lexically-scoped). +# You can also use the capture variables (`$0`, `$1`, ... starting at 0, not 1 !). # # You can also note that `~~` does not perform start/end checking # (meaning the regexp can be matched with just one char of the string), # we're going to explain later how you can do it. -# In Perl 6, you can have any alphanumeric as a literal, everything else has to be escaped, -# using a backslash or quotes. +# In Perl 6, you can have any alphanumeric as a literal, +# everything else has to be escaped, using a backslash or quotes. say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it. @@ -1137,10 +1244,11 @@ so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s so 'ac' ~~ / a b* c /; # `True`, they're all optional. so 'abc' ~~ / a b* c /; # `True` so 'abbbbc' ~~ / a b* c /; # `True` -so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, but can't be something else. +so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable. # - `**` - "Quantify It Yourself". -# If you squint hard enough, you might understand the why exponentation means quantity. +# If you squint hard enough, you might understand +# why exponentation is used for quantity. so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time) so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times) so 'abbbc' ~~ / a b ** 1..3 c /; # `True` @@ -1151,13 +1259,14 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing -so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # `True`. - # We match the "abc" 1 or more time. - # (the `+` was applied to the group) +so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; +# The previous line returns `True`. +# We match the "abc" 1 or more time (the `+` was applied to the group). -# But this does not go far enough, because we can't actually get back what we matched. +# But this does not go far enough, because we can't actually get back what +# we matched. # Capture: We can actually *capture* the results of the regexp, using parentheses. -so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (we keep `so` here and use `$/` below) +so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below) # So, starting with the grouping explanations. # As we said before, our `Match` object is available as `$/`: @@ -1165,13 +1274,15 @@ say $/; # Will print some weird stuff (we'll explain) (or "Nil" if nothing match # As we also said before, it has array indexing: say $/[0]; #=> 「ABC」 「ABC」 - # These weird brackets are `Match` objects. So here, we have an array of that. -say $0; # the same as above. + # These weird brackets are `Match` objects. + # Here, we have an array of these. +say $0; # The same as above. # Our capture is `$0` because it's the first and only one capture in the regexp. # You might be wondering why it's an array, and the answer is simple: # Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array -# IF it can have more than one element (so, with `*`, `+` and any `**`, but not with `?`). +# IFF it can have more than one element +# (so, with `*`, `+` and any `**`, but not with `?`). # Let's use examples to see that: so 'fooABCbar' ~~ / foo ( A B C )? bar /; # `True` say $/[0]; #=> 「ABC」 @@ -1206,8 +1317,9 @@ sub MAIN($name) { say "Hello, you !" } # t.pl <name> # And since it's a regular Perl 6 sub, you can haz multi-dispatch: -# (using a "Bool" for the named argument so that we get `--replace` instead of `--replace=`) -subset File of Str where *.IO.d; # convert to IO object, then check the file exists +# (using a "Bool" for the named argument so that we get `--replace` +# instead of `--replace=1`) +subset File of Str where *.IO.d; # convert to IO object to check the file exists multi MAIN('add', $key, $value, Bool :$replace) { ... } multi MAIN('remove', $key) { ... } @@ -1218,12 +1330,15 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # t.pl [--replace] add <key> <value> # t.pl remove <key> # t.pl [--as=<Str>] import (File) -# As you can see, this is *very* powerful. It even went as far as to show inline the constants. -# (the type is only displayed if 1. there's no argument name 2. it's a named argument) +# As you can see, this is *very* powerful. +# It even went as far as to show inline the constants. +# (the type is only displayed if the argument is `$`/is named) ``` If you want to go further, you can: + - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. + diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 32c8fbdd..c7339831 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -75,7 +75,7 @@ func learnTypes() { pode incluir quebras de linha.` // mesmo tipo string // literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8. - g := 'Σ' // tipo rune, um alias para uint32, que contém um código unicode + g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754) c := 3 + 4i // complex128, representado internamente com dois float64s diff --git a/purescript.html.markdown b/purescript.html.markdown new file mode 100644 index 00000000..6bff7545 --- /dev/null +++ b/purescript.html.markdown @@ -0,0 +1,195 @@ +--- +language: purescript +contributors: + - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] +--- + +PureScript is a small strongly, statically typed language compiling to Javascript. + +* Learn more at [http://www.purescript.org/](http://www.purescript.org/) +* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) + +```haskell + +-- +-- 1. Primitive datatypes that corresponds to their Javascript +-- equivalents at runtime. + +-- Numbers +1 + 7*5 :: Number -- 36 +-- Types are inferred, so the following works fine +9 / 2.5 + 4.4 -- 8 +-- Hexadecimal literals +0xff + 1 -- 256 +-- Unary negation +6 * -3 -- -18 +6 * negate 3 -- -18 +-- Modulus +3 % 2 -- 1 +4 % 2 -- 0 +-- Inspect the type of an expression in psci +:t 9 / 2.5 + 4.4 -- Prim.Number + +-- Booleans +true :: Boolean -- true +false :: Boolean -- false +-- Negation +not true --false +23 == 23 -- true +1 /= 4 -- true +1 >= 4 -- false +-- Comparisions < <= > >= +-- are defined in terms of compare +compare 1 2 -- LT +compare 2 2 -- EQ +compare 3 2 -- GT +-- Conjunction and Disjunction +true && (9 >= 19 || 1 < 2) -- true + +-- Strings +"Hellow" :: String -- "Hellow" +-- Multiline string +"Hellow\ +\orld" -- "Helloworld" +-- Concatenate +"such " ++ "amaze" -- "such amaze" + +-- +-- 2. Arrays are Javascript arrays, but must be homogeneous + +[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] +[true, true, false] :: [Boolean] -- [true,true,false] +-- [1,2, true, "false"] won't work +-- `Cannot unify Prim.Number with Prim.Boolean` +-- Cons (prepend) +1 : [2,4,3] -- [1,2,4,3] + +-- Requires purescript-arrays (Data.Array) +-- and purescript-maybe (Data.Maybe) + +-- Safe access return Maybe a +head [1,2,3] -- Just (1) +tail [3,2,1] -- Just ([2,1]) +init [1,2,3] -- Just ([1,2]) +last [3,2,1] -- Just (1) +-- Random access - indexing +[3,4,5,6,7] !! 2 -- Just (5) +-- Range +1..5 -- [1,2,3,4,5] +length [2,2,2] -- 3 +drop 3 [5,4,3,2,1] -- [2,1] +take 3 [5,4,3,2,1] -- [5,4,3] +append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] + +-- +-- 3. Records are Javascript objects, with zero or more fields, which +-- can have different types +let book = {title: "Foucault's pendulum", author: "Umberto Eco"} +-- Access properties +book.title -- "Foucault's pendulum" + +getTitle b = b.title +-- Works on all records with a title (but doesn't require any other field) +getTitle book -- "Foucault's pendulum" +getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Update a record +changeTitle b t = b {title = t} +changeTitle book "Ill nome della rosa" -- {title: "Ill nome della + -- rosa", author: "Umberto Eco"} + +-- +-- 4. Functions +sumOfSquares x y = x*x+y*y +sumOfSquares 3 4 -- 25 +-- In psci you have to write `let` in front of the function to get a +-- top level binding +mod x y = x % y +mod 3 2 -- 1 +-- Infix application of function +3 `mod` 2 -- 1 + +-- function application have higher precedence than all other +-- operators +sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 + +-- Conditional +abs' n = if n>=0 then n else -n +abs' (-3) -- 3 + +-- Guarded equations +abs n | n >= 0 = n + | otherwise = -n + +-- Pattern matching + +-- Note the type signature, input is an array of numbers The pattern +-- matching destructures and binds the array into parts +first :: [Number] -> Number +first (x:_) = x +first [3,4,5] -- 3 +second :: [Number] -> Number +second (_:y:_) = y +second [3,4,5] -- 4 +sumTwo :: [Number] -> [Number] +sumTwo (x:y:rest) = (x+y) : rest +sumTwo [2,3,4,5,6] -- [5,4,5,6] + +-- sumTwo doesn't handle when the array is empty or just have one +-- element in which case you get an error +sumTwo [1] -- Failed pattern match + +-- Complementing patterns to match +-- Good ol' Fibonacci +fib 1 = 1 +fib 2 = 2 +fib x = fib (x-1) + fib (x-2) +fib 10 -- 89 + +-- Use underscore to match any, where you don't care about the binding name +isZero 0 = true +isZero _ = false + +-- Pattern matching on records +ecoTitle {author = "Umberto Eco", title = t} = Just t +ecoTitle _ = Nothing + +ecoTitle book -- Just ("Foucault's pendulum") +ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing +-- ecoTitle requires both field to type check: +ecoTitle {title: "The Quantum Thief"} -- Object does not have property author + +-- Lambda expressions +(\x -> x*x) 3 -- 9 +(\x y -> x*x + y*y) 4 5 -- 41 +sqr = \x -> x*x + +-- Currying +add x y = x + y -- is equivalent with +add = \x -> (\y -> x+y) +add3 = add 3 +:t add3 -- Prim.Number -> Prim.Number + +-- Forward and backward function composition +-- drop 3 followed by taking 5 +(drop 3 >>> take 5) (1..20) -- [4,5,6,7,8] +-- take 5 followed by dropping 3 +(drop 3 <<< take 5) (1..20) -- [4,5] + +-- Operations using higher order functions +even x = x % 2 == 0 +filter even (1..10) -- [2,4,6,8,10] +map (\x -> x+11) (1..5) -- [12,13,14,15,16] + +-- Requires purescript-foldable-traversabe (Data.Foldable) + +foldr (+) 0 (1..10) -- 55 +sum (1..10) -- 55 +product (1..10) -- 3628800 + +-- Testing with predicate +any even [1,2,3] -- true +all even [1,2,3] -- false + +``` + diff --git a/python.html.markdown b/python.html.markdown index 5bec5190..9057dde2 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -45,9 +45,11 @@ to Python 2.x. Look for another tour of Python 3 soon! 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better -# Truncation or Integer division +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # Modulo operation 7 % 3 # => 1 @@ -439,7 +441,10 @@ class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" - # Basic initializer + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -523,11 +528,15 @@ def double_numbers(iterable): # Instead of generating and returning all values at once it creates one in each # iteration. This means values bigger than 15 wont be processed in # double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made -_range = range(1, 900000000) +# Note xrange is a generator that does the same thing range does. +# Creating a list 1-900000000 would take lot of time and space to be made. +# xrange creates an xrange generator object instead of creating the entire list like range does. +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +xrange_ = xrange(1, 900000000) + # will double all numbers until a result >=30 found -for i in double_numbers(_range): +for i in double_numbers(xrange_): print(i) if i >= 30: break @@ -540,10 +549,10 @@ for i in double_numbers(_range): from functools import wraps -def beg(_say): - @wraps(_say) +def beg(target_function): + @wraps(target_function) def wrapper(*args, **kwargs): - msg, say_please = _say(*args, **kwargs) + msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg diff --git a/python3.html.markdown b/python3.html.markdown index 531d3b5a..f6babaff 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -38,9 +38,11 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Except division which returns floats by default 35 / 5 # => 7.0 -# Truncation or Integer division +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 -5.0 // 3.0 # => 1.0 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # When you use a float, results are floats 3 * 2.0 # => 6.0 @@ -51,7 +53,6 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Enforce precedence with parentheses (1 + 3) * 2 # => 8 - # Boolean values are primitives True False @@ -60,7 +61,6 @@ False not True # => False not False # => True - # Equality is == 1 == 1 # => True 2 == 1 # => False @@ -79,7 +79,6 @@ not False # => True 1 < 2 < 3 # => True 2 < 3 < 2 # => False - # Strings are created with " or ' "This is a string." 'This is also a string.' @@ -94,7 +93,9 @@ not False # => True "{} can be {}".format("strings", "interpolated") # You can repeat the formatting arguments to save some typing. -"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") #=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" @@ -471,7 +472,10 @@ class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" - # Basic initializer + # Basic initializer, this is called when this class is instantiated. + # Note that the double leading and trailing underscores denote objects + # or attributes that are used by python but that live in user-controlled + # namespaces. You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -557,9 +561,11 @@ def double_numbers(iterable): # double_numbers. # Note range is a generator too. Creating a list 1-900000000 would take lot of # time to be made -_range = range(1, 900000000) +# We use a trailing underscore in variable names when we want to use a name that +# would normally collide with a python keyword +range_ = range(1, 900000000) # will double all numbers until a result >=30 found -for i in double_numbers(_range): +for i in double_numbers(range_): print(i) if i >= 30: break @@ -572,10 +578,10 @@ for i in double_numbers(_range): from functools import wraps -def beg(_say): - @wraps(_say) +def beg(target_function): + @wraps(target_function) def wrapper(*args, **kwargs): - msg, say_please = _say(*args, **kwargs) + msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index ffda01b7..44a22b45 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -13,11 +13,11 @@ lang: ru-ru --- Go - это язык общего назначения, целью которого является удобство, простота, -конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый +конкурентность. Это не тренд в компьютерных науках, а новейший и быстрый способ решать насущные проблемы. Концепции Go схожи с другими императивными статически типизированными языками. -Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции +Быстро компилируется и быстро исполняется, имеет лёгкие в понимании конструкции для создания масштабируемых и многопоточных программ. Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным @@ -57,7 +57,7 @@ func main() { func beyondHello() { var x int // Переменные должны быть объявлены до их использования. x = 3 // Присвоение значения переменной. - // Краткое определение := позволяет объявить перменную с автоматической + // Краткое определение := позволяет объявить переменную с автоматической // подстановкой типа из значения. y := 4 sum, prod := learnMultiple(x, y) // Функция возвращает два значения. @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } -// Некотрые встроенные типы и литералы. +// Некоторые встроенные типы и литералы. func learnTypes() { // Краткое определение переменной говорит само за себя. s := "Learn Go!" // Тип string. @@ -79,7 +79,7 @@ func learnTypes() { может содержать переносы строк` // Тоже тип данных string // Символ не из ASCII. Исходный код Go в кодировке UTF-8. - g := 'Σ' // тип rune, это алиас для типа uint32, содержит символ юникода. + g := 'Σ' // тип rune, это алиас для типа int32, содержит символ юникода. f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754). c := 3 + 4i // complex128, внутри себя содержит два float64. @@ -97,7 +97,7 @@ func learnTypes() { // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще. - s3 := []int{4, 5, 9} // Сравните с a3. Тут нет троеточия. + s3 := []int{4, 5, 9} // Сравните с a3, тут нет троеточия. s4 := make([]int, 4) // Выделение памяти для слайса из 4-х int (нули). var d2 [][]float64 // Только объявление, память не выделяется. bs := []byte("a slice") // Синтаксис приведения типов. @@ -113,7 +113,7 @@ func learnTypes() { delete(m, "three") // Встроенная функция, удаляет элемент из map-а. // Неиспользуемые переменные в Go являются ошибкой. - // Нижнее подчеркивание позволяет игнорировать такие переменные. + // Нижнее подчёркивание позволяет игнорировать такие переменные. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной. fmt.Println(s, c, a4, s3, d2, m) @@ -121,16 +121,16 @@ func learnTypes() { learnFlowControl() // Идем дальше. } -// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики +// У Go есть полноценный сборщик мусора. В нем есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя. func learnMemory() (p, q *int) { // Именованные возвращаемые значения p и q являются указателями на int. p = new(int) // Встроенная функция new выделяет память. - // Выделенный int проинициализирован нулем, p больше не содержит nil. + // Выделенный int проинициализирован нулём, p больше не содержит nil. s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов. s[3] = 7 // Присвоить значение одному из них. - r := -2 // Определить еще одну локальную переменную. + r := -2 // Определить ещё одну локальную переменную. return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной. } @@ -139,7 +139,7 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // If-ы всегда требуют наличине фигурных скобок, но не круглых. + // If-ы всегда требуют наличие фигурных скобок, но не круглых. if true { fmt.Println("told ya") } @@ -178,7 +178,7 @@ func learnFlowControl() { } // Функции являются замыканиями. xBig := func() bool { - return x > 10000 // Ссылается на x, объявленый выше switch. + return x > 10000 // Ссылается на x, объявленный выше switch. } fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10). x = 1.3e3 // Тут х == 1300 @@ -189,7 +189,7 @@ func learnFlowControl() { love: learnDefer() // Быстрый обзор важного ключевого слова. - learnInterfaces() // О! Интерфейсы, идем далее. + learnInterfaces() // О! Интерфейсы, идём далее. } func learnDefer() (ok bool) { @@ -214,7 +214,7 @@ type pair struct { // Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer. func (p pair) String() string { // p в данном случае называют receiver-ом. - // Sprintf – еще одна функция из пакета fmt. + // Sprintf – ещё одна функция из пакета fmt. // Обращение к полям p через точку. return fmt.Sprintf("(%d, %d)", p.x, p.y) } @@ -234,7 +234,7 @@ func learnInterfaces() { fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String. fmt.Println(i) // Вывод такой же, что и выше. - learnVariadicParams("Учиться", "учиться", "и еще раз учиться!") + learnVariadicParams("Учиться", "учиться", "и ещё раз учиться!") } // Функции могут иметь варьируемое количество параметров. @@ -263,22 +263,22 @@ func learnErrorHandling() { // выведет "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } - // Мы еще обратимся к интерфейсам чуть позже, а пока... + // Мы ещё обратимся к интерфейсам чуть позже, а пока... learnConcurrency() } -// c – это тип данных channel (канал), объект для конкуррентного взаимодействия. +// c – это тип данных channel (канал), объект для конкурентного взаимодействия. func inc(i int, c chan int) { c <- i + 1 // когда channel слева, <- являтся оператором "отправки". } -// Будем использовать функцию inc для конкуррентной инкрементации чисел. +// Будем использовать функцию inc для конкурентной инкрементации чисел. func learnConcurrency() { // Тот же make, что и в случае со slice. Он предназначен для выделения // памяти и инициализации типов slice, map и channel. c := make(chan int) - // Старт трех конкуррентных goroutine. Числа будут инкрементированы - // конкуррентно и, может быть параллельно, если машина правильно + // Старт трех конкурентных goroutine. Числа будут инкрементированы + // конкурентно и, может быть параллельно, если машина правильно // сконфигурирована и позволяет это делать. Все они будут отправлены в один // и тот же канал. go inc(0, c) // go начинает новую горутину. @@ -291,7 +291,7 @@ func learnConcurrency() { cs := make(chan string) // другой канал, содержит строки. cc := make(chan chan string) // канал каналов со строками. go func() { c <- 84 }() // пуск новой горутины для отправки значения - go func() { cs <- "wordy" }() // еще раз, теперь для cs + go func() { cs <- "wordy" }() // ещё раз, теперь для cs // Select тоже что и switch, но работает с каналами. Он случайно выбирает // готовый для взаимодействия канал. select { @@ -327,7 +327,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { Основа всех основ в Go это [официальный веб сайт](http://golang.org/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать -объемную документацию. +объёмную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она diff --git a/scala.html.markdown b/scala.html.markdown index 432933c2..379c092c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less then 10"); + println("x is still less than 10"); x += 1 } while (x < 10) @@ -299,7 +299,6 @@ Person("George", "1234") == Person("Kate", "1236") - // Pattern matching val me = Person("George", "1234") @@ -322,15 +321,21 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions - val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex - -val email(user, domain) = "henry@zkpr.com" - -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name +val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax + +val matcher = (value: String) => { + println(value match { + case email(name, domain) => s"It was an email: $name" + case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" + case _ => s"No match on '$value'" // default if no match found + }) } +matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" +matcher("nope..") // => "No match on 'nope..'" +matcher("52917") // => "No match on '52917'" +matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" // Strings @@ -347,17 +352,27 @@ println("ABCDEF".length) println("ABCDEF".substring(2, 6)) println("ABCDEF".replace("C", "3")) +// String interpolation val n = 45 -println(s"We have $n apples") +println(s"We have $n apples") // => "We have 45 apples" +// Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" + +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" + +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." // Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes - val html = """<form id="daform"> <p>Press belo', Joe</p> | <input type="submit"> @@ -403,7 +418,10 @@ for(line <- Source.fromFile("myfile.txt").getLines()) println(line) // To write a file use Java's PrintWriter - +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() ``` diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..e7f2f9a2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,30 +2,51 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] filename: learnswift.swift --- Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. ```js // -// Basics +// MARK: Basics // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code + println("Hello, world") + var myVariable = 42 +let øπΩ = "value" // unicode variable names let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +let `class` = "keyword" // backticks allow keywords to be used as variable names let explicitDouble: Double = 70 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant)" // String interpolation -var optionalString: String? = "optional" // Can be nil +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation +var optionalString: String? = "optional" // Can be nil optionalString = nil +/* +Comment here + /* + Nested comments are also supported + */ +*/ // -// Arrays and Dictionaries +// MARK: Collections // // Array @@ -35,97 +56,108 @@ let emptyArray = [String]() // Dictionary var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = Dictionary<String, Float>() +let emptyDictionary = [String: Float]() // -// Control Flow +// MARK: Control Flow // // for loop (array) let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + println("One!") + } else { + println("Not one!") + } } // for loop (dictionary) +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + println("\(key): \(value)") } // for loop (range) for i in -1...1 { // [-1, 0, 1] - println(i) + println(i) } // use ..< to exclude the last number // while loop var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while loop do { - println("hello") + println("hello") } while 1 == 2 // Switch let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." + let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" + let vegetableComment = "Is it a spicy \(x)?" default: // required (in order to cover all possible input) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "Everything tastes good in soup." } // -// Functions +// MARK: Functions // // Functions are a first-class type, meaning they can be nested // in functions and can be passed around -// Function +// Function with Swift header docs (format as reStructedText) +/** + A greet operation + + - A bullet in docs + - Another bullet in the docs + + :param: name A name + :param: day A day + :returns: A string containing the name and day value. +*/ func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") // Function that returns multiple items in a tuple func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) + return (3.59, 3.69, 3.79) } -// Args +// Variadic Args func setup(numbers: Int...) {} // Passing and returning functions func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) // -// Closures +// MARK: Closures // var numbers = [1, 2, 6] @@ -135,93 +167,243 @@ var numbers = [1, 2, 6] // `->` separates the arguments and return type // `in` separates the closure header from the closure body numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) // When the type is known, like above, we can do this numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this //numbers = numbers.map({ $0 * 3 }) print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] // -// Classes +// MARK: Structures // +// Structures and classes have very similar capabilites +struct NamesTable { + let names: [String] + + // Custom subscript + subscript(index: Int) -> String { + return names[index] + } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + // All methods and properties of a class are public. // If you just need to store data in a // structured object, you should use a `struct` -// A simple class `Square` extends `Shape` -class Rect: Shape { - var sideLength: Int = 1 +internal class Rect: Shape { + var sideLength: Int = 1 + + // Custom getter and setter property + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` is an implicit variable available to setters + sideLength = newValue / 4 + } + } - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + // Lazily load a property + // subShape remains nil (uninitialized) until getter called + lazy var subShape = Rect(sideLength: 4) + + // If you don't need a custom getter and setter, + // but still want to run code before and after getting or setting + // a property, you can use `willSet` and `didSet` + var identifier: String = "defaultID" { + // the `willSet` arg will be the variable name for the new value + willSet(someIdentifier) { + print(someIdentifier) + } } - set { - sideLength = newValue / 4 + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength } - } - - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } - - func shrink() { - if sideLength > 0 { - --sideLength + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength } - } +} - override func getArea() -> Int { - return sideLength * sideLength - } +// A simple class `Square` extends `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` +// compare instances, not the same as == which compares objects (equal to) +if mySquare === mySquare { + println("Yep, it's mySquare") +} // -// Enums +// MARK: Enums // // Enums can optionally be of a specific type or on their own. // They can contain methods like classes. enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } } - } } // -// Other +// MARK: Protocols +// + +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods, +// operators, and subscripts. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} +*/ + +// +// MARK: Other // -// `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +// `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Square: \(mySquare)") + +// You can also extend built-in types +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 + // Generics: Similar to Java. Use the `where` keyword to specify the // requirements of the generics. +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true + +// Operators: +// Custom operators can start with the characters: +// / = - + * % < > ! & | ^ . ~ +// or +// Unicode math, symbol, arrow, dingbat, and line/box drawing characters. +prefix operator !!! {} + +// A prefix operator that triples the side length when used +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 + ``` diff --git a/typescript.html.markdown b/typescript.html.markdown new file mode 100644 index 00000000..8173aac8 --- /dev/null +++ b/typescript.html.markdown @@ -0,0 +1,158 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +filename: learntypescript.ts +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. + +This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). + +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. + +```ts +//There are 3 basic types in TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +//..When it's impossible to know, there is the "Any" type +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okay, definitely a boolean + +//For collections, there are typed arrays and generic arrays +var list: number[] = [1, 2, 3]; +//Alternatively, using the generic array type +var list: Array<number> = [1, 2, 3]; + +//For enumerations: +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +//Lastly, "void" is used in the special case of a function not returning anything +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference +//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted +var f1 = function(i: number) : number { return i * i; } +var f2 = function(i: number) { return i * i; } //Return type infered +var f3 = (i : number) : number => { return i * i; } +var f4 = (i: number) => { return i * i; } //Return type infered +var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed + +//Interfaces are structural, anything that has the properties is compliant with the interface +interface Person { + name: string; + //Optional properties, marked with a "?" + age?: number; + //And of course functions + move(): void; +} + +//..Object that implements the "Person" interface +var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties +//..Objects that have the optional property: +var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; +var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number + +//..Interfaces can also describe a function type +interface SearchFunc { + (source: string, subString: string): boolean; +} +//..Only the parameters' types are important, names are not important. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +//Classes - members are public by default +class Point { + //Properties + x: number; + + //Constructor - the public/private keywords in this context will generate the boiler plate code + // for the property and the initialization in the constructor. + // In this example, "y" will be defined just like "x" is, but with less code + //Default values are also supported + constructor(x: number, public y: number = 0) { + this.x = x; + } + + //Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + //Static members + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y will be 0 + +//Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); //Explicit call to the super class constructor is mandatory + } + + //Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +//Modules, "." can be used as separator for sub modules +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +//..Local alias for referencing a module +import G = Geometry; + +var s2 = new G.Square(10); + +//Generics +//..Classes +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +//..Interfaces +interface Pair<T> { + item1: T; + item2: T; +} + +//..And functions +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +//Including references to a definition file: +/// <reference path="jquery.d.ts" /> + +``` + +## Further Reading + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) diff --git a/whip.html.markdown b/whip.html.markdown index dc5a0b39..3faee98a 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -31,7 +31,7 @@ not_in_form (called_function args) ; Majority of operations are done with functions -; All the basic arihmetic is pretty straight forward +; All the basic arithmetic is pretty straight forward (+ 1 1) ; => 2 (- 2 1) ; => 1 (* 1 2) ; => 2 @@ -48,7 +48,7 @@ not_in_form true false -; String are created with ". +; Strings are created with ". "Hello, world" ; Single chars are created with '. @@ -66,7 +66,7 @@ false (= 1 1) ; => true (equal 2 1) ; => false -; For example, inequality would be combinding the not and equal functions. +; For example, inequality would be combining the not and equal functions. (! (= 2 1)) ; => true ; More comparisons @@ -96,10 +96,10 @@ undefined ; user to indicate a value that hasn't been set ; 2. Vairbles, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. -; Variab;es that haven't been set will be `undefined`. +; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside it's context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a wierder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -129,7 +129,7 @@ undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; 3. Logic and Control sequences -; The `if` function is pretty simple, though different than most imperitave langs. +; The `if` function is pretty simple, though different than most imperative langs. (if true "returned if first arg is true" "returned if first arg is false") ; => "returned if first arg is true" @@ -159,12 +159,12 @@ undefined ; user to indicate a value that hasn't been set ; | | arguments ; | lambda declaration function ; | -; name of the to-be-decalred lambda +; name of the to-be-declared lambda (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 ; Obiously, all lambdas by definition are anonymous and -; technically always used anonymouesly. Redundancy. +; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 ;;;;;;;;;;;;;;;; diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 4a87dc21..9f6a8c15 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -68,7 +68,7 @@ func learnTypes() { can include line breaks.` // 同样是String类型 // 非ascii字符。Go使用UTF-8编码。 - g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + g := 'Σ' // rune类型,int32的别名,使用UTF-8编码 f := 3.14195 // float64类型,IEEE-754 64位浮点数 c := 3 + 4i // complex128类型,内部使用两个float64表示 diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 86ad1d07..7dee9cc4 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -363,8 +363,8 @@ var myNumberObj = new Number(12) myNumber == myNumberObj // = true // 但是它们并非严格等价 -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' +typeof myNumber // = 'number' +typeof myNumberObj // = 'object' myNumber === myNumberObj // = false if (0){ // 这段代码不会执行,因为0代表假 diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown new file mode 100644 index 00000000..975ebcb5 --- /dev/null +++ b/zh-cn/markdown-cn.html.markdown @@ -0,0 +1,240 @@ +--- +language: Markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Fangzhou Chen"] +filename: learnmarkdown-cn.md +lang: zh-cn +--- + +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。 + +欢迎您多多反馈以及分支和请求合并。 + + +``` +<!-- Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。 +这意味着我们可以在 Markdown 里使用任何 HTML 元素,比如注释元素, +且不会被 Markdown 解析器所影响。不过如果你在 Markdown 文件内创建了 HTML 元素, +你将无法在 HTML 元素的内容中使用 Markdown 语法。--> + +<!-- 在不同的解析器中,Markdown 的实现方法有所不同。 +此教程会指出当某功能是否通用及是否只对某一解析器有效。 --> + +<!-- 标头 --> +<!-- 通过在文本前加上不同数量的hash(#), 你可以创建相对应的 <h1> +到 <h6> HTML元素。--> + +# 这是一个 <h1> +## 这是一个 <h2> +### 这是一个 <h3> +#### 这是一个 <h4> +##### 这是一个 <h5> +###### 这是一个 <h6> + +<!-- 对于 <h1> 和 <h2> 元素,Markdown 额外提供了两种添加方式。 --> +这是一个 h1 +============= + +这是一个 h2 +------------- + +<!-- 简易文本样式 --> +<!-- 文本的斜体,粗体,和删除线在 Markdown 中可以轻易地被实现。--> + +*此文本为斜体。* +_此文本也是。_ + +**此文本为粗体。** +__此文本也是__ + +***此文本是斜体加粗体。*** +**_或者这样。_** +*__这个也是!__* + +<!-- 在 Github 采用的 Markdown 中 --> + +~~此文本为删除线效果。~~ + +<!-- 单个段落由一句或多句邻近的句子组成,这些句子由一个或多个空格分隔。--> + +这是第一段落. 这句话在同一个段落里,好玩么? + +现在我是第二段落。 +这句话也在第二段落! + +这句话在第三段落! + +<!-- 如果你插入一个 HTML中的<br />标签,你可以在段末加入两个以上的空格, +然后另起一段。--> + +此段落结尾有两个空格(选中以显示)。 + +上文有一个 <br /> ! + +<!-- 段落引用可由 > 字符轻松实现。--> + +> 这是一个段落引用. 你可以 +> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 +> 只要你的文字以“>” 字符开头,两种方式无异。 + +> 你也对文本进行 +>> 多层引用 +> 这多机智啊! + +<!-- 序列 --> +<!-- 无序序列可由星号,加号或者减号来建立 --> + +* 项目 +* 项目 +* 另一个项目 + +或者 + ++ 项目 ++ 项目 ++ 另一个项目 + +或者 + +- 项目 +- 项目 +- 最后一个项目 + +<!-- 有序序列可由数字加点来实现 --> + +1. 项目一 +2. 项目二 +3. 项目三 + +<!-- 即使你的标签数字有误,Markdown 依旧会呈现出正确的序号, +不过这并不是一个好主意--> + +1. 项目一 +1. 项目二 +1. 项目三 +<!-- (此段与前例一模一样) --> + +<!-- 你也可以使用子序列 --> + +1. 项目一 +2. 项目二 +3. 项目三 + * 子项目 + * 子项目 +4. 项目四 + +<!-- 代码段落 --> +<!-- 代码段落(HTML中 <code>标签)可以由缩进四格(spaces) +或者一个标签页(tab)实现--> + + This is code + So is this + +<!-- 在你的代码中,你仍然使用tab可以进行缩进操作 --> + + my_array.each do |item| + puts item + end + +<!-- 内联代码可由反引号 ` 实现 --> + +John 甚至不知道 `go_to()` 方程是干嘛的! + +<!-- 在Github的 Markdown中,对于代码你可以使用特殊的语法 --> + +\`\`\`ruby <!-- 插入时记得移除反斜线, 仅留```ruby ! --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- 这里也是,移除反斜线,仅留 ``` --> + +<!-- 以上代码不需要缩进,而且 Github 会根据```后表明的语言来进行语法高亮 --> + +<!-- 水平线 (<hr />) --> +<!-- 水平线可由三个或以上的星号或者减号创建,可带可不带空格。 --> + +*** +--- +- - - +**************** + +<!-- 链接 --> +<!-- Markdown 最棒的地方就是简易的链接制作。链接文字放在中括号[]内, +在随后的括弧()内加入url。--> + +[点我点我!](http://test.com/) + +<!-- 你也可以为链接加入一个标题:在括弧内使用引号 --> + +[点我点我!](http://test.com/ "连接到Test.com") + +<!-- 相对路径也可以有 --> + +[去 music](/music/). + +<!-- Markdown同样支持引用样式的链接 --> + +[点此链接][link1]以获取更多信息! +[看一看这个链接][foobar] 如果你愿意的话. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + +<!-- 链接的标题可以处于单引号中,括弧中或是被忽略。引用名可以在文档的任意何处, +并且可以随意命名,只要名称不重复。--> + +<!-- “隐含式命名” 的功能可以让链接文字作为引用名 --> + +[This][] is a link. + +[this]: http://thisisalink.com/ + +<!-- 但这并不常用 --> + +<!-- 图像 --> +<!-- 图像与链接相似,只需在前添加一个感叹号 --> + +![这是我图像的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名") + +<!-- 引用样式也同样起作用 --> + +![这是我的悬停文本.][myimage] + +[myimage]: relative/urls/cool/image.jpg "在此输入标题" + +<!-- 杂项 --> +<!-- 自动链接 --> + +<http://testwebsite.com/> 与 +[http://testwebsite.com/](http://testwebsite.com/) 等同 + +<!-- 电子邮件的自动链接 --> + +<foo@bar.com> + +<!-- 转义字符 --> + +我希望 *将这段文字置于星号之间* 但是我不希望它被 +斜体化, 所以我就: \*这段置文字于星号之间\*。 + +<!-- 表格 --> +<!-- 表格只被 Github 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: --> + +| 第一列 | 第二列 | 第三列 | +| :---------- | :------: | ----------: | +| 左对齐 | 居个中 | 右对齐 | +| 某某某 | 某某某 | 某某某 | + +<!-- 或者, 同样的 --> + +第一列 | 第二列 | 第三列 +:-- | :-: | --: +这太丑了 | 药不能 | 停 + +<!-- 结束! --> + +``` + +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 |