summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--c.html.markdown30
-rw-r--r--csharp.html.markdown2
-rw-r--r--fr-fr/scala.html.markdown458
-rw-r--r--git.html.markdown2
-rw-r--r--go.html.markdown43
-rw-r--r--pt-br/git-pt.html.markdown402
-rw-r--r--pt-br/json-pt.html.markdown62
-rw-r--r--ruby-ecosystem.html.markdown67
-rw-r--r--rust.html.markdown265
-rw-r--r--scala.html.markdown2
-rw-r--r--whip.html.markdown4
11 files changed, 1272 insertions, 65 deletions
diff --git a/c.html.markdown b/c.html.markdown
index c89f2b88..22f251f2 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -23,7 +23,7 @@ Multi-line comments look like this. They work in C89 as well.
// Constants: #define <keyword>
#define DAYS_IN_YEAR 365
-//enumeration constants are also ways to declare constants.
+// Enumeration constants are also ways to declare constants.
enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
// MON gets 2 automatically, TUE gets 3, etc.
@@ -96,7 +96,7 @@ int main() {
// is not evaluated (except VLAs (see below)).
// The value it yields in this case is a compile-time constant.
int a = 1;
- // size_t is an unsiged integer type of at least 2 bytes used to represent
+ // size_t is an unsigned integer type of at least 2 bytes used to represent
// the size of an object.
size_t size = sizeof(a++); // a++ is not evaluated
printf("sizeof(a++) = %zu where a = %d\n", size, a);
@@ -135,9 +135,9 @@ int main() {
// > Enter the array size: 10
// > sizeof array = 40
- // Strings are just arrays of chars terminated by a NUL (0x00) byte,
+ // Strings are just arrays of chars terminated by a NULL (0x00) byte,
// represented in strings as the special character '\0'.
- // (We don't have to include the NUL byte in string literals; the compiler
+ // (We don't have to include the NULL byte in string literals; the compiler
// inserts it at the end of the array for us.)
char a_string[20] = "This is a string";
printf("%s\n", a_string); // %s formats a string
@@ -182,7 +182,7 @@ int main() {
11 % 3; // => 2
// Comparison operators are probably familiar, but
- // there is no boolean type in c. We use ints instead.
+ // there is no Boolean type in c. We use ints instead.
// (Or _Bool or bool in C99.)
// 0 is false, anything else is true. (The comparison
// operators always yield 0 or 1.)
@@ -281,7 +281,7 @@ int main() {
// branching with multiple choices: switch()
switch (some_integral_expression) {
- case 0: // labels need to be integral *constant* epxressions
+ case 0: // labels need to be integral *constant* expressions
do_stuff();
break; // if you don't break, control flow falls over labels
case 1:
@@ -312,7 +312,7 @@ int main() {
// Types will overflow without warning
printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 if char is 8 bits long)
- // For determining the max value of a `char`, a `signed char` and an `unisigned char`,
+ // For determining the max value of a `char`, a `signed char` and an `unsigned char`,
// respectively, use the CHAR_MAX, SCHAR_MAX and UCHAR_MAX macros from <limits.h>
// Integral types can be cast to floating-point types, and vice-versa.
@@ -342,13 +342,13 @@ int main() {
// => Prints "8, 4" on a typical 64-bit system
// To retrieve the value at the address a pointer is pointing to,
- // put * in front to de-reference it.
+ // put * in front to dereference it.
// Note: yes, it may be confusing that '*' is used for _both_ declaring a
// pointer and dereferencing it.
printf("%d\n", *px); // => Prints 0, the value of x
// You can also change the value the pointer is pointing to.
- // We'll have to wrap the de-reference in parenthesis because
+ // We'll have to wrap the dereference in parenthesis because
// ++ has a higher precedence than *.
(*px)++; // Increment the value px is pointing to by 1
printf("%d\n", *px); // => Prints 1
@@ -532,7 +532,7 @@ int area(const rect *r)
// Function pointers
///////////////////////////////////////
/*
-At runtime, functions are located at known memory addresses. Function pointers are
+At run time, functions are located at known memory addresses. Function pointers are
much like any other pointer (they just store a memory address), but can be used
to invoke functions directly, and to pass handlers (or callback functions) around.
However, definition syntax may be initially confusing.
@@ -542,7 +542,7 @@ Example: use str_reverse from a pointer
void str_reverse_through_pointer(char *str_in) {
// Define a function pointer variable, named f.
void (*f)(char *); // Signature should exactly match the target function.
- f = &str_reverse; // Assign the address for the actual function (determined at runtime)
+ f = &str_reverse; // Assign the address for the actual function (determined at run time)
// f = str_reverse; would work as well - functions decay into pointers, similar to arrays
(*f)(str_in); // Just calling the function through the pointer
// f(str_in); // That's an alternative but equally valid syntax for calling it.
@@ -564,10 +564,10 @@ typedef void (*my_fnp_type)(char *);
'\n' // newline character
'\t' // tab character (left justifies text)
'\v' // vertical tab
-'\f' // new page (formfeed)
+'\f' // new page (form feed)
'\r' // carriage return
'\b' // backspace character
-'\0' // null character. Usually put at end of strings in C lang.
+'\0' // NULL character. Usually put at end of strings in C.
// hello\n\0. \0 used by convention to mark end of string.
'\\' // backslash
'\?' // question mark
@@ -586,7 +586,7 @@ typedef void (*my_fnp_type)(char *);
"%7.4s" // (can do with strings too)
"%c" // char
"%p" // pointer
-"%x" // hexidecimal
+"%x" // hexadecimal
"%o" // octal
"%%" // prints %
@@ -628,7 +628,7 @@ If you have a question, read the [compl.lang.c Frequently Asked Questions](http:
It's very important to use proper spacing, indentation and to be consistent with your coding style in general.
Readable code is better than clever code and fast code. For a good, sane coding style to adopt, see the
-[Linux kernel coding stlye](https://www.kernel.org/doc/Documentation/CodingStyle).
+[Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle).
Other than that, Google is your friend.
diff --git a/csharp.html.markdown b/csharp.html.markdown
index 4fa8deba..136f6c50 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -367,7 +367,7 @@ on a new line! ""Wow!"", the masses cried";
}
// Methods can have the same name, as long as the signature is unique
- public static void MethodSignature(string maxCount)
+ public static void MethodSignatures(string maxCount)
{
}
diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown
new file mode 100644
index 00000000..da562138
--- /dev/null
+++ b/fr-fr/scala.html.markdown
@@ -0,0 +1,458 @@
+---
+language: Scala
+filename: learnscala.scala
+contributors:
+ - ["George Petrov", "http://github.com/petrovg"]
+ - ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+translators:
+ - ["Anne-Catherine Dehier", "https://github.com/spellart"]
+filename: learn.scala
+lang: fr-fr
+---
+
+### Scala - le langage évolutif
+
+```scala
+
+/*
+ Pour vous préparer :
+
+ 1) (Téléchargez Scala)[http://www.scala-lang.org/downloads]
+ 2) Dézippez/décompressez dans votre endroit préféré
+ et ajoutez le chemin du sous-répertoire bin au chemin du système
+ 3) Commencez un REPL de Scala en tapant juste scala. Vous devriez voir le prompteur :
+
+ scala>
+
+ C'est ce qu'on appelle un REPL (Read-Eval-Print-Loop), c'est une interface de programmation interactive.
+ Vous pouvez y exécuter des commandes.
+ Allons-y :
+*/
+
+println(10) // affiche l'integer 10
+
+println("Boo!") // affiche avec retour à la ligne la chaîne de caractère Boo!
+
+
+// Quelques basiques
+
+// Imprimer et forcer une nouvelle ligne à la prochaine impression
+println("Hello world!")
+// Imprimer sans forcer une nouvelle ligne à la prochaine impression
+print("Hello world")
+
+// Pour déclarer des valeurs on utilise var ou val
+// Les déclarations val sont immuables, tandis que les var sont muables.
+// L'immuabilité est une bonne chose.
+
+val x = 10 // x vaut maintenant 10
+x = 20 // erreur : réaffectation à val
+var x = 10
+x = 20 // x vaut maintenant 20
+
+// Les commentaires d'une ligne commencent par deux slashs
+
+/*
+Les commentaires multilignes ressemblent à ça.
+*/
+
+// les valeurs booléennes
+true
+false
+
+// Les opérateurs booléens
+!true // false
+!false // true
+true == false // false
+10 > 5 // true
+
+// Les opérateurs mathématiques sont habituels
+1 + 1 // 2
+2 - 1 // 1
+5 * 3 // 15
+6 / 2 // 3
+
+
+// Le REPL donne le type et la valeur du résultat quand vous évaluez une commande
+
+1 + 7
+
+/* Les lignes ci-dessous donnent les résultats :
+
+ scala> 1 + 7
+ res29: Int = 8
+
+ Ça signifie que le résultat de l'évaluation 1 + 7 est un objet de
+ type Int avec une valeur de 8
+
+ 1+7 donnera le même résultat
+*/
+
+
+// Tout est un objet, même une fonction. Tapez ceci dans le REPL :
+
+7 // donne res30: Int = 7 (res30 est seulement un nom de variable généré pour le résultat)
+
+
+// La ligne suivante est une fonction qui prend un Int et retourne son carré
+(x:Int) => x * x
+
+
+// On peut assigner cette fonction à un identifieur comme ceci :
+val sq = (x:Int) => x * x
+
+/* La ligne suivante nous dit :
+
+ sq: Int => Int = <function1>
+
+ Ce qui signifie que cette fois-ci nous avons donné un nom explicite à la valeur.
+ sq est une fonction qui prend un Int et retourne un Int.
+
+
+ sq peut être exécutée comme ci-dessous :
+*/
+
+sq(10) // donne comme résultat : res33: Int = 100.
+
+
+// les deux-points définissent explicitement le type de la valeur,
+// dans ce cas une fonction qui prend un Int et retourne un Int.
+val add10: Int => Int = _ + 10
+
+// Scala autorise des méthodes et des fonctions à retourner
+// ou prendre comme paramètres des autres fonctions ou méthodes
+
+
+List(1, 2, 3) map add10 // List(11, 12, 13) - add10 est appliqué à chaque éléments
+
+
+// Les fonctions anonymes peuvent être utilisées à la place des fonctions nommées :
+List(1, 2, 3) map (x => x + 10)
+
+
+
+
+// Le tiret du bas peut être utilisé si la fonction anonyme ne prend qu'un paramètre.
+// Il se comporte comme une variable
+List(1, 2, 3) map (_ + 10)
+
+
+
+// Si le bloc et la fonction anonyme prennent tous les deux un seul argument,
+// vous pouvez omettre le tiret du bas
+List("Dom", "Bob", "Natalia") foreach println
+
+
+
+// Les structures de données
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Lance une exception
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Lance une exception
+
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
+
+val s = Set(1, 3, 7)
+s(0)
+s(1)
+
+/* Jetez un oeil sur la documentation de map ici -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+ */
+
+
+// Tuples
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "three")
+
+(a, 2, "three")
+
+// Exemple d'utilisation
+val divideInts = (x:Int, y:Int) => (x / y, x % y)
+
+
+divideInts(10,3) // La fonction divideInts donne le résultat et le reste de la division
+
+// Pour accéder à un élément d'un tuple, utilisez _._n
+// où n est l'index de base 1 de l'élément
+val d = divideInts(10,3)
+
+d._1
+
+d._2
+
+
+
+// Des combinaisons
+
+s.map(sq)
+
+val sSquared = s. map(sq)
+
+sSquared.filter(_ < 10)
+
+sSquared.reduce (_+_)
+
+
+
+// La fonction filter prend un prédicat (une fonction de type A -> Booléen) et
+// sélectionne tous les éléments qui satisfont ce prédicat
+List(1, 2, 3) filter (_ > 2) // List(3)
+List(
+ Person(name = "Dom", age = 23),
+ Person(name = "Bob", age = 30)
+).filter(_.age > 25) // List(Person("Bob", 30))
+
+
+
+// Scala a une méthode foreach définie pour certaines collections
+// qui prend en argument une fonction renvoyant Unit (une méthode void)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+
+
+
+// Compréhensions de listes
+
+for { n <- s } yield sq(n)
+
+val nSquared2 = for { n <- s } yield sq(n)
+
+for { n <- nSquared2 if n < 10 } yield n
+
+for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+
+
+
+/* Les exemples précédents ne sont pas des boucles for. La sémantique des boucles for
+ est "répète", alors qu'une for-compréhension définit une relation
+ entre deux ensembles de données. */
+
+
+
+// Boucles et itération
+
+1 to 5
+val r = 1 to 5
+r.foreach( println )
+
+r foreach println
+// NB: Scala est vraiment tolérant par rapport aux points et aux parenthèses en étudiant les roles séparément.
+// Ça aide pour écrire des DSL ou des API qui se lisent comme en anglais.
+
+
+(5 to 1 by -1) foreach ( println )
+
+// Une boucle while
+var i = 0
+while (i < 10) { println("i " + i); i+=1 }
+
+while (i < 10) { println("i " + i); i+=1 } // Oui, encore. Qu'est-ce qui s'est passé ? Pourquoi ?
+
+
+
+
+
+
+i // Montre la valeur de i. Notez que while est une boucle au sens classique.
+ // Il exécute séquentiellement pendant que la variable de boucle change.
+ // While est très rapide,
+ // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus
+ // facile pour comprendre et pour faire la parallélisation
+
+// La boucle do while
+do {
+ println("x is still less then 10");
+ x += 1
+} while (x < 10)
+
+
+// La récursivité est un moyen idiomatique de faire une chose répétitive en Scala.
+// Les fonctions récursives ont besoin d'un type de retour explicite,
+// le compilateur ne peut pas le déduire.
+// Ici c'est Unit.
+def showNumbersInRange(a:Int, b:Int):Unit = {
+ print(a)
+ if (a < b)
+ showNumbersInRange(a + 1, b)
+}
+
+
+
+// Structures de contrôle
+
+val x = 10
+
+if (x == 1) println("yeah")
+if (x == 10) println("yeah")
+if (x == 11) println("yeah")
+if (x == 11) println ("yeah") else println("nay")
+
+println(if (x == 10) "yeah" else "nope")
+val text = if (x == 10) "yeah" else "nope"
+
+var i = 0
+while (i < 10) { println("i " + i); i+=1 }
+
+
+
+// Les caractéristiques "Orienté Objet"
+
+// Création d'une classe Dog
+class Dog {
+ // Une méthode appelée bark qui retourne une chaîne de caractère
+ def bark: String = {
+ // le corps de la méthode
+ "Woof, woof!"
+ }
+}
+
+
+// Les classes peuvent contenir presque n'importe quelle autre construction, incluant d'autres classes,
+// des fonctions, des méthodes, des objets, des classes case, des traits, etc ...
+
+
+
+// Les classes case
+
+case class Person(name:String, phoneNumber:String)
+
+Person("George", "1234") == Person("Kate", "1236")
+
+
+
+
+// Correspondances de motifs
+
+val me = Person("George", "1234")
+
+me match { case Person(name, number) => {
+ "We matched someone : " + name + ", phone : " + number }}
+
+me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." }
+
+me match { case Person("George", number) => "Match"; case _ => "Hm..." }
+
+me match { case Person("Kate", number) => "Match"; case _ => "Hm..." }
+
+me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
+
+val kate = Person("Kate", "1234")
+
+kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
+
+
+
+// Expressions régulières
+
+val email = "(.*)@(.*)".r // On fait une Regex en invoquant r sur la chaîne de caractère
+
+val email(user, domain) = "henry@zkpr.com"
+
+"mrbean@pyahoo.com" match {
+ case email(name, domain) => "I know your name, " + name
+}
+
+
+
+// Les chaînes de caractères
+
+"Les chaînes de caractères Scala sont entourées de doubles guillements"
+'a' // Un caractère de Scala
+'Les simples guillemets n'existent pas en Scala // Erreur
+"Les chaînes de caractères possèdent les méthodes usuelles de Java".length
+"Il y a aussi quelques méthodes extra de Scala.".reverse
+
+// Voir également : scala.collection.immutable.StringOps
+
+println("ABCDEF".length)
+println("ABCDEF".substring(2, 6))
+println("ABCDEF".replace("C", "3"))
+
+val n = 45
+println(s"We have $n apples")
+
+val a = Array(11, 9, 6)
+println(s"My second daughter is ${a(2-1)} years old")
+
+// Certains caractères ont besoin d'être "échappés",
+// ex un guillemet à l'intérieur d'une chaîne de caractères :
+val a = "They stood outside the \"Rose and Crown\""
+
+// Les triples guillemets permettent d'écrire des chaînes de caractères
+// sur plusieurs lignes et peuvent contenir des guillemets
+
+val html = """<form id="daform">
+ <p>Press belo', Joe</p>
+ | <input type="submit">
+ </form>"""
+
+
+
+// Structure et organisation d'une application
+
+// Importer des chaînes de caratères
+import scala.collection.immutable.List
+
+// Importer tous les sous-paquets
+import scala.collection.immutable._
+
+// Importer plusieurs classes en une seule instruction
+import scala.collection.immutable.{List, Map}
+
+// Renommer un import en utilisant '=>'
+import scala.collection.immutable.{ List => ImmutableList }
+
+// Importer toutes les classes, à l'exception de certaines.
+// La ligne suivante exclut Map et Set :
+import scala.collection.immutable.{Map => _, Set => _, _}
+
+// Le point d'entrée du programme est défini dans un fichier scala
+// utilisant un objet, avec une simple méthode main :
+object Application {
+ def main(args: Array[String]): Unit = {
+ // Votre code ici.
+ }
+}
+
+// Les fichiers peuvent contenir plusieurs classes et plusieurs objets.
+// On les compile avec scalac
+
+
+
+
+// Entrée et Sortie
+
+// Pour lire un fichier ligne par ligne
+import scala.io.Source
+for(line <- Source.fromFile("myfile.txt").getLines())
+ println(line)
+
+// On utilise le PrintWriter de Java pour écrire un fichier
+
+
+```
+
+## Autres ressources
+
+[Scala for the impatient](http://horstmann.com/scala/)
+
+[Twitter Scala school](http://twitter.github.io/scala_school/)
+
+[The scala documentation](http://docs.scala-lang.org/)
+
+[Try Scala in your browser](http://scalatutorials.com/tour/)
+
+Rejoindre le [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
diff --git a/git.html.markdown b/git.html.markdown
index 65e57f05..618d1906 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -395,3 +395,5 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
* [GitGuys](http://www.gitguys.com/)
+
+* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) \ No newline at end of file
diff --git a/go.html.markdown b/go.html.markdown
index 88e2c8da..0ecc6120 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -202,25 +202,28 @@ func learnFlowControl() {
goto love
love:
+ learnFunctionFactory() // func returning func is fun(3)(3)
learnDefer() // A quick detour to an important keyword.
learnInterfaces() // Good stuff coming up!
}
+func learnFunctionFactory() {
+ // Next two are equivalent, with second being more practical
+ fmt.Println(sentenceFactory("summer")("A beautiful", "day!"))
+
+ d := sentenceFactory("summer")
+ fmt.Println(d("A beautiful", "day!"))
+ fmt.Println(d("A lazy", "afternoon!"))
+}
+
// Decorators are common in other languages. Same can be done in Go
// with function literals that accept arguments.
-func learnFunctionFactory(mystring string) func(before, after string) string {
- return func(before, after string) string {
- return fmt.Sprintf("%s %s %s", before, mystring, after) // new string
- }
+func sentenceFactory(mystring string) func(before, after string) string {
+ return func(before, after string) string {
+ return fmt.Sprintf("%s %s %s", before, mystring, after) // new string
+ }
}
-// Next two are equivalent, with second being more practical
-fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!"))
-
-d := learnFunctionFactory("summer")
-fmt.Println(d("A beautiful", "day!"))
-fmt.Println(d("A lazy", "afternoon!"))
-
func learnDefer() (ok bool) {
// Deferred statements are executed just before the function returns.
defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
@@ -339,17 +342,31 @@ func learnConcurrency() {
// A single function from package http starts a web server.
func learnWebProgramming() {
+
// First parameter of ListenAndServe is TCP address to listen to.
// Second parameter is an interface, specifically http.Handler.
- err := http.ListenAndServe(":8080", pair{})
- fmt.Println(err) // don't ignore errors
+ go func() {
+ err := http.ListenAndServe(":8080", pair{})
+ fmt.Println(err) // don't ignore errors
+ }()
+
+ requestServer();
}
+
// Make pair an http.Handler by implementing its only method, ServeHTTP.
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Serve data with a method of http.ResponseWriter.
w.Write([]byte("You learned Go in Y minutes!"))
}
+
+func requestServer() {
+ resp, err := http.Get("http://localhost:8080")
+ fmt.Println(err)
+ defer resp.Body.Close()
+ body, err := ioutil.ReadAll(resp.Body)
+ fmt.Printf("\nWebserver said: `%s`", string(body))
+}
```
## Further Reading
diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown
new file mode 100644
index 00000000..6d2a55cd
--- /dev/null
+++ b/pt-br/git-pt.html.markdown
@@ -0,0 +1,402 @@
+---
+category: tool
+tool: git
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+translators:
+ - ["Miguel Araújo", "https://github.com/miguelarauj1o"]
+lang: pt-br
+filename: learngit-pt.txt
+---
+
+Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte.
+
+Ele faz isso através de uma série de momentos instantâneos de seu projeto, e ele funciona
+com esses momentos para lhe fornecer a funcionalidade para a versão e
+gerenciar o seu código-fonte.
+
+## Versionando Conceitos
+
+### O que é controle de versão?
+
+O controle de versão é um sistema que registra alterações em um arquivo ou conjunto
+de arquivos, ao longo do tempo.
+
+### Versionamento Centralizado VS Versionamento Distribuído
+
+* Controle de versão centralizado concentra-se na sincronização, controle e backup de arquivos.
+* Controle de versão distribuído concentra-se na partilha de mudanças. Toda mudança tem um ID único.
+* Sistemas Distribuídos não têm estrutura definida. Você poderia facilmente ter um estilo SVN,
+sistema centralizado, com git.
+
+[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control)
+
+### Porque usar o Git?
+
+* Possibilidade de trabalhar offline
+* Colaborar com os outros é fácil!
+* Ramificação é fácil
+* Mesclagem é fácil
+* Git é rápido
+* Git é flexível.
+
+## Arquitetura Git
+
+### Repositório
+
+Um conjunto de arquivos, diretórios, registros históricos, cometes, e cabeças. Imagine-o
+como uma estrutura de dados de código-fonte, com o atributo que cada "elemento" do
+código-fonte dá-lhe acesso ao seu histórico de revisão, entre outras coisas.
+
+Um repositório git é composto do diretório git. e árvore de trabalho.
+
+### Diretório .git (componente do repositório)
+
+O diretório git. contém todas as configurações, registros, galhos, cabeça(HEAD) e muito mais.
+[Lista Detalhada](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html)
+
+### Árvore de trabalho (componente do repositório)
+
+Esta é, basicamente, os diretórios e arquivos no seu repositório. Ele é muitas vezes referida
+como seu diretório de trabalho.
+
+### Índice (componente do diretório .git)
+
+O Índice é a área de teste no git. É basicamente uma camada que separa a sua árvore de trabalho
+a partir do repositório Git. Isso dá aos desenvolvedores mais poder sobre o que é enviado para o
+repositório Git.
+
+### Comete (commit)
+
+A commit git é um instantâneo de um conjunto de alterações ou manipulações a sua árvore de trabalho.
+Por exemplo, se você adicionou 5 imagens, e removeu outros dois, estas mudanças serão contidas
+em um commit (ou instantâneo). Esta confirmação pode ser empurrado para outros repositórios, ou não!
+
+### Ramo (branch)
+
+Um ramo é, essencialmente, um ponteiro que aponta para o último commit que você fez. Como
+você se comprometer, este ponteiro irá atualizar automaticamente e apontar para o último commit.
+
+### Cabeça (HEAD) e cabeça (head) (componente do diretório .git)
+
+HEAD é um ponteiro que aponta para o ramo atual. Um repositório tem apenas 1 * ativo * HEAD.
+head é um ponteiro que aponta para qualquer commit. Um repositório pode ter qualquer número de commits.
+
+### Recursos Conceituais
+
+* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/)
+* [Git para Designers](http://hoth.entp.com/output/git_for_designers.html)
+
+## Comandos
+
+### init
+
+Criar um repositório Git vazio. As configurações do repositório Git, informações armazenadas,
+e mais são armazenados em um diretório (pasta) com o nome ". git".
+
+```bash
+$ git init
+```
+
+### config
+
+Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou
+configurações globais.
+
+```bash
+# Impressão e definir algumas variáveis ​​de configuração básica (global)
+$ git config --global user.email
+$ git config --global user.name
+
+$ git config --global user.email "MyEmail@Zoho.com"
+$ git config --global user.name "My Name"
+```
+
+[Saiba mais sobre o git config.](http://git-scm.com/docs/git-config)
+
+### help
+
+Para lhe dar um acesso rápido a um guia extremamente detalhada de cada comando. ou
+apenas dar-lhe um rápido lembrete de algumas semânticas.
+
+```bash
+# Rapidamente verificar os comandos disponíveis
+$ git help
+
+# Confira todos os comandos disponíveis
+$ git help -a
+
+# Ajuda específica de comando - manual do usuário
+# git help <command_here>
+$ git help add
+$ git help commit
+$ git help init
+```
+
+### status
+
+Para mostrar as diferenças entre o arquivo de índice (basicamente o trabalho de
+copiar/repo) e a HEAD commit corrente.
+
+```bash
+# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças
+$ git status
+
+# Para saber outras "tid bits" sobre git status
+$ git help status
+```
+
+### add
+
+Para adicionar arquivos para a atual árvore/directory/repo trabalho. Se você não
+der `git add` nos novos arquivos para o trabalhando árvore/diretório, eles não serão
+incluídos em commits!
+
+```bash
+# Adicionar um arquivo no seu diretório de trabalho atual
+$ git add HelloWorld.java
+
+# Adicionar um arquivo em um diretório aninhado
+$ git add /path/to/file/HelloWorld.c
+
+# Suporte a expressões regulares!
+$ git add ./*.java
+```
+
+### branch
+
+Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando.
+
+```bash
+# Lista ramos e controles remotos existentes
+$ git branch -a
+
+# Criar um novo ramo
+$ git branch myNewBranch
+
+# Apagar um ramo
+$ git branch -d myBranch
+
+# Renomear um ramo
+# git branch -m <oldname> <newname>
+$ git branch -m myBranchName myNewBranchName
+
+# Editar a descrição de um ramo
+$ git branch myBranchName --edit-description
+```
+
+### checkout
+
+Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no
+índice, ou árvore especificada.
+
+```bash
+# Finalizar um repo - padrão de ramo mestre
+$ git checkout
+# Checa um ramo especificado
+$ git checkout branchName
+# Criar um novo ramo e mudar para ela, como: "<nome> git branch; git checkout <nome>"
+$ git checkout -b newBranch
+```
+
+### clone
+
+Clones, ou cópias, de um repositório existente para um novo diretório. Ele também adiciona
+filiais remotas de rastreamento para cada ramo no repo clonado, que permite que você empurre
+a um ramo remoto.
+
+```bash
+# Clone learnxinyminutes-docs
+$ git clone https://github.com/adambard/learnxinyminutes-docs.git
+```
+
+### commit
+
+Armazena o conteúdo atual do índice em um novo "commit". Este commit contém
+as alterações feitas e uma mensagem criada pelo utilizador.
+
+```bash
+# commit com uma mensagem
+$ git commit -m "Added multiplyNumbers() function to HelloWorld.c"
+```
+
+### diff
+
+Mostra as diferenças entre um arquivo no diretório, o índice de trabalho e commits.
+
+```bash
+# Mostrar diferença entre o seu diretório de trabalho e o índice.
+$ git diff
+
+# Mostrar diferenças entre o índice e o commit mais recente.
+$ git diff --cached
+
+# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente.
+$ git diff HEAD
+```
+
+### grep
+
+Permite procurar rapidamente um repositório.
+
+Configurações opcionais:
+
+```bash
+# Obrigado ao Travis Jeffery por isto
+# Configure os números de linha a serem mostrados nos resultados de busca grep
+$ git config --global grep.lineNumber true
+
+# Fazer resultados de pesquisa mais legível, incluindo agrupamento
+$ git config --global alias.g "grep --break --heading --line-number"
+```
+
+```bash
+# Procure por "variableName" em todos os arquivos java
+$ git grep 'variableName' -- '*.java'
+
+# Procure por uma linha que contém "arrayListName" e "adicionar" ou "remover"
+$ git grep -e 'arrayListName' --and \( -e add -e remove \)
+```
+
+Google é seu amigo; para mais exemplos
+[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja)
+
+### log
+
+Mostrar commits para o repositório.
+
+```bash
+# Mostrar todos os commits
+$ git log
+
+# Mostrar um número X de commits
+$ git log -n 10
+
+# Mostrar somente commits mesclados
+$ git log --merges
+```
+
+### merge
+
+"Merge" em mudanças de commits externos no branch atual.
+
+```bash
+# Mesclar o ramo especificado para o atual.
+$ git merge branchName
+
+# Gera sempre uma mesclagem commit ao mesclar
+$ git merge --no-ff branchName
+```
+
+### mv
+
+Renomear ou mover um arquivo
+
+```bash
+# Renomear um arquivo
+$ git mv HelloWorld.c HelloNewWorld.c
+
+# Mover um arquivo
+$ git mv HelloWorld.c ./new/path/HelloWorld.c
+
+# Força renomear ou mover
+# "ExistingFile" já existe no diretório, será substituído
+$ git mv -f myFile existingFile
+```
+
+### pull
+
+Puxa de um repositório e se funde com outro ramo.
+
+```bash
+# Atualize seu repo local, através da fusão de novas mudanças
+# A partir da "origem" remoto e ramo "master (mestre)".
+# git pull <remote> <branch>
+# git pull => implícito por padrão => git pull origin master
+$ git pull origin master
+
+# Mesclar em mudanças de ramo remoto e rebase
+# Ramo commita em seu repo local, como: "git pull <remote> <branch>, git rebase <branch>"
+$ git pull origin master --rebase
+```
+
+### push
+
+Empurre e mesclar as alterações de uma ramificação para uma remota e ramo.
+
+```bash
+# Pressione e mesclar as alterações de um repo local para um
+# Chamado remoto "origem" e ramo de "mestre".
+# git push <remote> <branch>
+# git push => implícito por padrão => git push origin master
+$ git push origin master
+
+# Para ligar atual filial local com uma filial remota, bandeira add-u:
+$ git push -u origin master
+# Agora, a qualquer hora que você quer empurrar a partir desse mesmo ramo local, uso de atalho:
+$ git push
+```
+
+### rebase (CAUTELA)
+
+Tire todas as alterações que foram commitadas em um ramo, e reproduzi-las em outro ramo.
+* Não rebase commits que você tenha empurrado a um repo público *.
+
+```bash
+# Rebase experimentBranch para mestre
+# git rebase <basebranch> <topicbranch>
+$ git rebase master experimentBranch
+```
+
+[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing)
+
+### reset (CAUTELA)
+
+Repor o atual HEAD de estado especificado. Isto permite-lhe desfazer fusões (merge),
+puxa (push), commits, acrescenta (add), e muito mais. É um grande comando, mas também
+perigoso se não saber o que se está fazendo.
+
+```bash
+# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado)
+$ git reset
+
+# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado
+$ git reset --hard
+
+# Move a ponta ramo atual para o especificado commit (deixa diretório inalterado)
+# Todas as alterações ainda existem no diretório.
+$ git reset 31f2bb1
+
+# Move a ponta ramo atual para trás, para o commit especificado
+# E faz o jogo dir trabalho (exclui mudanças não commitadas e todos os commits
+# Após o commit especificado).
+$ git reset --hard 31f2bb1
+```
+
+### rm
+
+O oposto do git add, git rm remove arquivos da atual árvore de trabalho.
+
+```bash
+# remove HelloWorld.c
+$ git rm HelloWorld.c
+
+# Remove um arquivo de um diretório aninhado
+$ git rm /pather/to/the/file/HelloWorld.c
+```
+
+# # Mais informações
+
+* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1)
+
+* [git-scm - Video Tutorials](http://git-scm.com/videos)
+
+* [git-scm - Documentation](http://git-scm.com/docs)
+
+* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/)
+
+* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
+
+* [GitGuys](http://www.gitguys.com/)
+
+* [Git - guia prático](http://rogerdudler.github.io/git-guide/index.pt_BR.html) \ No newline at end of file
diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown
new file mode 100644
index 00000000..fc63b126
--- /dev/null
+++ b/pt-br/json-pt.html.markdown
@@ -0,0 +1,62 @@
+---
+language: json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Miguel Araújo", "https://github.com/miguelarauj1o"]
+lang: pt-br
+filename: learnjson-pt.json
+---
+
+Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o
+"Learn X in Y minutes" mais simples existente.
+
+JSON na sua forma mais pura não tem comentários em reais, mas a maioria dos analisadores
+aceitarão comentários no estilo C (//, /\* \*/). Para os fins do presente, no entanto,
+tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si.
+
+
+```json
+{
+ "chave": "valor",
+
+ "chaves": "deve ser sempre entre aspas (junto ou separado)",
+ "números": 0,
+ "strings": "Olá, mundo. Todo o padrão UNICODE é permitido, junto com \"escapando\".",
+ "possui booleano?": true,
+ "nada": null,
+
+ "número grande": 1.2e+100,
+
+ "objetos": {
+ "comentário": "A maior parte da sua estrutura virá de objetos.",
+
+ "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5],
+
+ "outro objeto": {
+ "ccomentário": "Estas coisas podem ser aninhadas, muito úteis."
+ }
+ },
+
+ "tolice": [
+ {
+ "fonte de potássio": ["bananas"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "estilo alternativo": {
+ "comentário": "verificar isso!"
+ , "posição da vírgula": "não importa - enquanto é antes do valor, então é válido"
+ , "outro comentário": "que bom"
+ },
+
+ "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.".
+}
+```
diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown
index d186f712..8b292edd 100644
--- a/ruby-ecosystem.html.markdown
+++ b/ruby-ecosystem.html.markdown
@@ -3,21 +3,22 @@ category: tool
tool: ruby ecosystem
contributors:
- ["Jon Smock", "http://github.com/jonsmock"]
+ - ["Rafal Chmiel", "http://github.com/rafalchmiel"]
---
-People using ruby generally have a way to install different ruby versions,
+People using Ruby generally have a way to install different Ruby versions,
manage their packages (or gems), and manage their gem dependencies.
## Ruby Managers
-Some platforms have ruby pre-installed or available as a package. Most rubyists
-do not use these, or if they do, they only use them to bootstrap another ruby
-installer or implementation. Instead rubyists tend to install a ruby manager to
-install and switch between many versions of ruby and their projects' ruby
+Some platforms have Ruby pre-installed or available as a package. Most rubyists
+do not use these, or if they do, they only use them to bootstrap another Ruby
+installer or implementation. Instead rubyists tend to install a Ruby manager to
+install and switch between many versions of Ruby and their projects' Ruby
environments.
-The following are the popular ruby/environment managers:
+The following are the popular Ruby environment managers:
* [RVM](https://rvm.io/) - Installs and switches between rubies. RVM also has
the concept of gemsets to isolate projects' environments completely.
@@ -32,11 +33,11 @@ The following are the popular ruby/environment managers:
Ruby was created by Yukihiro "Matz" Matsumoto, who remains somewhat of a
[BDFL](https://en.wikipedia.org/wiki/Benevolent_Dictator_for_Life), although
-that is changing recently. As a result, the reference implementation of ruby is
-called MRI (Matz' Reference Implementation), and when you hear a ruby version,
+that is changing recently. As a result, the reference implementation of Ruby is
+called MRI (Matz' Reference Implementation), and when you hear a Ruby version,
it is referring to the release version of MRI.
-The three major version of ruby in use are:
+The three major version of Ruby in use are:
* 2.0.0 - Released in February 2013. Most major libraries and frameworks support
2.0.0.
@@ -52,38 +53,38 @@ the community has moved to at least 1.9.2 or 1.9.3.
## Ruby Implementations
-The ruby ecosystem enjoys many different implementations of ruby, each with
+The Ruby ecosystem enjoys many different implementations of Ruby, each with
unique strengths and states of compatability. To be clear, the different
-implementations are written in different languages, but *they are all ruby*.
+implementations are written in different languages, but *they are all Ruby*.
Each implementation has special hooks and extra features, but they all run
-normal ruby files well. For instance, JRuby is written in Java, but you do
+normal Ruby files well. For instance, JRuby is written in Java, but you do
not need to know Java to use it.
Very mature/compatible:
-* MRI - Written in C, this is the reference implementation of ruby. By
+* [MRI](https://github.com/ruby/ruby) - Written in C, this is the reference implementation of Ruby. By
definition it is 100% compatible (with itself). All other rubies
maintain compatibility with MRI (see [RubySpec](#rubyspec) below).
-* JRuby - Written in Java and ruby, this robust implementation is quite fast.
+* [JRuby](http://jruby.org/) - Written in Java and Ruby, this robust implementation is quite fast.
Most importantly, JRuby's strength is JVM/Java interop, leveraging existing
JVM tools, projects, and languages.
-* Rubinius - Written primarily in ruby itself with a C++ bytecode VM. Also
- mature and fast. Because it is implemented in ruby itself, it exposes many VM
+* [Rubinius](http://rubini.us/) - Written primarily in Ruby itself with a C++ bytecode VM. Also
+ mature and fast. Because it is implemented in Ruby itself, it exposes many VM
features into rubyland.
Medium mature/compatible:
-* Maglev - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some
- impressive tooling, and this project tries to bring that into ruby
+* [Maglev](http://maglev.github.io/) - Built on top of Gemstone, a Smalltalk VM. Smalltalk has some
+ impressive tooling, and this project tries to bring that into Ruby
development.
-* RubyMotion - Brings ruby to iOS development.
+* [RubyMotion](http://www.rubymotion.com/) - Brings Ruby to iOS development.
Less mature/compatible:
-* Topaz - Written in RPython (using the PyPy toolchain), Topaz is fairly young
- and not yet compatible. It shows promise to be a high-performance ruby
+* [Topaz](http://topazruby.com/) - Written in RPython (using the PyPy toolchain), Topaz is fairly young
+ and not yet compatible. It shows promise to be a high-performance Ruby
implementation.
-* IronRuby - Written in C# targeting the .NET platform, work on IronRuby seems
+* [IronRuby](http://ironruby.net/) - Written in C# targeting the .NET platform, work on IronRuby seems
to have stopped since Microsoft pulled their support.
Ruby implementations may have their own release version numbers, but they always
@@ -93,14 +94,14 @@ which MRI version to target.
## RubySpec
-Most ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby
+Most Ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby
has no official specification, so the community has written executable specs in
-ruby to test their implementations' compatability with MRI.
+Ruby to test their implementations' compatibility with MRI.
## RubyGems
-[RubyGems](http://rubygems.org/) is a community-run package manager for ruby.
-RubyGems ships with ruby, so there is no need to download it separately.
+[RubyGems](http://rubygems.org/) is a community-run package manager for Ruby.
+RubyGems ships with Ruby, so there is no need to download it separately.
Ruby packages are called "gems," and they can be hosted by the community at
RubyGems.org. Each gem contains its source code and some metadata, including
@@ -121,17 +122,17 @@ dependency graph to resolve.
# Testing
-Testing is a large part of ruby culture. Ruby comes with its own Unit-style
-testing framework called minitest (Or TestUnit for ruby version 1.8.x). There
+Testing is a large part of Ruby culture. Ruby comes with its own Unit-style
+testing framework called minitest (Or TestUnit for Ruby version 1.8.x). There
are many testing libraries with different goals.
-* TestUnit - Ruby 1.8's built-in "Unit-style" testing framework
-* minitest - Ruby 1.9/2.0's built-in testing framework
-* RSpec - A testing framework that focuses on expressivity
-* Cucumber - A BDD testing framework that parses Gherkin formatted tests
+* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Ruby 1.8's built-in "Unit-style" testing framework
+* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Ruby 1.9/2.0's built-in testing framework
+* [RSpec](http://rspec.info/) - A testing framework that focuses on expressivity
+* [Cucumber](http://cukes.info/) - A BDD testing framework that parses Gherkin formatted tests
## Be Nice
-The ruby community takes pride in being an open, diverse, welcoming community.
+The Ruby community takes pride in being an open, diverse, welcoming community.
Matz himself is extremely friendly, and the generosity of rubyists on the whole
is amazing.
diff --git a/rust.html.markdown b/rust.html.markdown
new file mode 100644
index 00000000..0b9a5e58
--- /dev/null
+++ b/rust.html.markdown
@@ -0,0 +1,265 @@
+---
+language: rust
+contributors:
+ - ["P1start", "http://p1start.github.io/"]
+filename: learnrust.rs
+---
+
+Rust is an in-development programming language developed by Mozilla Research.
+It is relatively unique among systems languages in that it can assert memory
+safety *at compile time*. Rust’s first alpha release occurred in January
+2012, and development moves so quickly that at the moment the use of stable
+releases is discouraged, and instead one should use nightly builds.
+
+Although Rust is a relatively low-level language, Rust has some functional
+concepts that are generally found in higher-level languages. This makes
+Rust not only fast, but also easy and efficient to code in.
+
+```rust
+// This is a comment. Single-line look like this...
+/* ...and multi-line comment look like this */
+
+///////////////
+// 1. Basics //
+///////////////
+
+// Functions
+fn add2(x: int, y: int) -> int {
+ // Implicit return (no semicolon)
+ x + y
+}
+
+// Main function
+fn main() {
+ // Numbers //
+
+ // Immutable bindings
+ let x: int = 1;
+
+ // Integer/float suffixes
+ let y: int = 13i;
+ let f: f64 = 1.3f64;
+
+ // Type inference
+ let implicit_x = 1i;
+ let implicit_f = 1.3f64;
+
+ // Maths
+ let sum = x + y + 13i;
+
+ // Mutable variable
+ let mut mutable = 1;
+ mutable += 2;
+
+ // Strings //
+
+ // String literals
+ let x: &'static str = "hello world!";
+
+ // Printing
+ println!("{} {}", f, x); // 1.3 hello world
+
+ // A `String` - a heap-allocated string
+ let s: String = "hello world".to_string();
+
+ // A string slice - an immutable view into another string
+ // This is basically an immutable pointer to a string - it doesn’t
+ // actually contain the characters of a string, just a pointer to
+ // something that does (in this case, `s`)
+ let s_slice: &str = s.as_slice();
+
+ println!("{} {}", s, s_slice); // hello world hello world
+
+ // Vectors/arrays //
+
+ // A fixed-size array
+ let four_ints: [int, ..4] = [1, 2, 3, 4];
+
+ // A dynamically-sized vector
+ let mut vector: Vec<int> = vec![1, 2, 3, 4];
+ vector.push(5);
+
+ // A slice - an immutable view into a vector or array
+ // This is much like a string slice, but for vectors
+ let slice: &[int] = vector.as_slice();
+
+ println!("{} {}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
+
+ //////////////
+ // 2. Types //
+ //////////////
+
+ // Struct
+ struct Point {
+ x: int,
+ y: int,
+ }
+
+ let origin: Point = Point { x: 0, y: 0 };
+
+ // Tuple struct
+ struct Point2(int, int);
+
+ let origin2 = Point2(0, 0);
+
+ // Basic C-like enum
+ enum Direction {
+ Left,
+ Right,
+ Up,
+ Down,
+ }
+
+ let up = Up;
+
+ // Enum with fields
+ enum OptionalInt {
+ AnInt(int),
+ Nothing,
+ }
+
+ let two: OptionalInt = AnInt(2);
+ let nothing: OptionalInt = Nothing;
+
+ // Generics //
+
+ struct Foo<T> { bar: T }
+
+ // This is defined in the standard library as `Option`
+ enum Optional<T> {
+ SomeVal(T),
+ NoVal,
+ }
+
+ // Methods //
+
+ impl<T> Foo<T> {
+ // Methods take an explicit `self` parameter
+ fn get_bar(self) -> T {
+ self.bar
+ }
+ }
+
+ let a_foo = Foo { bar: 1i };
+ println!("{}", a_foo.get_bar()); // 1
+
+ // Traits (interfaces) //
+
+ trait Frobnicate<T> {
+ fn frobnicate(self) -> Option<T>;
+ }
+
+ impl<T> Frobnicate<T> for Foo<T> {
+ fn frobnicate(self) -> Option<T> {
+ Some(self.bar)
+ }
+ }
+
+ println!("{}", a_foo.frobnicate()); // Some(1)
+
+ /////////////////////////
+ // 3. Pattern matching //
+ /////////////////////////
+
+ let foo = AnInt(1);
+ match foo {
+ AnInt(n) => println!("it’s an int: {}", n),
+ Nothing => println!("it’s nothing!"),
+ }
+
+ // Advanced pattern matching
+ struct FooBar { x: int, y: OptionalInt }
+ let bar = FooBar { x: 15, y: AnInt(32) };
+
+ match bar {
+ FooBar { x: 0, y: AnInt(0) } =>
+ println!("The numbers are zero!"),
+ FooBar { x: n, y: AnInt(m) } if n == m =>
+ println!("The numbers are the same"),
+ FooBar { x: n, y: AnInt(m) } =>
+ println!("Different numbers: {} {}", n, m),
+ FooBar { x: _, y: Nothing } =>
+ println!("The second number is Nothing!"),
+ }
+
+ /////////////////////
+ // 4. Control flow //
+ /////////////////////
+
+ // `for` loops/iteration
+ let array = [1i, 2, 3];
+ for i in array.iter() {
+ println!("{}", i);
+ }
+
+ for i in range(0u, 10) {
+ print!("{} ", i);
+ }
+ println!("");
+ // prints `0 1 2 3 4 5 6 7 8 9 `
+
+ // `if`
+ if 1i == 1 {
+ println!("Maths is working!");
+ } else {
+ println!("Oh no...");
+ }
+
+ // `if` as expression
+ let value = if true {
+ "good"
+ } else {
+ "bad"
+ };
+
+ // `while` loop
+ while 1i == 1 {
+ println!("The universe is operating normally.");
+ }
+
+ // Infinite loop
+ loop {
+ println!("Hello!");
+ }
+
+ /////////////////////////////////
+ // 5. Memory safety & pointers //
+ /////////////////////////////////
+
+ // Owned pointer - only one thing can ‘own’ this pointer at a time
+ let mut mine: Box<int> = box 3;
+ *mine = 5; // dereference
+ let mut now_its_mine = mine;
+ *now_its_mine += 2;
+ println!("{}", now_its_mine); // 7
+ // println!("{}", mine); // this would error
+
+ // Reference - an immutable pointer that refers to other data
+ let mut var = 4i;
+ var = 3;
+ let ref_var: &int = &var;
+ println!("{}", var); // Unlike `box`, `var` can still be used
+ println!("{}", *ref_var);
+ // var = 5; // this would error
+ // *ref_var = 6; // this would too
+
+ // Mutable reference
+ let mut var2 = 4i;
+ let ref_var2: &mut int = &mut var2;
+ *ref_var2 += 2;
+ println!("{}", *ref_var2); // 6
+ // var2 = 2; // this would error
+}
+```
+
+## Further reading
+
+There’s a lot more to Rust—this is just the basics of Rust so you can
+understand the most important things. To learn more about Rust, read the
+[Rust tutorial](http://doc.rust-lang.org/tutorial.html) and check out the
+[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel
+on irc.mozilla.org are also always keen to help newcomers.
+
+You can also try out features of Rust with an online compiler at the official
+[Rust playpen](http://play.rust-lang.org) or on the main
+[Rust website](http://rust-lang.org).
diff --git a/scala.html.markdown b/scala.html.markdown
index 2666746e..432933c2 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -37,7 +37,7 @@ println("Hello world!")
print("Hello world")
// Declaring values is done using either var or val
-// val declarations are immutable, whereas var's are mutable. Immutablility is
+// val declarations are immutable, whereas var's are mutable. Immutability is
// a good thing.
val x = 10 // x is now 10
x = 20 // error: reassignment to val
diff --git a/whip.html.markdown b/whip.html.markdown
index 3429ec24..dc5a0b39 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -153,8 +153,8 @@ undefined ; user to indicate a value that hasn't been set
; Lambdas in Whip are declared with the `lambda` or `->` function.
; And functions are really just lambdas with names.
-(def my_function (-> (x y) (+ (x y) 10)))
-; | | | |
+(def my_function (-> (x y) (+ (+ x y) 10)))
+; | | | |
; | | | returned value(with scope containing argument vars)
; | | arguments
; | lambda declaration function