diff options
-rw-r--r-- | c.html.markdown | 883 | ||||
-rw-r--r-- | csharp.html.markdown | 2 | ||||
-rw-r--r-- | de-de/haskell-de.html.markdown | 425 | ||||
-rw-r--r-- | fr-fr/csharp-fr.html.markdown | 2 | ||||
-rw-r--r-- | fr-fr/scala.html.markdown | 458 | ||||
-rw-r--r-- | git.html.markdown | 2 | ||||
-rw-r--r-- | go.html.markdown | 436 | ||||
-rw-r--r-- | matlab.html.markdown | 3 | ||||
-rw-r--r-- | pt-br/git-pt.html.markdown | 402 | ||||
-rw-r--r-- | pt-br/json-pt.html.markdown | 62 | ||||
-rw-r--r-- | python.html.markdown | 23 | ||||
-rw-r--r-- | python3.html.markdown | 34 | ||||
-rw-r--r-- | ruby-ecosystem.html.markdown | 67 | ||||
-rw-r--r-- | rust.html.markdown | 265 | ||||
-rw-r--r-- | scala.html.markdown | 2 | ||||
-rw-r--r-- | swift.html.markdown | 11 |
16 files changed, 2388 insertions, 689 deletions
diff --git a/c.html.markdown b/c.html.markdown index 22f251f2..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 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 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 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 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* expressions - 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 `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 + // 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 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 +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 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. + // 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 (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 +/* +'\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" // hexadecimal -"%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 /////////////////////////////////////// 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/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 a9a7de72..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,87 +34,88 @@ 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 @@ -122,223 +124,249 @@ can include line breaks.` // Same string type. // 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. + 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 learnFunctionFactory(mystring string) func(before, after string) string { +func sentenceFactory(mystring string) func(before, after string) string { return func(before, after string) string { return fmt.Sprintf("%s %s %s", before, mystring, after) // new string } } -// Next two are equivalent, with second being more practical -fmt.Println(learnFunctionFactory("summer")("A beautiful", "day!")) - -d := learnFunctionFactory("summer") -fmt.Println(d("A beautiful", "day!")) -fmt.Println(d("A lazy", "afternoon!")) - func learnDefer() (ok bool) { - // Deferred statements are executed just before the function returns. - defer fmt.Println("deferred statements execute in reverse (LIFO) order.") - 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/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 +``` |