summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown11
-rw-r--r--c.html.markdown887
-rw-r--r--csharp.html.markdown2
-rw-r--r--de-de/haskell-de.html.markdown425
-rw-r--r--es-es/json-es.html.markdown59
-rw-r--r--es-es/markdown-es.html.markdown252
-rw-r--r--fr-fr/csharp-fr.html.markdown2
-rw-r--r--fr-fr/scala.html.markdown458
-rw-r--r--git.html.markdown2
-rw-r--r--go.html.markdown441
-rw-r--r--ja-jp/bash-jp.html.markdown172
-rw-r--r--ja-jp/r-jp.html.markdown775
-rw-r--r--matlab.html.markdown3
-rw-r--r--pt-br/git-pt.html.markdown402
-rw-r--r--pt-br/json-pt.html.markdown62
-rw-r--r--python.html.markdown23
-rw-r--r--python3.html.markdown34
-rw-r--r--ruby-ecosystem.html.markdown67
-rw-r--r--rust.html.markdown265
-rw-r--r--scala.html.markdown2
-rw-r--r--swift.html.markdown11
-rw-r--r--whip.html.markdown4
22 files changed, 3671 insertions, 688 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index d5d08e9d..15d1c068 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -6,6 +6,7 @@ contributors:
- ["Darren Lin", "https://github.com/CogBear"]
- ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
- ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
filename: LearnBash.sh
---
@@ -155,14 +156,14 @@ bar ()
foo "My name is" $NAME
# There are a lot of useful commands you should learn:
-tail -n 10 file.txt
# prints last 10 lines of file.txt
-head -n 10 file.txt
+tail -n 10 file.txt
# prints first 10 lines of file.txt
-sort file.txt
+head -n 10 file.txt
# sort file.txt's lines
-uniq -d file.txt
+sort file.txt
# report or omit repeated lines, with -d it reports them
-cut -d ',' -f 1 file.txt
+uniq -d file.txt
# prints only the first column before the ',' character
+cut -d ',' -f 1 file.txt
```
diff --git a/c.html.markdown b/c.html.markdown
index c89f2b88..8e170300 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -16,16 +16,16 @@ memory management and C will take you as far as you need to go.
```c
// Single-line comments start with // - only available in C99 and later.
-/*
+ /*
Multi-line comments look like this. They work in C89 as well.
-*/
+ */
-// Constants: #define <keyword>
+ // Constants: #define <keyword>
#define DAYS_IN_YEAR 365
-//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.
+ // 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.
// Import headers with #include
#include <stdlib.h>
@@ -34,388 +34,386 @@ enum days {SUN = 1, MON, TUE, WED, THU, FRI, SAT};
// (File names between <angle brackets> are headers from the C standard library.)
// For your own headers, use double quotes instead of angle brackets:
-#include "my_header.h"
+//#include "my_header.h"
// Declare function signatures in advance in a .h file, or at the top of
// your .c file.
-void function_1(char c);
+void function_1();
int function_2(void);
// Must declare a 'function prototype' before main() when functions occur after
// your main() function.
-int add_two_ints(int x1, int x2); // function prototype
+int add_two_ints(int x1, int x2); // function prototype
// Your program's entry point is a function called
// main with an integer return type.
int main() {
- // print output using printf, for "print formatted"
- // %d is an integer, \n is a newline
- printf("%d\n", 0); // => Prints 0
- // All statements must end with a semicolon
-
- ///////////////////////////////////////
- // Types
- ///////////////////////////////////////
-
- // ints are usually 4 bytes
- int x_int = 0;
-
- // shorts are usually 2 bytes
- short x_short = 0;
-
- // chars are guaranteed to be 1 byte
- char x_char = 0;
- char y_char = 'y'; // Char literals are quoted with ''
-
- // longs are often 4 to 8 bytes; long longs are guaranteed to be at least
- // 64 bits
- long x_long = 0;
- long long x_long_long = 0;
-
- // floats are usually 32-bit floating point numbers
- float x_float = 0.0;
-
- // doubles are usually 64-bit floating-point numbers
- double x_double = 0.0;
-
- // Integral types may be unsigned.
- unsigned short ux_short;
- unsigned int ux_int;
- unsigned long long ux_long_long;
-
- // chars inside single quotes are integers in machine's character set.
- '0' // => 48 in the ASCII character set.
- 'A' // => 65 in the ASCII character set.
-
- // sizeof(T) gives you the size of a variable with type T in bytes
- // sizeof(obj) yields the size of the expression (variable, literal, etc.).
- printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
-
-
- // If the argument of the `sizeof` operator is an expression, then its argument
- // 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
- // the size of an object.
- size_t size = sizeof(a++); // a++ is not evaluated
- printf("sizeof(a++) = %zu where a = %d\n", size, a);
- // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
-
- // Arrays must be initialized with a concrete size.
- char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes
- int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
- // (assuming 4-byte words)
-
-
- // You can initialize an array to 0 thusly:
- char my_array[20] = {0};
-
- // Indexing an array is like other languages -- or,
- // rather, other languages are like C
- my_array[0]; // => 0
-
- // Arrays are mutable; it's just memory!
- my_array[1] = 2;
- printf("%d\n", my_array[1]); // => 2
-
- // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
- // can be declared as well. The size of such an array need not be a compile
- // time constant:
- printf("Enter the array size: "); // ask the user for an array size
- char buf[0x100];
- fgets(buf, sizeof buf, stdin);
-
- // strtoul parses a string to an unsigned integer
- size_t size = strtoul(buf, NULL, 10);
- int var_length_array[size]; // declare the VLA
- printf("sizeof array = %zu\n", sizeof var_length_array);
-
- // A possible outcome of this program may be:
- // > Enter the array size: 10
- // > sizeof array = 40
-
- // Strings are just arrays of chars terminated by a NUL (0x00) byte,
- // represented in strings as the special character '\0'.
- // (We don't have to include the NUL 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
-
- printf("%d\n", a_string[16]); // => 0
- // i.e., byte #17 is 0 (as are 18, 19, and 20)
-
- // If we have characters between single quotes, that's a character literal.
- // It's of type `int`, and *not* `char` (for historical reasons).
- int cha = 'a'; // fine
- char chb = 'a'; // fine too (implicit conversion from int to char)
-
- //Multi-dimensional arrays:
- int multi_array[2][5] = {
- {1, 2, 3, 4, 5},
- {6, 7, 8, 9, 0}
- };
- //access elements:
- int array_int = multi_array[0][2]; // => 3
-
- ///////////////////////////////////////
- // Operators
- ///////////////////////////////////////
-
- // Shorthands for multiple declarations:
- int i1 = 1, i2 = 2;
- float f1 = 1.0, f2 = 2.0;
-
- int a, b, c;
- a = b = c = 0;
-
- // Arithmetic is straightforward
- i1 + i2; // => 3
- i2 - i1; // => 1
- i2 * i1; // => 2
- i1 / i2; // => 0 (0.5, but truncated towards 0)
-
- f1 / f2; // => 0.5, plus or minus epsilon
- // Floating-point numbers and calculations are not exact
-
- // Modulo is there as well
- 11 % 3; // => 2
-
- // Comparison operators are probably familiar, but
- // 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.)
- 3 == 2; // => 0 (false)
- 3 != 2; // => 1 (true)
- 3 > 2; // => 1
- 3 < 2; // => 0
- 2 <= 2; // => 1
- 2 >= 2; // => 1
-
- // C is not Python - comparisons don't chain.
- int a = 1;
- // WRONG:
- int between_0_and_2 = 0 < a < 2;
- // Correct:
- int between_0_and_2 = 0 < a && a < 2;
-
- // Logic works on ints
- !3; // => 0 (Logical not)
- !0; // => 1
- 1 && 1; // => 1 (Logical and)
- 0 && 1; // => 0
- 0 || 1; // => 1 (Logical or)
- 0 || 0; // => 0
-
- //Conditional expression ( ? : )
- int a = 5;
- int b = 10;
- int z;
- z = (a > b) ? a : b; // => 10 "if a > b return a, else return b."
-
- //Increment and decrement operators:
- char *s = "iLoveC";
- int j = 0;
- s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
- j = 0;
- s[++j]; // => "L". Increments value of j THEN returns j-th value of s.
- // same with j-- and --j
-
- // Bitwise operators!
- ~0x0F; // => 0xF0 (bitwise negation, "1's complement")
- 0x0F & 0xF0; // => 0x00 (bitwise AND)
- 0x0F | 0xF0; // => 0xFF (bitwise OR)
- 0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
- 0x01 << 1; // => 0x02 (bitwise left shift (by 1))
- 0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
-
- // Be careful when shifting signed integers - the following are undefined:
- // - shifting into the sign bit of a signed integer (int a = 1 << 32)
- // - left-shifting a negative number (int a = -1 << 2)
- // - shifting by an offset which is >= the width of the type of the LHS:
- // int a = 1 << 32; // UB if int is 32 bits wide
-
- ///////////////////////////////////////
- // Control Structures
- ///////////////////////////////////////
-
- if (0) {
- printf("I am never run\n");
- } else if (0) {
- printf("I am also never run\n");
- } else {
- printf("I print\n");
- }
-
- // While loops exist
- int ii = 0;
- while (ii < 10) { //ANY value not zero is true.
- printf("%d, ", ii++); // ii++ increments ii AFTER using its current value.
- } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
- printf("\n");
-
- int kk = 0;
- do {
- printf("%d, ", kk);
- } while (++kk < 10); // ++kk increments kk BEFORE using its current value.
- // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
- printf("\n");
-
- // For loops too
- int jj;
- for (jj=0; jj < 10; jj++) {
- printf("%d, ", jj);
- } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
-
- printf("\n");
-
- // *****NOTES*****:
- // Loops and Functions MUST have a body. If no body is needed:
- int i;
- for (i = 0; i <= 5; i++) {
- ; // use semicolon to act as the body (null statement)
- }
-
- // branching with multiple choices: switch()
- switch (some_integral_expression) {
- case 0: // labels need to be integral *constant* epxressions
- do_stuff();
- break; // if you don't break, control flow falls over labels
- case 1:
- do_something_else();
- break;
- default:
- // if `some_integral_expression` didn't match any of the labels
- fputs("error!\n", stderr);
- exit(-1);
- break;
- }
-
-
- ///////////////////////////////////////
- // Typecasting
- ///////////////////////////////////////
-
- // Every value in C has a type, but you can cast one value into another type
- // if you want (with some constraints).
-
- int x_hex = 0x01; // You can assign vars with hex literals
-
- // Casting between types will attempt to preserve their numeric values
- printf("%d\n", x_hex); // => Prints 1
- printf("%d\n", (short) x_hex); // => Prints 1
- printf("%d\n", (char) x_hex); // => Prints 1
-
- // 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`,
- // 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.
- printf("%f\n", (float)100); // %f formats a float
- printf("%lf\n", (double)100); // %lf formats a double
- printf("%d\n", (char)100.0);
-
- ///////////////////////////////////////
- // Pointers
- ///////////////////////////////////////
-
- // A pointer is a variable declared to store a memory address. Its declaration will
- // also tell you the type of data it points to. You can retrieve the memory address
- // of your variables, then mess with them.
-
- int x = 0;
- printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable
- // (%p formats an object pointer of type void *)
- // => Prints some address in memory;
-
-
- // Pointers start with * in their declaration
- int *px, not_a_pointer; // px is a pointer to an int
- px = &x; // Stores the address of x in px
- printf("%p\n", (void *)px); // => Prints some address in memory
- printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
- // => 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.
- // 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
- // ++ has a higher precedence than *.
- (*px)++; // Increment the value px is pointing to by 1
- printf("%d\n", *px); // => Prints 1
- printf("%d\n", x); // => Prints 1
-
- // Arrays are a good way to allocate a contiguous block of memory
- int x_array[20]; //declares array of size 20 (cannot change size)
- int xx;
- for (xx = 0; xx < 20; xx++) {
- x_array[xx] = 20 - xx;
- } // Initialize x_array to 20, 19, 18,... 2, 1
+ // print output using printf, for "print formatted"
+ // %d is an integer, \n is a newline
+ printf("%d\n", 0); // => Prints 0
+ // All statements must end with a semicolon
+
+ ///////////////////////////////////////
+ // Types
+ ///////////////////////////////////////
+
+ // ints are usually 4 bytes
+ int x_int = 0;
+
+ // shorts are usually 2 bytes
+ short x_short = 0;
+
+ // chars are guaranteed to be 1 byte
+ char x_char = 0;
+ char y_char = 'y'; // Char literals are quoted with ''
+
+ // longs are often 4 to 8 bytes; long longs are guaranteed to be at least
+ // 64 bits
+ long x_long = 0;
+ long long x_long_long = 0;
+
+ // floats are usually 32-bit floating point numbers
+ float x_float = 0.0;
+
+ // doubles are usually 64-bit floating-point numbers
+ double x_double = 0.0;
+
+ // Integral types may be unsigned.
+ unsigned short ux_short;
+ unsigned int ux_int;
+ unsigned long long ux_long_long;
+
+ // chars inside single quotes are integers in machine's character set.
+ '0'; // => 48 in the ASCII character set.
+ 'A'; // => 65 in the ASCII character set.
+
+ // sizeof(T) gives you the size of a variable with type T in bytes
+ // sizeof(obj) yields the size of the expression (variable, literal, etc.).
+ printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words)
+
+
+ // If the argument of the `sizeof` operator is an expression, then its argument
+ // 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 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);
+ // prints "sizeof(a++) = 4 where a = 1" (on a 32-bit architecture)
+
+ // Arrays must be initialized with a concrete size.
+ char my_char_array[20]; // This array occupies 1 * 20 = 20 bytes
+ int my_int_array[20]; // This array occupies 4 * 20 = 80 bytes
+ // (assuming 4-byte words)
+
+
+ // You can initialize an array to 0 thusly:
+ char my_array[20] = {0};
+
+ // Indexing an array is like other languages -- or,
+ // rather, other languages are like C
+ my_array[0]; // => 0
+
+ // Arrays are mutable; it's just memory!
+ my_array[1] = 2;
+ printf("%d\n", my_array[1]); // => 2
+
+ // In C99 (and as an optional feature in C11), variable-length arrays (VLAs)
+ // can be declared as well. The size of such an array need not be a compile
+ // time constant:
+ printf("Enter the array size: "); // ask the user for an array size
+ char buf[0x100];
+ fgets(buf, sizeof buf, stdin);
+
+ // strtoul parses a string to an unsigned integer
+ size_t size2 = strtoul(buf, NULL, 10);
+ int var_length_array[size2]; // declare the VLA
+ printf("sizeof array = %zu\n", sizeof var_length_array);
+
+ // A possible outcome of this program may be:
+ // > Enter the array size: 10
+ // > sizeof array = 40
+
+ // 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 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
+
+ printf("%d\n", a_string[16]); // => 0
+ // i.e., byte #17 is 0 (as are 18, 19, and 20)
+
+ // If we have characters between single quotes, that's a character literal.
+ // It's of type `int`, and *not* `char` (for historical reasons).
+ int cha = 'a'; // fine
+ char chb = 'a'; // fine too (implicit conversion from int to char)
+
+ //Multi-dimensional arrays:
+ int multi_array[2][5] = {
+ {1, 2, 3, 4, 5},
+ {6, 7, 8, 9, 0}
+ };
+ //access elements:
+ int array_int = multi_array[0][2]; // => 3
+
+ ///////////////////////////////////////
+ // Operators
+ ///////////////////////////////////////
+
+ // Shorthands for multiple declarations:
+ int i1 = 1, i2 = 2;
+ float f1 = 1.0, f2 = 2.0;
+
+ int b, c;
+ b = c = 0;
+
+ // Arithmetic is straightforward
+ i1 + i2; // => 3
+ i2 - i1; // => 1
+ i2 * i1; // => 2
+ i1 / i2; // => 0 (0.5, but truncated towards 0)
+
+ f1 / f2; // => 0.5, plus or minus epsilon
+ // Floating-point numbers and calculations are not exact
+
+ // Modulo is there as well
+ 11 % 3; // => 2
+
+ // Comparison operators are probably familiar, but
+ // 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.)
+ 3 == 2; // => 0 (false)
+ 3 != 2; // => 1 (true)
+ 3 > 2; // => 1
+ 3 < 2; // => 0
+ 2 <= 2; // => 1
+ 2 >= 2; // => 1
+
+ // C is not Python - comparisons don't chain.
+ // WRONG:
+ //int between_0_and_2 = 0 < a < 2;
+ // Correct:
+ int between_0_and_2 = 0 < a && a < 2;
+
+ // Logic works on ints
+ !3; // => 0 (Logical not)
+ !0; // => 1
+ 1 && 1; // => 1 (Logical and)
+ 0 && 1; // => 0
+ 0 || 1; // => 1 (Logical or)
+ 0 || 0; // => 0
+
+ //Conditional expression ( ? : )
+ int e = 5;
+ int f = 10;
+ int z;
+ z = (a > b) ? a : b; // => 10 "if a > b return a, else return b."
+
+ //Increment and decrement operators:
+ char *s = "iLoveC";
+ int j = 0;
+ s[j++]; // => "i". Returns the j-th item of s THEN increments value of j.
+ j = 0;
+ s[++j]; // => "L". Increments value of j THEN returns j-th value of s.
+ // same with j-- and --j
+
+ // Bitwise operators!
+ ~0x0F; // => 0xF0 (bitwise negation, "1's complement")
+ 0x0F & 0xF0; // => 0x00 (bitwise AND)
+ 0x0F | 0xF0; // => 0xFF (bitwise OR)
+ 0x04 ^ 0x0F; // => 0x0B (bitwise XOR)
+ 0x01 << 1; // => 0x02 (bitwise left shift (by 1))
+ 0x02 >> 1; // => 0x01 (bitwise right shift (by 1))
+
+ // Be careful when shifting signed integers - the following are undefined:
+ // - shifting into the sign bit of a signed integer (int a = 1 << 32)
+ // - left-shifting a negative number (int a = -1 << 2)
+ // - shifting by an offset which is >= the width of the type of the LHS:
+ // int a = 1 << 32; // UB if int is 32 bits wide
+
+ ///////////////////////////////////////
+ // Control Structures
+ ///////////////////////////////////////
+
+ if (0) {
+ printf("I am never run\n");
+ } else if (0) {
+ printf("I am also never run\n");
+ } else {
+ printf("I print\n");
+ }
+
+ // While loops exist
+ int ii = 0;
+ while (ii < 10) { //ANY value not zero is true.
+ printf("%d, ", ii++); // ii++ increments ii AFTER using its current value.
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ int kk = 0;
+ do {
+ printf("%d, ", kk);
+ } while (++kk < 10); // ++kk increments kk BEFORE using its current value.
+ // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // For loops too
+ int jj;
+ for (jj=0; jj < 10; jj++) {
+ printf("%d, ", jj);
+ } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "
+
+ printf("\n");
+
+ // *****NOTES*****:
+ // Loops and Functions MUST have a body. If no body is needed:
+ int i;
+ for (i = 0; i <= 5; i++) {
+ ; // use semicolon to act as the body (null statement)
+ }
+
+ // branching with multiple choices: switch()
+ switch (a) {
+ case 0: // labels need to be integral *constant* expressions
+ printf("Hey, 'a' equals 0!\n");
+ break; // if you don't break, control flow falls over labels
+ case 1:
+ printf("Huh, 'a' equals 1!\n");
+ break;
+ default:
+ // if `some_integral_expression` didn't match any of the labels
+ fputs("error!\n", stderr);
+ exit(-1);
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Typecasting
+ ///////////////////////////////////////
+
+ // Every value in C has a type, but you can cast one value into another type
+ // if you want (with some constraints).
+
+ int x_hex = 0x01; // You can assign vars with hex literals
+
+ // Casting between types will attempt to preserve their numeric values
+ printf("%d\n", x_hex); // => Prints 1
+ printf("%d\n", (short) x_hex); // => Prints 1
+ printf("%d\n", (char) x_hex); // => Prints 1
+
+ // 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 `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.
+ printf("%f\n", (float)100); // %f formats a float
+ printf("%lf\n", (double)100); // %lf formats a double
+ printf("%d\n", (char)100.0);
+
+ ///////////////////////////////////////
+ // Pointers
+ ///////////////////////////////////////
+
+ // A pointer is a variable declared to store a memory address. Its declaration will
+ // also tell you the type of data it points to. You can retrieve the memory address
+ // of your variables, then mess with them.
+
+ int x = 0;
+ printf("%p\n", (void *)&x); // Use & to retrieve the address of a variable
+ // (%p formats an object pointer of type void *)
+ // => Prints some address in memory;
+
+
+ // Pointers start with * in their declaration
+ int *px, not_a_pointer; // px is a pointer to an int
+ px = &x; // Stores the address of x in px
+ printf("%p\n", (void *)px); // => Prints some address in memory
+ printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer));
+ // => 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 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 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
+ printf("%d\n", x); // => Prints 1
+
+ // Arrays are a good way to allocate a contiguous block of memory
+ int x_array[20]; //declares array of size 20 (cannot change size)
+ int xx;
+ for (xx = 0; xx < 20; xx++) {
+ x_array[xx] = 20 - xx;
+ } // Initialize x_array to 20, 19, 18,... 2, 1
// Declare a pointer of type int and initialize it to point to x_array
- int* x_ptr = x_array;
- // x_ptr now points to the first element in the array (the integer 20).
- // This works because arrays often decay into pointers to their first element.
- // For example, when an array is passed to a function or is assigned to a pointer,
- // it decays into (implicitly converted to) a pointer.
- // Exceptions: when the array is the argument of the `&` (address-of) operator:
- int arr[10];
- int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`!
- // It's of type "pointer to array" (of ten `int`s).
- // or when the array is a string literal used for initializing a char array:
- char arr[] = "foobarbazquirk";
- // or when it's the argument of the `sizeof` or `alignof` operator:
- int arr[10];
- int *ptr = arr; // equivalent with int *ptr = &arr[0];
- printf("%zu, %zu\n", sizeof arr, sizeof ptr); // probably prints "40, 4" or "40, 8"
-
-
- // Pointers are incremented and decremented based on their type
- // (this is called pointer arithmetic)
- printf("%d\n", *(x_ptr + 1)); // => Prints 19
- printf("%d\n", x_array[1]); // => Prints 19
-
- // You can also dynamically allocate contiguous blocks of memory with the
- // standard library function malloc, which takes one argument of type size_t
- // representing the number of bytes to allocate (usually from the heap, although this
- // may not be true on e.g. embedded systems - the C standard says nothing about it).
- int *my_ptr = malloc(sizeof(*my_ptr) * 20);
- for (xx = 0; xx < 20; xx++) {
- *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
- } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
+ int* x_ptr = x_array;
+ // x_ptr now points to the first element in the array (the integer 20).
+ // This works because arrays often decay into pointers to their first element.
+ // For example, when an array is passed to a function or is assigned to a pointer,
+ // it decays into (implicitly converted to) a pointer.
+ // Exceptions: when the array is the argument of the `&` (address-of) operator:
+ int arr[10];
+ int (*ptr_to_arr)[10] = &arr; // &arr is NOT of type `int *`!
+ // It's of type "pointer to array" (of ten `int`s).
+ // or when the array is a string literal used for initializing a char array:
+ char otherarr[] = "foobarbazquirk";
+ // or when it's the argument of the `sizeof` or `alignof` operator:
+ int arraythethird[10];
+ int *ptr = arraythethird; // equivalent with int *ptr = &arr[0];
+ printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); // probably prints "40, 4" or "40, 8"
+
+
+ // Pointers are incremented and decremented based on their type
+ // (this is called pointer arithmetic)
+ printf("%d\n", *(x_ptr + 1)); // => Prints 19
+ printf("%d\n", x_array[1]); // => Prints 19
+
+ // You can also dynamically allocate contiguous blocks of memory with the
+ // standard library function malloc, which takes one argument of type size_t
+ // representing the number of bytes to allocate (usually from the heap, although this
+ // may not be true on e.g. embedded systems - the C standard says nothing about it).
+ int *my_ptr = malloc(sizeof(*my_ptr) * 20);
+ for (xx = 0; xx < 20; xx++) {
+ *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx
+ } // Initialize memory to 20, 19, 18, 17... 2, 1 (as ints)
// Dereferencing memory that you haven't allocated gives
// "unpredictable results" - the program is said to invoke "undefined behavior"
- printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash.
-
- // When you're done with a malloc'd block of memory, you need to free it,
- // or else no one else can use it until your program terminates
- // (this is called a "memory leak"):
- free(my_ptr);
-
- // Strings are arrays of char, but they are usually represented as a
- // pointer-to-char (which is a pointer to the first element of the array).
- // It's good practice to use `const char *' when referring to a string literal,
- // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.)
- const char *my_str = "This is my very own string literal";
- printf("%c\n", *my_str); // => 'T'
-
- // This is not the case if the string is an array
- // (potentially initialized with a string literal)
- // that resides in writable memory, as in:
- char foo[] = "foo";
- foo[0] = 'a'; // this is legal, foo now contains "aoo"
-
- function_1();
+ printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? It may even crash.
+
+ // When you're done with a malloc'd block of memory, you need to free it,
+ // or else no one else can use it until your program terminates
+ // (this is called a "memory leak"):
+ free(my_ptr);
+
+ // Strings are arrays of char, but they are usually represented as a
+ // pointer-to-char (which is a pointer to the first element of the array).
+ // It's good practice to use `const char *' when referring to a string literal,
+ // since string literals shall not be modified (i.e. "foo"[0] = 'a' is ILLEGAL.)
+ const char *my_str = "This is my very own string literal";
+ printf("%c\n", *my_str); // => 'T'
+
+ // This is not the case if the string is an array
+ // (potentially initialized with a string literal)
+ // that resides in writable memory, as in:
+ char foo[] = "foo";
+ foo[0] = 'a'; // this is legal, foo now contains "aoo"
+
+ function_1();
} // end main function
///////////////////////////////////////
@@ -427,16 +425,16 @@ int main() {
int add_two_ints(int x1, int x2)
{
- return x1 + x2; // Use return to return a value
+ return x1 + x2; // Use return to return a value
}
/*
-Functions are call by value. When a function is called, the arguments passed to
-the function are copies of the original arguments (except arrays). Anything you
-do to the arguments in the function do not change the value of the original
-argument where the function was called.
+Functions are call by value. When a function is called, the arguments passed to
+≈the function are copies of the original arguments (except arrays). Anything you
+do to the arguments in the function do not change the value of the original
+argument where the function was called.
-Use pointers if you need to edit the original argument values.
+Use pointers if you need to edit the original argument values.
Example: in-place string reversal
*/
@@ -444,14 +442,14 @@ Example: in-place string reversal
// A void function returns no value
void str_reverse(char *str_in)
{
- char tmp;
- int ii = 0;
- size_t len = strlen(str_in); // `strlen()` is part of the c standard library
- for (ii = 0; ii < len / 2; ii++) {
- tmp = str_in[ii];
- str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
- str_in[len - ii - 1] = tmp;
- }
+ char tmp;
+ int ii = 0;
+ size_t len = strlen(str_in); // `strlen()` is part of the c standard library
+ for (ii = 0; ii < len / 2; ii++) {
+ tmp = str_in[ii];
+ str_in[ii] = str_in[len - ii - 1]; // ii-th char from end
+ str_in[len - ii - 1] = tmp;
+ }
}
/*
@@ -463,13 +461,13 @@ printf("%s\n", c); // => ".tset a si sihT"
//if referring to external variables outside function, must use extern keyword.
int i = 0;
void testFunc() {
- extern int i; //i here is now using external variable i
+ extern int i; //i here is now using external variable i
}
//make external variables private to source file with static:
-static int i = 0; //other files using testFunc() cannot access variable i
-void testFunc() {
- extern int i;
+static int j = 0; //other files using testFunc() cannot access variable i
+void testFunc2() {
+ extern int j;
}
//**You may also declare functions as static to make them private**
@@ -486,8 +484,8 @@ my_type my_type_var = 0;
// Structs are just collections of data, the members are allocated sequentially,
// in the order they are written:
struct rectangle {
- int width;
- int height;
+ int width;
+ int height;
};
// It's not generally true that
@@ -497,20 +495,20 @@ struct rectangle {
void function_1()
{
- struct rectangle my_rec;
+ struct rectangle my_rec;
- // Access struct members with .
- my_rec.width = 10;
- my_rec.height = 20;
+ // Access struct members with .
+ my_rec.width = 10;
+ my_rec.height = 20;
- // You can declare pointers to structs
- struct rectangle *my_rec_ptr = &my_rec;
+ // You can declare pointers to structs
+ struct rectangle *my_rec_ptr = &my_rec;
- // Use dereferencing to set struct pointer members...
- (*my_rec_ptr).width = 30;
+ // Use dereferencing to set struct pointer members...
+ (*my_rec_ptr).width = 30;
- // ... or even better: prefer the -> shorthand for the sake of readability
- my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10;
+ // ... or even better: prefer the -> shorthand for the sake of readability
+ my_rec_ptr->height = 10; // Same as (*my_rec_ptr).height = 10;
}
// You can apply a typedef to a struct for convenience
@@ -518,34 +516,34 @@ typedef struct rectangle rect;
int area(rect r)
{
- return r.width * r.height;
+ return r.width * r.height;
}
// if you have large structs, you can pass them "by pointer" to avoid copying
// the whole struct:
-int area(const rect *r)
+int areaptr(const rect *r)
{
- return r->width * r->height;
+ return r->width * r->height;
}
///////////////////////////////////////
-// Function pointers
+// Function pointers
///////////////////////////////////////
/*
-At runtime, 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
+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.
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; 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.
+ // 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 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.
}
/*
@@ -557,39 +555,40 @@ typedef void (*my_fnp_type)(char *);
// Then used when declaring the actual pointer variable:
// ...
-// my_fnp_type f;
+// my_fnp_type f;
//Special characters:
-'\a' // alert (bell) character
-'\n' // newline character
-'\t' // tab character (left justifies text)
-'\v' // vertical tab
-'\f' // new page (formfeed)
-'\r' // carriage return
-'\b' // backspace character
-'\0' // null character. Usually put at end of strings in C lang.
- // hello\n\0. \0 used by convention to mark end of string.
-'\\' // backslash
-'\?' // question mark
-'\'' // single quote
-'\"' // double quote
-'\xhh' // hexadecimal number. Example: '\xb' = vertical tab character
-'\ooo' // octal number. Example: '\013' = vertical tab character
+/*
+'\a'; // alert (bell) character
+'\n'; // newline character
+'\t'; // tab character (left justifies text)
+'\v'; // vertical tab
+'\f'; // new page (form feed)
+'\r'; // carriage return
+'\b'; // backspace character
+'\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
+'\''; // single quote
+'\"'; // double quote
+'\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character
+'\ooo'; // octal number. Example: '\013' = vertical tab character
//print formatting:
-"%d" // integer
-"%3d" // integer with minimum of length 3 digits (right justifies text)
-"%s" // string
-"%f" // float
-"%ld" // long
-"%3.2f" // minimum 3 digits left and 2 digits right decimal float
-"%7.4s" // (can do with strings too)
-"%c" // char
-"%p" // pointer
-"%x" // hexidecimal
-"%o" // octal
-"%%" // prints %
-
+"%d"; // integer
+"%3d"; // integer with minimum of length 3 digits (right justifies text)
+"%s"; // string
+"%f"; // float
+"%ld"; // long
+"%3.2f"; // minimum 3 digits left and 2 digits right decimal float
+"%7.4s"; // (can do with strings too)
+"%c"; // char
+"%p"; // pointer
+"%x"; // hexadecimal
+"%o"; // octal
+"%%"; // prints %
+*/
///////////////////////////////////////
// Order of Evaluation
///////////////////////////////////////
@@ -628,7 +627,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/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
new file mode 100644
index 00000000..df6267f9
--- /dev/null
+++ b/de-de/haskell-de.html.markdown
@@ -0,0 +1,425 @@
+---
+language: haskell
+lang: de-de
+contributors:
+ - ["Adit Bhargava", "http://adit.io"]
+translators:
+ - ["Henrik Jürges", "https://github.com/santifa"]
+filename: haskell-de.hs
+
+---
+
+Haskell wurde als praktische und funktionale Sprache entworfen.
+Es ist berühmt für das Schema der Monaden und des Typsystems, aber
+es sticht vor allem die Einfachheit und Eleganz hervor.
+
+```haskell
+-- Einfache Kommentare beginnen mit 2 Bindestriche.
+{- So wird ein Kommentar
+über mehrere Zeilen angelegt.
+-}
+
+----------------------------------------------------
+-- 1. Primitive Datentypen und Operatoren
+----------------------------------------------------
+
+-- Normale Zahlen.
+3 -- 3
+
+-- Einfache Rechenoperationen.
+1 + 1 -- 2
+8 - 1 -- 7
+10 * 2 -- 20
+35 / 5 -- 7.0
+
+-- Die Division ist per se auf Fließkommazahlen.
+35 / 4 -- 8.75
+
+-- Ganzzahlige Division
+35 `div` 4 -- 8
+
+-- Boolesche Werte sind Primitiven.
+True
+False
+
+-- Logik Operationen
+not True -- False
+not False -- True
+1 == 1 -- True
+1 /= 1 -- False
+1 < 10 -- True
+
+-- `not` ist eine Funktion die ein Argument entgegenimmt.
+-- Haskell benötigt keine Klammern um Argumente.
+-- Sie werden einfach aufgelistet: func arg1 arg2 arg3...
+-- Wie man Funktionen definiert kommt weiter unten.
+
+
+-- Strings und Zeichen
+"Das ist ein String."
+'a' -- Zeichen
+'Einfache Anfuehrungszeichen gehen nicht.' -- error!
+
+-- Strings können konkateniert werden.
+"Hello " ++ "world!" -- "Hello world!"
+
+-- Ein String ist eine Liste von Zeichen.
+"Das ist eine String" !! 0 -- 'D'
+
+
+----------------------------------------------------
+-- Listen und Tupel
+----------------------------------------------------
+
+-- Jedes Element einer Liste muss vom gleichen Typ sein.
+-- Zwei gleiche Listen
+[1, 2, 3, 4, 5]
+[1..5]
+
+-- Haskell unterstuetzt unendliche Listen!
+[1..] -- Die Liste aller natuerlichen Zahlen
+
+-- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation"
+-- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird.
+-- Somit kannst du nach dem 1000. Element fragen und Haskell gibt es dir:
+
+[1..] !! 999 -- 1000
+
+-- Haskell evaluiert nun die ersten 1 - 1000 Elemente, aber der Rest der Liste
+-- bleibt unangetastet. Haskell wird sie solange nicht weiterevalieren
+-- bis es muss.
+
+-- Zwei Listen konkatenieren
+[1..5] ++ [6..10]
+
+-- Ein Element als Head hinzufuegen
+0:[1..5] -- [0, 1, 2, 3, 4, 5]
+
+-- Gibt den 5. Index zurueck
+[0..] !! 5 -- 5
+
+-- Weitere Listenoperationen
+head [1..5] -- 1
+tail [1..5] -- [2, 3, 4, 5]
+init [1..5] -- [1, 2, 3, 4]
+last [1..5] -- 5
+
+-- list comprehensions | Listen erschaffen
+[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10]
+
+-- Mit Bedingungen
+[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10]
+
+-- Tupel haben eine feste Länge, jedes Element darf aber ein anderen Typ haben.
+-- Ein Tupel:
+("haskell", 1)
+
+-- Auf Elemente eines Tupels zugreifen:
+fst ("haskell", 1) -- "haskell"
+snd ("haskell", 1) -- 1
+
+----------------------------------------------------
+-- 3. Funktionen
+----------------------------------------------------
+-- Eine einfache Funktion die zwei Argumente hat.
+add a b = a + b
+
+-- Wenn man ghci (den Haskell Interpreter) benutzt, muss ein `let` davor.
+-- let add a b = a + b
+
+-- Eine Funktion aufrufen
+add 1 2 -- 3
+
+-- Man kann eine Funktion auch Infix verwenden,
+-- wenn man sie mit backticks umgibt
+1 `add` 2 -- 3
+
+-- So sieht die Definition eines eigenen Operators aus.
+-- Also einer Funktion deren Name aus Symbolen besteht.
+-- Die Integer Division:
+(//) a b = a `div` b
+35 // 4 -- 8
+
+-- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen.
+fib x
+ | x < 2 = x
+ | otherwise = fib (x - 1) + fib (x - 2)
+
+-- Pattern Matching funktioniert ähnlich.
+-- Hier sind drei Definitionen von fib. Haskell wird automatisch
+-- die erste Funktionen nehmen die dem Pattern der Eingabe entspricht.
+fib 1 = 1
+fib 2 = 2
+fib x = fib (x - 1) + fib (x - 2)
+
+-- Pattern matching auf Tupeln:
+foo (x, y) = (x + 1, y + 2)
+
+-- Pattern matching auf Listen.
+-- `x` ist das erste Element der Liste und `xs` der Rest der Liste.
+-- Damit können wir unsere eigene map Funktion bauen:
+myMap func [] = []
+myMap func (x:xs) = func x:(myMap func xs)
+
+-- Anonyme Funktionen (Lambda-Funktionen) werden mit einem
+-- Backslash eingeleitet, gefolgt von allen Argumenten.
+myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7]
+
+-- Fold (`inject` in einigen Sprachen)
+-- Foldl1 bedeutet: fold von links nach rechts und nehme den ersten
+-- Wert der Liste als Basiswert f[r den Akkumulator.
+foldl1 (\acc x -> acc + x) [1..5] -- 15
+
+----------------------------------------------------
+-- 4. Mehr Funktionen
+----------------------------------------------------
+
+-- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt,
+-- so wird sie eine neue Funktion gebildet ("curried").
+-- Es findet eine partielle Applikation statt und die neue Funktion
+-- nimmt die fehlenden Argumente auf.
+
+add a b = a + b
+foo = add 10 -- foo ist nun Funktion die ein Argument nimmt und 10 addiert
+foo 5 -- 15
+
+-- Ein alternativer Weg
+foo = (+10)
+foo 5 -- 15
+
+-- Funktionskomposition
+-- Die (.) Funktion verkettet Funktionen.
+-- Zum Beispiel, die Funktion Foo nimmt ein Argument addiert 10 dazu und
+-- multipliziert dieses Ergebnis mit 5.
+foo = (*5) . (+10)
+
+-- (5 + 10) * 5 = 75
+foo 5 -- 75
+
+
+-- Haskell hat eine Funktion `$`. Diese ändert den Vorrang,
+-- so dass alles links von ihr zuerst berechnet wird und
+-- und dann an die rechte Seite weitergegeben wird.
+-- Mit `.` und `$` kann man sich viele Klammern ersparen.
+
+-- Vorher
+(even (fib 7)) -- true
+
+-- Danach
+even . fib $ 7 -- true
+
+----------------------------------------------------
+-- 5. Typensystem
+----------------------------------------------------
+
+-- Haskell hat ein sehr starkes Typsystem.
+-- Alles hat einen Typ und eine Typsignatur.
+
+-- Einige grundlegende Typen:
+5 :: Integer
+"hello" :: String
+True :: Bool
+
+-- Funktionen haben genauso Typen.
+-- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt:
+-- not :: Bool -> Bool
+
+-- Eine Funktion die zwei Integer Argumente annimmt:
+-- add :: Integer -> Integer -> Integer
+
+-- Es ist guter Stil zu jeder Funktionsdefinition eine
+-- Typdefinition darueber zu schreiben:
+double :: Integer -> Integer
+double x = x * 2
+
+----------------------------------------------------
+-- 6. If-Anweisung und Kontrollstrukturen
+----------------------------------------------------
+
+-- If-Anweisung:
+haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
+
+-- If-Anweisungen können auch ueber mehrere Zeilen verteilt sein.
+-- Das Einruecken ist dabei äußerst wichtig.
+haskell = if 1 == 1
+ then "awesome"
+ else "awful"
+
+-- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen.
+case args of
+ "help" -> printHelp
+ "start" -> startProgram
+ _ -> putStrLn "bad args"
+
+-- Haskell nutzt Rekursion anstatt Schleifen.
+-- map wendet eine Funktion auf jedes Element einer Liste an.
+
+map (*2) [1..5] -- [2, 4, 6, 8, 10]
+
+-- So kann man auch eine for-Funktion kreieren.
+for array func = map func array
+
+-- und so benutzt man sie:
+for [0..5] $ \i -> show i
+
+-- wir hätten sie auch so benutzen können:
+for [0..5] show
+
+-- foldl oder foldr reduziren Listen auf einen Wert.
+-- foldl <fn> <initial value> <list>
+foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
+
+-- die Abarbeitung sieht so aus:
+(2 * (2 * (2 * 4 + 1) + 2) + 3)
+
+-- foldl ist linksseitig und foldr rechtsseitig.
+foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
+
+-- die Abarbeitung sieht so aus:
+(2 * 3 + (2 * 2 + (2 * 1 + 4)))
+
+----------------------------------------------------
+-- 7. Datentypen
+----------------------------------------------------
+
+-- So kann man seine eigenen Datentypen in Haskell anlegen:
+
+data Color = Red | Blue | Green
+
+-- Nun können wir sie in einer Funktion benutzen.
+
+say :: Color -> String
+say Red = "You are Red!"
+say Blue = "You are Blue!"
+say Green = "You are Green!"
+
+-- Datentypen können auch Parameter aufnehmen:
+
+data Maybe a = Nothing | Just a
+
+-- Diese sind alle vom Typ Maybe:
+Just "hello" -- vom Typ `Maybe String`
+Just 1 -- vom Typ `Maybe Int`
+Nothing -- vom Typ `Maybe a` fuer jedes `a`
+
+----------------------------------------------------
+-- 8. Haskell IO
+----------------------------------------------------
+
+-- IO kann nicht völlig erklärt werden ohne Monaden zu erklären,
+-- aber man kann die grundlegenden Dinge erklären.
+
+-- Wenn eine Haskell Programm ausgefuehrt wird, so wird `main` aufgerufen.
+-- Diese muss etwas vom Typ `IO ()` zurueckgeben. Zum Beispiel:
+
+main :: IO ()
+main = putStrLn $ "Hello, sky! " ++ (say Blue)
+-- putStrLn hat den Typ String -> IO ()
+
+-- Es ist am einfachsten, wenn man sein Programm als Funktion von
+-- String nach String implementiert.
+-- Zum Beispiel die Funktion interact :: (String -> String) -> IO ()
+-- nimmt einen Text, tut etwas damit und gibt diesen wieder aus.
+
+countLines :: String -> String
+countLines = show . length . lines
+
+main' = interact countLines
+
+-- Man kann den Typ `IO ()` als Repräsentation einer Sequenz von
+-- Aktionen sehen, die der Computer abarbeiten muss.
+-- Wie bei einem Programm das in einer Imperativen Sprache geschreiben wurde.
+-- Mit der `do` Notation können Aktionen verbunden werden.
+
+sayHello :: IO ()
+sayHello = do
+ putStrLn "What is your name?"
+ name <- getLine -- eine Zeile wird geholt und
+ -- an die Variable "name" gebunden
+ putStrLn $ "Hello, " ++ name
+
+-- Uebung: Schreibe deine eigene Version von `interact`,
+-- die nur eine Zeile einliest.
+
+-- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt.
+-- Um `sayHello` laufen zulassen kommentiere die Definition von `main`
+-- aus und ersetze sie mit:
+-- main = sayHello
+
+-- Lass uns untersuchen wie `getLine` arbeitet.
+-- Der Typ ist: getLine :: IO String
+-- Man kann sich vorstellen das der Wert vom Typ `IO a` ein
+-- Programm repräsentiert das etwas vom Typ `a` generiert.
+-- Der Wert wird mit `<-` gespeichert und kann wieder benutzt werden.
+-- Wir könne auch eigene Funktionen vom Typ `IO String` definieren:
+
+action :: IO String
+action = do
+ putStrLn "This is a line. Duh"
+ input1 <- getLine
+ input2 <- getLine
+ -- Der Typ von `do` ergibt sich aus der letzten Zeile.
+ -- `return` ist eine Funktion und keine Schluesselwort
+ return (input1 ++ "\n" ++ input2) -- return :: String -> IO String
+
+-- Nun können wir `action` wie `getLine` benutzen:
+
+main'' = do
+ putStrLn "I will echo two lines!"
+ result <- action
+ putStrLn result
+ putStrLn "This was all, folks!"
+
+-- Der Typ `IO` ist ein Beispiel fuer eine Monade.
+-- Haskell benutzt Monaden Seiteneffekte zu kapseln und somit
+-- eine rein funktional Sprache zu sein.
+-- Jede Funktion die mit der Außenwelt interagiert (z.B. IO)
+-- hat den Typ `IO` in seiner Signatur.
+-- Damit kann man zwischen "reinen" Funktionen (interagieren nicht
+-- mit der Außenwelt oder ändern ihren Zustand) und Anderen unterscheiden.
+
+-- Nebenläufigkeit ist in Haskell sehr einfach, da reine Funktionen
+-- leicht nebenläufig arbeiten können.
+
+----------------------------------------------------
+-- 9. Die Haskell REPL
+----------------------------------------------------
+
+-- Starte die REPL mit dem Befehl `ghci`
+-- Nun kann man Haskell Code eingeben.
+-- Alle neuen Werte muessen mit `let` gebunden werden:
+
+let foo = 5
+
+-- `:t` zeigt den Typen von jedem Wert an:
+
+>:t foo
+foo :: Integer
+
+-- Auch jede `IO ()` Funktion kann ausgefuehrt werden.
+
+> sayHello
+What is your name?
+Friend!
+Hello, Friend!
+
+```
+
+Es gibt noch viel mehr in Haskell, wie zum Beispiel Typklassen und Monaden.
+Dies sind die Ideen durch die Haskell Programmierung zum Spaß wird.
+Mit dem folgenden kleinen Beispiel werde ich euch verlassen:
+Quicksort in Haskell:
+
+```haskell
+qsort [] = []
+qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater
+ where lesser = filter (< p) xs
+ greater = filter (>= p) xs
+```
+
+Haskell ist sehr einfach zu installieren.
+Hohl es dir von [hier](http://www.haskell.org/platform/).
+
+Eine sehr viele langsamere Einfuehrung findest du unter:
+[Learn you a Haskell](http://learnyouahaskell.com/) oder
+[Real World Haskell](http://book.realworldhaskell.org/).
diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown
new file mode 100644
index 00000000..fff678eb
--- /dev/null
+++ b/es-es/json-es.html.markdown
@@ -0,0 +1,59 @@
+---
+language: json
+filename: learnjson-es.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Daniel Zendejas","https://github.com/DanielZendejas"]
+lang: es-es
+---
+
+Siendo JSON un formato de intercambio de infomación tan sencillo, probablemente este será el Learn X in Y más sencillo jamás.
+
+JSON en su forma más pura no tiene comentarios, pero la mayoría de los parseadores aceptarán comentarios de C (//, /\* \*/). De todas formas, para el propóstio de esto todo será JSON 100% válido. Por suerte, habla por sí mismo.
+
+```json
+
+{
+ "llave": "valor",
+
+ "llaves": "siempre debe estar entre comillas (ya sean dobles o simples)",
+ "numeros": 0,
+ "strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".",
+ "soporta booleanos?": true,
+ "vacios": null,
+
+ "numero grande": 1.2e+100,
+
+ "objetos": {
+ "comentario": "La mayoria de tu estructura vendra de objetos.",
+
+ "arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5],
+
+ "otro objeto": {
+ "comentario": "Estas cosas pueden estar anidadas, muy util."
+ }
+ },
+
+ "tonteria": [
+ {
+ "fuentes de potasio": ["bananas"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "estilo alternativo": {
+ "comentario": "Mira esto!"
+ , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido"
+ , "otro comentario": "que lindo"
+ },
+
+ "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer."
+}
+```
diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown
new file mode 100644
index 00000000..3865126c
--- /dev/null
+++ b/es-es/markdown-es.html.markdown
@@ -0,0 +1,252 @@
+---
+language: markdown
+filename: markdown-es.md
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Daniel Zendejas", "https://github.com/DanielZendejas"]
+lang: es-es
+---
+
+Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta
+fácilmente a HTML (y, actualmente, otros formatos también).
+
+¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
+
+
+```
+<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
+válido, eso significa que podemos usar elementos HTML en Markdown como, por
+ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún
+así si creas un elemento HTML en tu archivo Markdown no podrás usar sintaxis
+Markdown dentro de él. -->
+
+<!-- La implementación de Markdown cambia de acuerdo al parseador. Esta
+guía servirá para clarificar cuales características son universales y
+cuales son específicas de cada parseador-->
+
+<!-- Headers -->
+<!-- Puedes crear headers HTML fácilmente precediendo al texto con una serie
+de símbolos de números (#)-->
+
+# Esto es un <h1>
+## Esto es un <h2>
+### Esto es un <h3>
+#### Esto es un <h4>
+##### Esto es un <h5>
+###### Esto es un <h6>
+
+<!-- Markdown también nos proveé con dos alternativas para indicar h1 y h2 -->
+Esto es un h1
+=============
+
+Esto es un h2
+-------------
+
+<!-- Estilos para texto plano -->
+<!-- El texto puede ser fácilmente estilizaedo con italicas, negritas o tachado
+usando markdown -->
+
+*Este texto está en itálicas.*
+_Al igual que este texto._
+
+**Este texto está en negritas.**
+__Al igual que este texto.__
+
+***Este texto tiene ambos estilos.***
+**_Al igual que este!_**
+*__¡Y este!__*
+
+<!-- En Github Flavored Markdown, el cual es usado para mostrar archivos
+Markdown en Github, también tenemos: -->
+
+~~Este texto está tachado.~~
+
+<!-- Los párrafos son una o múltuples líneas de texto adyacentes separadas por
+una o múltiples líneas en blanco-->
+
+Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido?
+
+Ahora estoy en el párrafo dos.
+¡Sigo en el párrafo dos!
+
+¡Estoy en el párrafo tres!
+
+<!-- Si en algún momento quieres insertar un break HTML <br />, puedes terminar
+un párrafo con dos o más espacios y luego empieza un párrafo nuevo-->
+
+Termino con dos espacios (selecciona esta línea completa para que los veas).
+
+¡Hay un <br /> arriba de mí!
+
+<!-- Las citas de bloque son fáciles y se pueden hacer con el caracter >. -->
+
+> Esta es una cita de bloque. Puedes
+> envolver tus líneas manualmente y poner un `>` antes de cada línea o puedes dejar que tus líneas sean muy largas y que se envuelvan solas.
+> No hay diferencia, siempre y cuando empiecen con `>`.
+
+> ¿También puedes usar más de un nivel
+>> de indentación?
+> Esto es muy útil ¿No?
+
+<!-- Listas -->
+<!-- Las listas desordenadas se hacen usando asteriscos, símbolos de más,
+ o guiones -->
+
+* Item
+* Item
+* Otro item
+
+o
+
++ Item
++ Item
++ Un item más
+
+o
+
+- Item
+- Item
+- El último item
+
+<!-- Las listas ordenadas se logran con un número seguido de un punto -->
+
+1. Item uno
+2. Item dos
+3. Item tres
+
+<!-- Aunque Markdown mostrará los items correctamente en orden, esto no
+es una buena idea -->
+
+1. Item uno
+1. Item dos
+1. Item tres
+<!-- (Esto muestra lo mismo que el ejemplo de arriba) -->
+
+<!-- También puedes usar sub-listas -->
+
+1. Item uno
+2. Item dos
+3. Item tres
+ * Sub-item
+ * Sub-item
+4. Item cuatro
+
+<!-- Bloques de código -->
+<!-- Puedes indicar un bloque de código (usan los elementos <code>) indentando
+una línea con cuatro espacios o un tab-->
+
+ Esto es código
+ Esto también
+
+<!-- También puedes insertar dos tabs (o cuatro espacios adicionales)
+para indentar dentro del código -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Código dentro de la línea puede ser escrito usando la comilla ` -->
+
+¡John no sabía lo que la función `go_to()` hacía!
+
+<!-- Con Github Flavored Markdown, puedes usar una sintaxis especial para código -->
+
+\`\`\`ruby <!-- quita esas comillas cuando lo hagas, deja sólo ```ruby ! -->
+def foobar
+ puts "Hello world!"
+end
+\`\`\` <!-- aquí también, sin comillas, sólo ``` -->
+
+<!-- El texto de arriba no necesita indentación, aparte Github usará
+resaltará la sintaxis del lenguaje que especifiques después de ``` -->
+
+<!-- Regla horizontal (<hr />) -->
+<!-- Las reglas horizontales se agregan fácilmente con tres o más asteriscos o guiones,
+con o sin espacios. -->
+
+***
+---
+- - -
+****************
+
+<!-- Ligas -->
+<!-- Una de las mejores cosas de Markdown es la facilidad para hacer ligas. Pon
+el texto a mostrar en corchetes [] seguidos por la URL en paréntesis () -->
+
+[¡Haz click!](http://test.com/)
+
+<!-- También puedes agregar el titulo de la liga usando comillas dentro de los paréntesis -->
+
+[¡Haz click!](http://test.com/ "Liga al test.com")
+
+<!-- También funcionan las rutas relativas. -->
+
+[Ir a la música](/music/).
+
+<!-- Markdown también soporta ligas con estilo de referencia -->
+
+¡[Has click a esta liga][liga1] para más información!
+[También mira esta liag][foobar] si quieres.
+
+
+
+
+<!-- El título también puede estar en comillas simples o dentro de paréntesis,
+también se pueden omitir completamente. Las referencias pueden estar en cualquier
+lugar en tu documento y los IDs de referencia pueden ser lo que sea mientras sean únicos. -->
+
+<!-- También hay "nombramiento implicito" el cual te permite usar el texto de la liga como id -->
+
+[Esta][] es una liga.
+
+
+
+<!-- Pero no se usa comúnmente. -->
+
+<!-- Imagenes -->
+<!-- Las imagenes se hacen de la misma forma que las ligas pero con un símbolo de exclamaciónal frente! -->
+
+![Esta es una etiqueta (texto alternativo) para mi imagen](http://imgur.com/myimage.jpg "Un titulo opcional")
+
+<!-- Y el estilo de referencia funciona como se espera -->
+
+![Esta es una etiqueta.][myimage]
+
+
+
+<!-- Misceláneos -->
+<!-- Auto-ligas -->
+
+<http://testwebsite.com/> equivale a
+[http://testwebsite.com/](http://testwebsite.com/)
+
+<!-- Auto-ligas para correos electrónicos -->
+
+<foo@bar.com>
+
+<!-- Escapando caracteres -->
+
+Quiero escribir *este texto rodeado por asteriscos* pero no quiero que esté en itálicas,
+así que hago esto: \*Este texto está rodeado de asteriscos\*.
+
+<!-- Tablas -->
+<!-- Las tablas sólo están disponibles en Github Flavored Markdown y son un poco pesadas,
+pero si de verdad las quieres: -->
+
+| Col1 | Col2 | Col3 |
+| :----------- | :------: | ------------: |
+| Izquierda | Centrado | Derecha |
+| blah | blah | blah |
+
+<!-- o, para los mismos resultados -->
+
+Col 1 | Col2 | Col3
+:-- | :-: | --:
+Ugh esto es feo | has que | pare.
+
+<!-- ¡El fin! -->
+
+```
+
+Para más información, mira el post oficial de John Gruber's [aquí](http://daringfireball.net/projects/markdown/syntax) y la gran referencia de Adam Pritchard's [aquí](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown
index c1641716..e51eacc8 100644
--- a/fr-fr/csharp-fr.html.markdown
+++ b/fr-fr/csharp-fr.html.markdown
@@ -7,7 +7,7 @@ contributors:
- ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
translators:
- ["Olivier Hoarau", "https://github.com/Olwaro"]
-filename: LearnCSharp.cs
+filename: LearnCSharp-fr.cs
lang: fr-fr
---
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 bb6b04eb..a1be08af 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -9,6 +9,7 @@ contributors:
- ["Jesse Johnson", "https://github.com/holocronweaver"]
- ["Quint Guvernator", "https://github.com/qguv"]
- ["Jose Donizetti", "https://github.com/josedonizetti"]
+ - ["Alexej Friesen", "https://github.com/heyalexej"]
---
Go was created out of the need to get work done. It's not the latest trend
@@ -33,287 +34,339 @@ package main
// Import declaration declares library packages referenced in this file.
import (
- "fmt" // A package in the Go standard library.
- "net/http" // Yes, a web server!
- "strconv" // String conversions.
- m "math" // Math library with local alias m.
+ "fmt" // A package in the Go standard library.
+ "io/ioutil" // Implements some I/O utility functions.
+ m "math" // Math library with local alias m.
+ "net/http" // Yes, a web server!
+ "strconv" // String conversions.
)
// A function definition. Main is special. It is the entry point for the
// executable program. Love it or hate it, Go uses brace brackets.
func main() {
- // Println outputs a line to stdout.
- // Qualify it with the package name, fmt.
- fmt.Println("Hello world!")
+ // Println outputs a line to stdout.
+ // Qualify it with the package name, fmt.
+ fmt.Println("Hello world!")
- // Call another function within this package.
- beyondHello()
+ // Call another function within this package.
+ beyondHello()
}
// Functions have parameters in parentheses.
// If there are no parameters, empty parentheses are still required.
func beyondHello() {
- var x int // Variable declaration. Variables must be declared before use.
- 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.
- learnTypes() // < y minutes, learn more!
+ var x int // Variable declaration. Variables must be declared before use.
+ 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.
+ 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.
+ // Short declaration usually gives you what you want.
+ s := "Learn Go!" // string type.
- s2 := `A "raw" string literal
+ s2 := `A "raw" string literal
can include line breaks.` // Same string type.
- // Non-ASCII literal. Go source is UTF-8.
- g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
+ // Non-ASCII literal. Go source is UTF-8.
+ g := 'Σ' // rune type, an alias for 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 float64's.
+ 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 pi float32 = 22. / 7
+ // Var syntax with an initializers.
+ 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.
+ // Conversion syntax with a short declaration.
+ 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.
+ // 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.
- // 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.
+ // 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.
- p, q := learnMemory() // Declares p, q to be type pointer to int.
- fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
+ 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
- // hash or dictionary types of some other languages.
- m := map[string]int{"three": 3, "four": 4}
- m["one"] = 1
+ // Maps are a dynamically growable associative array type, like the
+ // hash or dictionary types of some other languages.
+ m := map[string]int{"three": 3, "four": 4}
+ m["one"] = 1
- // Unused variables are an error in Go.
- // The underbar lets you "use" a variable but discard its value.
- _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
- // Output of course counts as using a variable.
- fmt.Println(s, c, a4, s3, d2, m)
+ // Unused variables are an error in Go.
+ // The underbar lets you "use" a variable but discard its value.
+ _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
+ // 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.
+}
+
+// It is possible, unlike in many other languages for functions in go
+// to have named return values.
+// Assigning a name to the type being returned in the function declaration line
+// allows us to easily return from multiple points in a function as well as to
+// only use the return keyword, without anything further.
+func learnNamedReturns(x, y int) (z int) {
+ z = x * y
+ return // z is implicit here, because we named it earlier.
}
// 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.
- // 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.
- return &s[3], &r // & takes the address of an object.
+ // Named return values p and q have type pointer to int.
+ 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.
+ return &s[3], &r // & takes the address of an object.
}
func expensiveComputation() float64 {
- return m.Exp(10)
+ return m.Exp(10)
}
func learnFlowControl() {
- // If statements require brace brackets, and do not require parens.
- if true {
- fmt.Println("told ya")
- }
- // Formatting is standardized by the command line command "go fmt."
- if false {
- // Pout.
- } else {
- // Gloat.
- }
- // Use switch in preference to chained if statements.
- x := 42.0
- switch x {
- case 0:
- case 1:
- case 42:
- // Cases don't "fall through".
- case 43:
- // Unreached.
- }
- // Like if, for doesn't use parens either.
- // 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 == 42 here.
-
- // For is the only loop statement in Go, but it has alternate forms.
- 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.
- if y := expensiveComputation(); y > x {
- x = y
- }
- // Function literals are closures.
- xBig := func() bool {
- return x > 10000 // References x declared above switch statement.
- }
- fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x).
- x = 1.3e3 // This makes x == 1300
- fmt.Println("xBig:", xBig()) // false now.
-
- // When you need it, you'll love it.
- goto love
+ // If statements require brace brackets, and do not require parens.
+ if true {
+ fmt.Println("told ya")
+ }
+ // Formatting is standardized by the command line command "go fmt."
+ if false {
+ // Pout.
+ } else {
+ // Gloat.
+ }
+ // Use switch in preference to chained if statements.
+ x := 42.0
+ switch x {
+ case 0:
+ case 1:
+ case 42:
+ // Cases don't "fall through".
+ case 43:
+ // Unreached.
+ }
+ // Like if, for doesn't use parens either.
+ // 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 == 42 here.
+
+ // For is the only loop statement in Go, but it has alternate forms.
+ 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.
+ if y := expensiveComputation(); y > x {
+ x = y
+ }
+ // Function literals are closures.
+ xBig := func() bool {
+ return x > 10000 // References x declared above switch statement.
+ }
+ fmt.Println("xBig:", xBig()) // true (we last assigned e^10 to x).
+ x = 1.3e3 // This makes x == 1300
+ fmt.Println("xBig:", xBig()) // false now.
+
+ // What's more is function literals may be defined and called inline,
+ // acting as an argument to function, as long as:
+ // a) function literal is called immediately (),
+ // b) result type matches expected type of argument.
+ fmt.Println("Add + double two numbers: ",
+ func(a, b int) int {
+ return (a + b) * 2
+ }(10, 2)) // Called with args 10 and 2
+ // => Add + double two numbers: 24
+
+ // When you need it, you'll love it.
+ goto love
love:
- learnDefer() // A quick detour to an important keyword.
- learnInterfaces() // Good stuff coming up!
+ 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 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
+ }
}
func learnDefer() (ok bool) {
- // Deferred statements are executed just before the function returns.
- defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
- defer fmt.Println("\nThis line is being printed first because")
- // Defer is commonly used to close a file, so the function closing the file
- // stays close to the function opening the file
- return true
+ // Deferred statements are executed just before the function returns.
+ defer fmt.Println("deferred statements execute in reverse (LIFO) order.")
+ defer fmt.Println("\nThis line is being printed first because")
+ // Defer is commonly used to close a file, so the function closing the
+ // file stays close to the function opening the file.
+ return true
}
// Define Stringer as an interface type with one method, String.
type Stringer interface {
- String() string
+ String() string
}
// Define pair as a struct with two fields, ints named x and y.
type pair struct {
- x, y int
+ x, y int
}
// Define a method on type pair. Pair now implements Stringer.
func (p pair) String() string { // p is called the "receiver"
- // Sprintf is another public function in package fmt.
- // Dot syntax references fields of p.
- return fmt.Sprintf("(%d, %d)", p.x, p.y)
+ // Sprintf is another public function in package fmt.
+ // Dot syntax references fields of p.
+ return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
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
- // 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.
-
- learnVariadicParams("great", "learning", "here!")
+ // Brace syntax is a "struct literal." It evaluates to an initialized
+ // struct. The := syntax declares and initializes p to this struct.
+ p := pair{3, 4}
+ fmt.Println(p.String()) // Call String method of p, of type pair.
+ var i Stringer // Declare i of interface type Stringer.
+ i = p // Valid because pair implements Stringer
+ // Call String method of i, of type Stringer. Output same as above.
+ 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.
+
+ learnVariadicParams("great", "learning", "here!")
}
// Functions can have variadic parameters.
func learnVariadicParams(myStrings ...interface{}) {
- // Iterate each value of the variadic.
- // The underbar here is ignoring the index argument of the array.
- for _, param := range myStrings {
- fmt.Println("param:", param)
- }
+ // Iterate each value of the variadic.
+ // The underbar here is ignoring the index argument of the array.
+ for _, param := range myStrings {
+ fmt.Println("param:", param)
+ }
- // Pass variadic value as a variadic parameter.
- fmt.Println("params:", fmt.Sprintln(myStrings...))
+ // Pass variadic value as a variadic parameter.
+ fmt.Println("params:", fmt.Sprintln(myStrings...))
- learnErrorHandling()
+ learnErrorHandling()
}
func learnErrorHandling() {
- // ", ok" idiom used to tell if something worked or not.
- m := map[int]string{3: "three", 4: "four"}
- if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
- fmt.Println("no one there")
- } else {
- fmt.Print(x) // x would be the value, if it were in the map.
- }
- // 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'
- fmt.Println(err)
- }
- // We'll revisit interfaces a little later. Meanwhile,
- learnConcurrency()
+ // ", ok" idiom used to tell if something worked or not.
+ m := map[int]string{3: "three", 4: "four"}
+ if x, ok := m[1]; !ok { // ok will be false because 1 is not in the map.
+ fmt.Println("no one there")
+ } else {
+ fmt.Print(x) // x would be the value, if it were in the map.
+ }
+ // 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'
+ fmt.Println(err)
+ }
+ // We'll revisit interfaces a little later. Meanwhile,
+ learnConcurrency()
}
// c is a channel, a concurrency-safe communication object.
func inc(i int, c chan int) {
- c <- i + 1 // <- is the "send" operator when a channel appears on the left.
+ c <- i + 1 // <- is the "send" operator when a channel appears on the left.
}
// We'll use inc to increment some numbers concurrently.
func learnConcurrency() {
- // Same make function used earlier to make a slice. Make allocates and
- // initializes slices, maps, and channels.
- c := make(chan int)
- // Start three concurrent goroutines. Numbers will be incremented
- // concurrently, perhaps in parallel if the machine is capable and
- // properly configured. All three send to the same channel.
- go inc(0, c) // go is a statement that starts a new goroutine.
- go inc(10, c)
- go inc(-805, c)
- // Read three results from the channel and print them out.
- // 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.
- 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,
- fmt.Printf("it's a %T", i)
- case <-cs: // or the value received can be discarded.
- fmt.Println("it's a string")
- 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
- // goroutines started above has completed, the other will remain blocked.
-
- learnWebProgramming() // Go does it. You want to do it too.
+ // Same make function used earlier to make a slice. Make allocates and
+ // initializes slices, maps, and channels.
+ c := make(chan int)
+ // Start three concurrent goroutines. Numbers will be incremented
+ // concurrently, perhaps in parallel if the machine is capable and
+ // properly configured. All three send to the same channel.
+ go inc(0, c) // go is a statement that starts a new goroutine.
+ go inc(10, c)
+ go inc(-805, c)
+ // Read three results from the channel and print them out.
+ // 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.
+ 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,
+ fmt.Printf("it's a %T", i)
+ case <-cs: // or the value received can be discarded.
+ fmt.Println("it's a string")
+ 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
+ // goroutines started above has completed, the other will remain blocked.
+
+ learnWebProgramming() // Go does it. You want to do it too.
}
// 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
+
+ // First parameter of ListenAndServe is TCP address to listen to.
+ // Second parameter is an interface, specifically http.Handler.
+ 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!"))
+ // 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))
}
```
diff --git a/ja-jp/bash-jp.html.markdown b/ja-jp/bash-jp.html.markdown
new file mode 100644
index 00000000..88e5ff1c
--- /dev/null
+++ b/ja-jp/bash-jp.html.markdown
@@ -0,0 +1,172 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+translators:
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+filename: LearnBash-jp.sh
+lang: ja-jp
+---
+
+Bash はunixシェルの1つです。GNUオペレーションシステムのシェルとして配布されています。
+LinuxやMac OS Xの、デフォルトシェルにもなっています。
+以下にある例は、ほぼ全部シェルスクリプトの一部として使えます。また、一部はそのままシェルから実行できます。
+
+[ちゃんとした説明は、こちらをどうぞ](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+# 最初の行はShebang(シェバング、シバン)というもので、システムに対して何を使って実行するのかを教えるためのものです
+# ちゃんとした説明、こちらをどうぞ: http://en.wikipedia.org/wiki/Shebang_(Unix)
+# 既にお気づきのように、コメント行は#で始まります. Shebangもコメントです
+
+# まずは Hello world です
+echo Hello world!
+
+# コマンド毎に改行を入れるか、セミコロンで区切ります
+echo 'This is the first line'; echo 'This is the second line'
+
+# 変数の宣言はこのようにやります
+VARIABLE="Some string"
+
+# が、以下のようにやってはダメです
+VARIABLE = "Some string"
+# このように(空白を入れて)書くと、Bash はVARIABLEを実行するべきコマンドとみなし、実行します。
+# そして、VARIABLEというコマンドはない(はずな)ので、エラーになります
+
+
+# 変数の使い方
+echo $VARIABLE
+echo "$VARIABLE"
+echo '$VARIABLE'
+# 変数の値(中身)を使わず、変数名だけを使うとき(代入するときや渡すときなど)は、$なしで変数名を書いてください
+# 変数の値(中身)を使うときは、$をつけます
+# 上記例の最後にある、' (シングルクォート) で囲んだ場合は、変数の値は表示されません!
+
+# 変数値の文字列置換
+echo ${VARIABLE/Some/A}
+# 最初に出てくる "Some" を "A" で置換します
+
+# 変数値の一部を取り出します
+echo ${VARIABLE:0:7}
+# 最初の7文字だけを取り出します
+
+# デフォルトの変数値設定(訳注:シェル実行時に引数で変数値を設定できるが、設定しなかった場合の値を指定できる)
+echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"}
+# 上記は、FOO番目の引数がnullだったとき(FOO番目=)や、空文字が指定されたとき(FOO番目="")に、変数に0を入れます
+# ( 当然ですが、引数に0を指定したとき(FOO番目=0) も、0は入ります)
+
+# 組込み変数
+# 以下のような便利な組込み変数があります
+echo "Last program return value: $?"
+echo "Script's PID: $$"
+echo "Number of arguments: $#"
+echo "Scripts arguments: $@"
+echo "Scripts arguments seperated in different variables: $1 $2..."
+
+# 入力値の読み込み
+echo "What's your name?"
+read NAME # 新しく変数を宣言する必要はないことに注意
+echo Hello, $NAME!
+
+# 普通のif文も使えます
+# 利用できる判定条件については、'man test' で参照してください
+if [ $NAME -ne $USER ]
+then
+ echo "Your name is your username"
+else
+ echo "Your name isn't your username"
+fi
+
+# 他にも、条件判定ができます
+echo "Always executed" || echo "Only executed if first command fails"
+echo "Always executed" && echo "Only executed if first command does NOT fail"
+
+# 数式は以下のように書きます
+echo $(( 10 + 5 ))
+
+# 他のプログラム言語とは違ってbashはシェルなので、現在いるディレクトリ位置が異なると、異なる結果になります
+# lsコマンドで、現在いるディレクトリにあるファイルと、ディレクトリのリストが取得できます
+ls
+
+# これらのコマンドには、実行オプションがいろいろあります
+ls -l # ファイルとディレクトリのリストを行に分けて表示します
+
+# あるコマンド実行による返値を、次のコマンドの入力値としてつかえます
+# 例えばですが、lsコマンドの返値を、grepコマンドによって指定したルールに基づいてフィルタできます。
+# 以下は、現在いるディレクトリにある、.txtファイルのリストを表示する例です
+ls -l | grep "\.txt"
+
+# コマンドに対する入力元や出力先、またエラー出力先などを変更できます
+python2 hello.py < "input.in"
+python2 hello.py > "output.out"
+python2 hello.py 2> "error.err"
+# 出力先として指定したファイルが既に存在する場合は、上書きされます
+# もしもファイルに追記したい場合は、代わりに">>" を使ってください
+
+# コマンド文中で、$()内に別コマンドを入れると、その別コマンドの返値をコマンド文の一部として使う事ができます
+# 次のコマンドは、現在いるディレクトリにあるファイルの数を表示します
+echo "There are $(ls | wc -l) items here."
+
+# バッククォート(backticks) `` でも同じことができますが、入れ子にはできません
+# そのため、$()がお勧めです
+echo "There are `ls | wc -l` items here."
+
+# BashはJavaやC++のように、case文による分岐ができます
+case "$VARIABLE" in
+ #分岐条件として使いたいパターンを並べてください
+ 0) echo "There is a zero.";;
+ 1) echo "There is a one.";;
+ *) echo "It is not null.";;
+esac
+
+# 指定した回数、処理を繰り返し
+# 変数の値 $VARIABLE が3回表示されます
+for VARIABLE in {1..3}
+do
+ echo "$VARIABLE"
+done
+
+# while ループです
+while [true]
+do
+ echo "loop body here..."
+ break
+done
+
+# 関数の定義もできます
+function foo ()
+{
+ echo "Arguments work just like script arguments: $@"
+ echo "And: $1 $2..."
+ echo "This is a function"
+ return 0
+}
+
+# 以下のように、もっと簡単な書き方もあります
+bar ()
+{
+ echo "Another way to declare functions!"
+ return 0
+}
+
+# 自作関数を呼びます
+foo "My name is" $NAME
+
+# 他にもいろいろと、知っておくと便利なコマンドがあります
+# file.txtの最後10行を表示します
+tail -n 10 file.txt
+# file.txtの最初10行を表示します
+head -n 10 file.txt
+# file.txt's の行を並び替えます
+sort file.txt
+# 重複している行を表示するか、削除できます。-dオプションをつけると、表示します
+uniq -d file.txt
+# 1行ごとに、','が最初に出てくる前の部分を表示します
+cut -d ',' -f 1 file.txt
+
+```
diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown
new file mode 100644
index 00000000..3e6621f5
--- /dev/null
+++ b/ja-jp/r-jp.html.markdown
@@ -0,0 +1,775 @@
+---
+language: R
+contributors:
+ - ["e99n09", "http://github.com/e99n09"]
+ - ["isomorphismes", "http://twitter.com/isomorphisms"]
+translators:
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+filename: learnr-jp.r
+lang: ja-jp
+---
+
+
+R は統計計算用の言語です。
+データの取得やクリーニング、統計処理やグラフ作成をするために便利な、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます
+
+
+```python
+# コメント行は、#で開始します
+
+
+# 複数行をまとめてコメントにすることはできないので、
+# コメントを複数の行に分けたい場合、このように、単に毎行をコメントにしてください
+
+
+# WindowsやMacでは、 COMMAND-ENTERで、コマンドを1行実行できます
+
+
+
+
+
+
+#############################################################################
+# プログラミングがわからなくとも使えるコマンド類
+#############################################################################
+
+
+# この節では、プログラミングがわからなくとも使える便利なRコマンドを紹介します
+# 全てを理解できなくとも、まずはやってみましょう!
+
+
+data() # 既にロードされているデータを閲覧します
+data(rivers) # "北米にある大きな川の長さ"データを取得します
+ls() # "rivers" がワークスペースに表示されました
+head(rivers) # データの先頭部分です
+# 735 320 325 392 524 450
+
+
+length(rivers) # 何本の川がデータにある?
+# 141
+summary(rivers) # 統計的に要約するとどうなる?
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 135.0 310.0 425.0 591.2 680.0 3710.0
+
+
+# 茎葉図(ヒストグラムに似た図)を描く
+stem(rivers)
+
+
+# The decimal point is 2 digit(s) to the right of the |
+#
+# 0 | 4
+# 2 | 011223334555566667778888899900001111223333344455555666688888999
+# 4 | 111222333445566779001233344567
+# 6 | 000112233578012234468
+# 8 | 045790018
+# 10 | 04507
+# 12 | 1471
+# 14 | 56
+# 16 | 7
+# 18 | 9
+# 20 |
+# 22 | 25
+# 24 | 3
+# 26 |
+# 28 |
+# 30 |
+# 32 |
+# 34 |
+# 36 | 1
+
+
+stem(log(rivers)) # このデータは、正規分布でも対数正規分布でもないので、注意!
+# 特に正規分布原理主義のみなさん
+
+
+# The decimal point is 1 digit(s) to the left of the |
+#
+# 48 | 1
+# 50 |
+# 52 | 15578
+# 54 | 44571222466689
+# 56 | 023334677000124455789
+# 58 | 00122366666999933445777
+# 60 | 122445567800133459
+# 62 | 112666799035
+# 64 | 00011334581257889
+# 66 | 003683579
+# 68 | 0019156
+# 70 | 079357
+# 72 | 89
+# 74 | 84
+# 76 | 56
+# 78 | 4
+# 80 |
+# 82 | 2
+
+
+# ヒストグラム作成
+hist(rivers, col="#333333", border="white", breaks=25) # これらのパラメータをつかいます
+hist(log(rivers), col="#333333", border="white", breaks=25) # いろいろな使い方ができます
+
+
+# 別のロード済データでやってみましょう。Rには、いろいろなデータがロードされています。
+data(discoveries)
+plot(discoveries, col="#333333", lwd=3, xlab="Year",
+ main="Number of important discoveries per year")
+plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year",
+ main="Number of important discoveries per year")
+
+
+# 年次のソートだけではなく、
+# 標準的な並べ替えもできます
+sort(discoveries)
+# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
+# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3
+# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4
+# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12
+
+
+stem(discoveries, scale=2)
+#
+# The decimal point is at the |
+#
+# 0 | 000000000
+# 1 | 000000000000
+# 2 | 00000000000000000000000000
+# 3 | 00000000000000000000
+# 4 | 000000000000
+# 5 | 0000000
+# 6 | 000000
+# 7 | 0000
+# 8 | 0
+# 9 | 0
+# 10 | 0
+# 11 |
+# 12 | 0
+
+
+max(discoveries)
+# 12
+summary(discoveries)
+# Min. 1st Qu. Median Mean 3rd Qu. Max.
+# 0.0 2.0 3.0 3.1 4.0 12.0
+
+
+# サイコロを振ります
+round(runif(7, min=.5, max=6.5))
+# 1 4 6 1 4 6 4
+# 私と同じrandom.seed(31337)を使わない限りは、別の値になります
+
+
+# ガウス分布を9回生成します
+rnorm(9)
+# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271
+# [7] -0.59975593 0.57629164 1.08455362
+
+
+
+
+
+
+##################################################
+# データ型と基本計算
+##################################################
+
+
+# ここからは、プログラミングをつかうチュートリアルです
+# この節ではRで重要なデータ型(データクラス)の、整数型、数字型、文字型、論理型と因子(ファクター)型をつかいます
+# 他にもいろいろありますが、これらの必要最小限なものから始めましょう
+
+
+# 整数型
+# 整数型はLで指定します
+5L # 5
+class(5L) # "integer"
+# (?class を実行すると、class()関数について、さらなる情報が得られます)
+# Rでは、この5Lのような1つの値は、長さ1のベクトルとして扱われます
+length(5L) # 1
+# 整数型のベクトルはこのようにつくります
+c(4L, 5L, 8L, 3L) # 4 5 8 3
+length(c(4L, 5L, 8L, 3L)) # 4
+class(c(4L, 5L, 8L, 3L)) # "integer"
+
+
+# 数字型
+# 倍精度浮動小数点数です
+5 # 5
+class(5) # "numeric"
+# しつこいですが、すべてはベクトルです
+# 1つ以上の要素がある数字のベクトルも、作ることができます
+c(3,3,3,2,2,1) # 3 3 3 2 2 1
+# 指数表記もできます
+5e4 # 50000
+6.02e23 # アボガドロ数
+1.6e-35 # プランク長
+# 無限大、無限小もつかえます
+class(Inf) # "numeric"
+class(-Inf) # "numeric"
+# 例のように、"Inf"を使ってください。integrate( dnorm(x), 3, Inf);
+# Z-スコア表が必要なくなります
+
+
+# 基本的な計算
+# 数を計算できます
+# 整数と整数以外の数字を両方使った計算をすると、結果は整数以外の数字になります
+10L + 66L # 76 # 整数足す整数は整数
+53.2 - 4 # 49.2 # 整数引く数字は数字
+2.0 * 2L # 4 # 数字かける整数は数字
+3L / 4 # 0.75 # 整数割る数字は数字
+3 %% 2 # 1 # 二つの数字を割った余りは数字
+# 不正な計算は "not-a-number"になります
+0 / 0 # NaN
+class(NaN) # "numeric"
+# 長さが1より大きなベクター同士の計算もできます
+# どちらかが長い場合、短い方は何度も繰り返して使われます
+c(1,2,3) + c(1,2,3) # 2 4 6
+
+# 文字
+# Rでは、文字列と文字に区別がありません
+"Horatio" # "Horatio"
+class("Horatio") # "character"
+class('H') # "character"
+# 上記は両方とも、長さ1のベクターです
+# 以下は、より長い場合です
+c('alef', 'bet', 'gimmel', 'dalet', 'he')
+# =>
+# "alef" "bet" "gimmel" "dalet" "he"
+length(c("Call","me","Ishmael")) # 3
+# 正規表現処理を文字ベクターに適用できます
+substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis "
+gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis."
+# Rはいくつかの文字ベクターを組み込みで持っています
+letters
+# =>
+# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
+# [20] "t" "u" "v" "w" "x" "y" "z"
+month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
+
+
+# 論理
+# Rでは、Booleanは論理(logical)型です
+class(TRUE) # "logical"
+class(FALSE) # "logical"
+# 以下は比較演算子の例です
+TRUE == TRUE # TRUE
+TRUE == FALSE # FALSE
+FALSE != FALSE # FALSE
+FALSE != TRUE # TRUE
+# 無いデータ (NA) も論理型です
+class(NA) # "logical"
+# 以下のようにすると、複数の要素を持つ、論理型ベクターが返ります
+c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE
+c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
+
+
+# 因子(ファクター)
+# 因子型は、カテゴリカルデータ用の型です
+# 因子には、子供の学年のように順序がつけられるものか、性別のように順序がないものがあります
+factor(c("female", "female", "male", "NA", "female"))
+# female female male NA female
+# Levels: female male NA
+# "levels" は、カテゴリカルデータがとりうる値を返します
+levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA"
+# 因子ベクターの長さが1ならば、そのlevelも1です
+length(factor("male")) # 1
+length(levels(factor("male"))) # 1
+# 因子型は、この後で紹介するデータフレーム(というデータ型)内で、よくみられます
+data(infert) # "Infertility after Spontaneous and Induced Abortion"
+levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs"
+
+
+# NULL
+# "NULL" は特殊な型なのですが、ベクターを空にするときに使います
+class(NULL) # NULL
+parakeet
+# =>
+# [1] "beak" "feathers" "wings" "eyes"
+parakeet <- NULL
+parakeet
+# =>
+# NULL
+
+
+# 型の強制
+# 型の強制とは、ある値を、強制的に別の型として利用する事です
+as.character(c(6, 8)) # "6" "8"
+as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE
+# さまざまな要素が入っているベクターに対して型の強制を行うと、おかしなことになります
+c(TRUE, 4) # 1 4
+c("dog", TRUE, 4) # "dog" "TRUE" "4"
+as.numeric("Bilbo")
+# =>
+# [1] NA
+# Warning message:
+# NAs introduced by coercion
+
+
+# 追記: ここで紹介したのは、基本的な型だけです
+# 実際には、日付(dates)や時系列(time series)など、いろいろな型があります
+
+
+
+
+
+
+##################################################
+# 変数、ループ、もし/ほかに(if/else)
+##################################################
+
+
+# 変数は、ある値を後で使うために入れておく、箱のようなものです
+# 箱に入れることを、変数に値を代入する、といいます
+# 変数を使うと、ループや関数、if/else 分岐を利用できます
+
+
+# 変数
+# 代入する方法はいろいろあります
+x = 5 # これはできます
+y <- "1" # これがおすすめです
+TRUE -> z # これも使えますが、ちょっとわかりにくいですね
+
+
+# ループ
+# forでループできます
+for (i in 1:4) {
+ print(i)
+}
+# whileでループできます
+a <- 10
+while (a > 4) {
+ cat(a, "...", sep = "")
+ a <- a - 1
+}
+# Rでは、forやwhileは遅いことを覚えておいてください
+# ベクターを丸ごと処理する(つまり、行全体や、列全体を指定して処理する)か、
+# 後述する、apply()系の関数を使うのが、速度的にはお勧めです
+
+
+# IF/ELSE
+# ごく普通のif文です
+if (4 > 3) {
+ print("4 is greater than 3")
+} else {
+ print("4 is not greater than 3")
+}
+# =>
+# [1] "4 is greater than 3"
+
+
+# 関数
+# 以下のように定義します
+jiggle <- function(x) {
+ x = x + rnorm(1, sd=.1) #すこしだけ(制御された)ノイズを入れます
+ return(x)
+}
+# 他の関数と同じように、呼びます
+jiggle(5) # 5±ε. set.seed(2716057)をすると、jiggle(5)==5.005043
+
+
+
+
+
+
+###########################################################################
+# データ構造: ベクター、行列、データフレーム、配列
+###########################################################################
+
+
+# 1次元
+
+
+# まずは基本からです。ご存じベクターからです
+vec <- c(8, 9, 10, 11)
+vec # 8 9 10 11
+# 特定の要素を、[角括弧]による指定で取り出せます
+# (Rでは、最初の要素は1番目と数えます)
+vec[1] # 8
+letters[18] # "r"
+LETTERS[13] # "M"
+month.name[9] # "September"
+c(6, 8, 7, 5, 3, 0, 9)[3] # 7
+# 特定のルールに当てはまる要素を見つけることもできます
+which(vec %% 2 == 0) # 1 3
+# 最初か最後の数個を取り出すこともできます
+head(vec, 1) # 8
+tail(vec, 2) # 10 11
+# ある値がベクターにあるかどうかをみることができます
+any(vec == 10) # TRUE
+# ベクターの数より大きなインデックスを指定すると、NAが返ります
+vec[6] # NA
+# ベクターの長さは、length()で取得できます
+length(vec) # 4
+# ベクター全体、または1部に対して、操作ができます
+vec * 4 # 16 20 24 28
+vec[2:3] * 5 # 25 30
+any(vec[2:3] == 8) # FALSE
+# R には、ベクターにある値を要約するための様々な関数があります
+mean(vec) # 9.5
+var(vec) # 1.666667
+sd(vec) # 1.290994
+max(vec) # 11
+min(vec) # 8
+sum(vec) # 38
+# 他にも、ベクター関連ではいろいろな関数があります。以下はベクターをつくるための方法です
+5:15 # 5 6 7 8 9 10 11 12 13 14 15
+seq(from=0, to=31337, by=1337)
+# =>
+# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707
+# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751
+
+
+# 2次元配列 (すべての値が同じ型の場合)
+
+
+# 同じ型の値が含まれる2次元配列は、このように作れます
+mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6))
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# ベクターとは違い、2次元配列の型名は"matrix"です。
+class(mat) # => "matrix"
+# 最初の行
+mat[1,] # 1 4
+# 最初の列に対する操作
+3 * mat[,1] # 3 6 9
+# 特定のセルを取り出し
+mat[3,2] # 6
+
+
+# 2次元配列全体を転置します
+t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 1 2 3
+# [2,] 4 5 6
+
+
+# 2次元配列の積
+mat %*% t(mat)
+# =>
+# [,1] [,2] [,3]
+# [1,] 17 22 27
+# [2,] 22 29 36
+# [3,] 27 36 45
+
+
+# cbind() は、複数のベクターを、別々の列に並べて2次元配列を作ります
+mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog"))
+mat2
+# =>
+# [,1] [,2]
+# [1,] "1" "dog"
+# [2,] "2" "cat"
+# [3,] "3" "bird"
+# [4,] "4" "dog"
+class(mat2) # matrix
+# ここでいま1度、2次元配列内の型について注意してください!
+# 2次元配列にある値は、すべて同じ型にする必要があります。そのため、すべて文字型に変換されています
+c(class(mat2[,1]), class(mat2[,2]))
+
+
+# rbind() は、複数のベクターを、別々の行に並べて2次元配列を作ります
+mat3 <- rbind(c(1,2,4,5), c(6,7,0,4))
+mat3
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 2 4 5
+# [2,] 6 7 0 4
+# 全ての値は同じ型になります。上記例は幸い、強制変換がされないものでした
+
+
+# 2次元配列 (いろいろな型を含む場合)
+
+
+# 異なる型の値を含む配列をつくりたい場合、データフレームを使ってください
+# データフレームは、統計処理を行うプログラムをする際にとても便利です
+# Pythonでも、 "pandas"というパッケージにて、似たものが利用可能です
+
+
+students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"),
+ c(3,2,2,1,0,-1),
+ c("H", "G", "G", "R", "S", "G"))
+names(students) <- c("name", "year", "house") #カラム名
+class(students) # "data.frame"
+students
+# =>
+# name year house
+# 1 Cedric 3 H
+# 2 Fred 2 G
+# 3 George 2 G
+# 4 Cho 1 R
+# 5 Draco 0 S
+# 6 Ginny -1 G
+class(students$year) # "numeric"
+class(students[,3]) # "factor"
+# 行と列の数をみます
+nrow(students) # 6
+ncol(students) # 3
+dim(students) # 6 3
+# このdata.frame() 関数は、デフォルトでは文字列ベクターを因子ベクターに変換します
+# stringsAsFactors = FALSE に設定してからデータフレームを作成すると、変換されません
+?data.frame
+
+
+# データフレームの1部を取り出すには、いろいろな(変な)、似たような方法があります
+students$year # 3 2 2 1 0 -1
+students[,2] # 3 2 2 1 0 -1
+students[,"year"] # 3 2 2 1 0 -1
+
+
+# データフレームの拡張版が、データテーブルです。
+# 大きなデータやパネルデータ、データセットの結合が必要な場合には、データテーブルを使うべきです。
+# 以下に駆け足で説明します
+install.packages("data.table") # CRANからパッケージをダウンロードします
+require(data.table) # ロードします
+students <- as.data.table(students)
+students # 若干異なる出力がされることに注意
+# =>
+# name year house
+# 1: Cedric 3 H
+# 2: Fred 2 G
+# 3: George 2 G
+# 4: Cho 1 R
+# 5: Draco 0 S
+# 6: Ginny -1 G
+students[name=="Ginny"] # name == "Ginny"の行を取り出します
+# =>
+# name year house
+# 1: Ginny -1 G
+students[year==2] # year == 2の行を取り出します
+# =>
+# name year house
+# 1: Fred 2 G
+# 2: George 2 G
+# データテーブルは、二つのデータセットを結合するのにも便利です
+# 結合用に、生徒データが入った別のデータテーブルをつくります
+founders <- data.table(house=c("G","H","R","S"),
+ founder=c("Godric","Helga","Rowena","Salazar"))
+founders
+# =>
+# house founder
+# 1: G Godric
+# 2: H Helga
+# 3: R Rowena
+# 4: S Salazar
+setkey(students, house)
+setkey(founders, house)
+students <- founders[students] # 二つのデータテーブルを、"house"をキーとして結合します
+setnames(students, c("house","houseFounderName","studentName","year"))
+students[,order(c("name","year","house","houseFounderName")), with=F]
+# =>
+# studentName year house houseFounderName
+# 1: Fred 2 G Godric
+# 2: George 2 G Godric
+# 3: Ginny -1 G Godric
+# 4: Cedric 3 H Helga
+# 5: Cho 1 R Rowena
+# 6: Draco 0 S Salazar
+
+
+# データテーブルは、要約を作るのも簡単です
+students[,sum(year),by=house]
+# =>
+# house V1
+# 1: G 3
+# 2: H 3
+# 3: R 1
+# 4: S 0
+
+
+# データフレームやデータテーブルから列を消したい場合は、NULL値を代入します
+students$houseFounderName <- NULL
+students
+# =>
+# studentName year house
+# 1: Fred 2 G
+# 2: George 2 G
+# 3: Ginny -1 G
+# 4: Cedric 3 H
+# 5: Cho 1 R
+# 6: Draco 0 S
+
+
+# データテーブルから行を消す場合は、以下のように除く行を指定すればできます
+students[studentName != "Draco"]
+# =>
+# house studentName year
+# 1: G Fred 2
+# 2: G George 2
+# 3: G Ginny -1
+# 4: H Cedric 3
+# 5: R Cho 1
+# データフレームの場合も同様です
+students <- as.data.frame(students)
+students[students$house != "G",]
+# =>
+# house houseFounderName studentName year
+# 4 H Helga Cedric 3
+# 5 R Rowena Cho 1
+# 6 S Salazar Draco 0
+
+
+# 多次元 (すべての値が同じ型の場合)
+
+
+# 配列を並べて、N次元の表を作ります
+# 配列なので、すべての値は同じ型にする必要があります
+# ちなみに、以下のようにすれば2次元配列・2次元表も作成可能です
+array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4))
+# =>
+# [,1] [,2] [,3] [,4]
+# [1,] 1 4 8 3
+# [2,] 2 5 9 6
+# 2次元配列を並べて、3次元配列を作ることもできます
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+# =>
+# , , 1
+#
+# [,1] [,2]
+# [1,] 2 8
+# [2,] 300 9
+# [3,] 4 0
+#
+# , , 2
+#
+# [,1] [,2]
+# [1,] 5 66
+# [2,] 60 7
+# [3,] 0 847
+
+
+# リスト(多次元、不完全または複数の型が使われているもの)
+
+
+# ついにRのリストです
+list1 <- list(time = 1:40)
+list1$price = c(rnorm(40,.5*list1$time,4)) # random
+list1
+# リストの要素は以下のようにして取得できます
+list1$time # ある方法
+list1[["time"]] # 別の方法
+list1[[1]] # また別の方法
+# =>
+# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
+# [34] 34 35 36 37 38 39 40
+# 他のベクターと同じく、1部を取り出すことができます
+list1$price[4]
+
+
+# リストは、Rで1番効率的なデータ型ではありません
+# 特別な理由がない限りは、リストの代わりにデータフレームを使うべきです
+# リストは、線形回帰関数の返値として、しばしば使われています
+
+
+##################################################
+# apply() 系の関数
+##################################################
+
+
+# matは覚えていますよね?
+mat
+# =>
+# [,1] [,2]
+# [1,] 1 4
+# [2,] 2 5
+# [3,] 3 6
+# apply(X, MARGIN, FUN) は、行列Xの行(MARGIN=1で指定)または列(MARGIN=2で指定)に対して、関数FUNを実行します
+# Rで、このように指定してXの全行または全列に関数を実行するのは、forやwhileループを使うよりも、遥かに速いです
+apply(mat, MAR = 2, jiggle)
+# =>
+# [,1] [,2]
+# [1,] 3 15
+# [2,] 7 19
+# [3,] 11 23
+# 他にも便利な関数があります。?lapply, ?sapply で確認してみてください
+
+
+# apply()系関数の使い方は、ちょっとややこしいです(みんなそう思ってます)。なので、あまり怖がりすぎないでください
+
+
+# plyr パッケージは、*apply() 系の関数を置き換えて(さらに改善して)いこうとしています
+install.packages("plyr")
+require(plyr)
+?plyr
+
+
+
+
+
+
+#########################
+# データロード
+#########################
+
+
+# "pets.csv"は、インターネット上に置いてあるファイルです
+# (しかし、自分のPCにあるのと同じぐらい簡単に扱う事ができます)
+pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv")
+pets
+head(pets, 2) # 最初の2行
+tail(pets, 1) # 最後の行
+
+
+# データフレームか行列をcsvファイルとして保存します
+write.csv(pets, "pets2.csv") # 新しくcsvファイルを作ります
+# ワーキングディレクトリを、setwd()で設定します。 ワーキングディレクトリは getwd()で確認可能です
+
+
+# ?read.csv や ?write.csv を入力すると、よりたくさんの情報を確認できます
+
+
+
+
+
+
+#########################
+# プロット
+#########################
+
+
+# Rに組込まれているプロット関数をつかいます
+# 散布図!
+plot(list1$time, list1$price, main = "fake data")
+# 回帰図!
+linearModel <- lm(price ~ time, data = list1)
+linearModel # outputs result of regression
+# 回帰直線を既存の図上に引きます
+abline(linearModel, col = "red")
+# いろいろな散布図をつくって、確認できます
+plot(linearModel)
+# ヒストグラム!
+hist(rpois(n = 10000, lambda = 5), col = "thistle")
+# 棒グラフ!
+barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow"))
+
+
+# GGPLOT2
+# 上記の組込み関数を使うよりも、もっときれいな図を描くこともできます
+# ggplot2 パッケージを使って、より多くのよい図を描いてみましょう
+install.packages("ggplot2")
+require(ggplot2)
+?ggplot2
+pp <- ggplot(students, aes(x=house))
+pp + geom_histogram()
+ll <- as.data.table(list1)
+pp <- ggplot(ll, aes(x=time,price))
+pp + geom_point()
+# ggplot2 には、素晴らしい関連ドキュメントがそろっています (http://docs.ggplot2.org/current/)
+
+
+
+
+
+
+```
+
+
+## Rの入手方法
+
+
+* RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/)
+* [RStudio](http://www.rstudio.com/ide/) 別のGUI \ No newline at end of file
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 9baefe68..d9a82890 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -423,7 +423,8 @@ tril(x) % Returns the lower triangular part of x
cross(A,B) % Returns the cross product of the vectors A and B
dot(A,B) % Returns scalar product of two vectors (must have the same length)
transpose(A) % Returns the transpose of A
-flipl(A) % Flip matrix left to right
+fliplr(A) % Flip matrix left to right
+flipud(A) % Flip matrix up to down
% Matrix Factorisations
[L, U, P] = lu(A) % LU decomposition: PA = LU,L is lower triangular, U is upper triangular, P is permutation matrix
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/python.html.markdown b/python.html.markdown
index 210c9619..aa077e57 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -45,6 +45,13 @@ to Python 2.x. Look for another tour of Python 3 soon!
2.0 # This is a float
11.0 / 4.0 # => 2.75 ahhh...much better
+# Truncation or Integer division
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # works on floats too
+
+# Modulo operation
+7 % 3 # => 1
+
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -380,6 +387,22 @@ all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+# Function Scope
+x = 5
+
+def setX(num):
+ # Local var x not the same as global variable x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
# Python has first class functions
def create_adder(x):
diff --git a/python3.html.markdown b/python3.html.markdown
index 778076f8..bc0c05bd 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -2,6 +2,7 @@
language: python3
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
filename: learnpython3.py
---
@@ -37,9 +38,16 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Except division which returns floats by default
35 / 5 # => 7.0
+# Truncation or Integer division
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0
+
# When you use a float, results are floats
3 * 2.0 # => 6.0
+# Modulo operation
+7 % 3 # => 1
+
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -90,6 +98,10 @@ not False # => True
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+# If your Python 3 code also needs to run on Python 2.5 and below, you can also
+# still use the old style of formatting:
+"%s can be %s the %s way" % ("strings", "interpolated", "old")
+
# None is an object
None # => None
@@ -284,7 +296,7 @@ prints:
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
- # You can use % to interpolate formatted strings
+ # You can use format() to interpolate formatted strings
print("{} is a mammal".format(animal))
"""
@@ -406,6 +418,24 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+# Function Scope
+x = 5
+
+def setX(num):
+ # Local var x not the same as global variable x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # global var x is now set to 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
# Python has first class functions
def create_adder(x):
def adder(y):
@@ -445,7 +475,7 @@ class Human(object):
# An instance method. All methods take "self" as the first argument
def say(self, msg):
- return "{name}: {message}" % (name=self.name, message=msg)
+ return "{name}: {message}".format(name=self.name, message=msg)
# A class method is shared among all instances
# They are called with the calling class as the first argument
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/swift.html.markdown b/swift.html.markdown
index f24b1592..a47b085a 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -31,7 +31,7 @@ optionalString = nil
// Array
var shoppingList = ["catfish", "water", "lemons"]
shoppingList[1] = "bottle of water"
-let emptyArray = String[]()
+let emptyArray = [String]()
// Dictionary
var occupations = [
@@ -65,7 +65,7 @@ for (key, value) in dict {
for i in -1...1 { // [-1, 0, 1]
println(i)
}
-// use .. to exclude the last number
+// use ..< to exclude the last number
// while loop
var i = 1
@@ -127,6 +127,7 @@ increment(7)
//
// Closures
//
+var numbers = [1, 2, 6]
// Functions are special case closures ({})
@@ -140,8 +141,10 @@ numbers.map({
})
// When the type is known, like above, we can do this
-var numbers = [1, 2, 6]
numbers = numbers.map({ number in 3 * number })
+//Or even this
+//numbers = numbers.map({ $0 * 3 })
+
print(numbers) // [3, 6, 18]
@@ -221,4 +224,4 @@ enum Suit {
// Generics: Similar to Java. Use the `where` keyword to specify the
// requirements of the generics.
-``` \ No newline at end of file
+```
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