diff options
-rw-r--r-- | bash.html.markdown | 4 | ||||
-rw-r--r-- | c.html.markdown | 2 | ||||
-rw-r--r-- | compojure.html.markdown | 225 | ||||
-rw-r--r-- | de-de/coffeescript-de.html.markdown | 106 | ||||
-rw-r--r-- | es-es/perl-es.html.markdown | 120 | ||||
-rw-r--r-- | go.html.markdown | 63 | ||||
-rw-r--r-- | java.html.markdown | 2 | ||||
-rw-r--r-- | learntmux.html.markdown | 71 | ||||
-rw-r--r-- | matlab.html.markdown | 2 | ||||
-rw-r--r-- | perl6.html.markdown | 93 | ||||
-rw-r--r-- | purescript.html.markdown | 195 | ||||
-rw-r--r-- | python3.html.markdown | 4 | ||||
-rw-r--r-- | ru-ru/go-ru.html.markdown | 42 | ||||
-rw-r--r-- | ruby.html.markdown | 102 | ||||
-rw-r--r-- | scala.html.markdown | 2 | ||||
-rw-r--r-- | swift.html.markdown | 336 | ||||
-rw-r--r-- | typescript.html.markdown | 158 | ||||
-rw-r--r-- | zh-cn/markdown-cn.html.markdown | 240 |
18 files changed, 1485 insertions, 282 deletions
diff --git a/bash.html.markdown b/bash.html.markdown index 061d35b0..57fb5c55 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -73,9 +73,9 @@ 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 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/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/go.html.markdown b/go.html.markdown index f7bd8ee3..b4c6afff 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,7 +77,7 @@ func learnTypes() { s2 := `A "raw" string literal can include line breaks.` // Same string type. - // Non-ASCII literal. Go source is UTF-8. + // 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. @@ -92,17 +92,32 @@ can include line breaks.` // Same string type. // Arrays have size fixed at compile time. var a4 [4]int // An array of 4 ints, initialized to all 0. - a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown. + a3 := [...]int{3, 1, 5} // An array initialized 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. @@ -128,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. @@ -206,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 @@ -253,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. @@ -261,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 @@ -305,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() } @@ -316,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) @@ -334,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, @@ -344,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. @@ -383,15 +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 3484aee5..dffc3828 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -101,7 +101,7 @@ 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>]; //<datatype> <var name>[] = new <datatype>[<array size>]; int [] intArray = new int[10]; 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 fca863af..fe5b197c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -30,7 +30,7 @@ double paragraphs, and single notes. # In Perl 6, you declare a lexical variable using `my` my $variable; -# Perl 6 has 4 variable types : +# Perl 6 has 4 kinds of variables: ## * Scalars. They represent a single value. They start with a `$` @@ -56,7 +56,8 @@ my @array = <a b c>; # array of words, delimited by space. 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`), @@ -99,7 +100,7 @@ my &s = &say-hello; 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". +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(' / ') ~ " !"; @@ -191,7 +192,7 @@ named-def(def => 15); #=> 15 # 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` : +# 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 !"; @@ -199,7 +200,7 @@ 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 @@ -210,7 +211,7 @@ 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 @@ -246,7 +247,7 @@ my $a = $condition ?? $value-if-true !! $value-if-false; # 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. + when /foo/ { # Don't worry about smart matching -- just know `when` uses it. # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } @@ -262,7 +263,7 @@ 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` : +# 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 @@ -270,8 +271,8 @@ loop { loop (my $i = 0; $i < 5; $i++) { 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. + # in other languages. Note that you can also use postfix + # conditionals, loops, etc. say "This is a C-style for loop !"; } @@ -292,12 +293,12 @@ for @array { for @array { # You can... - next if $_ == 3; # Skip to the next iteration (like `continue` in C-like languages). + 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"; } @@ -308,12 +309,12 @@ if long-computation() -> $result { ## 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. @@ -334,7 +335,8 @@ if long-computation() -> $result { (1, 2) eqv (1, 3); # - `~~` is smart matching -# For a complete list of combinations, 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` @@ -415,7 +417,7 @@ 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 +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`. } @@ -485,7 +487,8 @@ sub truthy-array(@array) { # 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 @@ -494,7 +497,8 @@ say ((*+3)/5)(5); #=> 1.6 # 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 }` @@ -576,7 +580,7 @@ sub foo { bar(); # call `bar` in-place } sub bar { - say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`, + 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 } @@ -589,8 +593,9 @@ sub bar { # 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. @@ -685,7 +690,7 @@ class Item does PrintableVal { } ### Exceptions -# Exceptions are built on top of classes, usually in the package `X` (like `X::IO`). +# 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 {} }`). @@ -709,7 +714,7 @@ die X::AdHoc.new(payload => 'Error !'); # 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 play a big part in a language, especially as Perl is well-known for CPAN, +# 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`: @@ -719,7 +724,7 @@ module Hello::World { # Bracketed form # ... 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, @@ -841,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 } @@ -951,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 @@ -1004,8 +1009,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # 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. +# 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 @@ -1068,6 +1074,11 @@ 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, -> $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. @@ -1127,15 +1138,15 @@ for <well met young hero we shall meet later> { .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 + # "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 + # 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" } @@ -1190,8 +1201,8 @@ say so 'a' ~~ / a /; # More readable with some spaces! # 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 !). +# 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), @@ -1233,7 +1244,7 @@ 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 @@ -1255,7 +1266,7 @@ so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # 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 `$/`: @@ -1308,7 +1319,7 @@ sub MAIN($name) { say "Hello, you !" } # 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=1`) -subset File of Str where *.IO.d; # convert to IO object, then check the file exists +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) { ... } @@ -1325,7 +1336,9 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name ``` 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/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/python3.html.markdown b/python3.html.markdown index b494dc1e..f6babaff 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -93,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" diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 5b9d8ebf..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. @@ -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/ruby.html.markdown b/ruby.html.markdown index 962853a2..3c67de2e 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Nick LaMuro", "https://github.com/NickLaMuro"] - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] --- @@ -35,7 +36,7 @@ You shouldn't either 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 -2 ** 5 #=> 32 +2**5 #=> 32 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -78,14 +79,17 @@ false.class #=> FalseClass 'I am a string'.class #=> String "I am a string too".class #=> String -placeholder = "use string interpolation" +placeholder = 'use string interpolation' "I can #{placeholder} when using double quoted strings" #=> "I can use string interpolation when using double quoted strings" +# Prefer single quoted strings to double quoted ones where possible +# Double quoted strings perform additional inner calculations + # Combine strings, but not with numbers -"hello " + "world" #=> "hello world" -"hello " + 3 #=> TypeError: can't convert Fixnum into String -"hello " + 3.to_s #=> "hello 3" +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" # print to the output puts "I'm printing!" @@ -130,7 +134,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can contain different types of items -[1, "hello", false] #=> [1, "hello", false] +[1, 'hello', false] #=> [1, "hello", false] # Arrays can be indexed # From the front @@ -157,7 +161,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: -hash = {'color' => 'green', 'number' => 5} +hash = { 'color' => 'green', 'number' => 5 } hash.keys #=> ['color', 'number'] @@ -170,7 +174,7 @@ hash['nothing here'] #=> nil # Since Ruby 1.9, there's a special syntax when using symbols as keys: -new_hash = { defcon: 3, action: true} +new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] @@ -180,11 +184,11 @@ new_hash.keys #=> [:defcon, :action] # Control structures if true - "if statement" + 'if statement' elsif false - "else if, optional" + 'else if, optional' else - "else, also optional" + 'else, also optional' end for counter in 1..5 @@ -216,7 +220,7 @@ end #=> iteration 5 # You can also surround blocks in curly brackets: -(1..5).each {|counter| puts "iteration #{counter}"} +(1..5).each { |counter| puts "iteration #{counter}" } # The contents of data structures can also be iterated using each. array.each do |element| @@ -241,32 +245,30 @@ grade = 'B' case grade when 'A' - puts "Way to go kiddo" + puts 'Way to go kiddo' when 'B' - puts "Better luck next time" + puts 'Better luck next time' when 'C' - puts "You can do better" + puts 'You can do better' when 'D' - puts "Scraping through" + puts 'Scraping through' when 'F' - puts "You failed!" + puts 'You failed!' else - puts "Alternative grading system, eh?" + puts 'Alternative grading system, eh?' end - #=> "Better luck next time" # cases can also use ranges grade = 82 case grade - when 90..100 - puts "Hooray!" - when 80...90 - puts "OK job" - else - puts "You failed!" +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' end - #=> "OK job" @@ -284,23 +286,23 @@ double 3 #=> 6 double double 3 #=> 12 -def sum(x,y) +def sum(x, y) x + y end # Method arguments are separated by a comma sum 3, 4 #=> 7 -sum sum(3,4), 5 #=> 12 +sum sum(3, 4), 5 #=> 12 # yield # All methods have an implicit, optional block parameter # it can be called with the 'yield' keyword def surround - puts "{" + puts '{' yield - puts "}" + puts '}' end surround { puts 'hello world' } @@ -311,25 +313,25 @@ surround { puts 'hello world' } # You can pass a block to a function -# "&" marks a reference to a passed block +# "&" marks a reference to a passed block def guests(&block) - block.call "some_argument" + block.call 'some_argument' end - + # You can pass a list of arguments, which will be converted into an array -# That's what splat operator ("*") is for +# That's what splat operator ("*") is for def guests(*array) - array.each { |guest| puts "#{guest}" } + array.each { |guest| puts guest } end # Define a class with the class keyword class Human # A class variable. It is shared by all instances of this class. - @@species = "H. sapiens" + @@species = 'H. sapiens' # Basic initializer - def initialize(name, age=0) + def initialize(name, age = 0) # Assign the argument to the "name" instance variable for the instance @name = name # If no age given, we will fall back to the default in the arguments list. @@ -356,20 +358,19 @@ class Human # A class method uses self to distinguish from instance methods. # It can only be called on the class, not an instance. def self.say(msg) - puts "#{msg}" + puts msg end def species @@species end - end # Instantiate a class -jim = Human.new("Jim Halpert") +jim = Human.new('Jim Halpert') -dwight = Human.new("Dwight K. Schrute") +dwight = Human.new('Dwight K. Schrute') # Let's call a couple of methods jim.species #=> "H. sapiens" @@ -380,7 +381,7 @@ dwight.species #=> "H. sapiens" dwight.name #=> "Dwight K. Schrute" # Call the class method -Human.say("Hi") #=> "Hi" +Human.say('Hi') #=> "Hi" # Variable's scopes are defined by the way we name them. # Variables that start with $ have global scope @@ -399,7 +400,7 @@ defined? @@var #=> "class variable" Var = "I'm a constant" defined? Var #=> "constant" -# Class also is object in ruby. So class can have instance variables. +# Class is also an object in ruby. So class can have instance variables. # Class variable is shared among the class and all of its descendants. # base class @@ -415,7 +416,7 @@ class Human end end -# derived class +# derived class class Worker < Human end @@ -451,8 +452,8 @@ module ModuleExample end end -# Including modules binds the methods to the object instance -# Extending modules binds the methods to the class instance +# Including modules binds their methods to the class instances +# Extending modules binds their methods to the class itself class Person include ModuleExample @@ -467,7 +468,7 @@ Person.new.foo # => 'foo' Book.foo # => 'foo' Book.new.foo # => NoMethodError: undefined method `foo' -# Callbacks when including and extending a module are executed +# Callbacks are executed when including and extending a module module ConcernExample def self.included(base) @@ -500,9 +501,8 @@ Something.new.qux # => 'qux' ## Additional resources -- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. - [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) - [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) -- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. - - +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/scala.html.markdown b/scala.html.markdown index 6b398b4b..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) 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/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 的摘要笔记。 |