summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--coffeescript.html.markdown2
-rw-r--r--css.html.markdown1
-rw-r--r--de-de/css-de.html.markdown1
-rw-r--r--es-es/go-es.html.markdown195
-rw-r--r--fa-ir/javascript.html.markdown2
-rw-r--r--fr-fr/haskell.html.markdown1
-rw-r--r--fr-fr/objective-c-fr.html.markdown7
-rw-r--r--go.html.markdown132
-rw-r--r--java.html.markdown2
-rw-r--r--ko-kr/coffeescript-kr.html.markdown2
-rw-r--r--ko-kr/go-kr.html.markdown2
-rw-r--r--ko-kr/javascript-kr.html.markdown1
-rw-r--r--ko-kr/lua-kr.html.markdown1
-rw-r--r--ko-kr/php-kr.html.markdown2
-rw-r--r--objective-c.html.markdown222
-rw-r--r--pt-br/java-pt.html.markdown2
-rw-r--r--pt-br/ruby-pt.html.markdown4
-rw-r--r--ru-ru/c-ru.html.markdown4
-rw-r--r--ru-ru/julia-ru.html.markdown3
-rw-r--r--zh-cn/r-cn.html.markdown2
-rw-r--r--zh-cn/racket-cn.html.markdown2
-rw-r--r--zh-cn/scala-cn.html.markdown1
22 files changed, 424 insertions, 167 deletions
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index 429f10b5..c61cad67 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -5,6 +5,8 @@ contributors:
filename: coffeescript.coffee
---
+See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
+
``` coffeescript
# CoffeeScript is a hipster language.
# It goes with the trends of many modern languages.
diff --git a/css.html.markdown b/css.html.markdown
index b16b364d..26eaae53 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -2,6 +2,7 @@
language: css
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
+filename: learncss.css
---
In early days of web there was no visual elements, just pure text. But with the
diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown
index e03b3174..8909b251 100644
--- a/de-de/css-de.html.markdown
+++ b/de-de/css-de.html.markdown
@@ -5,6 +5,7 @@ contributors:
translators:
- ["Kyr", "http://github.com/kyrami"]
lang: de-de
+filename: learncss-de.css
---
In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwickliung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard.
diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown
index 434f6713..a7166dc1 100644
--- a/es-es/go-es.html.markdown
+++ b/es-es/go-es.html.markdown
@@ -2,21 +2,25 @@
name: Go
category: language
language: Go
-filename: learngo.go
+filename: learngo-es.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
translators:
- ["Adrian Espinosa", "http://www.adrianespinosa.com"]
+ - ["Jesse Johnson, "https://github.com/holocronweaver"]
lang: es-es
-
-
---
-Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la última
-tendencia en informática, pero es la forma nueva y más rápida de resolver problemas reales.
+Go fue creado por la necesidad de hacer el trabajo rápidamente. No es
+la última tendencia en informática, pero es la forma nueva y más
+rápida de resolver problemas reales.
+
+Tiene conceptos familiares de lenguajes imperativos con tipado
+estático. Es rápido compilando y rápido al ejecutar, añade una
+concurrencia fácil de entender para las CPUs de varios núcleos de hoy
+en día, y tiene características que ayudan con la programación a gran
+escala.
-Tiene conceptos familiares de lenguajes imperativos con tipado estático.
-Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de entender para las CPUs de varios núcleos de hoy en día, y tiene características que ayudan con la programación a gran escala.
Go viene con una librería estándar muy buena y una comunidad entusiasta.
```go
@@ -28,15 +32,17 @@ Go viene con una librería estándar muy buena y una comunidad entusiasta.
// Main es un nombre especial que declara un ejecutable en vez de una librería.
package main
-// La declaración Import declara los paquetes de librerías referenciados en este archivo.
+// La declaración Import declara los paquetes de librerías
+// referenciados en este archivo.
import (
- "fmt" // Un paquete en la librería estándar de Go
+ "fmt" // Un paquete en la librería estándar de Go.
"net/http" // Sí, un servidor web!
- "strconv" // Conversiones de cadenas
+ "strconv" // Conversiones de cadenas.
+ m "math" // Librería matemáticas con alias local m.
)
-// Definición de una función. Main es especial. Es el punto de entrada para el ejecutable.
-// Te guste o no, Go utiliza llaves.
+// Definición de una función. Main es especial. Es el punto de
+// entrada para el ejecutable. Te guste o no, Go utiliza llaves.
func main() {
// Println imprime una línea a stdout.
// Cualificalo con el nombre del paquete, fmt.
@@ -49,19 +55,19 @@ func main() {
// Las funciones llevan parámetros entre paréntesis.
// Si no hay parámetros, los paréntesis siguen siendo obligatorios.
func beyondHello() {
- var x int // Declaración de una variable. Las variables se deben declarar antes de
- // utilizarlas.
+ var x int // Declaración de una variable.
+ // Las variables se deben declarar antes de utilizarlas.
x = 3 // Asignación de variables.
// Declaración "corta" con := para inferir el tipo, declarar y asignar.
y := 4
- sum, prod := learnMultiple(x, y) // función devuelve dos valores
- fmt.Println("sum:", sum, "prod:", prod) // simple salida
+ sum, prod := learnMultiple(x, y) // Función devuelve dos valores.
+ fmt.Println("sum:", sum, "prod:", prod) // Simple salida.
learnTypes() // < y minutes, learn more!
}
// Las funciones pueden tener parámetros y (múltiples!) valores de retorno.
func learnMultiple(x, y int) (sum, prod int) {
- return x + y, x * y // devolver dos valores
+ return x + y, x * y // Devolver dos valores.
}
// Algunos tipos incorporados y literales.
@@ -73,32 +79,33 @@ func learnTypes() {
saltos de línea.` // mismo tipo cadena
// Literal no ASCII. Los fuentes de Go son UTF-8.
- g := 'Σ' // tipo rune, un alias de uint32, alberga un punto unicode.
- f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit
- c := 3 + 4i // complex128, representado internamente por dos float64
+ g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode.
+ f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit.
+ c := 3 + 4i // complex128, representado internamente por dos float64.
// Sintaxis Var con inicializadores.
- var u uint = 7 // sin signo, pero la implementación depende del tamaño como en int
+ var u uint = 7 // Sin signo, pero la implementación depende del
+ // tamaño como en int.
var pi float32 = 22. / 7
// Sintáxis de conversión con una declaración corta.
- n := byte('\n') // byte es un alias de uint8
+ n := byte('\n') // byte es un alias de uint8.
// Los Arrays tienen un tamaño fijo a la hora de compilar.
- var a4 [4]int // un array de 4 ints, inicializados a 0
- a3 := [...]int{3, 1, 5} // un array de 3 ints, inicializados como se indica
+ var a4 [4]int // Un array de 4 ints, inicializados a 0.
+ a3 := [...]int{3, 1, 5} // Un array de 3 ints, inicializados como se indica.
// Los Slices tienen tamaño dinámico. Los arrays y slices tienen sus ventajas
// y desventajas pero los casos de uso para los slices son más comunes.
- s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos
- s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0
- var d2 [][]float64 // solo declaración, sin asignación
- bs := []byte("a slice") // sintaxis de conversión de tipo
+ s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos.
+ s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0.
+ var d2 [][]float64 // Solo declaración, sin asignación.
+ bs := []byte("a slice") // Sintaxis de conversión de tipo.
- p, q := learnMemory() // declara p, q para ser un tipo puntero a int.
+ p, q := learnMemory() // Declara p, q para ser un tipo puntero a int.
fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints.
- // Los Maps son arrays asociativos dinámicos, como los hash o diccionarios
- // de otros lenguajes
+ // Los Maps son arrays asociativos dinámicos, como los hash o
+ // diccionarios de otros lenguajes.
m := map[string]int{"three": 3, "four": 4}
m["one"] = 1
@@ -108,23 +115,24 @@ saltos de línea.` // mismo tipo cadena
// Esto cuenta como utilización de variables.
fmt.Println(s, c, a4, s3, d2, m)
- learnFlowControl() // vuelta al flujo
+ learnFlowControl() // Vuelta al flujo.
}
-// Go posee recolector de basura. Tiene puntero pero no aritmética de punteros.
-// Puedes cometer un errores con un puntero nil, pero no incrementando un puntero.
+// Go posee recolector de basura. Tiene puntero pero no aritmética de
+// punteros. Puedes cometer un errores con un puntero nil, pero no
+// incrementando un puntero.
func learnMemory() (p, q *int) {
// q y p tienen un tipo puntero a int.
- p = new(int) // función incorporada que asigna memoria.
+ p = new(int) // Función incorporada que asigna memoria.
// La asignación de int se inicializa a 0, p ya no es nil.
- s := make([]int, 20) // asigna 20 ints a un solo bloque de memoria.
- s[3] = 7 // asignar uno de ellos
- r := -2 // declarar otra variable local
+ s := make([]int, 20) // Asigna 20 ints a un solo bloque de memoria.
+ s[3] = 7 // Asignar uno de ellos.
+ r := -2 // Declarar otra variable local.
return &s[3], &r // & toma la dirección de un objeto.
}
-func expensiveComputation() int {
- return 1e6
+func expensiveComputation() float64 {
+ return m.Exp(10)
}
func learnFlowControl() {
@@ -134,29 +142,31 @@ func learnFlowControl() {
}
// El formato está estandarizado por el comando "go fmt."
if false {
- // pout
+ // Pout.
} else {
- // gloat
+ // Gloat.
}
// Utiliza switch preferiblemente para if encadenados.
- x := 1
+ x := 42.0
switch x {
case 0:
case 1:
- // los cases no se mezclan, no requieren de "break"
- case 2:
- // no llega
+ case 42:
+ // Los cases no se mezclan, no requieren de "break".
+ case 43:
+ // No llega.
}
// Como if, for no utiliza paréntesis tampoco.
- for x := 0; x < 3; x++ { // ++ es una sentencia
+ // Variables declaradas en for y if son locales de su ámbito local.
+ for x := 0; x < 3; x++ { // ++ es una sentencia.
fmt.Println("iteration", x)
}
- // x == 1 aqui.
+ // x == 42 aqui.
// For es la única sentencia de bucle en Go, pero tiene formas alternativas.
- for { // bucle infinito
- break // solo bromeaba!
- continue // no llega
+ for { // Bucle infinito.
+ break // Solo bromeaba!
+ continue // No llega.
}
// Como en for, := en una sentencia if significa declarar y asignar primero,
// luego comprobar y > x.
@@ -165,11 +175,11 @@ func learnFlowControl() {
}
// Los literales de funciones son "closures".
xBig := func() bool {
- return x > 100 // referencia a x declarada encima de la sentencia switch.
+ return x > 100 // Referencia a x declarada encima de la sentencia switch.
}
- fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x)
- x /= 1e5 // esto lo hace == 10
- fmt.Println("xBig:", xBig()) // ahora es falso
+ fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x).
+ x /= m.Exp(9) // Esto lo hace x == e.
+ fmt.Println("xBig:", xBig()) // Ahora es falso.
// Cuando lo necesites, te encantará.
goto love
@@ -199,16 +209,29 @@ func learnInterfaces() {
// La sintaxis de llaves es un "literal struct". Evalúa a un struct
// inicializado. La sintaxis := declara e inicializa p a este struct.
p := pair{3, 4}
- fmt.Println(p.String()) // llamar al método String de p, de tipo pair.
- var i Stringer // declarar i como interfaz tipo Stringer.
- i = p // válido porque pair implementa Stringer
- // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba
+ fmt.Println(p.String()) // Llamar al método String de p, de tipo pair.
+ var i Stringer // Declarar i como interfaz tipo Stringer.
+ i = p // Válido porque pair implementa Stringer.
+ // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba.
fmt.Println(i.String())
- // Las funciones en el paquete fmt llaman al método String para preguntar a un objeto
- // por una versión imprimible de si mismo
- fmt.Println(p) // salida igual que arriba. Println llama al método String.
- fmt.Println(i) // salida igual que arriba.
+ // Las funciones en el paquete fmt llaman al método String para
+ // preguntar a un objeto por una versión imprimible de si mismo.
+ fmt.Println(p) // Salida igual que arriba. Println llama al método String.
+ fmt.Println(i) // Salida igual que arriba.
+
+ learnVariadicParams("great", "learning", "here!")
+}
+
+// Las funciones pueden tener número variable de argumentos.
+func learnVariadicParams(myStrings ...interface{}) {
+ // Iterar cada valor de la variadic.
+ for _, param := range myStrings {
+ fmt.Println("param:", param)
+ }
+
+ // Pasar valor variadic como parámetro variadic.
+ fmt.Println("params:", fmt.Sprintln(myStrings...))
learnErrorHandling()
}
@@ -223,7 +246,7 @@ func learnErrorHandling() {
}
// Un valor de error comunica más información sobre el problema aparte de "ok".
if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta el valor
- // imprime "strconv.ParseInt: parsing "non-int": invalid syntax"
+ // Imprime "strconv.ParseInt: parsing "non-int": invalid syntax".
fmt.Println(err)
}
// Revisarmeos las interfaces más tarde. Mientras tanto,
@@ -248,25 +271,28 @@ func learnConcurrency() {
go inc(-805, c)
// Leer los tres resultados del channel e imprimirlos.
// No se puede saber en que orden llegarán los resultados!
- fmt.Println(<-c, <-c, <-c) // channel a la derecha, <- es el operador "recibir".
-
- cs := make(chan string) // otro channel, este gestiona cadenas.
- cc := make(chan chan string) // un channel de cadenas de channels.
- go func() { c <- 84 }() // iniciar una nueva goroutine solo para enviar un valor.
- go func() { cs <- "wordy" }() // otra vez, para cs en esta ocasión
- // Select tiene una sintáxis parecida a la sentencia switch pero cada caso involucra
- // una operacion de channels. Selecciona un caso de forma aleatoria de los casos
- // que están listos para comunicarse.
+ fmt.Println(<-c, <-c, <-c) // Channel a la derecha, <- es el operador "recibir".
+
+ cs := make(chan string) // Otro channel, este gestiona cadenas.
+ ccs := make(chan chan string) // Un channel de cadenas de channels.
+ go func() { c <- 84 }() // Iniciar una nueva goroutine solo para
+ // enviar un valor.
+ go func() { cs <- "wordy" }() // Otra vez, para cs en esta ocasión.
+ // Select tiene una sintáxis parecida a la sentencia switch pero
+ // cada caso involucra una operacion de channels. Selecciona un caso
+ // de forma aleatoria de los casos que están listos para comunicarse.
select {
- case i := <-c: // el valor recibido puede ser asignado a una variable
+ case i := <-c: // El valor recibido puede ser asignado a una variable,
fmt.Printf("it's a %T", i)
- case <-cs: // o el valor puede ser descartado
+ case <-cs: // o el valor puede ser descartado.
fmt.Println("it's a string")
- case <-cc: // channel vacío, no está listo para la comunicación.
+ case <-ccs: // Channel vacío, no está listo para la comunicación.
fmt.Println("didn't happen.")
}
+
// En este punto un valor fue devuelvto de c o cs. Uno de las dos
- // goroutines que se iniciaron se ha completado, la otrá permancerá bloqueada.
+ // goroutines que se iniciaron se ha completado, la otrá permancerá
+ // bloqueada.
learnWebProgramming() // Go lo hace. Tu también quieres hacerlo.
}
@@ -281,7 +307,7 @@ func learnWebProgramming() {
// Haz pair un http.Handler implementando su único método, ServeHTTP.
func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Servir datos con un método de http.ResponseWriter
+ // Servir datos con un método de http.ResponseWriter.
w.Write([]byte("You learned Go in Y minutes!"))
}
```
@@ -291,11 +317,12 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
La raíz de todas las cosas de Go es la [web oficial de Go](http://golang.org/).
Ahí puedes seguir el tutorial, jugar interactivamente y leer mucho.
-La propia definición del lenguaje también está altamente recomendada. Es fácil de leer
-e increíblemente corta (como otras definiciones de lenguajes hoy en día)
+La propia definición del lenguaje también está altamente
+recomendada. Es fácil de leer e increíblemente corta (como otras
+definiciones de lenguajes hoy en día)
-En la lista de lectura de estudiantes de Go está el código fuente de la
-librería estándar. Muy bien documentada, demuestra lo mejor de Go leíble, comprendible,
-estilo Go y formas Go. Pincha en el nombre de una función en la documentación
-y te aparecerá el código fuente!
+En la lista de lectura de estudiantes de Go está el código fuente de
+la librería estándar. Muy bien documentada, demuestra lo mejor de Go
+leíble, comprendible, estilo Go y formas Go. Pincha en el nombre de
+una función en la documentación y te aparecerá el código fuente!
diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown
index f1beae87..922fe416 100644
--- a/fa-ir/javascript.html.markdown
+++ b/fa-ir/javascript.html.markdown
@@ -4,7 +4,7 @@ contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
translators:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
-filename: javascript.js
+filename: javascript-fa.js
lang: fa-ir
---
diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown
index 9d0cec99..989db1d5 100644
--- a/fr-fr/haskell.html.markdown
+++ b/fr-fr/haskell.html.markdown
@@ -5,6 +5,7 @@ contributors:
translators:
- ["David Baumgartner", "http://davidbaumgartner.ch"]
lang: fr-fr
+filename: learnhaskell-fr.hs
---
Haskell a été conçu pour être un langage fonctionnel pur et maniable. Il est connu pour ses monades et son système de types, mais je n'ai cesse d'y revenir pour son élégance. Pour moi, Haskell fait de la programmation une joie.
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index b14b3a52..b98d161e 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -7,13 +7,14 @@ contributors:
- ["Levi Bostian", "https://github.com/levibostian"]
translators:
- ["Yannick Loriot", "https://github.com/YannickL"]
-filename: LearnObjectiveC.m
+filename: LearnObjectiveC-fr.m
+lang: fr-fr
---
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
-```objective-c
+```cpp
// Les commentaires sur une seule ligne commencent par //
/*
@@ -524,4 +525,4 @@ __unsafe_unretained NSArray *unsafeArray; // Comme __weak, mais la variable n'es
[iOS pour les écoliers : Votre première app iOS](http://www.raywenderlich.com/fr/39272/ios-pour-les-ecoliers-votre-premiere-app-ios-partie-12)
-[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) \ No newline at end of file
+[Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf)
diff --git a/go.html.markdown b/go.html.markdown
index ee41642a..d1a0ae34 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -5,6 +5,8 @@ language: Go
filename: learngo.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
+ - ["Christopher Bess", "https://github.com/cbess"]
+ - ["Jesse Johnson", "https://github.com/holocronweaver"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -29,9 +31,10 @@ package main
// Import declaration declares library packages referenced in this file.
import (
- "fmt" // A package in the Go standard library
+ "fmt" // A package in the Go standard library.
"net/http" // Yes, a web server!
- "strconv" // String conversions
+ "strconv" // String conversions.
+ m "math" // Math library with local alias m.
)
// A function definition. Main is special. It is the entry point for the
@@ -52,49 +55,49 @@ func beyondHello() {
x = 3 // Variable assignment.
// "Short" declarations use := to infer the type, declare, and assign.
y := 4
- sum, prod := learnMultiple(x, y) // function returns two values
- fmt.Println("sum:", sum, "prod:", prod) // simple output
+ sum, prod := learnMultiple(x, y) // Function returns two values.
+ fmt.Println("sum:", sum, "prod:", prod) // Simple output.
learnTypes() // < y minutes, learn more!
}
// Functions can have parameters and (multiple!) return values.
func learnMultiple(x, y int) (sum, prod int) {
- return x + y, x * y // return two values
+ return x + y, x * y // Return two values.
}
// Some built-in types and literals.
func learnTypes() {
// Short declaration usually gives you what you want.
- s := "Learn Go!" // string type
+ s := "Learn Go!" // string type.
s2 := `A "raw" string literal
-can include line breaks.` // same string type
+can include line breaks.` // Same string type.
- // non-ASCII literal. Go source is UTF-8.
- g := 'Σ' // rune type, an alias for uint32, holds a unicode code point
+ // Non-ASCII literal. Go source is UTF-8.
+ g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
- f := 3.14195 // float64, an IEEE-754 64-bit floating point number
- c := 3 + 4i // complex128, represented internally with two float64s
+ f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
+ c := 3 + 4i // complex128, represented internally with two float64's.
// Var syntax with an initializers.
- var u uint = 7 // unsigned, but implementation dependent size as with int
+ var u uint = 7 // Unsigned, but implementation dependent size as with int.
var pi float32 = 22. / 7
// Conversion syntax with a short declaration.
- n := byte('\n') // byte is an alias for uint8
+ n := byte('\n') // byte is an alias for uint8.
// 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
+ 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.
// 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
- 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
+ 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.
- p, q := learnMemory() // declares p, q to be type pointer to int.
+ p, q := learnMemory() // Declares p, q to be type pointer to int.
fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
// Maps are a dynamically growable associative array type, like the
@@ -108,23 +111,23 @@ can include line breaks.` // same string type
// Output of course counts as using a variable.
fmt.Println(s, c, a4, s3, d2, m)
- learnFlowControl() // back in the flow
+ learnFlowControl() // Back in the flow.
}
// 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.
- p = new(int) // built-in function new allocates memory.
+ p = new(int) // Built-in function new allocates memory.
// The allocated int is initialized to 0, p is no longer nil.
- s := make([]int, 20) // allocate 20 ints as a single block of memory
- s[3] = 7 // assign one of them
- r := -2 // declare another local variable
+ s := make([]int, 20) // Allocate 20 ints as a single block of memory.
+ s[3] = 7 // Assign one of them.
+ r := -2 // Declare another local variable.
return &s[3], &r // & takes the address of an object.
}
-func expensiveComputation() int {
- return 1e6
+func expensiveComputation() float64 {
+ return m.Exp(10)
}
func learnFlowControl() {
@@ -134,29 +137,31 @@ func learnFlowControl() {
}
// Formatting is standardized by the command line command "go fmt."
if false {
- // pout
+ // Pout.
} else {
- // gloat
+ // Gloat.
}
// Use switch in preference to chained if statements.
- x := 1
+ x := 42.0
switch x {
case 0:
case 1:
- // cases don't "fall through"
- case 2:
- // unreached
+ case 42:
+ // Cases don't "fall through".
+ case 43:
+ // Unreached.
}
// Like if, for doesn't use parens either.
- for x := 0; x < 3; x++ { // ++ is a statement
+ // Variables declared in for and if are local to their scope.
+ for x := 0; x < 3; x++ { // ++ is a statement.
fmt.Println("iteration", x)
}
- // x == 1 here.
+ // x == 42 here.
// For is the only loop statement in Go, but it has alternate forms.
- for { // infinite loop
- break // just kidding
- continue // unreached
+ for { // Infinite loop.
+ break // Just kidding.
+ continue // Unreached.
}
// As with for, := in an if statement means to declare and assign y first,
// then test y > x.
@@ -165,11 +170,11 @@ func learnFlowControl() {
}
// Function literals are closures.
xBig := func() bool {
- return x > 100 // references x declared above switch statement.
+ return x > 100 // References x declared above switch statement.
}
- fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x)
- x /= 1e5 // this makes it == 10
- fmt.Println("xBig:", xBig()) // false now
+ fmt.Println("xBig:", xBig()) // true (we last assigned 1e6 to x).
+ x /= m.Exp(9) // This makes x == e.
+ fmt.Println("xBig:", xBig()) // false now.
// When you need it, you'll love it.
goto love
@@ -199,16 +204,29 @@ func learnInterfaces() {
// 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
+ 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.
fmt.Println(i.String())
// Functions in the fmt package call the String method to ask an object
// for a printable representation of itself.
- fmt.Println(p) // output same as above. Println calls String method.
- fmt.Println(i) // output same as above
+ fmt.Println(p) // Output same as above. Println calls String method.
+ fmt.Println(i) // Output same as above.
+
+ learnVariadicParams("great", "learning", "here!")
+}
+
+// Functions can have variadic parameters.
+func learnVariadicParams(myStrings ...interface{}) {
+ // Iterate each value of the variadic.
+ for _, param := range myStrings {
+ fmt.Println("param:", param)
+ }
+
+ // Pass variadic value as a variadic parameter.
+ fmt.Println("params:", fmt.Sprintln(myStrings...))
learnErrorHandling()
}
@@ -223,7 +241,7 @@ func learnErrorHandling() {
}
// An error value communicates not just "ok" but more about the problem.
if _, err := strconv.Atoi("non-int"); err != nil { // _ discards value
- // prints "strconv.ParseInt: parsing "non-int": invalid syntax"
+ // prints 'strconv.ParseInt: parsing "non-int": invalid syntax'
fmt.Println(err)
}
// We'll revisit interfaces a little later. Meanwhile,
@@ -250,19 +268,19 @@ func learnConcurrency() {
// There is no telling in what order the results will arrive!
fmt.Println(<-c, <-c, <-c) // channel on right, <- is "receive" operator.
- cs := make(chan string) // another channel, this one handles strings.
- cc := make(chan chan string) // a channel of string channels.
- go func() { c <- 84 }() // start a new goroutine just to send a value
- go func() { cs <- "wordy" }() // again, for cs this time
+ cs := make(chan string) // Another channel, this one handles strings.
+ ccs := make(chan chan string) // A channel of string channels.
+ 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
// that are ready to communicate.
select {
- case i := <-c: // the value received can be assigned to a variable
+ case i := <-c: // The value received can be assigned to a variable,
fmt.Printf("it's a %T", i)
- case <-cs: // or the value received can be discarded
+ case <-cs: // or the value received can be discarded.
fmt.Println("it's a string")
- case <-cc: // empty channel, not ready for communication.
+ 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
@@ -273,7 +291,7 @@ func learnConcurrency() {
// A single function from package http starts a web server.
func learnWebProgramming() {
- // ListenAndServe first parameter is TCP address to listen at.
+ // 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
@@ -281,7 +299,7 @@ func learnWebProgramming() {
// 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
+ // Serve data with a method of http.ResponseWriter.
w.Write([]byte("You learned Go in Y minutes!"))
}
```
diff --git a/java.html.markdown b/java.html.markdown
index b4624d5e..1fbf6a21 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -191,7 +191,7 @@ public class LearnJava {
{
//System.out.println(fooWhile);
//Increment the counter
- //Iterated 99 times, fooWhile 0->99
+ //Iterated 100 times, fooWhile 0,1,2...99
fooWhile++;
}
System.out.println("fooWhile Value: " + fooWhile);
diff --git a/ko-kr/coffeescript-kr.html.markdown b/ko-kr/coffeescript-kr.html.markdown
index 7d00a0fe..f8ac8069 100644
--- a/ko-kr/coffeescript-kr.html.markdown
+++ b/ko-kr/coffeescript-kr.html.markdown
@@ -3,7 +3,7 @@ language: coffeescript
category: language
contributors:
- ["Tenor Biel", "http://github.com/L8D"]
-filename: coffeescript.coffee
+filename: coffeescript-kr.coffee
translators:
- ["wikibook", "http://wikibook.co.kr"]
lang: ko-kr
diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown
index 7404572c..e6ebe097 100644
--- a/ko-kr/go-kr.html.markdown
+++ b/ko-kr/go-kr.html.markdown
@@ -2,7 +2,7 @@
name: Go
category: language
language: Go
-filename: learngo.go
+filename: learngo-kr.go
contributors:
- ["Sonia Keys", "https://github.com/soniakeys"]
translators:
diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown
index e5517aa8..f651fbe7 100644
--- a/ko-kr/javascript-kr.html.markdown
+++ b/ko-kr/javascript-kr.html.markdown
@@ -5,6 +5,7 @@ contributors:
- ["Adam Brenecki", "http://adam.brenecki.id.au"]
translators:
- ["wikibook", "http://wikibook.co.kr"]
+filename: javascript-kr.js
lang: ko-kr
---
diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown
index 862c47a7..850587a0 100644
--- a/ko-kr/lua-kr.html.markdown
+++ b/ko-kr/lua-kr.html.markdown
@@ -6,6 +6,7 @@ contributors:
translators:
- ["wikibook", "http://wikibook.co.kr"]
lang: ko-kr
+filename: learnlua-kr.lua
---
```lua
diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown
index 2382a8fb..80f324f3 100644
--- a/ko-kr/php-kr.html.markdown
+++ b/ko-kr/php-kr.html.markdown
@@ -4,7 +4,7 @@ category: language
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
-filename: learnphp.php
+filename: learnphp-kr.php
translators:
- ["wikibook", "http://wikibook.co.kr"]
lang: ko-kr
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 453a42a5..0f0165ec 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -12,7 +12,7 @@ filename: LearnObjectiveC.m
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
-```objective-c
+```cpp
// Single-line comments start with //
/*
@@ -430,7 +430,8 @@ distance = 18; // References "long distance" from MyClass implementation
return @42;
}
-// To create a private method, create the method in the @implementation but not in the @interface
+// Objective-C does not have private method declarations, but you can simulate them.
+// To simulate a private method, create the method in the @implementation but not in the @interface.
- (NSNumber *)secretPrivateMethod {
return @72;
}
@@ -444,15 +445,218 @@ distance = 18; // References "long distance" from MyClass implementation
@end // States the end of the implementation
-/*
- * A protocol declares methods that can be implemented by any class.
- * Protocols are not classes themselves. They simply define an interface
- * that other objects are responsible for implementing.
- */
-@protocol MyProtocol
- - (void)myProtocolMethod;
+///////////////////////////////////////
+// Categories
+///////////////////////////////////////
+// A category is a group of methods designed to extend a class. They allow you to add new methods
+// to an existing class for organizational purposes. This is not to be mistaken with subclasses.
+// Subclasses are meant to CHANGE functionality of an object while categories instead ADD
+// functionality to an object.
+// Categories allow you to:
+// -- Add methods to an existing class for organizational purposes.
+// -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods.
+// -- Add ability to create protected and private methods to classes.
+// NOTE: Do not override methods of the base class in a category even though you have the ability
+// to. Overriding methods may cause compiler errors later between different categories and it
+// ruins the purpose of categories to only ADD functionality. Subclass instead to override methods.
+
+// Here is a simple Car base class.
+@interface Car : NSObject
+
+@property NSString *make;
+@property NSString *color;
+
+- (void)turnOn;
+- (void)accelerate;
+
+@end
+
+// And the simple Car base class implementation:
+#import "Car.h"
+
+@implementation Car
+
+@synthesize make = _make;
+@synthesize color = _color;
+
+- (void)turnOn {
+ NSLog(@"Car is on.");
+}
+- (void)accelerate {
+ NSLog(@"Accelerating.");
+}
+
+@end
+
+// Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would
+// be changing the functionality of the Car to behave like a truck. But lets say we want to just add
+// functionality to this existing Car. A good example would be to clean the car. So we would create
+// a category to add these cleaning methods:
+// @interface filename: Car+Clean.h (BaseClassName+CategoryName.h)
+#import "Car.h" // Make sure to import base class to extend.
+
+@interface Car (Clean) // The category name is inside () following the name of the base class.
+
+- (void)washWindows; // Names of the new methods we are adding to our Car object.
+- (void)wax;
+
@end
+// @implementation filename: Car+Clean.m (BaseClassName+CategoryName.m)
+#import "Car+Clean.h" // Import the Clean category's @interface file.
+
+@implementation Car (Clean)
+
+- (void)washWindows {
+ NSLog(@"Windows washed.");
+}
+- (void)wax {
+ NSLog(@"Waxed.");
+}
+
+@end
+
+// Any Car object instance has the ability to use a category. All they need to do is import it:
+#import "Car+Clean.h" // Import as many different categories as you want to use.
+#import "Car.h" // Also need to import base class to use it's original functionality.
+
+int main (int argc, const char * argv[]) {
+ @autoreleasepool {
+ Car *mustang = [[Car alloc] init];
+ mustang.color = @"Red";
+ mustang.make = @"Ford";
+
+ [mustang turnOn]; // Use methods from base Car class.
+ [mustang washWindows]; // Use methods from Car's Clean category.
+ }
+ return 0;
+}
+
+// Objective-C does not have protected method declarations but you can simulate them.
+// Create a category containing all of the protected methods, then import it ONLY into the
+// @implementation file of a class belonging to the Car class:
+@interface Car (Protected) // Naming category 'Protected' to remember methods are protected.
+
+- (void)lockCar; // Methods listed here may only be created by Car objects.
+
+@end
+//To use protected methods, import the category, then implement the methods:
+#import "Car+Protected.h" // Remember, import in the @implementation file only.
+
+@implementation Car
+
+- (void)lockCar {
+ NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface.
+}
+
+@end
+
+///////////////////////////////////////
+// Extensions
+///////////////////////////////////////
+// Extensions allow you to override public access property attributes and methods of an @interface.
+// @interface filename: Shape.h
+@interface Shape : NSObject // Base Shape class extension overrides below.
+
+@property (readonly) NSNumber *numOfSides;
+
+- (int)getNumOfSides;
+
+@end
+// You can override numOfSides variable or getNumOfSides method to edit them with an extension:
+// @implementation filename: Shape.m
+#import "Shape.h"
+// Extensions live in the same file as the class @implementation.
+@interface Shape () // () after base class name declares an extension.
+
+@property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly.
+-(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int.
+-(void)privateMethod; // You can also create new private methods inside of extensions.
+
+@end
+// The main @implementation:
+@implementation Shape
+
+@synthesize numOfSides = _numOfSides;
+
+-(NSNumber)getNumOfSides { // All statements inside of extension must be in the @implementation.
+ return _numOfSides;
+}
+-(void)privateMethod {
+ NSLog(@"Private method created by extension. Shape instances cannot call me.");
+}
+
+@end
+
+///////////////////////////////////////
+// Protocols
+///////////////////////////////////////
+// A protocol declares methods that can be implemented by any class.
+// Protocols are not classes themselves. They simply define an interface
+// that other objects are responsible for implementing.
+ // @protocol filename: "CarUtilities.h"
+@protocol CarUtilities <NSObject> // <NSObject> => Name of another protocol this protocol includes.
+ @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and
+ - (void)turnOnEngine; // all defined methods.
+@end
+// Below is an example class implementing the protocol.
+#import "CarUtilities.h" // Import the @protocol file.
+
+@interface Car : NSObject <CarUtilities> // Name of protocol goes inside <>
+ // You don't need the @property or method names here for CarUtilities. Only @implementation does.
+- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // You can use protocols as data too.
+@end
+// The @implementation needs to implement the @properties and methods for the protocol.
+@implementation Car : NSObject <CarUtilities>
+
+@synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property.
+
+- (void)turnOnEngine { // Implement turnOnEngine however you would like. Protocols do not define
+ _engineOn = YES; // how you implement a method, it just requires that you do implement it.
+}
+// You may use a protocol as data as you know what methods and variables it has implemented.
+- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind {
+ [objectOfSomeKind engineOn]; // You have access to object variables
+ [objectOfSomeKind turnOnEngine]; // and the methods inside.
+ [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants.
+}
+
+@end
+// Instances of Car now have access to the protocol.
+Car *carInstance = [[Car alloc] init];
+[[carInstance setEngineOn:NO];
+[carInstance turnOnEngine];
+if ([carInstance engineOn]) {
+ NSLog(@"Car engine is on."); // prints => "Car engine is on."
+}
+// Make sure to check if an object of type 'id' implements a protocol before calling protocol methods:
+if ([myClass conformsToProtocol:@protocol(CarUtilities)]) {
+ NSLog(@"This does not run as the MyClass class does not implement the CarUtilities protocol.");
+} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) {
+ NSLog(@"This does run as the Car class implements the CarUtilities protocol.");
+}
+// Categories may implement protocols as well: @interface Car (CarCategory) <CarUtilities>
+// You may implement many protocols: @interface Car : NSObject <CarUtilities, CarCleaning>
+// NOTE: If two or more protocols rely on each other, make sure to forward-declare them:
+#import "Brother.h"
+
+@protocol Brother; // Forward-declare statement. Without it, compiler would through error.
+
+@protocol Sister <NSObject>
+
+- (void)beNiceToBrother:(id <Brother>)brother;
+
+@end
+// See the problem is that Sister relies on Brother, and Brother relies on Sister.
+#import "Sister.h"
+
+@protocol Sister; // These lines stop the recursion, resolving the issue.
+
+@protocol Brother <NSObject>
+
+- (void)beNiceToSister:(id <Sister>)sister;
+
+@end
///////////////////////////////////////
// Memory Management
diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown
index e8d5a538..a884f273 100644
--- a/pt-br/java-pt.html.markdown
+++ b/pt-br/java-pt.html.markdown
@@ -8,7 +8,7 @@ translators:
- ["Victor Kléber Santos L. Melo", "http://victormelo.com.br/blog"]
- ["Renê Douglas N. de Morais", "mailto:rene.douglas.bsi@gmail.com"]
lang: pt-br
-filename: LearnJava.java
+filename: LearnJava-pt.java
---
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index a2f40c3b..4a8a1b5c 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -1,7 +1,7 @@
---
language: ruby
-lang: br-pt
-filename: learnruby.rb
+lang: pt-br
+filename: learnruby-pt.rb
contributors:
- ["Bruno Henrique - Garu", "http://garulab.com"]
translators:
diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown
index 874e0821..5988b159 100644
--- a/ru-ru/c-ru.html.markdown
+++ b/ru-ru/c-ru.html.markdown
@@ -1,6 +1,6 @@
---
language: c
-filename: learnc.c
+filename: learnc-ru.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
@@ -480,4 +480,4 @@ void str_reverse_through_pointer(char *str_in) {
Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья.
-[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member \ No newline at end of file
+[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown
index 51654cfe..c9213a42 100644
--- a/ru-ru/julia-ru.html.markdown
+++ b/ru-ru/julia-ru.html.markdown
@@ -4,7 +4,8 @@ contributors:
- ["Leah Hanson", "http://leahhanson.us"]
translators:
- ["Sergey Skovorodkin", "https://github.com/skovorodkin"]
-filename: learnjulia.jl
+filename: learnjulia-ru.jl
+lang: ru-ru
---
Julia — гомоиконный функциональный язык программирования для технических расчётов.
diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown
index ed8c43b6..19c5f25d 100644
--- a/zh-cn/r-cn.html.markdown
+++ b/zh-cn/r-cn.html.markdown
@@ -6,7 +6,7 @@ contributors:
translators:
- ["小柒", "http://weibo.com/u/2328126220"]
- ["alswl", "https://github.com/alswl"]
-filename: learnr.r
+filename: learnr-zh.r
lang: zh-cn
---
diff --git a/zh-cn/racket-cn.html.markdown b/zh-cn/racket-cn.html.markdown
index d43511ea..8ef3671f 100644
--- a/zh-cn/racket-cn.html.markdown
+++ b/zh-cn/racket-cn.html.markdown
@@ -2,7 +2,7 @@
language: racket
lang: zh-cn
-filename: learnracket.rkt
+filename: learnracket-zh.rkt
contributors:
- ["th3rac25", "https://github.com/voila"]
- ["Eli Barzilay", "https://github.com/elibarzilay"]
diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown
index 1ce41ac6..24f73bb5 100644
--- a/zh-cn/scala-cn.html.markdown
+++ b/zh-cn/scala-cn.html.markdown
@@ -6,7 +6,6 @@ contributors:
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
translators:
- ["Peiyong Lin", ""]
-filename: learn.scala
lang: zh-cn
---