diff options
author | C. Bess <cbess@company.com> | 2015-11-09 17:55:53 -0600 |
---|---|---|
committer | C. Bess <cbess@company.com> | 2015-11-09 17:55:53 -0600 |
commit | df0992d72c2a28f140e6ff9681c505f36e19249a (patch) | |
tree | 508aa3abe4c25b957dca442560d9c95c9b1fc97a | |
parent | afc5ea14654e0e9cd11c7ef1b672639d12418bad (diff) | |
parent | c460e1fafa0e9b4edc6a5cb35b970bb5cc030a81 (diff) |
Merge remote-tracking branch 'adambard/master'
Conflicts:
swift.html.markdown
222 files changed, 45309 insertions, 4689 deletions
diff --git a/README.markdown b/README.markdown index 774797d5..94afbcbe 100644 --- a/README.markdown +++ b/README.markdown @@ -18,7 +18,7 @@ All contributions are welcome, from the tiniest typo to a brand new article. Tra in all languages are welcome (or, for that matter, original articles in any language). Send a pull request or open an issue any time of day or night. -**Please tag your issues pull requests with [language/lang-code] at the beginning** +**Please tag your issues and pull requests with [language/lang-code] at the beginning** **(e.g. [python/en] for English Python).** This will help everyone pick out things they care about. diff --git a/amd.html.markdown b/amd.html.markdown index b3237dc7..d7fb41ba 100644 --- a/amd.html.markdown +++ b/amd.html.markdown @@ -8,10 +8,10 @@ filename: learnamd.js ## Getting Started with AMD
-The **Asynchronous Module Definition** API specifies a mechanism for defining
-JavaScript modules such that the module and its dependencies can be asynchronously
-loaded. This is particularly well suited for the browser environment where
-synchronous loading of modules incurs performance, usability, debugging, and
+The **Asynchronous Module Definition** API specifies a mechanism for defining
+JavaScript modules such that the module and its dependencies can be asynchronously
+loaded. This is particularly well suited for the browser environment where
+synchronous loading of modules incurs performance, usability, debugging, and
cross-domain access problems.
### Basic concept
diff --git a/asymptotic-notation.html.markdown b/asymptotic-notation.html.markdown new file mode 100644 index 00000000..a516737e --- /dev/null +++ b/asymptotic-notation.html.markdown @@ -0,0 +1,139 @@ +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] +--- + +# Asymptotic Notations + +## What are they? + +Asymptotic Notations are languages that allow us to analyze an algorithm's running time by +identifying its behavior as the input size for the algorithm increases. This is also known as +an algorithm's growth rate. Does the algorithm suddenly become incredibly slow when the input +size grows? Does it mostly maintain its quick run time as the input size increases? +Asymptotic Notation gives us the ability to answer these questions. + +## Are there alternatives to answering these questions? + +One way would be to count the number of primitive operations at different input sizes. +Though this is a valid solution, the amount of work this takes for even simple algorithms +does not justify its use. + +Another way is to physically measure the amount of time an algorithm takes to complete +given different input sizes. However, the accuracy and relativity (times obtained would +only be relative to the machine they were computed on) of this method is bound to +environmental variables such as computer hardware specifications, processing power, etc. + +## Types of Asymptotic Notation + +In the first section of this doc we described how an Asymptotic Notation identifies the +behavior of an algorithm as the input size changes. Let us imagine an algorithm as a function +f, n as the input size, and f(n) being the running time. So for a given algorithm f, with input +size n you get some resultant run time f(n). This results in a graph where the Y axis is the +runtime, X axis is the input size, and plot points are the resultants of the amount of time +for a given input size. + +You can label a function, or algorithm, with an Asymptotic Notation in many different ways. +Some examples are, you can describe an algorithm by its best case, worse case, or equivalent case. +The most common is to analyze an algorithm by its worst case. You typically don't evaluate by best case because those conditions aren't what you're planning for. A very good example of this is sorting algorithms; specifically, adding elements to a tree structure. Best case for most algorithms could be as low as a single operation. However, in most cases, the element you're adding will need to be sorted appropriately through the tree, which could mean examining an entire branch. This is the worst case, and this is what we plan for. + +### Types of functions, limits, and simplification + +``` +Logarithmic Function - log n +Linear Function - an + b +Quadratic Function - an^2 + bn + c +Polynomial Function - an^z + . . . + an^2 + a*n^1 + a*n^0, where z is some constant +Exponential Function - a^n, where a is some constant +``` + +These are some basic function growth classifications used in various notations. The list starts at the slowest growing function (logarithmic, fastest execution time) and goes on to the fastest growing (exponential, slowest execution time). Notice that as 'n', or the input, increases in each of those functions, the result clearly increases much quicker in quadratic, polynomial, and exponential, compared to logarithmic and linear. + +One extremely important note is that for the notations about to be discussed you should do your best to use simplest terms. This means to disregard constants, and lower order terms, because as the input size (or n in our f(n) +example) increases to infinity (mathematical limits), the lower order terms and constants are of little +to no importance. That being said, if you have constants that are 2^9001, or some other ridiculous, +unimaginable amount, realize that simplifying will skew your notation accuracy. + +Since we want simplest form, lets modify our table a bit... + +``` +Logarithmic - log n +Linear - n +Quadratic - n^2 +Polynomial - n^z, where z is some constant +Exponential - a^n, where a is some constant +``` + +### Big-O +Big-O, commonly written as O, is an Asymptotic Notation for the worst case, or ceiling of growth +for a given function. Say `f(n)` is your algorithm runtime, and `g(n)` is an arbitrary time complexity +you are trying to relate to your algorithm. `f(n)` is O(g(n)), if for any real constant c (c > 0), +`f(n)` <= `c g(n)` for every input size n (n > 0). + +*Example 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +Is `f(n)` O(g(n))? +Is `3 log n + 100` O(log n)? +Let's look to the definition of Big-O. + +``` +3log n + 100 <= c * log n +``` + +Is there some constant c that satisfies this for all n? + +``` +3log n + 100 <= 150 * log n, n > 2 (undefined at n = 1) +``` + +Yes! The definition of Big-O has been met therefore `f(n)` is O(g(n)). + +*Example 2* + +``` +f(n) = 3*n^2 +g(n) = n +``` + +Is `f(n)` O(g(n))? +Is `3 * n^2` O(n)? +Let's look at the definition of Big-O. + +``` +3 * n^2 <= c * n +``` + +Is there some constant c that satisfies this for all n? +No, there isn't. `f(n)` is NOT O(g(n)). + +### Big-Omega +Big-Omega, commonly written as Ω, is an Asymptotic Notation for the best case, or a floor growth rate +for a given function. + +`f(n)` is Ω(g(n)), if for any real constant c (c > 0), `f(n)` is >= `c g(n)` for every input size n (n > 0). + +Feel free to head over to additional resources for examples on this. Big-O is the primary notation used +for general algorithm time complexity. + +### Ending Notes +It's hard to keep this kind of topic short, and you should definitely go through the books and online +resources listed. They go into much greater depth with definitions and examples. +More where x='Algorithms & Data Structures' is on its way; we'll have a doc up on analyzing actual +code examples soon. + +## Books + +* [Algorithms](http://www.amazon.com/Algorithms-4th-Robert-Sedgewick/dp/032157351X) +* [Algorithm Design](http://www.amazon.com/Algorithm-Design-Foundations-Analysis-Internet/dp/0471383651) + +## Online Resources + +* [MIT](http://web.mit.edu/16.070/www/lecture/big_o.pdf) +* [KhanAcademy](https://www.khanacademy.org/computing/computer-science/algorithms/asymptotic-notation/a/asymptotic-notation) diff --git a/bash.html.markdown b/bash.html.markdown index 3b163638..211d2944 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Anton Strömkvist", "http://lutic.org/"] - ["Rahil Momin", "https://github.com/iamrahil"] - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] filename: LearnBash.sh --- @@ -31,75 +32,93 @@ echo Hello world! echo 'This is the first line'; echo 'This is the second line' # Declaring a variable looks like this: -VARIABLE="Some string" +Variable="Some string" # But not like this: -VARIABLE = "Some string" -# Bash will decide that VARIABLE is a command it must execute and give an error -# because it couldn't be found. +Variable = "Some string" +# Bash will decide that Variable is a command it must execute and give an error +# because it can't be found. + +# Or like this: +Variable= 'Some string' +# Bash will decide that 'Some string' is a command it must execute and give an +# error because it can't be found. (In this case the 'Variable=' part is seen +# as a variable assignment valid only for the scope of the 'Some string' +# command.) # Using the variable: -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' +echo $Variable +echo "$Variable" +echo '$Variable' # When you use the variable itself — assign it, export it, or else — you write -# its name without $. If you want to use variable's value, you should use $. +# its name without $. If you want to use the variable's value, you should use $. # Note that ' (single quote) won't expand the variables! # String substitution in variables -echo ${VARIABLE/Some/A} -# This will substitute the first occurance of "Some" with "A" +echo ${Variable/Some/A} +# This will substitute the first occurrence of "Some" with "A" # Substring from a variable -echo ${VARIABLE:0:7} +Length=7 +echo ${Variable:0:Length} # This will return only the first 7 characters of the value # Default value for variable -echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} -# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0. +# Note that it only returns default value and doesn't change variable value. # Builtin variables: # There are some useful builtin variables, like -echo "Last program return value: $?" +echo "Last program's return value: $?" echo "Script's PID: $$" -echo "Number of arguments: $#" -echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." +echo "Number of arguments passed to script: $#" +echo "All arguments passed to script: $@" +echo "Script's arguments separated into different variables: $1 $2..." # Reading a value from input: echo "What's your name?" -read NAME # Note that we didn't need to declare a new variable -echo Hello, $NAME! +read Name # Note that we didn't need to declare a new variable +echo Hello, $Name! # We have the usual if structure: # use 'man test' for more info about conditionals -if [ $NAME -ne $USER ] +if [ $Name -ne $USER ] then echo "Your name isn't your username" else echo "Your name is your username" fi +# NOTE: if $Name is empty, bash sees the above condition as: +if [ -ne $USER ] +# which is invalid syntax +# so the "safe" way to use potentially empty variables in bash is: +if [ "$Name" -ne $USER ] ... +# which, when $Name is empty, is seen by bash as: +if [ "" -ne $USER ] ... +# which works as expected + # There is also conditional execution echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" # To use && and || with if statements, you need multiple pairs of square brackets: -if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +if [ "$Name" == "Steve" ] && [ "$Age" -eq 15 ] then - echo "This will run if $NAME is Steve AND $AGE is 15." + echo "This will run if $Name is Steve AND $Age is 15." fi -if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +if [ "$Name" == "Daniya" ] || [ "$Name" == "Zach" ] then - echo "This will run if $NAME is Daniya OR Zach." + echo "This will run if $Name is Daniya OR Zach." fi # Expressions are denoted with the following format: echo $(( 10 + 5 )) -# Unlike other programming languages, bash is a shell — so it works in a context -# of current directory. You can list files and directories in the current +# Unlike other programming languages, bash is a shell so it works in the context +# of a current directory. You can list files and directories in the current # directory with the ls command: ls @@ -134,7 +153,7 @@ python hello.py > /dev/null 2>&1 # if you want to append instead, use ">>": python hello.py >> "output.out" 2>> "error.err" -# Overwrite output.txt, append to error.err, and count lines: +# Overwrite output.out, append to error.err, and count lines: info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err wc -l output.out error.err @@ -142,7 +161,7 @@ wc -l output.out error.err # see: man fd echo <(echo "#helloworld") -# Overwrite output.txt with "#helloworld": +# Overwrite output.out with "#helloworld": cat > output.out <(echo "#helloworld") echo "#helloworld" > output.out echo "#helloworld" | cat > output.out @@ -161,7 +180,7 @@ echo "There are $(ls | wc -l) items here." echo "There are `ls | wc -l` items here." # Bash uses a case statement that works similarly to switch in Java and C++: -case "$VARIABLE" in +case "$Variable" in #List patterns for the conditions you want to meet 0) echo "There is a zero.";; 1) echo "There is a one.";; @@ -169,10 +188,10 @@ case "$VARIABLE" in esac # for loops iterate for as many arguments given: -# The contents of $VARIABLE is printed three times. -for VARIABLE in {1..3} +# The contents of $Variable is printed three times. +for Variable in {1..3} do - echo "$VARIABLE" + echo "$Variable" done # Or write it the "traditional for loop" way: @@ -183,16 +202,16 @@ done # They can also be used to act on files.. # This will run the command 'cat' on file1 and file2 -for VARIABLE in file1 file2 +for Variable in file1 file2 do - cat "$VARIABLE" + cat "$Variable" done # ..or the output from a command # This will cat the output from ls. -for OUTPUT in $(ls) +for Output in $(ls) do - cat "$OUTPUT" + cat "$Output" done # while loop: @@ -220,7 +239,7 @@ bar () } # Calling your function -foo "My name is" $NAME +foo "My name is" $Name # There are a lot of useful commands you should learn: # prints last 10 lines of file.txt @@ -235,12 +254,14 @@ uniq -d file.txt cut -d ',' -f 1 file.txt # replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible) sed -i 's/okay/great/g' file.txt -# print to stdout all lines of file.txt which match some regex, the example prints lines which begin with "foo" and end in "bar" +# print to stdout all lines of file.txt which match some regex +# The example prints lines which begin with "foo" and end in "bar" grep "^foo.*bar$" file.txt # pass the option "-c" to instead print the number of lines matching the regex grep -c "^foo.*bar$" file.txt -# if you literally want to search for the string, and not the regex, use fgrep (or grep -F) -fgrep "^foo.*bar$" file.txt +# if you literally want to search for the string, +# and not the regex, use fgrep (or grep -F) +fgrep "^foo.*bar$" file.txt # Read Bash shell builtins documentation with the bash 'help' builtin: diff --git a/brainfuck.html.markdown b/brainfuck.html.markdown index 27ac6921..a76169c8 100644 --- a/brainfuck.html.markdown +++ b/brainfuck.html.markdown @@ -8,6 +8,8 @@ contributors: Brainfuck (not capitalized except at the start of a sentence) is an extremely minimal Turing-complete programming language with just 8 commands. +You can try brainfuck on your browser with [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + ``` Any character not "><+-.,[]" (excluding quotation marks) is ignored. diff --git a/c++.html.markdown b/c++.html.markdown index 5f80f26f..6b452b1b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -4,6 +4,8 @@ filename: learncpp.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] lang: en --- @@ -30,10 +32,9 @@ one of the most widely-used programming languages. // C++ is _almost_ a superset of C and shares its basic syntax for // variable declarations, primitive types, and functions. -// However, C++ varies in some of the following ways: -// A main() function in C++ should return an int, -// though void main() is accepted by most compilers (gcc, clang, etc.) +// Just like in C, your program's entry point is a function called +// main with an integer return type. // This value serves as the program's exit status. // See http://en.wikipedia.org/wiki/Exit_status for more information. int main(int argc, char** argv) @@ -51,11 +52,13 @@ int main(int argc, char** argv) return 0; } -// In C++, character literals are one byte. -sizeof('c') == 1 +// However, C++ varies in some of the following ways: + +// In C++, character literals are chars +sizeof('c') == sizeof(char) == 1 -// In C, character literals are the same size as ints. -sizeof('c') == sizeof(10) +// In C, character literals are ints +sizeof('c') == sizeof(int) // C++ has strict prototyping @@ -157,11 +160,12 @@ void foo() int main() { - // Assume everything is from the namespace "Second" - // unless otherwise specified. + // Includes all symbols from namespace Second into the current scope. Note + // that simply foo() no longer works, since it is now ambiguous whether + // we're calling the foo in namespace Second or the top level. using namespace Second; - foo(); // prints "This is Second::foo" + Second::foo(); // prints "This is Second::foo" First::Nested::foo(); // prints "This is First::Nested::foo" ::foo(); // prints "This is global foo" } @@ -241,12 +245,135 @@ cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. +cout << &fooRef << endl; //Prints the address of foo fooRef = bar; +cout << &fooRef << endl; //Still prints the address of foo +cout << fooRef; // Prints "I am bar" + +//The address of fooRef remains the same, i.e. it is still referring to foo. + const string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. barRef += ". Hi!"; // Error, const references cannot be modified. +// Sidetrack: Before we talk more about references, we must introduce a concept +// called a temporary object. Suppose we have the following code: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// What happens in the second line is actually: +// - a string object is returned from tempObjectFun +// - a new string is constructed with the returned object as argument to the +// constructor +// - the returned object is destroyed +// The returned object is called a temporary object. Temporary objects are +// created whenever a function returns an object, and they are destroyed at the +// end of the evaluation of the enclosing expression (Well, this is what the +// standard says, but compilers are allowed to change this behavior. Look up +// "return value optimization" if you're into this kind of details). So in this +// code: +foo(bar(tempObjectFun())) + +// assuming foo and bar exist, the object returned from tempObjectFun is +// passed to bar, and it is destroyed before foo is called. + +// Now back to references. The exception to the "at the end of the enclosing +// expression" rule is if a temporary object is bound to a const reference, in +// which case its life gets extended to the current scope: + +void constReferenceTempObjectFun() { + // constRef gets the temporary object, and it is valid until the end of this + // function. + const string& constRef = tempObjectFun(); + ... +} + +// Another kind of reference introduced in C++11 is specifically for temporary +// objects. You cannot have a variable of its type, but it takes precedence in +// overload resolution: + +void someFun(string& s) { ... } // Regular reference +void someFun(string&& s) { ... } // Reference to temporary object + +string foo; +someFun(foo); // Calls the version with regular reference +someFun(tempObjectFun()); // Calls the version with temporary reference + +// For example, you will see these two versions of constructors for +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// Idea being if we are constructing a new string from a temporary object (which +// is going to be destroyed soon anyway), we can have a more efficient +// constructor that "salvages" parts of that temporary string. You will see this +// concept referred to as "move semantics". + +///////////////////// +// Enums +///////////////////// + +// Enums are a way to assign a value to a constant most commonly used for +// easier visualization and reading of code +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// As of C++11 there is an easy way to assign a type to the enum which can be +// useful in serialization of data and converting enums back-and-forth between +// the desired type and their respective constants +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // The enum is implicitly converted to a uint8_t due to its declared enum type + WriteByteToFile(InputCarType); +} + +// On the other hand you may not want enums to be accidentally cast to an integer +// type or to other enums so it is instead possible to create an enum class which +// won't be implicitly converted +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serialize the InputValue to a file +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // Won't compile even though ECarTypes is a uint8_t due to the enum + // being declared as an "enum class"! + WriteByteToFile(InputCarType); +} + ////////////////////////////////////////// // Classes and object-oriented programming ////////////////////////////////////////// @@ -287,19 +414,22 @@ public: // Functions can also be defined inside the class body. // Functions defined as such are automatically inlined. - void bark() const { std::cout << name << " barks!\n" } + void bark() const { std::cout << name << " barks!\n"; } // Along with constructors, C++ provides destructors. // These are called when an object is deleted or falls out of scope. // This enables powerful paradigms such as RAII // (see below) - // Destructors must be virtual to allow classes to be derived from this one. + // The destructor should be virtual if a class is to be derived from; + // if it is not virtual, then the derived class' destructor will + // not be called if the object is destroyed through a base-class reference + // or pointer. virtual ~Dog(); }; // A semicolon must follow the class definition. // Class member functions are usually implemented in .cpp files. -void Dog::Dog() +Dog::Dog() { std::cout << "A dog has been constructed\n"; } @@ -322,7 +452,7 @@ void Dog::print() const std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; } -void Dog::~Dog() +Dog::~Dog() { cout << "Goodbye " << name << "\n"; } @@ -331,16 +461,18 @@ int main() { Dog myDog; // prints "A dog has been constructed" myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg" + myDog.print(); // prints "Dog is Barkley and weighs 10 kg" return 0; } // prints "Goodbye Barkley" // Inheritance: // This class inherits everything public and protected from the Dog class +// as well as private but may not directly access private members/methods +// without a public or protected method for doing so class OwnedDog : public Dog { - void setOwner(const std::string& dogsOwner) + void setOwner(const std::string& dogsOwner); // Override the behavior of the print function for all OwnedDogs. See // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping @@ -424,7 +556,7 @@ int main () { Point up (0,1); Point right (1,0); // This calls the Point + operator - // Point up calls the + (function) with right as its paramater + // Point up calls the + (function) with right as its parameter Point result = up + right; // Prints "Result is upright (1,1)" cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; @@ -432,6 +564,86 @@ int main () { } ///////////////////// +// Templates +///////////////////// + +// Templates in C++ are mostly used for generic programming, though they are +// much more powerful than generic constructs in other languages. They also +// support explicit and partial specialization and functional-style type +// classes; in fact, they are a Turing-complete functional language embedded +// in C++! + +// We start with the kind of generic programming you might be familiar with. To +// define a class or function that takes a type parameter: +template<class T> +class Box { +public: + // In this class, T can be used as any other type. + void insert(const T&) { ... } +}; + +// During compilation, the compiler actually generates copies of each template +// with parameters substituted, so the full definition of the class must be +// present at each invocation. This is why you will see template classes defined +// entirely in header files. + +// To instantiate a template class on the stack: +Box<int> intBox; + +// and you can use it as you would expect: +intBox.insert(123); + +// You can, of course, nest templates: +Box<Box<int> > boxOfBox; +boxOfBox.insert(intBox); + +// Until C++11, you had to place a space between the two '>'s, otherwise '>>' +// would be parsed as the right shift operator. + +// You will sometimes see +// template<typename T> +// instead. The 'class' keyword and 'typename' keywords are _mostly_ +// interchangeable in this case. For the full explanation, see +// http://en.wikipedia.org/wiki/Typename +// (yes, that keyword has its own Wikipedia page). + +// Similarly, a template function: +template<class T> +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Notice that nothing is specified about the type parameters here. The compiler +// will generate and then type-check every invocation of the template, so the +// above function works with any type 'T' that has a const 'bark' method! + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. + +// Template parameters don't have to be classes: +template<int Y> +void printMessage() { + cout << "Learn C++ in " << Y << " minutes!" << endl; +} + +// And you can explicitly specialize templates for more efficient code. Of +// course, most real-world uses of specialization are not as trivial as this. +// Note that you still need to declare the function (or class) as a template +// even if you explicitly specified all parameters. +template<> +void printMessage<10>() { + cout << "Learn C++ faster in only 10 minutes!" << endl; +} + +printMessage<20>(); // Prints "Learn C++ in 20 minutes!" +printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" + + +///////////////////// // Exception Handling ///////////////////// @@ -439,19 +651,23 @@ int main () { // (see http://en.cppreference.com/w/cpp/error/exception) // but any type can be thrown an as exception #include <exception> +#include <stdexcept> // All exceptions thrown inside the _try_ block can be caught by subsequent // _catch_ handlers. try { // Do not allocate exceptions on the heap using _new_. - throw std::exception("A problem occurred"); + throw std::runtime_error("A problem occurred"); } + // Catch exceptions by const reference if they are objects catch (const std::exception& ex) { - std::cout << ex.what(); + std::cout << ex.what(); +} + // Catches any exception not caught by previous _catch_ blocks -} catch (...) +catch (...) { std::cout << "Unknown exception caught"; throw; // Re-throws the exception @@ -461,8 +677,8 @@ catch (const std::exception& ex) // RAII /////// -// RAII stands for Resource Allocation Is Initialization. -// It is often considered the most powerful paradigm in C++, +// RAII stands for "Resource Acquisition Is Initialization". +// It is often considered the most powerful paradigm in C++ // and is the simple concept that a constructor for an object // acquires that object's resources and the destructor releases them. @@ -483,16 +699,16 @@ void doSomethingWithAFile(const char* filename) // Unfortunately, things are quickly complicated by error handling. // Suppose fopen can fail, and that doSomethingWithTheFile and // doSomethingElseWithIt return error codes if they fail. -// (Exceptions are the preferred way of handling failure, -// but some programmers, especially those with a C background, -// disagree on the utility of exceptions). +// (Exceptions are the preferred way of handling failure, +// but some programmers, especially those with a C background, +// disagree on the utility of exceptions). // We now have to check each call for failure and close the file handle // if a problem occurred. bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) // The returned pointer is null on failure. - reuturn false; // Report that failure to the caller. + return false; // Report that failure to the caller. // Assume each function returns false if it failed if (!doSomethingWithTheFile(fh)) { @@ -513,7 +729,7 @@ bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); if (fh == nullptr) - reuturn false; + return false; if (!doSomethingWithTheFile(fh)) goto failure; @@ -535,7 +751,7 @@ void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // Open the file in read mode if (fh == nullptr) - throw std::exception("Could not open the file."); + throw std::runtime_error("Could not open the file."); try { doSomethingWithTheFile(fh); @@ -553,7 +769,7 @@ void doSomethingWithAFile(const char* filename) // Compare this to the use of C++'s file stream class (fstream) // fstream uses its destructor to close the file. // Recall from above that destructors are automatically called -// whenver an object falls out of scope. +// whenever an object falls out of scope. void doSomethingWithAFile(const std::string& filename) { // ifstream is short for input file stream @@ -584,8 +800,93 @@ void doSomethingWithAFile(const std::string& filename) // vector (i.e. self-resizing array), hash maps, and so on // all automatically destroy their contents when they fall out of scope. // - Mutexes using lock_guard and unique_lock + +// containers with object keys of non-primitive values (custom classes) require +// compare function in the object itself or as a function pointer. Primitives +// have default comparators, but you can override it. +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +//this isn't allowed (although it can vary depending on compiler) +//std::map<Foo, int> fooMap; +std::map<Foo, int, compareFunction> fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true + +///////////////////// +// Fun stuff +///////////////////// + +// Aspects of C++ that may be surprising to newcomers (and even some veterans). +// This section is, unfortunately, wildly incomplete; C++ is one of the easiest +// languages with which to shoot yourself in the foot. + +// You can override private methods! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Overrides Foo::bar! +}; + + +// 0 == false == NULL (most of the time)! +bool* pt = new bool; +*pt = 0; // Sets the value points by 'pt' to false. +pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings. + +// nullptr is supposed to fix some of that issue: +int* pt2 = new int; +*pt2 = nullptr; // Doesn't compile +pt2 = nullptr; // Sets pt2 to null. + +// There is an exception made for bools. +// This is to allow you to test for null pointers with if(!ptr), +// but as a consequence you can assign nullptr to a bool directly! +*pt = nullptr; // This still compiles, even though '*pt' is a bool! + + +// '=' != '=' != '='! +// Calls Foo::Foo(const Foo&) or some variant (see move semantics) copy +// constructor. +Foo f2; +Foo f1 = f2; + +// Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of +// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes +// horrifying behavior is called "object slicing." +FooSub fooSub; +Foo f1 = fooSub; + +// Calls Foo::operator=(Foo&) or variant. +Foo f1; +f1 = f2; + + +// How to truly clear a container: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// Following line sets size of v to 0, but destructors don't get called +// and resources aren't released! +v.empty(); +v.push_back(Foo()); // New value is copied into the first Foo we inserted + +// Truly destroys all values in v. See section about temporary objects for +// explanation of why this works. +v.swap(vector<Foo>()); + ``` -Futher Reading: +Further Reading: An up-to-date language reference can be found at <http://cppreference.com/w/cpp> diff --git a/c.html.markdown b/c.html.markdown index b5b804af..7c2386ef 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -6,7 +6,8 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] - ["Marco Scannadinari", "https://marcoms.github.io"] - + - ["Zachary Ferguson", "https://github.io/zfergus2"] + - ["himanshu", "https://github.com/himanshu81494"] --- Ah, C. Still **the** language of modern high-performance computing. @@ -18,15 +19,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. - */ +*/ /* Multi-line comments don't nest /* Be careful */ // comment ends on this line... */ // ...not this one! // Constants: #define <keyword> +// Constants are written in all-caps out of convention, not requirement #define DAYS_IN_YEAR 365 // Enumeration constants are also ways to declare constants. @@ -52,10 +54,21 @@ 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 +// although `int add_two_ints(int, int);` is also valid (no need to name the args), +// it is recommended to name arguments in the prototype as well for easier inspection // Your program's entry point is a function called // main with an integer return type. -int main() { +int main(void) { + // your program +} + +// The command line arguments used to run your program are also passed to main +// argc being the number of arguments - your program's name counts as 1 +// argv is an array of character arrays - containing the arguments themselves +// argv[0] = name of your program, argv[1] = first argument, etc. +int main (int argc, char** argv) +{ // print output using printf, for "print formatted" // %d is an integer, \n is a newline printf("%d\n", 0); // => Prints 0 @@ -63,6 +76,9 @@ int main() { /////////////////////////////////////// // Types /////////////////////////////////////// + + // All variables MUST be declared at the top of the current block scope + // we declare them dynamically along the code for the sake of the tutorial // ints are usually 4 bytes int x_int = 0; @@ -85,7 +101,7 @@ int main() { // doubles are usually 64-bit floating-point numbers double x_double = 0.0; // real numbers without any suffix are doubles - // integer types may be unsigned (only positive) + // integer types may be unsigned (greater than or equal to zero) unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; @@ -130,15 +146,12 @@ int main() { // 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 + int size; + fscanf(stdin, "%d", &size); + 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: + // Example: // > Enter the array size: 10 // > sizeof array = 40 @@ -157,12 +170,12 @@ int main() { int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) - //Multi-dimensional arrays: + // Multi-dimensional arrays: int multi_array[2][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 0} }; - //access elements: + // access elements: int array_int = multi_array[0][2]; // => 3 /////////////////////////////////////// @@ -183,8 +196,8 @@ int main() { i1 / i2; // => 0 (0.5, but truncated towards 0) // You need to cast at least one integer to float to get a floating-point result - (float)i1 / i2 // => 0.5f - i1 / (double)i2 // => 0.5 // Same with double + (float)i1 / i2; // => 0.5f + i1 / (double)i2; // => 0.5 // Same with double f1 / f2; // => 0.5, plus or minus epsilon // Floating-point numbers and calculations are not exact @@ -219,13 +232,13 @@ int main() { 0 || 1; // => 1 (Logical or) 0 || 0; // => 0 - //Conditional expression ( ? : ) + // Conditional ternary expression ( ? : ) int e = 5; int f = 10; int z; z = (e > f) ? e : f; // => 10 "if e > f return e, else return f." - //Increment and decrement operators: + // 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. @@ -234,7 +247,7 @@ int main() { // same with j-- and --j // Bitwise operators! - ~0x0F; // => 0xF0 (bitwise negation, "1's complement") + ~0x0F; // => 0xFFFFFFF0 (bitwise negation, "1's complement", example result for 32-bit int) 0x0F & 0xF0; // => 0x00 (bitwise AND) 0x0F | 0xF0; // => 0xFF (bitwise OR) 0x04 ^ 0x0F; // => 0x0B (bitwise XOR) @@ -242,7 +255,7 @@ int main() { 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) + // - shifting into the sign bit of a signed integer (int a = 1 << 31) // - 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 @@ -289,6 +302,8 @@ int main() { for (i = 0; i <= 5; i++) { ; // use semicolon to act as the body (null statement) } + // Or + for (i = 0; i <= 5; i++); // branching with multiple choices: switch() switch (a) { @@ -304,7 +319,29 @@ int main() { exit(-1); break; } - + /* + using "goto" in C + */ + typedef enum { false, true } bool; + // for C don't have bool as data type :( + bool disaster = false; + int i, j; + for(i=0;i<100;++i) + for(j=0;j<100;++j) + { + if((i + j) >= 150) + disaster = true; + if(disaster) + goto error; + } + error : + printf("Error occured at i = %d & j = %d.\n", i, j); + /* + https://ideone.com/GuPhd6 + this will print out "Error occured at i = 52 & j = 99." + */ + + /////////////////////////////////////// // Typecasting /////////////////////////////////////// @@ -371,7 +408,7 @@ int main() { 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 + // 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. @@ -386,7 +423,8 @@ int main() { // 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" + printf("%zu, %zu\n", sizeof arraythethird, sizeof ptr); + // probably prints "40, 4" or "40, 8" // Pointers are incremented and decremented based on their type @@ -402,9 +440,20 @@ int main() { 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" + + // Note that there is no standard way to get the length of a + // dynamically allocated array in C. Because of this, if your arrays are + // going to be passed around your program a lot, you need another variable + // to keep track of the number of elements (size) of an array. See the + // functions section for more info. + int size = 10; + int *my_arr = malloc(sizeof(int) * size); + // Add an element to the array + my_arr = realloc(my_arr, ++size); + my_arr[10] = 5; + + // 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, @@ -469,15 +518,55 @@ char c[] = "This is a test."; str_reverse(c); printf("%s\n", c); // => ".tset a si sihT" */ +/* +as we can return only one variable +to change values of more than one variables we use call by reference +*/ +void swapTwoNumbers(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} +/* +int first = 10; +int second = 20; +printf("first: %d\nsecond: %d\n", first, second); +swapTwoNumbers(&first, &second); +printf("first: %d\nsecond: %d\n", first, second); +// values will be swapped +*/ -//if referring to external variables outside function, must use extern keyword. +/* +With regards to arrays, they will always be passed to functions +as pointers. Even if you statically allocate an array like `arr[10]`, +it still gets passed as a pointer to the first element in any function calls. +Again, there is no standard way to get the size of a dynamically allocated +array in C. +*/ +// Size must be passed! +// Otherwise, this function has no way of knowing how big the array is. +void printIntArray(int *arr, int size) { + int i; + for (i = 0; i < size; i++) { + printf("arr[%d] is: %d\n", i, arr[i]); + } +} +/* +int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; +int size = 10; +printIntArray(my_arr, size); +// will print "arr[0] is: 1" etc +*/ + +// 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 } -//make external variables private to source file with static: -static int j = 0; //other files using testFunc() cannot access variable i +// make external variables private to source file with static: +static int j = 0; //other files using testFunc2() cannot access variable j void testFunc2() { extern int j; } @@ -625,15 +714,63 @@ typedef void (*my_fnp_type)(char *); // , | left to right // //---------------------------------------------------// -``` +/******************************* Header Files ********************************** + +Header files are an important part of c as they allow for the connection of c +source files and can simplify code and definitions by seperating them into +seperate files. + +Header files are syntaxtically similar to c source files but reside in ".h" +files. They can be included in your c source file by using the precompiler +command #include "example.h", given that example.h exists in the same directory +as the c file. +*/ + +/* A safe guard to prevent the header from being defined too many times. This */ +/* happens in the case of circle dependency, the contents of the header is */ +/* already defined. */ +#ifndef EXAMPLE_H /* if EXAMPLE_H is not yet defined. */ +#define EXAMPLE_H /* Define the macro EXAMPLE_H. */ +/* Other headers can be included in headers and therefore transitively */ +/* included into files that include this header. */ +#include <string.h> + +/* Like c source files macros can be defined in headers and used in files */ +/* that include this header file. */ +#define EXAMPLE_NAME "Dennis Ritchie" +/* Function macros can also be defined. */ +#define ADD(a, b) (a + b) + +/* Structs and typedefs can be used for consistency between files. */ +typedef struct node +{ + int val; + struct node *next; +} Node; + +/* So can enumerations. */ +enum traffic_light_state {GREEN, YELLOW, RED}; + +/* Function prototypes can also be defined here for use in multiple files, */ +/* but it is bad practice to define the function in the header. Definitions */ +/* should instead be put in a c file. */ +Node createLinkedList(int *vals, int len); + +/* Beyond the above elements, other definitions should be left to a c source */ +/* file. Excessive includeds or definitions should, also not be contained in */ +/* a header file but instead put into separate headers or a c file. */ + +#endif /* End of the if precompiler directive. */ + +``` ## Further Reading Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some inaccuracies (well, ideas that are not considered good anymore) or now-changed practices. -Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/). +Another good resource is [Learn C The Hard Way](http://c.learncodethehardway.org/book/). If you have a question, read the [compl.lang.c Frequently Asked Questions](http://c-faq.com). diff --git a/chapel.html.markdown b/chapel.html.markdown new file mode 100644 index 00000000..866e92d2 --- /dev/null +++ b/chapel.html.markdown @@ -0,0 +1,1103 @@ +--- +language: chapel +filename: learnchapel.chpl +contributors: + - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] +--- + +You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com). +In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. + +More information and support can be found at the bottom of this document. + +```c +// Comments are C-family style +// one line comment +/* + multi-line comment +*/ + +// Basic printing +write( "Hello, " ); +writeln( "World!" ); +// write and writeln can take a list of things to print. +// each thing is printed right next to each other, so include your spacing! +writeln( "There are ", 3, " commas (\",\") in this line of code" ); +// Different output channels +stdout.writeln( "This goes to standard output, just like plain writeln() does"); +stderr.writeln( "This goes to standard error" ); + +// Variables don't have to be explicitly typed as long as +// the compiler can figure out the type that it will hold. +var myVar = 10; // 10 is an int, so myVar is implicitly an int +myVar = -10; +var mySecondVar = myVar; +// var anError; // this would be a compile-time error. + +// We can (and should) explicitly type things +var myThirdVar: real; +var myFourthVar: real = -1.234; +myThirdVar = myFourthVar; + +// There are a number of basic types. +var myInt: int = -1000; // Signed ints +var myUint: uint = 1234; // Unsigned ints +var myReal: real = 9.876; // Floating point numbers +var myImag: imag = 5.0i; // Imaginary numbers +var myCplx: complex = 10 + 9i; // Complex numbers +myCplx = myInt + myImag ; // Another way to form complex numbers +var myBool: bool = false; // Booleans +var myStr: string = "Some string..."; // Strings + +// Some types can have sizes +var my8Int: int(8) = 10; // 8 bit (one byte) sized int; +var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real + +// Typecasting +var intFromReal = myReal : int; +var intFromReal2: int = myReal : int; + +// consts are constants, they cannot be changed after set in runtime. +const almostPi: real = 22.0/7.0; + +// params are constants whose value must be known statically at compile-time +// Their value cannot be changed. +param compileTimeConst: int = 16; + +// The config modifier allows values to be set at the command line +// and is much easier than the usual getOpts debacle +// config vars and consts can be changed through the command line at run time +config var varCmdLineArg: int = -123; +config const constCmdLineArg: int = 777; +// Set with --VarName=Value or --VarName Value at run time + +// config params can be set/changed at compile-time +config param paramCmdLineArg: bool = false; +// Set config with --set paramCmdLineArg=value at compile-time +writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); + +// refs operate much like a reference in C++ +var actual = 10; +ref refToActual = actual; // refToActual refers to actual +writeln( actual, " == ", refToActual ); // prints the same value +actual = -123; // modify actual (which refToActual refers to) +writeln( actual, " == ", refToActual ); // prints the same value +refToActual = 99999999; // modify what refToActual refers to (which is actual) +writeln( actual, " == ", refToActual ); // prints the same value + +// Math operators +var a: int, thisInt = 1234, thatInt = 5678; +a = thisInt + thatInt; // Addition +a = thisInt * thatInt; // Multiplication +a = thisInt - thatInt; // Subtraction +a = thisInt / thatInt; // Division +a = thisInt ** thatInt; // Exponentiation +a = thisInt % thatInt; // Remainder (modulo) + +// Logical Operators +var b: bool, thisBool = false, thatBool = true; +b = thisBool && thatBool; // Logical and +b = thisBool || thatBool; // Logical or +b = !thisBool; // Logical negation + +// Relational Operators +b = thisInt > thatInt; // Greater-than +b = thisInt >= thatInt; // Greater-than-or-equal-to +b = thisInt < a && a <= thatInt; // Less-than, and, less-than-or-equal-to +b = thisInt != thatInt; // Not-equal-to +b = thisInt == thatInt; // Equal-to + +// Bitwise operations +a = thisInt << 10; // Left-bit-shift by 10 bits; +a = thatInt >> 5; // Right-bit-shift by 5 bits; +a = ~thisInt; // Bitwise-negation +a = thisInt ^ thatInt; // Bitwise exclusive-or + +// Compound assignment operations +a += thisInt; // Addition-equals ( a = a + thisInt;) +a *= thatInt; // Times-equals ( a = a * thatInt; ) +b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) +a <<= 3; // Left-bit-shift-equals ( a = a << 10; ) +// and many, many more. +// Unlike other C family languages there are no +// pre/post-increment/decrement operators like +// ++j, --j, j++, j-- + +// Swap operator +var old_this = thisInt; +var old_that = thatInt; +thisInt <=> thatInt; // Swap the values of thisInt and thatInt +writeln( (old_this == thatInt) && (old_that == thisInt) ); + +// Operator overloads can also be defined, as we'll see with procedures + +// Tuples can be of the same type +var sameTup: 2*int = (10,-1); +var sameTup2 = (11, -6); +// or different types +var diffTup: (int,real,complex) = (5, 1.928, myCplx); +var diffTupe2 = ( 7, 5.64, 6.0+1.5i ); + +// Accessed using array bracket notation +// However, tuples are all 1-indexed +writeln( "(", sameTup[1], ",", sameTup[2], ")" ); +writeln( diffTup ); + +// Tuples can also be written into. +diffTup[1] = -1; + +// Can expand tuple values into their own variables +var (tupInt, tupReal, tupCplx) = diffTup; +writeln( diffTup == (tupInt, tupReal, tupCplx) ); + +// Useful for writing a list of variables ( as is common in debugging) +writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); + +// Type aliasing +type chroma = int; // Type of a single hue +type RGBColor = 3*chroma; // Type representing a full color +var black: RGBColor = ( 0,0,0 ); +var white: RGBColor = ( 255, 255, 255 ); + +// If-then-else works just like any other C-family language +if 10 < 100 then + writeln( "All is well" ); + +if -1 < 1 then + writeln( "Continuing to believe reality" ); +else + writeln( "Send mathematician, something's wrong" ); + +if ( 10 > 100 ) { + writeln( "Universe broken. Please reboot universe." ); +} + +if ( a % 2 == 0 ) { + writeln( a, " is even." ); +} else { + writeln( a, " is odd." ); +} + +if ( a % 3 == 0 ) { + writeln( a, " is even divisible by 3." ); +} else if ( a % 3 == 1 ){ + writeln( a, " is divided by 3 with a remainder of 1." ); +} else { + writeln( b, " is divided by 3 with a remainder of 2." ); +} + +// Ternary: if-then-else in a statement +var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; + +// Select statements are much like switch statements in other languages +// However, Select statements don't cascade like in C or Java +var inputOption = "anOption"; +select( inputOption ){ + when "anOption" do writeln( "Chose 'anOption'" ); + when "otherOption" { + writeln( "Chose 'otherOption'" ); + writeln( "Which has a body" ); + } + otherwise { + writeln( "Any other Input" ); + writeln( "the otherwise case doesn't need a do if the body is one line" ); + } +} + +// While and Do-While loops are basically the same in every language. +var j: int = 1; +var jSum: int = 0; +while( j <= 1000 ){ + jSum += j; + j += 1; +} +writeln( jSum ); + +// Do-While loop +do{ + jSum += j; + j += 1; +}while( j <= 10000 ); +writeln( jSum ); + +// For loops are much like those in python in that they iterate over a range. +// Ranges themselves are types, and can be stuffed into variables +// (more about that later) +for i in 1..10 do write( i , ", ") ; +writeln( ); + +var iSum: int = 0; +for i in 1..1000 { + iSum += i; +} +writeln( iSum ); + +for x in 1..10 { + for y in 1..10 { + write( (x,y), "\t" ); + } + writeln( ); +} + +// Ranges and Domains +// For-loops and arrays both use ranges and domains to +// define an index set that can be iterated over. +// Ranges are single dimensional +// Domains can be multi-dimensional and can +// represent indices of different types as well. +// They are first-class citizen types, and can be assigned into variables +var range1to10: range = 1..10; // 1, 2, 3, ..., 10 +var range2to11 = 2..11; // 2, 3, 4, ..., 11 +var rangeThistoThat: range = thisInt..thatInt; // using variables +var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices + +// Ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; +// 1, 2, 3, 4, 5, ... +// Note: the range(boundedType= ... ) is only +// necessary if we explicitly type the variable + +var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 + +// Ranges can be strided using the 'by' operator. +var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 +// Note: the range(stridable=true) is only +// necessary if we explicitly type the variable + +// Use by to create a reverse range +var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 + +// The end point of a range can be determined using the count (#) operator +var rangeCount: range = -5..#12; // range from -5 to 6 + +// Can mix operators +var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5 +writeln( rangeCountBy ); + +// Can query properties of the range +// Print the first index, last index, number of indices, +// stride, and ask if 2 is include in the range +writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, + rangeCountBy.stride, rangeCountBy.member( 2 ) ) ); + +for i in rangeCountBy{ + write( i, if i == rangeCountBy.last then "\n" else ", " ); +} + +// Rectangular domains are defined using the same range syntax +// However they are required to be bounded (unlike ranges) +var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; +var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges +var thirdDim: range = 1..16; +var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable + +// Can iterate over the indices as tuples +for idx in twoDimensions do + write( idx , ", "); +writeln( ); + +// or can deconstruct the tuple +for (x,y) in twoDimensions { + write( "(", x, ", ", y, ")", ", " ); +} +writeln( ); + +// Associative domains act like sets +var stringSet: domain(string); // empty set of strings +stringSet += "a"; +stringSet += "b"; +stringSet += "c"; +stringSet += "a"; // Redundant add "a" +stringSet -= "c"; // Remove "c" +writeln( stringSet ); + +// Both ranges and domains can be sliced to produce a range or domain with the +// intersection of indices +var rangeA = 1.. ; // range from 1 to infinity +var rangeB = ..5; // range from negative infinity to 5 +var rangeC = rangeA[rangeB]; // resulting range is 1..5 +writeln( (rangeA, rangeB, rangeC ) ); + +var domainA = {1..10, 5..20}; +var domainB = {-5..5, 1..10}; +var domainC = domainA[domainB]; +writeln( (domainA, domainB, domainC) ); + +// Array are similar to those of other languages. +// Their sizes are defined using domains that represent their indices +var intArray: [1..10] int; +var intArray2: [{1..10}] int; //equivalent + +// Accessed using bracket notation +for i in 1..10 do + intArray[i] = -i; +writeln( intArray ); +// We cannot access intArray[0] because it exists outside +// of the index set, {1..10}, we defined it to have. +// intArray[11] is illegal for the same reason. + +var realDomain: domain(2) = {1..5,1..7}; +var realArray: [realDomain] real; +var realArray2: [1..5,1..7] real; // Equivalent +var realArray3: [{1..5,1..7}] real; // Equivalent + +for i in 1..5 { + for j in realDomain.dim(2) { // Only use the 2nd dimension of the domain + realArray[i,j] = -1.61803 * i + 0.5 * j; // Access using index list + var idx: 2*int = (i,j); // Note: 'index' is a keyword + realArray[idx] = - realArray[(i,j)]; // Index using tuples + } +} + +// Arrays have domains as members that we can iterate over +for idx in realArray.domain { // Again, idx is a 2*int tuple + realArray[idx] = 1 / realArray[idx[1],idx[2]]; // Access by tuple and list +} + +writeln( realArray ); + +// Can also iterate over the values of an array +var rSum: real = 0; +for value in realArray { + rSum += value; // Read a value + value = rSum; // Write a value +} +writeln( rSum, "\n", realArray ); + +// Using associative domains we can create associative arrays (dictionaries) +var dictDomain: domain(string) = { "one", "two" }; +var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; +dict["three"] = 3; +for key in dictDomain do writeln( dict[key] ); + +// Arrays can be assigned to each other in different ways +var thisArray : [{0..5}] int = [0,1,2,3,4,5]; +var thatArray : [{0..5}] int; + +// Simply assign one to the other. +// This copies thisArray into thatArray, instead of just creating a reference. +// Modifying thisArray does not also modify thatArray. +thatArray = thisArray; +thatArray[1] = -1; +writeln( (thisArray, thatArray) ); + +// Assign a slice one array to a slice (of the same size) of the other. +thatArray[{4..5}] = thisArray[{1..2}]; +writeln( (thisArray, thatArray) ); + +// Operation can also be promoted to work on arrays. +var thisPlusThat = thisArray + thatArray; +writeln( thisPlusThat ); + +// Arrays and loops can also be expressions, where loop +// body's expression is the result of each iteration. +var arrayFromLoop = for i in 1..10 do i; +writeln( arrayFromLoop ); + +// An expression can result in nothing, +// such as when filtering with an if-expression +var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i; + +writeln( arrayFromLoop ); + +// Or could be written with a bracket notation +// Note: this syntax uses the 'forall' parallel concept discussed later. +var evensOrFivesAgain = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; + +// Or over the values of the array +arrayFromLoop = [ value in arrayFromLoop ] value + 1; + +// Note: this notation can get somewhat tricky. For example: +// evensOrFives = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; +// would break. +// The reasons for this are explained in depth when discussing zipped iterators. + +// Chapel procedures have similar syntax to other languages functions. +proc fibonacci( n : int ) : int { + if ( n <= 1 ) then return n; + return fibonacci( n-1 ) + fibonacci( n-2 ); +} + +// Input parameters can be untyped (a generic procedure) +proc doublePrint( thing ): void { + write( thing, " ", thing, "\n"); +} + +// Return type can be inferred (as long as the compiler can figure it out) +proc addThree( n ) { + return n + 3; +} + +doublePrint( addThree( fibonacci( 20 ) ) ); + +// Can also take 'unlimited' number of parameters +proc maxOf( x ...?k ) { + // x refers to a tuple of one type, with k elements + var maximum = x[1]; + for i in 2..k do maximum = if (maximum < x[i]) then x[i] else maximum; + return maximum; +} +writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); + +// The ? operator is called the query operator, and is used to take +// undetermined values (like tuple or array sizes, and generic types). + +// Taking arrays as parameters. +// The query operator is used to determine the domain of A. +// This is important to define the return type (if you wanted to) +proc invertArray( A: [?D] int ): [D] int{ + for a in A do a = -a; + return A; +} + +writeln( invertArray( intArray ) ); + +// Procedures can have default parameter values, and +// the parameters can be named in the call, even out of order +proc defaultsProc( x: int, y: real = 1.2634 ): (int,real){ + return (x,y); +} + +writeln( defaultsProc( 10 ) ); +writeln( defaultsProc( x=11 ) ); +writeln( defaultsProc( x=12, y=5.432 ) ); +writeln( defaultsProc( y=9.876, x=13 ) ); + +// Intent modifiers on the arguments convey how +// those arguments are passed to the procedure +// in: copy arg in, but not out +// out: copy arg out, but not in +// inout: copy arg in, copy arg out +// ref: pass arg by reference +proc intentsProc( in inarg, out outarg, inout inoutarg, ref refarg ){ + writeln( "Inside Before: ", (inarg, outarg, inoutarg, refarg) ); + inarg = inarg + 100; + outarg = outarg + 100; + inoutarg = inoutarg + 100; + refarg = refarg + 100; + writeln( "Inside After: ", (inarg, outarg, inoutarg, refarg) ); +} + +var inVar: int = 1; +var outVar: int = 2; +var inoutVar: int = 3; +var refVar: int = 4; +writeln( "Outside Before: ", (inVar, outVar, inoutVar, refVar) ); +intentsProc( inVar, outVar, inoutVar, refVar ); +writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); + +// Similarly we can define intents on the return type +// refElement returns a reference to an element of array +proc refElement( array : [?D] ?T, idx ) ref : T { + return array[ idx ]; // returns a reference to +} + +var myChangingArray : [1..5] int = [1,2,3,4,5]; +writeln( myChangingArray ); +// Store reference to element in ref variable +ref refToElem = refElement( myChangingArray, 5 ); +writeln( refToElem ); +refToElem = -2; // modify reference which modifies actual value in array +writeln( refToElem ); +writeln( myChangingArray ); +// This makes more practical sense for class methods where references to +// elements in a data-structure are returned via a method or iterator + +// We can query the type of arguments to generic procedures +// Here we define a procedure that takes two arguments of +// the same type, yet we don't define what that type is. +proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { + select( valueType ){ + when int do writeln( arg1, " and ", arg2, " are ints" ); + when real do writeln( arg1, " and ", arg2, " are reals" ); + otherwise writeln( arg1, " and ", arg2, " are somethings!" ); + } +} + +genericProc( 1, 2 ); +genericProc( 1.2, 2.3 ); +genericProc( 1.0+2.0i, 3.0+4.0i ); + +// We can also enforce a form of polymorphism with the 'where' clause +// This allows the compiler to decide which function to use. +// Note: that means that all information needs to be known at compile-time. +// The param modifier on the arg is used to enforce this constraint. +proc whereProc( param N : int ): void + where ( N > 0 ) { + writeln( "N is greater than 0" ); +} + +proc whereProc( param N : int ): void + where ( N < 0 ) { + writeln( "N is less than 0" ); +} + +whereProc( 10 ); +whereProc( -1 ); +// whereProc( 0 ) would result in a compiler error because there +// are no functions that satisfy the where clause's condition. +// We could have defined a whereProc without a where clause that would then have +// served as a catch all for all the other cases (of which there is only one). + +// Operator definitions are through procedures as well. +// We can define the unary operators: +// + - ! ~ +// and the binary operators: +// + - * / % ** == <= >= < > << >> & | ˆ by +// += -= *= /= %= **= &= |= ˆ= <<= >>= <=> + +// Boolean exclusive or operator +proc ^( left : bool, right : bool ): bool { + return (left || right) && !( left && right ); +} + +writeln( true ^ true ); +writeln( false ^ true ); +writeln( true ^ false ); +writeln( false ^ false ); + +// Define a * operator on any two types that returns a tuple of those types +proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ + return (left, right ); +} + +writeln( 1 * "a" ); // Uses our * operator +writeln( 1 * 2 ); // Uses the default * operator + +/* +Note: You could break everything if you get careless with your overloads. +This here will break everything. Don't do it. +proc +( left: int, right: int ): int{ + return left - right; +} +*/ + +// Iterators are a sisters to the procedure, and almost +// everything about procedures also applies to iterators +// However, instead of returning a single value, +// iterators yield many values to a loop. +// This is useful when a complicated set or order of iterations is needed but +// allows the code defining the iterations to be separate from the loop body. +iter oddsThenEvens( N: int ): int { + for i in 1..N by 2 do + yield i; // yield values instead of returning. + for i in 2..N by 2 do + yield i; +} + +for i in oddsThenEvens( 10 ) do write( i, ", " ); +writeln( ); + +// Iterators can also yield conditionally, the result of which can be nothing +iter absolutelyNothing( N ): int { + for i in 1..N { + if ( N < i ) { // Always false + yield i; // Yield statement never happens + } + } +} + +for i in absolutelyNothing( 10 ){ + writeln( "Woa there! absolutelyNothing yielded ", i ); +} + +// We can zipper together two or more iterators (who have the same number +// of iterations) using zip() to create a single zipped iterator, where each +// iteration of the zipped iterator yields a tuple of one value yielded +// from each iterator. + // Ranges have implicit iterators +for (positive, negative) in zip( 1..5, -5..-1) do + writeln( (positive, negative) ); + +// Zipper iteration is quite important in the assignment of arrays, +// slices of arrays, and array/loop expressions. +var fromThatArray : [1..#5] int = [1,2,3,4,5]; +var toThisArray : [100..#5] int; + +// The operation +toThisArray = fromThatArray; +// is produced through +for (i,j) in zip( toThisArray.domain, fromThatArray.domain) { + toThisArray[ i ] = fromThatArray[ j ]; +} + +toThisArray = [ j in -100..#5 ] j; +writeln( toThisArray ); +// is produced through +for (i, j) in zip( toThisArray.domain, -100..#5 ){ + toThisArray[i] = j; +} +writeln( toThisArray ); + +// This is all very important in understanding why the statement +// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; +// exhibits a runtime error. +// Even though the domain of the array and the loop-expression are +// the same size, the body of the expression can be thought of as an iterator. +// Because iterators can yield nothing, that iterator yields a different number +// of things than the domain of the array or loop, which is not allowed. + +// Classes are similar to those in C++ and Java. +// They currently lack privatization +class MyClass { + // Member variables + var memberInt : int; + var memberBool : bool = true; + + // Classes have default constructors that don't need to be coded (see below) + // Our explicitly defined constructor + proc MyClass( val : real ){ + this.memberInt = ceil( val ): int; + } + + // Our explicitly defined destructor + proc ~MyClass( ){ + writeln( "MyClass Destructor called ", (this.memberInt, this.memberBool) ); + } + + // Class methods + proc setMemberInt( val: int ){ + this.memberInt = val; + } + + proc setMemberBool( val: bool ){ + this.memberBool = val; + } + + proc getMemberInt( ): int{ + return this.memberInt; + } + + proc getMemberBool( ): bool { + return this.memberBool; + } + +} + +// Construct using default constructor, using default values +var myObject = new MyClass( 10 ); + myObject = new MyClass( memberInt = 10 ); // Equivalent +writeln( myObject.getMemberInt( ) ); +// ... using our values +var myDiffObject = new MyClass( -1, true ); + myDiffObject = new MyClass( memberInt = -1, + memberBool = true ); // Equivalent +writeln( myDiffObject ); + +// Construct using written constructor +var myOtherObject = new MyClass( 1.95 ); + myOtherObject = new MyClass( val = 1.95 ); // Equivalent +writeln( myOtherObject.getMemberInt( ) ); + +// We can define an operator on our class as well but +// the definition has to be outside the class definition +proc +( A : MyClass, B : MyClass) : MyClass { + return new MyClass( memberInt = A.getMemberInt( ) + B.getMemberInt( ), + memberBool = A.getMemberBool( ) || B.getMemberBool( ) ); +} + +var plusObject = myObject + myDiffObject; +writeln( plusObject ); + +// Destruction +delete myObject; +delete myDiffObject; +delete myOtherObject; +delete plusObject; + +// Classes can inherit from one or more parent classes +class MyChildClass : MyClass { + var memberComplex: complex; +} + +// Generic Classes +class GenericClass { + type classType; + var classDomain: domain(1); + var classArray: [classDomain] classType; + + // Explicit constructor + proc GenericClass( type classType, elements : int ){ + this.classDomain = {1..#elements}; + } + + // Copy constructor + // Note: We still have to put the type as an argument, but we can + // default to the type of the other object using the query (?) operator + // Further, we can take advantage of this to allow our copy constructor + // to copy classes of different types and cast on the fly + proc GenericClass( other : GenericClass(?otherType), + type classType = otherType ) { + this.classDomain = other.classDomain; + // Copy and cast + for idx in this.classDomain do this[ idx ] = other[ idx ] : classType; + } + + // Define bracket notation on a GenericClass + // object so it can behave like a normal array + // i.e. objVar[ i ] or objVar( i ) + proc this( i : int ) ref : classType { + return this.classArray[ i ]; + } + + // Define an implicit iterator for the class + // to yield values from the array to a loop + // i.e. for i in objVar do .... + iter these( ) ref : classType { + for i in this.classDomain do + yield this[i]; + } + +} + +var realList = new GenericClass( real, 10 ); +// We can assign to the member array of the object using the bracket +// notation that we defined ( proc this( i: int ){ ... } ) +for i in realList.classDomain do realList[i] = i + 1.0; +// We can iterate over the values in our list with the iterator +// we defined ( iter these( ){ ... } ) +for value in realList do write( value, ", " ); +writeln( ); + +// Make a copy of realList using the copy constructor +var copyList = new GenericClass( realList ); +for value in copyList do write( value, ", " ); +writeln( ); + +// Make a copy of realList and change the type, also using the copy constructor +var copyNewTypeList = new GenericClass( realList, int ); +for value in copyNewTypeList do write( value, ", " ); +writeln( ); + +// Modules are Chapel's way of managing name spaces. +// The files containing these modules do not need to be named after the modules +// (as in Java), but files implicitly name modules. +// In this case, this file implicitly names the 'learnchapel' module + +module OurModule { + // We can use modules inside of other modules. + use Time; // Time is one of the standard modules. + + // We'll use this procedure in the parallelism section. + proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } + } + + // Submodules of OurModule + // It is possible to create arbitrarily deep module nests. + module ChildModule { + proc foo(){ + writeln( "ChildModule.foo()"); + } + } + + module SiblingModule { + proc foo(){ + writeln( "SiblingModule.foo()" ); + } + } +} // end OurModule + +// Using OurModule also uses all the modules it uses. +// Since OurModule uses Time, we also use time. +use OurModule; + +// At this point we have not used ChildModule or SiblingModule so their symbols +// (i.e. foo ) are not available to us. +// However, the module names are, and we can explicitly call foo() through them. +SiblingModule.foo(); // Calls SiblingModule.foo() + +// Super explicit naming. +OurModule.ChildModule.foo(); // Calls ChildModule.foo() + +use ChildModule; +foo(); // Less explicit call on ChildModule.foo() + +// We can declare a main procedure +// Note: all the code above main still gets executed. +proc main(){ + + // Parallelism + // In other languages, parallelism is typically done with + // complicated libraries and strange class structure hierarchies. + // Chapel has it baked right into the language. + + // A begin statement will spin the body of that statement off + // into one new task. + // A sync statement will ensure that the progress of the main + // task will not progress until the children have synced back up. + sync { + begin { // Start of new task's body + var a = 0; + for i in 1..1000 do a += 1; + writeln( "Done: ", a); + } // End of new tasks body + writeln( "spun off a task!"); + } + writeln( "Back together" ); + + proc printFibb( n: int ){ + writeln( "fibonacci(",n,") = ", fibonacci( n ) ); + } + + // A cobegin statement will spin each statement of the body into one new task + cobegin { + printFibb( 20 ); // new task + printFibb( 10 ); // new task + printFibb( 5 ); // new task + { + // This is a nested statement body and thus is a single statement + // to the parent statement and is executed by a single task + writeln( "this gets" ); + writeln( "executed as" ); + writeln( "a whole" ); + } + } + // Notice here that the prints from each statement may happen in any order. + + // Coforall loop will create a new task for EACH iteration + var num_tasks = 10; // Number of tasks we want + coforall taskID in 1..#num_tasks { + writeln( "Hello from task# ", taskID ); + } + // Again we see that prints happen in any order. + // NOTE! coforall should be used only for creating tasks! + // Using it to iterating over a structure is very a bad idea! + + // forall loops are another parallel loop, but only create a smaller number + // of tasks, specifically --dataParTasksPerLocale=number of task + forall i in 1..100 { + write( i, ", "); + } + writeln( ); + // Here we see that there are sections that are in order, followed by + // a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). + // This is because each task is taking on a chunk of the range 1..10 + // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens + // in parallel. + // Your results may depend on your machine and configuration + + // For both the forall and coforall loops, the execution of the + // parent task will not continue until all the children sync up. + + // forall loops are particularly useful for parallel iteration over arrays. + // Lets run an experiment to see how much faster a parallel loop is + use Time; // Import the Time module to use Timer objects + var timer: Timer; + var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into + + // Serial Experiment + timer.start( ); // Start timer + for (x,y) in myBigArray.domain { // Serial iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); // Clear timer for parallel loop + + // Parallel Experiment + timer.start( ); // start timer + forall (x,y) in myBigArray.domain { // Parallel iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); + // You may have noticed that (depending on how many cores you have) + // that the parallel loop went faster than the serial loop + + // The bracket style loop-expression described + // much earlier implicitly uses a forall loop. + [ val in myBigArray ] val = 1 / val; // Parallel operation + + // Atomic variables, common to many languages, are ones whose operations + // occur uninterrupted. Multiple threads can both modify atomic variables + // and can know that their values are safe. + // Chapel atomic variables can be of type bool, int, uint, and real. + var uranium: atomic int; + uranium.write( 238 ); // atomically write a variable + writeln( uranium.read() ); // atomically read a variable + + // operations are described as functions, you could define your own operators. + uranium.sub( 3 ); // atomically subtract a variable + writeln( uranium.read() ); + + var replaceWith = 239; + var was = uranium.exchange( replaceWith ); + writeln( "uranium was ", was, " but is now ", replaceWith ); + + var isEqualTo = 235; + if ( uranium.compareExchange( isEqualTo, replaceWith ) ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); + } else { + writeln( "uranium was not equal to ", isEqualTo, + " so value stays the same... whatever it was" ); + } + + sync { + begin { // Reader task + writeln( "Reader: waiting for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); + } + + begin { // Writer task + writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); + countdown( 3 ); + uranium.write( isEqualTo ); + } + } + + // sync vars have two states: empty and full. + // If you read an empty variable or write a full variable, you are waited + // until the variable is full or empty again + var someSyncVar$: sync int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + var read_sync = someSyncVar$; + writeln( "Reader: value is ", read_sync ); + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSyncVar$ = 123; + } + } + + // single vars can only be written once. A read on an unwritten single results + // in a wait, but when the variable has a value it can be read indefinitely + var someSingleVar$: single int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + for i in 1..5 { + var read_single = someSingleVar$; + writeln( "Reader: iteration ", i,", and the value is ", read_single ); + } + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSingleVar$ = 5; // first and only write ever. + } + } + + // Heres an example of using atomics and a synch variable to create a + // count-down mutex (also known as a multiplexer) + var count: atomic int; // our counter + var lock$: sync bool; // the mutex lock + + count.write( 2 ); // Only let two tasks in at a time. + lock$.writeXF( true ); // Set lock$ to full (unlocked) + // Note: The value doesnt actually matter, just the state + // (full:unlocked / empty:locked) + // Also, writeXF() fills (F) the sync var regardless of its state (X) + + coforall task in 1..#5 { // Generate tasks + // Create a barrier + do{ + lock$; // Read lock$ (wait) + }while ( count.read() < 1 ); // Keep waiting until a spot opens up + + count.sub(1); // decrement the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + + // Actual 'work' + writeln( "Task #", task, " doing work." ); + sleep( 2 ); + + count.add( 1 ); // Increment the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + } + + // we can define the operations + * & | ^ && || min max minloc maxloc + // over an entire array using scans and reductions + // Reductions apply the operation over the entire array and + // result in a single value + var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; + var sumOfValues = + reduce listOfValues; + var maxValue = max reduce listOfValues; // 'max' give just max value + + // 'maxloc' gives max value and index of the max value + // Note: We have to zip the array and domain together with the zip iterator + var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + listOfValues.domain); + + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); + + // Scans apply the operation incrementally and return an array of the + // value of the operation at that index as it progressed through the + // array from array.domain.low to array.domain.high + var runningSumOfValues = + scan listOfValues; + var maxScan = max scan listOfValues; + writeln( runningSumOfValues ); + writeln( maxScan ); +} // end main() +``` + +Who is this tutorial for? +------------------------- + +This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [module documentation](http://chapel.cray.com/docs/latest/) for more details. + +Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. + +### What this tutorial is lacking: + + * Exposition of the [standard modules](http://chapel.cray.com/docs/latest/modules/modules.html) + * Multiple Locales (distributed memory system) + * Records + * Parallel iterators + +Your input, questions, and discoveries are important to the developers! +----------------------------------------------------------------------- + +The Chapel language is still in-development (version 1.12.0), so there are occasional hiccups with performance and language features. +The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. +Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). + +If you're really interested in the development of the compiler or contributing to the project, +[check out the master Github repository](https://github.com/chapel-lang/chapel). +It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). + +Installing the Compiler +----------------------- + +Chapel can be built and installed on your average 'nix machine (and cygwin). +[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) +and it's as easy as + + 1. `tar -xvf chapel-1.12.0.tar.gz` + 2. `cd chapel-1.12.0` + 3. `make` + 4. `source util/setchplenv.bash # or .sh or .csh or .fish` + +You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so it's suggested that you drop that command in a script that will get executed on startup (like .bashrc). + +Chapel is easily installed with Brew for OS X + + 1. `brew update` + 2. `brew install chapel` + +Compiling Code +-------------- + +Builds like other compilers: + +`chpl myFile.chpl -o myExe` + +Notable arguments: + + * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. + * `--set <Symbol Name>=<Value>`: set config param `<Symbol Name>` to `<Value>` at compile-time. + * `--main-module <Module Name>`: use the main() procedure found in the module `<Module Name>` as the executable's main. + * `--module-dir <Directory>`: includes `<Directory>` in the module search path. diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown index 8e671936..d74f77cf 100644 --- a/clojure-macros.html.markdown +++ b/clojure-macros.html.markdown @@ -109,7 +109,7 @@ You'll want to be familiar with Clojure. Make sure you understand everything in (list x) ; -> (4) ;; It's typical to use helper functions with macros. Let's create a few to -;; help us support a (dumb) inline arithmatic syntax +;; help us support a (dumb) inline arithmetic syntax (declare inline-2-helper) (defn clean-arg [arg] (if (seq? arg) @@ -142,11 +142,11 @@ You'll want to be familiar with Clojure. Make sure you understand everything in ### Further Reading -Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/) +Writing Macros from [Clojure for the Brave and True](http://www.braveclojure.com/) [http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) -Official docs +Official docs [http://clojure.org/macros](http://clojure.org/macros) -When to use macros? +When to use macros? [http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) diff --git a/clojure.html.markdown b/clojure.html.markdown index 7917ab08..58e835c9 100644 --- a/clojure.html.markdown +++ b/clojure.html.markdown @@ -22,7 +22,7 @@ and often automatically. ; Clojure is written in "forms", which are just ; lists of things inside parentheses, separated by whitespace. ; -; The clojure reader assumes that the first thing is a +; The clojure reader assumes that the first thing is a ; function or macro to call, and the rest are arguments. ; The first call in a file should be ns, to set the namespace @@ -264,6 +264,31 @@ keymap ; => {:a 1, :b 2, :c 3} (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Use the threading macros (-> and ->>) to express transformations of +; data more clearly. + +; The "Thread-first" macro (->) inserts into each form the result of +; the previous, as the first argument (second item) +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; This expression could be written as: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; The double arrow does the same thing, but inserts the result of +; each line at the *end* of the form. This is useful for collection +; operations in particular: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 4c080bc6..89a29677 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -6,8 +6,8 @@ contributors: filename: coffeescript.coffee --- -CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime. -As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime. +CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime. +As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime. See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript. @@ -54,35 +54,35 @@ math = square: square cube: (x) -> x * square x #=> var math = { -# "root": Math.sqrt, -# "square": square, -# "cube": function(x) { return x * square(x); } -#} +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; # Splats: race = (winner, runners...) -> print winner, runners #=>race = function() { -# var runners, winner; -# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; -# return print(winner, runners); -#}; +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; # Existence: alert "I knew it!" if elvis? #=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } # Array comprehensions: -cubes = (math.cube num for num in list) +cubes = (math.cube num for num in list) #=>cubes = (function() { -# var _i, _len, _results; -# _results = []; +# var _i, _len, _results; +# _results = []; # for (_i = 0, _len = list.length; _i < _len; _i++) { -# num = list[_i]; -# _results.push(math.cube(num)); -# } -# return _results; -# })(); +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); foods = ['broccoli', 'spinach', 'chocolate'] eat food for food in foods when food isnt 'chocolate' diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown new file mode 100644 index 00000000..d49ad254 --- /dev/null +++ b/coldfusion.html.markdown @@ -0,0 +1,330 @@ +--- +language: coldfusion +filename: learncoldfusion.cfm +contributors: + - ["Wayne Boka", "http://wboka.github.io"] + - ["Kevin Morris", "https://twitter.com/kevinmorris"] +--- + +ColdFusion is a scripting language for web development. +[Read more here.](http://www.adobe.com/products/coldfusion-family.html) + +### CFML +_**C**old**F**usion **M**arkup **L**anguage_ +ColdFusion started as a tag-based language. Almost all functionality is available using tags. + +```html +<em>HTML tags have been provided for output readability</em> + +<!--- Comments start with "<!---" and end with "--->" ---> +<!--- + Comments can + also + span + multiple lines +---> + +<!--- CFML tags have a similar format to HTML tags. ---> +<h1>Simple Variables</h1> +<!--- Variable Declaration: Variables are loosely typed, similar to javascript ---> +<p>Set <b>myVariable</b> to "myValue"</p> +<cfset myVariable = "myValue" /> +<p>Set <b>myNumber</b> to 3.14</p> +<cfset myNumber = 3.14 /> + +<!--- Displaying simple data ---> +<!--- Use <cfoutput> for simple values such as strings, numbers, and expressions ---> +<p>Display <b>myVariable</b>: <cfoutput>#myVariable#</cfoutput></p><!--- myValue ---> +<p>Display <b>myNumber</b>: <cfoutput>#myNumber#</cfoutput></p><!--- 3.14 ---> + +<hr /> + +<h1>Complex Variables</h1> +<!--- Declaring complex variables ---> +<!--- Declaring an array of 1 dimension: literal or bracket notation ---> +<p>Set <b>myArray1</b> to an array of 1 dimension using literal or bracket notation</p> +<cfset myArray1 = [] /> +<!--- Declaring an array of 1 dimension: function notation ---> +<p>Set <b>myArray2</b> to an array of 1 dimension using function notation</p> +<cfset myArray2 = ArrayNew(1) /> + +<!--- Outputting complex variables ---> +<p>Contents of <b>myArray1</b></p> +<cfdump var="#myArray1#" /> <!--- An empty array object ---> +<p>Contents of <b>myArray2</b></p> +<cfdump var="#myArray2#" /> <!--- An empty array object ---> + +<!--- Operators ---> +<!--- Arithmetic ---> +<h1>Operators</h1> +<h2>Arithmetic</h2> +<p>1 + 1 = <cfoutput>#1 + 1#</cfoutput></p> +<p>10 - 7 = <cfoutput>#10 - 7#<br /></cfoutput></p> +<p>15 * 10 = <cfoutput>#15 * 10#<br /></cfoutput></p> +<p>100 / 5 = <cfoutput>#100 / 5#<br /></cfoutput></p> +<p>120 % 5 = <cfoutput>#120 % 5#<br /></cfoutput></p> +<p>120 mod 5 = <cfoutput>#120 mod 5#<br /></cfoutput></p> + +<hr /> + +<!--- Comparison ---> +<h2>Comparison</h2> +<h3>Standard Notation</h3> +<p>Is 1 eq 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 neq 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 gt 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 lt 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 gte 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 lte 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<h3>Alternative Notation</h3> +<p>Is 1 == 1? <cfoutput>#1 eq 1#</cfoutput></p> +<p>Is 15 != 1? <cfoutput>#15 neq 1#</cfoutput></p> +<p>Is 10 > 8? <cfoutput>#10 gt 8#</cfoutput></p> +<p>Is 1 < 2? <cfoutput>#1 lt 2#</cfoutput></p> +<p>Is 10 >= 5? <cfoutput>#10 gte 5#</cfoutput></p> +<p>Is 1 <= 5? <cfoutput>#1 lte 5#</cfoutput></p> + +<hr /> + +<!--- Control Structures ---> +<h1>Control Structures</h1> + +<cfset myCondition = "Test" /> + +<p>Condition to test for: "<cfoutput>#myCondition#</cfoutput>"</p> + +<cfif myCondition eq "Test"> + <cfoutput>#myCondition#. We're testing.</cfoutput> +<cfelseif myCondition eq "Production"> + <cfoutput>#myCondition#. Proceed Carefully!!!</cfoutput> +<cfelse> + myCondition is unknown +</cfif> + +<hr /> + +<!--- Loops ---> +<h1>Loops</h1> +<h2>For Loop</h2> +<cfloop from="0" to="10" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<h2>For Each Loop (Complex Variables)</h2> + +<p>Set <b>myArray3</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray3 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray3#" index="i"> + <p>Index equals <cfoutput>#i#</cfoutput></p> +</cfloop> + +<p>Set <b>myArray4</b> to ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]</p> + +<cfset myArray4 = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"] /> + +<cfloop array="#myArray4#" index="s"> + <p>Index equals <cfoutput>#s#</cfoutput></p> +</cfloop> + +<h2>Switch Statement</h2> + +<p>Set <b>myArray5</b> to [5, 15, 99, 45, 100]</p> + +<cfset myArray5 = [5, 15, 99, 45, 100] /> + +<cfloop array="#myArray5#" index="i"> + <cfswitch expression="#i#"> + <cfcase value="5,15,45" delimiters=","> + <p><cfoutput>#i#</cfoutput> is a multiple of 5.</p> + </cfcase> + <cfcase value="99"> + <p><cfoutput>#i#</cfoutput> is ninety-nine.</p> + </cfcase> + <cfdefaultcase> + <p><cfoutput>#i#</cfoutput> is not 5, 15, 45, or 99.</p> + </cfdefaultcase> + </cfswitch> +</cfloop> + +<hr /> + +<h1>Converting types</h1> + +<style> + table.table th, table.table td { + border: 1px solid #000000; + padding: 2px; + } + + table.table th { + background-color: #CCCCCC; + } +</style> + +<table class="table" cellspacing="0"> + <thead> + <tr> + <th>Value</th> + <th>As Boolean</th> + <th>As number</th> + <th>As date-time</th> + <th>As string</th> + </tr> + </thead> + <tbody> + <tr> + <th>"Yes"</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>"No"</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>TRUE</th> + <td>TRUE</td> + <td>1</td> + <td>Error</td> + <td>"Yes"</td> + </tr> + <tr> + <th>FALSE</th> + <td>FALSE</td> + <td>0</td> + <td>Error</td> + <td>"No"</td> + </tr> + <tr> + <th>Number</th> + <td>True if Number is not 0; False otherwise.</td> + <td>Number</td> + <td>See "Date-time values" earlier in this chapter.</td> + <td>String representation of the number (for example, "8").</td> + </tr> + <tr> + <th>String</th> + <td>If "Yes", True <br>If "No", False <br>If it can be converted to 0, False <br>If it can be converted to any other number, True</td> + <td>If it represents a number (for example, "1,000" or "12.36E-12"), it is converted to the corresponding number.</td> + <td>If it represents a date-time (see next column), it is converted to the numeric value of the corresponding date-time object. <br>If it is an ODBC date, time, or timestamp (for example "{ts '2001-06-14 11:30:13'}", or if it is expressed in a standard U.S. date or time format, including the use of full or abbreviated month names, it is converted to the corresponding date-time value. <br>Days of the week or unusual punctuation result in an error. <br>Dashes, forward-slashes, and spaces are generally allowed.</td> + <td>String</td> + </tr> + <tr> + <th>Date</th> + <td>Error</td> + <td>The numeric value of the date-time object.</td> + <td>Date</td> + <td>An ODBC timestamp.</td> + </tr> + </tbody> +</table> + +<hr /> + +<h1>Components</h1> + +<em>Code for reference (Functions must return something to support IE)</em> + +<pre> +<cfcomponent> + <cfset this.hello = "Hello" /> + <cfset this.world = "world" /> + + <cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> + </cffunction> + + <cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> + </cffunction> + + <cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> + </cffunction> + + <cffunction name="getHello"> + <cfreturn this.hello /> + </cffunction> + + <cffunction name="getWorld"> + <cfreturn this.world /> + </cffunction> +</cfcomponent> +</pre> + +<cfset this.hello = "Hello" /> +<cfset this.world = "world" /> + +<cffunction name="sayHello"> + <cfreturn this.hello & ", " & this.world & "!" /> +</cffunction> + +<cffunction name="setHello"> + <cfargument name="newHello" type="string" required="true" /> + + <cfset this.hello = arguments.newHello /> + + <cfreturn true /> +</cffunction> + +<cffunction name="setWorld"> + <cfargument name="newWorld" type="string" required="true" /> + + <cfset this.world = arguments.newWorld /> + + <cfreturn true /> +</cffunction> + +<cffunction name="getHello"> + <cfreturn this.hello /> +</cffunction> + +<cffunction name="getWorld"> + <cfreturn this.world /> +</cffunction> + + +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +<b>setHello("Hola")</b> +<cfoutput><p>#setHello("Hola")#</p></cfoutput> +<b>setWorld("mundo")</b> +<cfoutput><p>#setWorld("mundo")#</p></cfoutput> +<b>sayHello()</b> +<cfoutput><p>#sayHello()#</p></cfoutput> +<b>getHello()</b> +<cfoutput><p>#getHello()#</p></cfoutput> +<b>getWorld()</b> +<cfoutput><p>#getWorld()#</p></cfoutput> +``` + +### CFScript +_**C**old**F**usion **S**cript_ +In recent years, the ColdFusion language has added script syntax to mirror tag functionality. When using an up-to-date CF server, almost all functionality is available using scrypt syntax. + +## Further Reading + +The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. + +1. [Coldfusion Reference From Adobe](https://helpx.adobe.com/coldfusion/cfml-reference/topics.html) +2. [Open Source Documentation](http://cfdocs.org/) diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index c4ecb5e8..63183c1e 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -175,7 +175,8 @@ nil ; for false - and the empty list :age 5)) *rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) -(dog-p *rover*) ; => t ;; ewww) +(dog-p *rover*) ; => true #| -p signifies "predicate". It's used to + check if *rover* is an instance of dog. |# (dog-name *rover*) ; => "rover" ;; Dog-p, make-dog, and dog-name are all created by defstruct! @@ -260,7 +261,7 @@ nil ; for false - and the empty list (defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) :adjustable t :fill-pointer t)) - + *adjvec* ; => #(1 2 3) ;; Adding new element: @@ -573,13 +574,15 @@ nil ; for false - and the empty list "While `condition` is true, `body` is executed. `condition` is tested prior to each execution of `body`" - (let ((block-name (gensym))) + (let ((block-name (gensym)) (done (gensym))) `(tagbody + ,block-name (unless ,condition - (go ,block-name)) + (go ,done)) (progn ,@body) - ,block-name))) + (go ,block-name) + ,done))) ;; Let's look at the high-level version of this: diff --git a/compojure.html.markdown b/compojure.html.markdown index 36a8d123..32181e26 100644 --- a/compojure.html.markdown +++ b/compojure.html.markdown @@ -155,8 +155,8 @@ Now, your handlers may utilize query parameters: ```clojure (defroutes myapp (GET "/posts" req - (let [title (get (:params req) "title") - author (get (:params req) "author")] + (let [title (get (:params req) :title) + author (get (:params req) :author)] (str "Title: " title ", Author: " author)))) ``` @@ -165,8 +165,8 @@ Or, for POST and PUT requests, form parameters as well ```clojure (defroutes myapp (POST "/posts" req - (let [title (get (:params req) "title") - author (get (:params req) "author")] + (let [title (get (:params req) :title) + author (get (:params req) :author)] (str "Title: " title ", Author: " author)))) ``` diff --git a/cs-cz/python3.html.markdown b/cs-cz/python3.html.markdown new file mode 100644 index 00000000..6d2fd1eb --- /dev/null +++ b/cs-cz/python3.html.markdown @@ -0,0 +1,636 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Tomáš Bedřich", "http://tbedrich.cz"] +translators: + - ["Tomáš Bedřich", "http://tbedrich.cz"] +filename: learnpython3.py +lang: cs-cz +--- + +Python byl vytvořen Guidem Van Rossum v raných 90. letech. Nyní je jedním z nejpopulárnějších jazyků. +Zamiloval jsem si Python pro jeho syntaktickou čistotu - je to vlastně spustitelný pseudokód. + +Vaše zpětná vazba je vítána! Můžete mě zastihnout na [@louiedinh](http://twitter.com/louiedinh) nebo louiedinh [at] [email od googlu] anglicky, +autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo ja [at] tbedrich.cz + +Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/python/). + +```python + +# Jednořádkový komentář začíná křížkem + +""" Víceřádkové komentáře používají tři uvozovky nebo apostrofy + a jsou často využívány jako dokumentační komentáře k metodám +""" + +#################################################### +## 1. Primitivní datové typy a operátory +#################################################### + +# Čísla +3 # => 3 + +# Aritmetické operace se chovají běžným způsobem +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Až na dělení, které vrací desetinné číslo +35 / 5 # => 7.0 + +# Při celočíselném dělení je desetinná část oříznuta (pro kladná i záporná čísla) +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # celočíselně dělit lze i desetinným číslem +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Pokud použijete desetinné číslo, výsledek je jím také +3 * 2.0 # => 6.0 + +# Modulo +7 % 3 # => 1 + +# Mocnění (x na y-tou) +2**4 # => 16 + +# Pro vynucení priority použijte závorky +(1 + 3) * 2 # => 8 + +# Logické hodnoty +True +False + +# Negace se provádí pomocí not +not True # => False +not False # => True + +# Logické operátory +# U operátorů záleží na velikosti písmen +True and False # => False +False or True # => True + +# Používání logických operátorů s čísly +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Rovnost je == +1 == 1 # => True +2 == 1 # => False + +# Nerovnost je != +1 != 1 # => False +2 != 1 # => True + +# Další porovnání +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porovnání se dají řetězit! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + + +# Řetězce používají " nebo ' a mohou obsahovat UTF8 znaky +"Toto je řetězec." +'Toto je také řetězec.' + +# Řetězce se také dají sčítat, ale nepoužívejte to +"Hello " + "world!" # => "Hello world!" +# Dají se spojovat i bez '+' +"Hello " "world!" # => "Hello world!" + +# Řetězec lze považovat za seznam znaků +"Toto je řetězec"[0] # => 'T' + +# .format lze použít ke skládání řetězců +"{} mohou být {}".format("řetězce", "skládány") + +# Formátovací argumenty můžete opakovat +"{0} {1} stříkaček stříkalo přes {0} {1} střech".format("tři sta třicet tři", "stříbrných") +# => "tři sta třicet tři stříbrných stříkaček stříkalo přes tři sta třicet tři stříbrných střech" + +# Pokud nechcete počítat, můžete použít pojmenované argumenty +"{jmeno} si dal {jidlo}".format(jmeno="Franta", jidlo="guláš") # => "Franta si dal guláš" + +# Pokud zároveň potřebujete podporovat Python 2.5 a nižší, můžete použít starší způsob formátování +"%s se dají %s jako v %s" % ("řetězce", "skládat", "jazyce C") + + +# None je objekt (jinde NULL, nil, ...) +None # => None + +# Pokud porovnáváte něco s None, nepoužívejte operátor rovnosti "==", +# použijte raději operátor "is", který testuje identitu. +"něco" is None # => False +None is None # => True + +# None, 0, a prázdný řetězec/seznam/slovník se vyhodnotí jako False +# Vše ostatní se vyhodnotí jako True +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False + + +#################################################### +## 2. Proměnné a kolekce +#################################################### + +# Python má funkci print +print("Jsem 3. Python 3.") + +# Proměnné není třeba deklarovat před přiřazením +# Konvence je používat male_pismo_s_podtrzitky +nazev_promenne = 5 +nazev_promenne # => 5 +# Názvy proměnných mohou obsahovat i UTF8 znaky +název_proměnné = 5 + +# Přístup k předtím nepoužité proměnné vyvolá výjimku +# Odchytávání vyjímek - viz další kapitola +neznama_promenna # Vyhodí NameError + +# Seznam se používá pro ukládání sekvencí +sez = [] +# Lze ho rovnou naplnit +jiny_seznam = [4, 5, 6] + +# Na konec seznamu se přidává pomocí append +sez.append(1) # sez je nyní [1] +sez.append(2) # sez je nyní [1, 2] +sez.append(4) # sez je nyní [1, 2, 4] +sez.append(3) # sez je nyní [1, 2, 4, 3] +# Z konce se odebírá se pomocí pop +sez.pop() # => 3 a sez je nyní [1, 2, 4] +# Vložme trojku zpátky +sez.append(3) # sez je nyní znovu [1, 2, 4, 3] + +# Přístup k prvkům funguje jako v poli +sez[0] # => 1 +# Mínus počítá odzadu (-1 je poslední prvek) +sez[-1] # => 3 + +# Přístup mimo seznam vyhodí IndexError +sez[4] # Vyhodí IndexError + +# Pomocí řezů lze ze seznamu vybírat různé intervaly +# (pro matematiky: jedná se o uzavřený/otevřený interval) +sez[1:3] # => [2, 4] +# Odříznutí začátku +sez[2:] # => [4, 3] +# Odříznutí konce +sez[:3] # => [1, 2, 4] +# Vybrání každého druhého prvku +sez[::2] # =>[1, 4] +# Vrácení seznamu v opačném pořadí +sez[::-1] # => [3, 4, 2, 1] +# Lze použít jakoukoliv kombinaci parametrů pro vytvoření složitějšího řezu +# sez[zacatek:konec:krok] + +# Odebírat prvky ze seznamu lze pomocí del +del sez[2] # sez je nyní [1, 2, 3] + +# Seznamy můžete sčítat +# Hodnoty sez a jiny_seznam přitom nejsou změněny +sez + jiny_seznam # => [1, 2, 3, 4, 5, 6] + +# Spojit seznamy lze pomocí extend +sez.extend(jiny_seznam) # sez je nyní [1, 2, 3, 4, 5, 6] + +# Kontrola, jestli prvek v seznamu existuje, se provádí pomocí in +1 in sez # => True + +# Délku seznamu lze zjistit pomocí len +len(sez) # => 6 + + +# N-tice je jako seznam, ale je neměnná +ntice = (1, 2, 3) +ntice[0] # => 1 +ntice[0] = 3 # Vyhodí TypeError + +# S n-ticemi lze dělat většinu operací, jako se seznamy +len(ntice) # => 3 +ntice + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +ntice[:2] # => (1, 2) +2 in ntice # => True + +# N-tice (nebo seznamy) lze rozbalit do proměnných jedním přiřazením +a, b, c = (1, 2, 3) # a je nyní 1, b je nyní 2 a c je nyní 3 +# N-tice jsou vytvářeny automaticky, když vynecháte závorky +d, e, f = 4, 5, 6 +# Prohození proměnných je tak velmi snadné +e, d = d, e # d je nyní 5, e je nyní 4 + + +# Slovníky ukládají klíče a hodnoty +prazdny_slovnik = {} +# Lze je také rovnou naplnit +slovnik = {"jedna": 1, "dva": 2, "tři": 3} + +# Přistupovat k hodnotám lze pomocí [] +slovnik["jedna"] # => 1 + +# Všechny klíče dostaneme pomocí keys() jako iterovatelný objekt. Nyní ještě +# potřebujeme obalit volání v list(), abychom dostali seznam. To rozebereme +# později. Pozor, že jakékoliv pořadí klíčů není garantováno - může být různé. +list(slovnik.keys()) # => ["dva", "jedna", "tři"] + +# Všechny hodnoty opět jako iterovatelný objekt získáme pomocí values(). Opět +# tedy potřebujeme použít list(), abychom dostali seznam. Stejně jako +# v předchozím případě, pořadí není garantováno a může být různé +list(slovnik.values()) # => [3, 2, 1] + +# Operátorem in se lze dotázat na přítomnost klíče +"jedna" in slovnik # => True +1 in slovnik # => False + +# Přístup k neexistujícímu klíči vyhodí KeyError +slovnik["čtyři"] # Vyhodí KeyError + +# Metoda get() funguje podobně jako [], ale vrátí None místo vyhození KeyError +slovnik.get("jedna") # => 1 +slovnik.get("čtyři") # => None +# Metodě get() lze předat i výchozí hodnotu místo None +slovnik.get("jedna", 4) # => 1 +slovnik.get("čtyři", 4) # => 4 + +# metoda setdefault() vloží prvek do slovníku pouze pokud tam takový klíč není +slovnik.setdefault("pět", 5) # slovnik["pět"] je nastaven na 5 +slovnik.setdefault("pět", 6) # slovnik["pět"] je pořád 5 + +# Přidání nové hodnoty do slovníku +slovnik["čtyři"] = 4 +# Hromadně aktualizovat nebo přidat data lze pomocí update(), parametrem je opět slovník +slovnik.update({"čtyři": 4}) # slovnik je nyní {"jedna": 1, "dva": 2, "tři": 3, "čtyři": 4, "pět": 5} + +# Odebírat ze slovníku dle klíče lze pomocí del +del slovnik["jedna"] # odebere klíč "jedna" ze slovnik + + +# Množiny ukládají ... překvapivě množiny +prazdna_mnozina = set() +# Také je lze rovnou naplnit. A ano, budou se vám plést se slovníky. Bohužel. +mnozina = {1, 1, 2, 2, 3, 4} # mnozina je nyní {1, 2, 3, 4} + +# Přidání položky do množiny +mnozina.add(5) # mnozina je nyní {1, 2, 3, 4, 5} + +# Průnik lze udělat pomocí operátoru & +jina_mnozina = {3, 4, 5, 6} +mnozina & jina_mnozina # => {3, 4, 5} + +# Sjednocení pomocí operátoru | +mnozina | jina_mnozina # => {1, 2, 3, 4, 5, 6} + +# Rozdíl pomocí operátoru - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Operátorem in se lze dotázat na přítomnost prvku v množině +2 in mnozina # => True +9 in mnozina # => False + + +#################################################### +## 3. Řízení toku programu, cykly +#################################################### + +# Vytvořme si proměnnou +promenna = 5 + +# Takto vypadá podmínka. Na odsazení v Pythonu záleží! +# Vypíše "proměnná je menší než 10". +if promenna > 10: + print("proměnná je velká jak Rusko") +elif promenna < 10: # Část elif je nepovinná + print("proměnná je menší než 10") +else: # Část else je také nepovinná + print("proměnná je právě 10") + + +""" +Smyčka for umí iterovat (nejen) přes seznamy +vypíše: + pes je savec + kočka je savec + myš je savec +""" +for zvire in ["pes", "kočka", "myš"]: + # Můžete použít formát pro složení řetězce + print("{} je savec".format(zvire)) + +""" +range(cislo) vrací iterovatelný objekt čísel od 0 do cislo +vypíše: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +range(spodni_limit, horni_limit) vrací iterovatelný objekt čísel mezi limity +vypíše: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +Smyčka while se opakuje, dokud je podmínka splněna. +vypíše: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Zkrácený zápis x = x + 1. Pozor, žádné x++ neexisuje. + + +# Výjimky lze ošetřit pomocí bloku try/except(/else/finally) +try: + # Pro vyhození výjimky použijte raise + raise IndexError("Přistoupil jste k neexistujícímu prvku v seznamu.") +except IndexError as e: + print("Nastala chyba: {}".format(e)) + # Vypíše: Nastala chyba: Přistoupil jste k neexistujícímu prvku v seznamu. +except (TypeError, NameError): # Více výjimek lze zachytit najednou + pass # Pass znamená nedělej nic - nepříliš vhodný způsob ošetření chyb +else: # Volitelný blok else musí být až za bloky except + print("OK!") # Vypíše OK! v případě, že nenastala žádná výjimka +finally: # Blok finally se spustí nakonec za všech okolností + print("Uvolníme zdroje, uzavřeme soubory...") + +# Místo try/finally lze použít with pro automatické uvolnění zdrojů +with open("soubor.txt") as soubor: + for radka in soubor: + print(radka) + +# Python běžně používá iterovatelné objekty, což je prakticky cokoliv, +# co lze považovat za sekvenci. Například to, co vrací metoda range(), +# nebo otevřený soubor, jsou iterovatelné objekty. + +slovnik = {"jedna": 1, "dva": 2, "tři": 3} +iterovatelny_objekt = slovnik.keys() +print(iterovatelny_objekt) # => dict_keys(["jedna", "dva", "tři"]). Toto je iterovatelný objekt. + +# Můžeme použít cyklus for na jeho projití +for klic in iterovatelny_objekt: + print(klic) # vypíše postupně: jedna, dva, tři + +# Ale nelze přistupovat k prvkům pod jejich indexem +iterovatelny_objekt[1] # Vyhodí TypeError + +# Všechny položky iterovatelného objektu lze získat jako seznam pomocí list() +list(slovnik.keys()) # => ["jedna", "dva", "tři"] + +# Z iterovatelného objektu lze vytvořit iterátor +iterator = iter(iterovatelny_objekt) + +# Iterátor je objekt, který si pamatuje stav v rámci svého iterovatelného objektu +# Další hodnotu dostaneme voláním next() +next(iterator) # => "jedna" + +# Iterátor si udržuje svůj stav v mezi jednotlivými voláními next() +next(iterator) # => "dva" +next(iterator) # => "tři" + +# Jakmile interátor vrátí všechna svá data, vyhodí výjimku StopIteration +next(iterator) # Vyhodí StopIteration + + +#################################################### +## 4. Funkce +#################################################### + +# Pro vytvoření nové funkce použijte klíčové slovo def +def secist(x, y): + print("x je {} a y je {}".format(x, y)) + return x + y # Hodnoty se vrací pomocí return + +# Volání funkce s parametry +secist(5, 6) # => Vypíše "x je 5 a y je 6" a vrátí 11 + +# Jiný způsob, jak volat funkci, je použít pojmenované argumenty +secist(y=6, x=5) # Pojmenované argumenty můžete předat v libovolném pořadí + +# Lze definovat funkce s proměnným počtem (pozičních) argumentů +def vrat_argumenty(*argumenty): + return argumenty + +vrat_argumenty(1, 2, 3) # => (1, 2, 3) + +# Lze definovat také funkce s proměnným počtem pojmenovaných argumentů +def vrat_pojmenovane_argumenty(**pojmenovane_argumenty): + return pojmenovane_argumenty + +vrat_pojmenovane_argumenty(kdo="se bojí", nesmi="do lesa") +# => {"kdo": "se bojí", "nesmi": "do lesa"} + + +# Pokud chcete, lze použít obojí najednou +# Konvence je používat pro tyto účely názvy *args a **kwargs +def vypis_vse(*args, **kwargs): + print(args, kwargs) # print() vypíše všechny své parametry oddělené mezerou + +vypis_vse(1, 2, a=3, b=4) # Vypíše: (1, 2) {"a": 3, "b": 4} + +# * nebo ** lze použít k rozbalení N-tic nebo slovníků! +ntice = (1, 2, 3, 4) +slovnik = {"a": 3, "b": 4} +vypis_vse(ntice) # Vyhodnotí se jako vypis_vse((1, 2, 3, 4)) – jeden parametr, N-tice +vypis_vse(*ntice) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4) +vypis_vse(**slovnik) # Vyhodnotí se jako vypis_vse(a=3, b=4) +vypis_vse(*ntice, **slovnik) # Vyhodnotí se jako vypis_vse(1, 2, 3, 4, a=3, b=4) + + +# Viditelnost proměnných - vytvořme si globální proměnnou x +x = 5 + +def nastavX(cislo): + # Lokální proměnná x překryje globální x + x = cislo # => 43 + print(x) # => 43 + +def nastavGlobalniX(cislo): + global x + print(x) # => 5 + x = cislo # Nastaví globální proměnnou x na 6 + print(x) # => 6 + +nastavX(43) +nastavGlobalniX(6) + + +# Funkce jsou first-class objekty +def vyrobit_scitacku(pricitane_cislo): + def scitacka(x): + return x + pricitane_cislo + return scitacka + +pricist_10 = vyrobit_scitacku(10) +pricist_10(3) # => 13 + +# Klíčové slovo lambda vytvoří anonymní funkci +(lambda parametr: parametr > 2)(3) # => True + +# Lze použít funkce map() a filter() z funkcionálního programování +map(pricist_10, [1, 2, 3]) +# => <map object at 0x0123467> - iterovatelný objekt s obsahem: [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) +# => <filter object at 0x0123467> - iterovatelný objekt s obsahem: [6, 7] + +# S generátorovou notací lze dosáhnout podobných výsledků, ale vrací seznam +[pricist_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +# Generátorová notace funguje i pro slovníky +{x: x**2 for x in range(1, 5)} # => {1: 1, 2: 4, 3: 9, 4: 16} +# A také pro množiny +{pismeno for pismeno in "abeceda"} # => {"d", "a", "c", "e", "b"} + + +#################################################### +## 5. Třídy +#################################################### + +# Třída Clovek je potomkem (dědí od) třídy object +class Clovek(object): + + # Atribut třídy - je sdílený všemi instancemi + druh = "H. sapiens" + + # Toto je kostruktor. Je volán, když vytváříme instanci třídy. Dvě + # podtržítka na začátku a na konci značí, že se jedná o atribut nebo + # objekt využívaný Pythonem ke speciálním účelům, ale můžete sami + # definovat jeho chování. Metody jako __init__, __str__, __repr__ + # a další se nazývají "magické metody". Nikdy nepoužívejte toto + # speciální pojmenování pro běžné metody. + def __init__(self, jmeno): + # Přiřazení parametru do atributu instance jmeno + self.jmeno = jmeno + + # Metoda instance - všechny metody instance mají "self" jako první parametr + def rekni(self, hlaska): + return "{jmeno}: {hlaska}".format(jmeno=self.jmeno, hlaska=hlaska) + + # Metoda třídy - sdílená všemi instancemi + # Dostává jako první parametr třídu, na které je volána + @classmethod + def vrat_druh(cls): + return cls.druh + + # Statická metoda je volána bez reference na třídu nebo instanci + @staticmethod + def odkaslej_si(): + return "*ehm*" + + +# Vytvoření instance +d = Clovek(jmeno="David") +a = Clovek("Adéla") +print(d.rekni("ahoj")) # Vypíše: "David: ahoj" +print(a.rekni("nazdar")) # Vypíše: "Adéla: nazdar" + +# Volání třídní metody +d.vrat_druh() # => "H. sapiens" + +# Změna atributu třídy +Clovek.druh = "H. neanderthalensis" +d.vrat_druh() # => "H. neanderthalensis" +a.vrat_druh() # => "H. neanderthalensis" + +# Volání statické metody +Clovek.odkaslej_si() # => "*ehm*" + + +#################################################### +## 6. Moduly +#################################################### + +# Lze importovat moduly +import math +print(math.sqrt(16)) # => 4 + +# Lze také importovat pouze vybrané funkce z modulu +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Můžete také importovat všechny funkce z modulu, ale radši to nedělejte +from math import * + +# Můžete si přejmenovat modul při jeho importu +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Modul v Pythonu není nic jiného, než obyčejný soubor .py +# Můžete si napsat vlastní a prostě ho importovat podle jména +from muj_modul import moje_funkce # Nyní vyhodí ImportError - muj_modul neexistuje + +# Funkcí dir() lze zjistit, co modul obsahuje +import math +dir(math) + + +#################################################### +## 7. Pokročilé +#################################################### + +# Generátory jsou funkce, které místo return obsahují yield +def nasobicka_2(sekvence): + for i in sekvence: + yield 2 * i + +# Generátor generuje hodnoty postupně, jak jsou potřeba. Místo toho, aby vrátil +# celou sekvenci s prvky vynásobenými dvěma, provádí jeden výpočet v každé iteraci. +# To znamená, že čísla větší než 15 se v metodě nasobicka_2 vůbec nezpracují. + +# Funkce range() je také generátor - vytváření seznamu 900000000 prvků by zabralo +# hodně času i paměti, proto se místo toho čísla generují postupně. + +for i in nasobicka_2(range(900000000)): + print(i) # Vypíše čísla 0, 2, 4, 6, 8, ... 30 + if i >= 30: + break + + +# Dekorátory jsou funkce, které se používají pro obalení jiné funkce, čímž mohou +# přidávat nebo měnit její stávající chování. Funkci dostávají jako parametr +# a typicky místo ní vrací jinou, která uvnitř volá tu původní. + +def nekolikrat(puvodni_funkce): + def opakovaci_funkce(*args, **kwargs): + for i in range(3): + puvodni_funkce(*args, **kwargs) + + return opakovaci_funkce + + +@nekolikrat +def pozdrav(jmeno): + print("Měj se {}!".format(jmeno)) + +pozdrav("Pepo") # Vypíše 3x: Měj se Pepo! +``` + +## Co dál? + +Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] +(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. diff --git a/csharp.html.markdown b/csharp.html.markdown index 47dd9683..dfdd98de 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -5,6 +5,9 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] + - ["Jo Pearce", "http://github.com/jdpearce"] + - ["Chris Zimmerman", "https://github.com/chriszimmerman"] filename: LearnCSharp.cs --- @@ -18,29 +21,36 @@ C# is an elegant and type-safe object-oriented language that enables developers Multi-line comments look like this */ /// <summary> -/// This is an XML documentation comment +/// This is an XML documentation comment which can be used to generate external +/// documentation or provide context help within an IDE /// </summary> +//public void MethodOrClassOrOtherWithParsableHelp() {} -// Specify namespaces application will be using +// Specify the namespaces this source code will be using +// The namespaces below are all part of the standard .NET Framework Class Libary using System; using System.Collections.Generic; -using System.Data.Entity; using System.Dynamic; using System.Linq; -using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; using System.IO; -// defines scope to organize code into "packages" -namespace Learning +// But this one is not: +using System.Data.Entity; +// In order to be able to use it, you need to add a dll reference +// This can be done with the NuGet package manager: `Install-Package EntityFramework` + +// Namespaces define scope to organize code into "packages" or "modules" +// Using this code from another source file: using Learning.CSharp; +namespace Learning.CSharp { // Each .cs file should at least contain a class with the same name as the file // you're allowed to do otherwise, but shouldn't for sanity. public class LearnCSharp { // BASIC SYNTAX - skip to INTERESTING FEATURES if you have used Java or C++ before - public static void Syntax() + public static void Syntax() { // Use Console.WriteLine to print lines Console.WriteLine("Hello World"); @@ -125,7 +135,7 @@ on a new line! ""Wow!"", the masses cried"; // Use const or read-only to make a variable immutable // const values are calculated at compile time - const int HOURS_I_WORK_PER_WEEK = 9001; + const int HoursWorkPerWeek = 9001; /////////////////////////////////////////////////// // Data Structures @@ -151,7 +161,7 @@ on a new line! ""Wow!"", the masses cried"; // List<datatype> <var name> = new List<datatype>(); List<int> intList = new List<int>(); List<string> stringList = new List<string>(); - List<int> z = new List<int> { 9000, 1000, 1337 }; // intialize + List<int> z = new List<int> { 9000, 1000, 1337 }; // initialize // The <> are for generics - Check out the cool stuff section // Lists don't default to a value; @@ -228,7 +238,8 @@ on a new line! ""Wow!"", the masses cried"; // Ternary operators // A simple if/else can be written as follows // <condition> ? <true> : <false> - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While loop int fooWhile = 0; @@ -242,8 +253,15 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //Iterated 100 times, fooDoWhile 0->99 + // Start iteration 100 times, fooDoWhile 0->99 + if (false) + continue; // skip the current iteration + fooDoWhile++; + + if (fooDoWhile == 50) + break; // breaks from the loop completely + } while (fooDoWhile < 100); //for loop structure => for(<start_statement>; <conditional>; <step>) @@ -301,7 +319,7 @@ on a new line! ""Wow!"", the masses cried"; // Converting data // Convert String To Integer - // this will throw an Exception on failure + // this will throw a FormatException on failure int.Parse("123");//returns an integer version of "123" // try parse will default to type default on failure @@ -315,6 +333,11 @@ on a new line! ""Wow!"", the masses cried"; Convert.ToString(123); // or tryInt.ToString(); + + // Casting + // Cast decimal 15 to a int + // and then implicitly cast to long + long x = (int) 15M; } /////////////////////////////////////// @@ -350,11 +373,11 @@ on a new line! ""Wow!"", the masses cried"; // // INTERESTING FEATURES // - + // DEFAULT METHOD SIGNATURES public // Visibility - static // Allows for direct call on class without object + static // Allows for direct call on class without object int // Return Type, MethodSignatures( int maxCount, // First variable, expects an int @@ -362,21 +385,26 @@ on a new line! ""Wow!"", the masses cried"; int another = 3, params string[] otherParams // captures all other parameters passed to method ) - { + { return -1; } // Methods can have the same name, as long as the signature is unique - public static void MethodSignatures(string maxCount) + // A method that differs only in return type is not unique + public static void MethodSignatures( + ref int maxCount, // Pass by reference + out int count) { + //the argument passed in as 'count' will hold the value of 15 outside of this function + count = 15; // out param must be assigned before control leaves the method } // GENERICS // The classes for TKey and TValue is specified by the user calling this function. // This method emulates the SetDefault of Python public static TValue SetDefault<TKey, TValue>( - IDictionary<TKey, TValue> dictionary, - TKey key, + IDictionary<TKey, TValue> dictionary, + TKey key, TValue defaultItem) { TValue result; @@ -385,7 +413,7 @@ on a new line! ""Wow!"", the masses cried"; return result; } - // You can narrow down the objects that are passed in + // You can narrow down the objects that are passed in public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int> { // We can iterate, since T is a IEnumerable @@ -393,12 +421,52 @@ on a new line! ""Wow!"", the masses cried"; // Item is an int Console.WriteLine(item.ToString()); } + + // YIELD + // Usage of the "yield" keyword indicates that the method it appears in is an Iterator + // (this means you can use it in a foreach loop) + public static IEnumerable<int> YieldCounter(int limit = 10) + { + for (var i = 0; i < limit; i++) + yield return i; + } + + // which you would call like this : + public static void PrintYieldCounterToConsole() + { + foreach (var counter in YieldCounter()) + Console.WriteLine(counter); + } + + // you can use more than one "yield return" in a method + public static IEnumerable<int> ManyYieldCounter() + { + yield return 0; + yield return 1; + yield return 2; + yield return 3; + } + + // you can also use "yield break" to stop the Iterator + // this method would only return half of the values from 0 to limit. + public static IEnumerable<int> YieldCounterWithBreak(int limit = 10) + { + for (var i = 0; i < limit; i++) + { + if (i > limit/2) yield break; + yield return i; + } + } public static void OtherInterestingFeatures() { // OPTIONAL PARAMETERS MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); - MethodSignatures(3, another: 3); // explicity set a parameter, skipping optional ones + MethodSignatures(3, another: 3); // explicitly set a parameter, skipping optional ones + + // BY REF AND OUT PARAMETERS + int maxCount = 0, count; // ref params must have value + MethodSignatures(ref maxCount, out count); // EXTENSION METHODS int i = 3; @@ -414,6 +482,9 @@ on a new line! ""Wow!"", the masses cried"; // ?? is syntactic sugar for specifying default value (coalesce) // in case variable is null int notNullable = nullable ?? 0; // 0 + + // ?. is an operator for null-propagation - a shorthand way of checking for null + nullable?.Print(); // Use the Print() extension method if nullable isn't null // IMPLICITLY TYPED VARIABLES - you can let the compiler work out what the type is: var magic = "magic is a string, at compile time, so you still get type safety"; @@ -421,13 +492,13 @@ on a new line! ""Wow!"", the masses cried"; // GENERICS // - var phonebook = new Dictionary<string, string>() { + var phonebook = new Dictionary<string, string>() { {"Sarah", "212 555 5555"} // Add some entries to the phone book }; // Calling SETDEFAULT defined as a generic above Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // No Phone - // nb, you don't need to specify the TKey and TValue since they can be + // nb, you don't need to specify the TKey and TValue since they can be // derived implicitly Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 @@ -435,28 +506,53 @@ on a new line! ""Wow!"", the masses cried"; Func<int, int> square = (x) => x * x; // Last T item is the return value Console.WriteLine(square(3)); // 9 + // ERROR HANDLING - coping with an uncertain world + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // will no longer execute because CreateWithGears throws an exception + string some = ""; + if (true) some = null; + some.ToLower(); // throws a NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // catch all other exceptions + { + throw new ApplicationException("It hit the fan", ex); + // throw; // A rethrow that preserves the callstack + } + // catch { } // catch-all without capturing the Exception + finally + { + // executes after try or catch + } + // DISPOSABLE RESOURCES MANAGEMENT - let you handle unmanaged resources easily. // Most of objects that access unmanaged resources (file handle, device contexts, etc.) - // implement the IDisposable interface. The using statement takes care of + // implement the IDisposable interface. The using statement takes care of // cleaning those IDisposable objects for you. using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("Nothing suspicious here"); // At the end of scope, resources will be released. // Even if an exception is thrown. - } + } // PARALLEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", "http://www.shaunmccarthy.com" }; var responses = new Dictionary<string, string>(); - + // Will spin up separate threads for each request, and join on them // before going to the next step! - Parallel.ForEach(websites, + Parallel.ForEach(websites, new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads website => { @@ -480,7 +576,7 @@ on a new line! ""Wow!"", the masses cried"; (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); Console.WriteLine(student.Introduce("Beth")); - // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of + // IQUERYABLE<T> - almost all collections implement this, which gives you a lot of // very useful Map / Filter / Reduce style methods var bikes = new List<Bicycle>(); bikes.Sort(); // Sorts the array @@ -502,8 +598,8 @@ on a new line! ""Wow!"", the masses cried"; // ASPARALLEL // And this is where things get wicked - combines linq and parallel operations var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // this will happen in parallel! Threads will automagically be spun up and the - // results divvied amongst them! Amazing for large datasets when you have lots of + // this will happen in parallel! Threads will automagically be spun up and the + // results divvied amongst them! Amazing for large datasets when you have lots of // cores // LINQ - maps a store to IQueryable<T> objects, with delayed execution @@ -521,9 +617,9 @@ on a new line! ""Wow!"", the masses cried"; .Select(b => b.Name); // still no query run // Now the query runs, but opens a reader, so only populates are you iterate through - foreach (string bike in query) + foreach (string bike in query) Console.WriteLine(result); - + } @@ -556,7 +652,7 @@ on a new line! ""Wow!"", the masses cried"; { return _cadence; } - set // set - define a method to set a proprety + set // set - define a method to set a property { _cadence = value; // Value is the value passed in to the setter } @@ -575,7 +671,7 @@ on a new line! ""Wow!"", the masses cried"; private set; // You can set modifiers on the get/set methods } - int _speed; // Everything is private by default: Only accessible from within this class. + int _speed; // Everything is private by default: Only accessible from within this class. // can also use keyword private public string Name { get; set; } @@ -595,10 +691,26 @@ on a new line! ""Wow!"", the masses cried"; public BikeBrand Brand; // After declaring an enum type, we can declare the field of this type + // Decorate an enum with the FlagsAttribute to indicate that multiple values can be switched on + [Flags] // Any class derived from Attribute can be used to decorate types, methods, parameters etc + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // need to set the values manually! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // Usage: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // Before .NET 4: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + // Static members belong to the type itself rather then specific object. // You can access them without a reference to any object: // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); - static public int BicyclesCreated = 0; + public static int BicyclesCreated { get; set; } // readonly values are set at run time // they can only be assigned upon declaration or in a constructor @@ -606,7 +718,7 @@ on a new line! ""Wow!"", the masses cried"; // Constructors are a way of creating classes // This is a default constructor - public Bicycle() + public Bicycle() { this.Gear = 1; // you can access members of the object with the keyword this Cadence = 50; // but you don't always need it @@ -618,13 +730,13 @@ on a new line! ""Wow!"", the masses cried"; // This is a specified constructor (it contains arguments) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, BikeBrand brand) + string name, bool hasCardsInSpokes, BikeBrand brand) : base() // calls base first { - Gear = startGear; + Gear = startGear; Cadence = startCadence; _speed = startSpeed; - Name = name; + Name = name; _hasCardsInSpokes = hasCardsInSpokes; Brand = brand; } @@ -680,9 +792,9 @@ on a new line! ""Wow!"", the masses cried"; // It's also possible to define custom Indexers on objects. // All though this is not entirely useful in this example, you - // could do bicycle[0] which yields "chris" to get the first passenger or + // could do bicycle[0] which returns "chris" to get the first passenger or // bicycle[1] = "lisa" to set the passenger. (of this apparent quattrocycle) - private string[] passengers = { "chris", "phil", "darren", "regina" } + private string[] passengers = { "chris", "phil", "darren", "regina" }; public string this[int i] { @@ -691,7 +803,7 @@ on a new line! ""Wow!"", the masses cried"; } set { - return passengers[i] = value; + passengers[i] = value; } } @@ -737,10 +849,17 @@ on a new line! ""Wow!"", the masses cried"; } set { - throw new ArgumentException("You can't change gears on a PennyFarthing"); + throw new InvalidOperationException("You can't change gears on a PennyFarthing"); } } + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // Oops, can't do this! + return penny; + } + public override string Info() { string result = "PennyFarthing bicycle "; @@ -760,7 +879,8 @@ on a new line! ""Wow!"", the masses cried"; bool Broken { get; } // interfaces can contain properties as well as methods & events } - // Class can inherit only one other class, but can implement any amount of interfaces + // Class can inherit only one other class, but can implement any amount of interfaces, however + // the base class name must be the first in the list and all interfaces follow class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -780,11 +900,11 @@ on a new line! ""Wow!"", the masses cried"; } /// <summary> - /// Used to connect to DB for LinqToSql example. + /// Used to connect to DB for LinqToSql example. /// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional) /// http://msdn.microsoft.com/en-us/data/jj193542.aspx /// </summary> - public class BikeRepository : DbSet + public class BikeRepository : DbContext { public BikeRepository() : base() @@ -793,18 +913,49 @@ on a new line! ""Wow!"", the masses cried"; public DbSet<Bicycle> Bikes { get; set; } } + + // Classes can be split across multiple .cs files + // A1.cs + public partial class A + { + public static void A1() + { + Console.WriteLine("Method A1 in class A"); + } + } + + // A2.cs + public partial class A + { + public static void A2() + { + Console.WriteLine("Method A2 in class A"); + } + } + + // Program using the partial class "A" + public class Program + { + static void Main() + { + A.A1(); + A.A2(); + } + } } // End Namespace ``` ## Topics Not Covered - * Flags * Attributes - * Static properties - * Exceptions, Abstraction - * ASP.NET (Web Forms/MVC/WebMatrix) - * Winforms - * Windows Presentation Foundation (WPF) + * async/await, pragma directives + * Web Development + * ASP.NET MVC & WebApi (new) + * ASP.NET Web Forms (old) + * WebMatrix (tool) + * Desktop Development + * Windows Presentation Foundation (WPF) (new) + * Winforms (old) ## Further Reading @@ -817,7 +968,4 @@ on a new line! ""Wow!"", the masses cried"; * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - - - -[C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) + * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) diff --git a/css.html.markdown b/css.html.markdown index e058d691..8ee4f4b9 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -4,25 +4,22 @@ contributors: - ["Mohammad Valipour", "https://github.com/mvalipour"] - ["Marco Scannadinari", "https://github.com/marcoms"] - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] + - ["Tyler Mumford", "https://tylermumford.com"] filename: learncss.css --- -In early days of web there was no visual elements, just pure text. But with the -further development of browser fully visual web pages also became common. -CSS is the standard language that exists to keep the separation between -the content (HTML) and the look-and-feel of web pages. +Web pages are built with HTML, which specifies the content of a page. CSS (Cascading Style Sheets) is a separate language which specifies a page's **appearance**. -In short, what CSS does is to provide a syntax that enables you to target -different elements on an HTML page and assign different visual properties to them. +CSS code is made of static *rules*. Each rule takes one or more *selectors* and gives specific *values* to a number of visual *properties*. Those properties are then applied to the page elements indicated by the selectors. -Like any other language, CSS has many versions. Here we focus on CSS2.0 -which is not the most recent but the most widely supported and compatible version. +This guide has been written with CSS 2 in mind, which is extended by the new features of CSS 3. -**NOTE:** Because the outcome of CSS is some visual effects, in order to -learn it, you need try all different things in a -CSS playground like [dabblet](http://dabblet.com/). +**NOTE:** Because CSS produces visual results, in order to learn it, you need to try everything in a CSS playground like [dabblet](http://dabblet.com/). The main focus of this article is on the syntax and some general tips. +## Syntax ```css /* comments appear inside slash-asterisk, just like this line! @@ -32,89 +29,103 @@ The main focus of this article is on the syntax and some general tips. ## SELECTORS #################### */ -/* Generally, the primary statement in CSS is very simple */ +/* the selector is used to target an element on a page. */ selector { property: value; /* more properties...*/ } -/* the selector is used to target an element on page. - -You can target all elments on the page using asterisk! */ -* { color:red; } - /* -Given an element like this on the page: +Here is an example element: -<div class='some-class class2' id='someId' attr='value' /> +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> */ -/* you can target it by its name */ -.some-class { } +/* You can target it using one of its CSS classes */ +.class1 { } -/*or by both classes! */ -.some-class.class2 { } +/* or both classes! */ +.class1.class2 { } -/* or by its element name */ +/* or its name */ div { } /* or its id */ -#someId { } +#anID { } -/* or by the fact that it has an attribute! */ +/* or using the fact that it has an attribute! */ [attr] { font-size:smaller; } /* or that the attribute has a specific value */ [attr='value'] { font-size:smaller; } -/* start with a value (CSS3) */ +/* starts with a value (CSS 3) */ [attr^='val'] { font-size:smaller; } -/* or ends with (CSS3) */ +/* or ends with a value (CSS 3) */ [attr$='ue'] { font-size:smaller; } -/* or even contains a value (CSS3) */ -[attr~='lu'] { font-size:smaller; } +/* or contains a value in a space-separated list */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } +/* or contains a value in a dash-separated list, ie, "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } -/* and more importantly you can combine these together -- there shouldn't be -any space between different parts because that makes it to have another -meaning. */ + +/* You can combine different selectors to create a more focused selector. Don't + put spaces between them. */ div.some-class[attr$='ue'] { } -/* you can also select an element based on its parent. */ +/* You can select an element which is a child of another element */ +div.some-parent > .class-name { } + +/* or a descendant of another element. Children are the direct descendants of + their parent element, only one level down the tree. Descendants can be any + level down the tree. */ +div.some-parent .class-name { } + +/* Warning: the same selector without a space has another meaning. + Can you guess what? */ +div.some-parent.class-name { } + +/* You may also select an element based on its adjacent sibling */ +.i-am-just-before + .this-element { } + +/* or any sibling preceding it */ +.i-am-any-element-before ~ .this-element { } -/* an element which is direct child of an element (selected the same way) */ -div.some-parent > .class-name {} +/* There are some selectors called pseudo classes that can be used to select an + element only when it is in a particular state */ -/* or any of its parents in the tree - the following basically means any element that has class "class-name" - and is child of a div with class name "some-parent" IN ANY DEPTH */ -div.some-parent .class-name {} +/* for example, when the cursor hovers over an element */ +selector:hover { } -/* warning: the same selector wihout spaaace has another meaning. - can you say what? */ -div.some-parent.class-name {} +/* or a link has been visited */ +selector:visited { } -/* you also might choose to select an element based on its direct - previous sibling */ -.i-am-before + .this-element { } +/* or hasn't been visited */ +selected:link { } -/* or any sibling before this */ -.i-am-any-before ~ .this-element {} +/* or an element is in focus */ +selected:focus { } -/* There are some pseudo classes that allows you to select an element - based on its page behaviour (rather than page structure) */ +/* any element that is the first child of its parent */ +selector:first-child {} -/* for example for when an element is hovered */ -selector:hover {} +/* any element that is the last child of its parent */ +selector:last-child {} -/* or a visited link */ -selected:visited {} +/* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */ -/* or not visited link */ -selected:link {} +/* matches a virtual first child of the selected element */ +selector::before {} -/* or an input element which is focused */ -selected:focus {} +/* matches a virtual last child of the selected element */ +selector::after {} +/* At appropriate places, an asterisk may be used as a wildcard to select every + element */ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ /* #################### ## PROPERTIES @@ -122,123 +133,122 @@ selected:focus {} selector { - /* Units */ - width: 50%; /* in percent */ - font-size: 2em; /* times current font-size */ - width: 200px; /* in pixels */ - font-size: 20pt; /* in points */ - width: 5cm; /* in centimeters */ - min-width: 50mm; /* in millimeters */ - max-width: 5in; /* in inches. max-(width|height) */ - height: 0.2vh; /* times vertical height of browser viewport (CSS3) */ - width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */ - min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */ - max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */ + /* Units of length can be absolute or relative. */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + max-width: 5in; /* inches */ /* Colors */ - background-color: #F6E; /* in short hex */ - background-color: #F262E2; /* in long hex format */ - background-color: tomato; /* can be a named color */ - background-color: rgb(255, 255, 255); /* in rgb */ - background-color: rgb(10%, 20%, 50%); /* in rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */ - background-color: transparent; /* see thru */ - background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */ - background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */ - + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + color: tomato; /* a named color */ + color: rgb(255, 255, 255); /* as rgb values */ + color: rgb(10%, 20%, 50%); /* as rgb percentages */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 <= a <= 1 */ + color: transparent; /* equivalent to setting the alpha to 0 */ + color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* as hsl percentages with alpha */ - /* Images */ - background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */ + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ /* Fonts */ font-family: Arial; - font-family: "Courier New"; /* if name has spaaace it appears in single or double quotes */ - font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found - browser uses the second font, and so forth */ + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; } - ``` ## Usage -Save any CSS you want in a file with extension `.css`. +Save a CSS stylesheet with the extension `.css`. ```xml -<!-- you need to include the css file in your page's <head>: --> +<!-- You need to include the css file in your page's <head>. This is the + recommended method. Refer to http://stackoverflow.com/questions/8284365 --> <link rel='stylesheet' type='text/css' href='path/to/style.css' /> -<!-- you can also include some CSS inline in your markup. However it is highly -recommended to avoid this. --> +<!-- You can also include some CSS inline in your markup. --> <style> a { color: purple; } </style> -<!-- or directly set CSS properties on the element. -This has to be avoided as much as you can. --> +<!-- Or directly set CSS properties on the element. --> <div style="border: 1px solid red;"> </div> - ``` -## Precedence +## Precedence or Cascade + +An element may be targeted by multiple selectors and may have a property set on it in more than once. In these cases, one of the rules takes precedence over others. Rules with a more specific selector take precedence over a less specific one, and a rule occuring later in the stylesheet overwrites a previous one. -As you noticed an element may be targetted by more than one selector. -and may have a property set on it in more than one. -In these cases, one of the rules takes precedence over others. +This process is called cascading, hence the name Cascading Style Sheets. Given the following CSS: ```css -/*A*/ +/* A */ p.class1[attr='value'] -/*B*/ -p.class1 {} +/* B */ +p.class1 { } -/*C*/ -p.class2 {} +/* C */ +p.class2 { } -/*D*/ -p {} +/* D */ +p { } -/*E*/ +/* E */ p { property: value !important; } - ``` and the following markup: ```xml -<p style='/*F*/ property:value;' class='class1 class2' attr='value'> -</p> +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> ``` -The precedence of style is as followed: -Remember, the precedence is for each **property**, not for the entire block. +The precedence of style is as follows. Remember, the precedence is for each **property**, not for the entire block. -* `E` has the highest precedence because of the keyword `!important`. - It is recommended to avoid this unless it is strictly necessary to use. -* `F` is next, because it is inline style. -* `A` is next, because it is more "specific" than anything else. - more specific = more specifiers. here 3 specifiers: 1 tagname `p` + - class name `class1` + 1 attribute `attr='value'` -* `C` is next. although it has the same specificness as `B` - but it appears last. -* Then is `B` -* and lastly is `D`. +* `E` has the highest precedence because of the keyword `!important`. It is recommended that you avoid its usage. +* `F` is next, because it is an inline style. +* `A` is next, because it is more "specific" than anything else. It has 3 specifiers: The name of the element `p`, its class `class1`, an attribute `attr='value'`. +* `C` is next, even though it has the same specificity as `B`. This is because it appears after `B`. +* `B` is next. +* `D` is the last one. ## Compatibility -Most of the features in CSS2 (and gradually in CSS3) are compatible across -all browsers and devices. But it's always vital to have in mind the compatiblity -of what you use in CSS with your target browsers. +Most of the features in CSS 2 (and many in CSS 3) are available across all browsers and devices. But it's always good practice to check before using a new feature. -[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this. +## Resources -To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. +* [CanIUse](http://caniuse.com) (Detailed compatibility info) +* [Dabblet](http://dabblet.com/) (CSS playground) +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (Tutorials and reference) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (Reference) ## Further Reading * [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) * [QuirksMode CSS](http://www.quirksmode.org/css/) * [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/d.html.markdown b/d.html.markdown new file mode 100644 index 00000000..6f3710ab --- /dev/null +++ b/d.html.markdown @@ -0,0 +1,258 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +```c +// You know what's coming... +module hello; + +import std.stdio; + +// args is optional +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +If you're like me and spend way too much time on the internet, odds are you've heard +about [D](http://dlang.org/). The D programming language is a modern, general-purpose, +multi-paradigm language with support for everything from low-level features to +expressive high-level abstractions. + +D is actively developed by a large group of super-smart people and is spearheaded by +[Walter Bright](https://en.wikipedia.org/wiki/Walter_Bright) and +[Andrei Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu). +With all that out of the way, let's look at some examples! + +```c +import std.stdio; + +void main() { + + // Conditionals and loops work as expected. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // 'auto' can be used for inferring types. + auto n = 1; + + // Numeric literals can use '_' as a digit separator for clarity. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For and while are nice, but in D-land we prefer 'foreach' loops. + // The '..' creates a continuous range, including the first value + // but excluding the last. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // There's also 'foreach_reverse' when you want to loop backwards. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions +are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, +we can use templates to parameterize all of these on both types and values! + +```c +// Here, 'T' is a type parameter. Think '<T>' from C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Use '!' to instantiate a parameterized type. Again, think '<T>'. + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // If there is only one template parameter, we can omit the parentheses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Use alias to create abbreviations for types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// We can create function templates as well! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// Use the ref keyword to ensure pass by reference. That is, even if 'a' and 'b' +// are value types, they will always be passed by reference to 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// With templates, we can also parameterize on values, not just types. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'. + +``` + +Speaking of classes, let's talk about properties for a second. A property +is roughly a function that may act like an lvalue, so we can +have the syntax of POD structures (`structure.x = 7`) with the semantics of +getter and setter methods (`object.setX(7)`)! + +```c +// Consider a class parameterized on types 'T' & 'U'. +class MyClass(T, U) { + T _data; + U _other; +} + +// And "getter" and "setter" methods like so: +class MyClass(T, U) { + T _data; + U _other; + + // Constructors are always named 'this'. + this(T t, U u) { + // This will call the setter methods below. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// And we use them in this manner: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Import the 'stdio' module from the standard library for writing to + // console (imports can be local to a scope). + import std.stdio; + + // Call the getters to fetch the values. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // Call the setters to assign new values. + mc.data = 8; + mc.other = "eight"; + + // Call the getters again to fetch the new values. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` + +With properties, we can add any amount of logic to +our getter and setter methods, and keep the clean syntax of +accessing members directly! + +Other object-oriented goodies at our disposal +include interfaces, abstract classes, +and overriding methods. D does inheritance just like Java: +Extend one class, implement as many interfaces as you please. + +We've seen D's OOP facilities, but let's switch gears. D offers +functional programming with first-class functions, `pure` +functions, and immutable data. In addition, all of your favorite +functional algorithms (map, filter, reduce and friends) can be +found in the wonderful `std.algorithm` module! + +```c +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // We want to print the sum of a list of squares of even ints + // from 1 to 100. Easy! + + // Just pass lambda expressions as template parameters! + // You can pass any old function you like, but lambdas are convenient here. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Notice how we got to build a nice Haskellian pipeline to compute num? +That's thanks to a D innovation know as Uniform Function Call Syntax. +With UFCS, we can choose whether to write a function call as a method +or free function call! Walter wrote a nice article on this +[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +In short, you can call functions whose first parameter +is of some type A on any expression of type A as a method. + +I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! + +```c +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // We want take the square root every number in our array, + // and take advantage of as many cores as we have available. + auto arr = new double[1_000_000]; + + // Use an index, and an array element by reference, + // and just call parallel on the array! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/dart.html.markdown b/dart.html.markdown index 34d1c6a8..fc7b220e 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -81,7 +81,7 @@ example5() { // Where classBody can include instance methods and variables, but also // class methods and variables. class Example6Class { - var example6InstanceVariable = "Example6 instance variable"; + var example6InstanceVariable = "Example6 instance variable"; sayIt() { print(example6InstanceVariable); } @@ -92,7 +92,7 @@ example6() { // Class methods and variables are declared with "static" terms. class Example7Class { - static var example7ClassVariable = "Example7 class variable"; + static var example7ClassVariable = "Example7 class variable"; static sayItFromClass() { print(example7ClassVariable); } @@ -111,7 +111,7 @@ example7() { // by default. But arrays and maps are not. They can be made constant by // declaring them "const". var example8A = const ["Example8 const array"], - example8M = const {"someKey": "Example8 const map"}; + example8M = const {"someKey": "Example8 const map"}; example8() { print(example8A[0]); print(example8M["someKey"]); @@ -245,7 +245,7 @@ example18() { // Strings with triple single-quotes or triple double-quotes span // multiple lines and include line delimiters. example19() { - print('''Example19 <a href="etc"> + print('''Example19 <a href="etc"> Example19 Don't can't I'm Etc Example19 </a>'''); } @@ -272,7 +272,7 @@ example20() { class Example21 { List<String> _names; Example21() { - _names = ["a", "b"]; + _names = ["a", "b"]; } List<String> get names => _names; set names(List<String> list) { @@ -498,7 +498,7 @@ main() { ## Further Reading -Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a +Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a useful Try Dart online. http://www.dartlang.org/ http://try.dartlang.org/ diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index ad782e06..541d28bb 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -17,7 +17,7 @@ Beinahe alle der folgenden Beispiele können als Teile eines Shell-Skripts oder ```bash #!/bin/bash -# Die erste Zeile des Scripts nennt sich Shebang in gibt dem System an, wie +# Die erste Zeile des Scripts nennt sich Shebang, dies gibt dem System an, # wie das Script ausgeführt werden soll: http://de.wikipedia.org/wiki/Shebang # Du hast es bestimmt schon mitgekriegt, Kommentare fangen mit # an. Das Shebang ist auch ein Kommentar @@ -28,18 +28,50 @@ echo Hello, world! echo 'Dies ist die erste Zeile'; echo 'Dies die zweite Zeile' # Variablen deklariert man so: -VARIABLE="irgendein String" +Variable="irgendein String" # Aber nicht so: -VARIABLE = "irgendein String" -# Bash wird VARIABLE für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +Variable = "irgendein String" +# Bash wird 'Variable' für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, # weil es den Befehl nicht findet. +# Und so auch nicht: +Variable= 'Some string' +# Bash wird 'Variable' wieder für einen Befehl halten, den es ausführen soll. Es wird einen Fehler ausgeben, +# Hier wird der Teil 'Variable=' als nur für diesen einen Befehl gültige Zuweisung an die Variable gesehen. + # Eine Variable wird so benutzt: -echo $VARIABLE -echo "$VARIABLE" -# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anders –, +echo $Variable +echo "$Variable" +echo ${Variable} +# aber +echo '$Variable' +# Wenn du eine Variable selbst benutzt – ihr Werte zuweist, sie exportierst oder irgendetwas anderes –, # dann über ihren Namen ohne $. Aber wenn du ihren zugewiesenen Wert willst, dann musst du $ voranstellen. +# Beachte: ' (Hochkomma) verhindert das Interpretieren der Variablen + +# Ersetzen von Zeichenketten in Variablen +echo ${Variable/irgendein/neuer} +# Ersetzt das erste Vorkommen von "irgendein" durch "neuer" + +# Teil einer Zeichenkette +Laenge=7 +echo ${Variable:0:Laenge} +# Gibt nur die ersten 7 Zeichen zurück + +# Standardwert verwenden +echo ${Foo:-"ErsatzWennLeerOderUngesetzt"} +# Das funktioniert mit nicht gesetzten Variablen (Foo=) und leeren Zeichenketten (Foo="") +# Die Zahl 0 (Foo=0) liefert 0. +# Beachte: der wert der Variablen wird nicht geändert + +# Eingebaute Variable (BUILTINS): +# Einige nützliche Beispiele +echo "Rückgabewert des letzten Befehls: $?" +echo "Die PID des skripts: $$" +echo "Anzahl der Argumente beim Aufruf: $#" +echo "Alle Argumente beim Aufruf: $@" +echo "Die Argumente in einzelnen Variablen: $1 $2..." # Einen Wert aus der Eingabe lesen: echo "Wie heisst du?" @@ -47,14 +79,30 @@ read NAME # Wir mussten nicht mal eine neue Variable deklarieren echo Hello, $NAME! # Wir haben die übliche if-Struktur: -if true +# 'man test' liefert weitere Informationen zu Bedingungen +if [ "$NAME" -ne $USER ] then - echo "Wie erwartet" + echo "Dein Name ist nicht dein Login-Name" else - echo "Und dies nicht" + echo "Dein Name ist dein Login-Name" +fi + +# Es gibt auch bedingte Ausführung +echo "immer ausgeführt" || echo "Nur ausgeführt wenn der erste Befehl fehlschlägt" +echo "immer ausgeführt" && echo "Nur ausgeführt wenn der erste Befehl Erfolg hat" + +# Um && und || mit if statements zu verwenden, braucht man mehrfache Paare eckiger Klammern: +if [ $NAME == "Steve" ] && [ $Alter -eq 15 ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Steve' UND $Alter gleich 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "Wird ausgeführt wenn $NAME gleich 'Daniya' ODER $NAME gleich 'Zach'." fi -# Ausdrücke werden im folgenden Format festgehalten: +# Ausdrücke haben folgendes Format: echo $(( 10 + 5 )) # Anders als andere Programmiersprachen ist Bash eine Shell – es arbeitet also im Kontext von Verzeichnissen. @@ -69,13 +117,60 @@ ls -l # Liste alle Dateien und Unterverzeichnisse auf einer eigenen Zeile auf # txt-Dateien im aktuellen Verzeichnis auflisten: ls -l | grep "\.txt" -# Befehle können innerhalb anderer Befehle mit $( ) erstetzt werden: +# Ein- und Ausgabe können umgeleitet werden (stdin, stdout, and stderr). +# Von stdin lesen bis "EOF" allein in einer Zeile auftaucht +# und die Datei hello.py mit den Zeilen zwischen den beiden "EOF" +# überschreiben: +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Führe hello.py mit verschiedenen Umleitungen von +# stdin, stdout und stderr aus: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Die Fehlerausgabe würde die Datei "error.err" überschreiben (falls sie existiert) +# verwende ">>" um stattdessen anzuhängen: +python hello.py >> "output.out" 2>> "error.err" + +# Überschreibe output.out, hänge an error.err an und zähle die Zeilen beider Dateien: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Führe einen Befehl aus und gib dessen "file descriptor" (zB /dev/fd/123) aus +# siehe: man fd +echo <(echo "#helloworld") + +# Mehrere Arten, um output.out mit "#helloworld" zu überschreiben: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Löschen der Hilfsdateien von oberhalb, mit Anzeige der Dateinamen +# (mit '-i' für "interactive" erfolgt für jede Date eine Rückfrage) +rm -v output.out error.err output-and-error.log + +# Die Ausgabe von Befehlen kann mit Hilfe von $( ) in anderen Befehlen verwendet weden: # Der folgende Befehl zeigt die Anzahl aller Dateien und Unterverzeichnisse # im aktuellen Verzeichnis an. echo "Dieser Ordner beinhaltet $(ls | wc -l) Dateien und Verzeichnisse." +# Dasselbe kann man mit "backticks" `` erreichen, aber diese können +# nicht verschachtelt werden. $() ist die empfohlene Methode. +echo "Dieser Ordner beinhaltet `ls | wc -l` Dateien und Verzeichnisse." + # Bash nutzt einen case-Ausdruck, der sich ähnlich wie switch in Java oder C++ verhält. -case "$VARIABLE" +case "$Variable" in # Liste der Fälle, die unterschieden werden sollen 0) echo "Hier ist eine Null." @@ -83,10 +178,106 @@ in *) echo "Das ist nicht Null." esac -# loops iterieren über die angegebene Zahl von Argumenten: -# Der Inhalt von $VARIABLE wird dreimal ausgedruckt. -for $VARIABLE in x y z +# 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: +# Der Inhalt von $Variable wird dreimal ausgedruckt. +for $Variable in {1..3} do - echo "$VARIABLE" + echo "$Variable" done + +# Oder verwende die "traditionelle 'for'-Schleife": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Schleifen können auch mit Dateien arbeiten: +# 'cat' zeigt zuerst file1 an und dann file2 +for Variable in file1 file2 +do + cat "$Variable" +done + +# .. oder mit der Ausgabe eines Befehls: +# Ausgabe des Inhalts jeder Datei, die von 'ls' aufgezählt wird +for Output in $(ls) +do + cat "$Output" +done + +# while Schleife: +while [ true ] +do + echo "Schleifenkörper..." + break +done + +# Funktionen definieren +# Definition: +function foo () +{ + echo "Argumente funktionieren wie bei skripts: $@" + echo Und: $1 $2..." + echo "Dies ist eine Funktion" + return 0 +} + +# oder einfacher +bar () +{ + echo "Auch so kann man Funktionen deklarieren!" + return 0 +} + +# Aufruf der Funktion: +foo "My name is" $Name + +# Was du noch lernen könntest: +# Ausgabe der letzten 10 Zeilen von file.txt +tail -n 10 file.txt +# Ausgabe der ersten 10 Zeilen von file.txt +head -n 10 file.txt +# sortierte Ausgabe von file.txt +sort file.txt +# Mehrfachzeilen in sortierten Dateien unterdrücken +# oder (mit -d) nur diese ausgeben +uniq -d file.txt +# Ausgabe nur der ersten Spalte (vor dem ersten ',') +cut -d ',' -f 1 file.txt +# ersetze in file.txt jedes vorkommende 'gut' durch 'super' (versteht regex) +sed -i 's/gut/super/g' file.txt +# Ausgabe nach stdout aller Zeilen von file.txt, die auf eine regex passen +# Im Beispiel: Zeilen, die mit "foo" beginnen und mit "bar" enden +grep "^foo.*bar$" file.txt +# Mit der Option "-c" wird stattdessen die Anzahl der gefundenen Zeilen ausgegeben +grep -c "^foo.*bar$" file.txt +# verwende 'fgrep' oder 'grep -F' wenn du buchstäblich nach den Zeichen +# suchen willst, ohne sie als regex zu interpretieren +fgrep "^foo.*bar$" file.txt + +# Dokumentation über die in bash eingebauten Befehle +# bekommst du mit dem eingebauten Befehl 'help' +help +help help +help for +help return +help source +help . + +# Das bash-Handbuch liest du mit 'man' +apropos bash +man 1 bash +man bash + +# Dann gibt es noch das 'info' System (drücke ? um Hilfe angezeigt zu bekommen) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# info Dokumentation über bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash ``` diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index dc77dda0..78bb0a6b 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -248,7 +248,8 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; // Ternärer Operator
// Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
// <condition> ? <true> : <false>
- string isTrue = true ? "Ja" : "Nein";
+ int zumVergleich = 17;
+ string isTrue = zumVergleich == 17 ? "Ja" : "Nein";
// while-Schleife
int fooWhile = 0;
@@ -882,8 +883,8 @@ zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
* [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
* [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
- * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix)
* [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
* [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
-[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
\ No newline at end of file +[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx)
diff --git a/de-de/git-de.html.markdown b/de-de/git-de.html.markdown index c7b6ad86..dea329d5 100644 --- a/de-de/git-de.html.markdown +++ b/de-de/git-de.html.markdown @@ -18,12 +18,12 @@ Anmerkung des Übersetzers: Einige englische Begriffe wie *Repository*, *Commit* ### Was ist Versionsverwaltung? -Eine Versionskontrolle erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. +Eine Versionsverwaltung erfasst die Änderungen einer Datei oder eines Verzeichnisses im Verlauf der Zeit. ### Zentrale im Vergleich mit verteilter Versionverwaltung -* Zentrale Versionskontrolle konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. -* Verteilte Versionskontrolle konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. +* Zentrale Versionsverwaltung konzentriert sich auf das Synchronisieren, Verfolgen und Sichern von Dateien. +* Verteilte Versionsverwaltung konzentriert sich auf das Teilen der Änderungen. Jede Änderung hat eine eindeutige ID. * Verteilte Systeme haben keine vorbestimmte Struktur. Ein SVN-ähnliches, zentrales System wäre mit Git ebenso umsetzbar. [Weiterführende Informationen](http://git-scm.com/book/en/Getting-Started-About-Version-Control) @@ -48,7 +48,7 @@ Ein Repository besteht in Git aus dem .git-Verzeichnis und dem Arbeitsverzeichni ### .git-Verzeichnis (Teil des Repositorys) -Das .git-Verzeichnis enth? alle Einstellung, Logs, Branches, den HEAD und mehr. +Das .git-Verzeichnis enthält alle Einstellung, Logs, Branches, den HEAD und mehr. [Ausführliche Übersicht](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) ### Arbeitsverzeichnis (Teil des Repositorys) @@ -61,7 +61,7 @@ Der Index ist die die Staging-Area von Git. Es ist im Grunde eine Ebene, die Arb ### Commit -Ein Commit ist ein Schnappschuss von Uderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositorys gepusht werden. Oder nicht! +Ein Commit ist ein Schnappschuss von Änderungen in deinem Arbeitsverzeichnis. Wenn du zum Beispiel 5 Dateien hinzugefügt und 2 andere entfernt hast, werden diese Änderungen im Commit (Schnappschuss) enthalten sein. Dieser Commit kann dann in andere Repositories gepusht werden. Oder nicht! ### Branch @@ -69,7 +69,9 @@ Ein Branch, ein Ast oder Zweig, ist im Kern ein Pointer auf den letzten Commit, ### HEAD und head (Teil des .git-Verzeichnisses) -HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. Ein head ist ein Pointer, der auf ein beliebige Zahl von heads zeigt. +HEAD ist ein Pointer auf den aktuellen Branch. Ein Repository hat nur einen *aktiven* HEAD. + +Ein *head* ist ein Pointer, der auf einen beliebigen Commit zeigt. Ein Repository kann eine beliebige Zahl von *heads* enthalten. ### Konzeptionelle Hintergründe @@ -127,7 +129,7 @@ Zeigt die Unterschiede zwischen Index (im Grunde dein Arbeitsverzeichnis/-reposi ```bash -# Zeigt den Branch, nicht-verfolgte Dateien, Uderungen und andere Unterschiede an +# Zeigt den Branch, nicht-verfolgte Dateien, Änderungen und andere Unterschiede an $ git status # Anderes Wissenswertes über git status anzeigen @@ -151,7 +153,7 @@ $ git add ./*.java ### branch -Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erschaffen oder löschen. +Verwalte alle Branches. Du kannst sie mit diesem Befehl ansehen, bearbeiten, neue erzeugen oder löschen. ```bash # Liste alle bestehenden Branches und Remotes auf @@ -186,7 +188,7 @@ $ git checkout -b newBranch ### clone -Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für hedes geklonte Repo remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. +Ein bestehendes Repository in ein neues Verzeichnis klonen oder kopieren. Es fügt außerdem für jedes geklonte Repository remote-tracking Branches hinzu. Du kannst auf diese Remote-Branches pushen. ```bash # Klone learnxinyminutes-docs @@ -288,16 +290,16 @@ $ git mv -f myFile existingFile ### pull -Führe einen Pull, zieht alle Daten, eines Repositorys und f?? einen Merge mit einem anderen Branch durch. +Führe einen Pull (zieht alle Daten eines Repositories) aus und führt einen Merge mit einem anderen Branch durch. ```bash -# Update deines lokalen Repos, indem ein Merge der neuen Uderungen -# von den remote-liegenden "origin"- und "master"-Branches durchgef?? wird. +# Update deines lokalen Repos, indem ein Merge der neuen Änderungen +# von den remote-liegenden "origin"- und "master"-Branches durchgeführt wird. # git pull <remote> <branch> # git pull => impliziter Verweis auf origin und master $ git pull origin master -# F?? einen Merge von Uderungen eines remote-Branch und ein Rebase +# Führt einen Merge von Änderungen eines remote-Branch und ein Rebase # des Branch-Commits im lokalen Repo durch. Wie: pull <remote> <branch>, git rebase <branch>" $ git pull origin master --rebase ``` @@ -337,8 +339,8 @@ $ git reset # Setze die Staging-Area zurück, um dem letzten Commit zu entsprechen und überschreibe das Arbeitsverzeichnis $ git reset --hard -# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unber??) -# Alle Uderungen bleiben im Verzeichnis erhalten +# Bewegt die Spitze des Branches zu dem angegebenen Commit (das Verzeichnis bleibt unberührt) +# Alle Änderungen bleiben im Verzeichnis erhalten $ git reset 31f2bb1 # Bewegt die Spitze des Branches zurück zu dem angegebenen Commit diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index ca27fdc7..d3a192fe 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -3,49 +3,50 @@ language: Go filename: learngo-de.go contributors: - ["Joseph Adams", "https://github.com/jcla1"] + - ["Dennis Keller", "https://github.com/denniskeller"] lang: de-de --- -Go wurde entwickelt um probleme zu lösen. Sie ist zwar nicht der neuste Trend in -der Informatik, aber sie ist eine der neusten und schnellsten Wege um Aufgabe in +Go wurde entwickelt, um Probleme zu lösen. Sie ist zwar nicht der neueste Trend in +der Informatik, aber sie ist einer der neuesten und schnellsten Wege, um Aufgabe in der realen Welt zu lösen. -Sie hat vertraute Elemente von imperativen Sprachen mit statisher Typisierung +Sie hat vertraute Elemente von imperativen Sprachen mit statischer Typisierung und kann schnell kompiliert und ausgeführt werden. Verbunden mit leicht zu verstehenden Parallelitäts-Konstrukten, um die heute üblichen mehrkern Prozessoren optimal nutzen zu können, eignet sich Go äußerst gut für große Programmierprojekte. -Außerdem beinhaltet Go eine gut ausgestattete standard bibliothek und hat eine -aktive community. +Außerdem beinhaltet Go eine gut ausgestattete Standardbibliothek und hat eine +aktive Community. ```go // Einzeiliger Kommentar /* Mehr- zeiliger Kommentar */ -// Eine jede Quelldatei beginnt mit einer Packet-Klausel. -// "main" ist ein besonderer Packetname, da er ein ausführbares Programm +// Eine jede Quelldatei beginnt mit einer Paket-Klausel. +// "main" ist ein besonderer Paketname, da er ein ausführbares Programm // einleitet, im Gegensatz zu jedem anderen Namen, der eine Bibliothek // deklariert. package main -// Ein "import" wird verwendet um Packte zu deklarieren, die in dieser +// Ein "import" wird verwendet, um Pakete zu deklarieren, die in dieser // Quelldatei Anwendung finden. import ( - "fmt" // Ein Packet in der Go standard Bibliothek + "fmt" // Ein Paket in der Go Standardbibliothek "net/http" // Ja, ein Webserver. "strconv" // Zeichenkettenmanipulation ) -// Es folgt die Definition einer Funktions, in diesem Fall von "main". Auch hier +// Es folgt die Definition einer Funktion, in diesem Fall von "main". Auch hier // ist der Name wieder besonders. "main" markiert den Eintrittspunkt des // Programms. Vergessen Sie nicht die geschweiften Klammern! func main() { // Println gibt eine Zeile zu stdout aus. - // Der Prefix "fmt" bestimmt das Packet aus welchem die Funktion stammt. + // Der Prefix "fmt" bestimmt das Paket aus welchem die Funktion stammt. fmt.Println("Hello world!") - // Aufruf einer weiteren Funktion definiert innerhalb dieses Packets. + // Aufruf einer weiteren Funktion definiert innerhalb dieses Pakets. beyondHello() } @@ -54,8 +55,8 @@ func main() { func beyondHello() { var x int // Deklaration einer Variable, muss vor Gebrauch geschehen. x = 3 // Zuweisung eines Werts. - // Kurze Deklaration: Benutzen Sie ":=" um die Typisierung automatisch zu - // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. + // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu + // folgern, die Variable zu deklarieren und ihr einen Wert zuzuweisen. y := 4 // Eine Funktion mit mehreren Rückgabewerten. @@ -70,7 +71,7 @@ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Wiedergabe zweier Werte } -// Überblick ueber einige eingebaute Typen und Literale. +// Überblick über einige eingebaute Typen und Literale. func learnTypes() { // Kurze Deklarationen sind die Norm. s := "Lernen Sie Go!" // Zeichenketten-Typ @@ -111,7 +112,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ m["eins"] = 1 // Ungebrauchte Variablen sind Fehler in Go - // Der Unterstrich wird verwendet um einen Wert zu verwerfen. + // Der Unterstrich wird verwendet, um einen Wert zu verwerfen. _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Die Ausgabe zählt natürlich auch als Gebrauch fmt.Println(s, c, a4, s3, d2, m) @@ -142,11 +143,11 @@ func learnFlowControl() { if true { fmt.Println("hab's dir ja gesagt!") } - // Die Formattierung ist durch den Befehl "go fmt" standardisiert + // Die Formatierung ist durch den Befehl "go fmt" standardisiert if false { // nicht hier } else { - // sonder hier! spielt die Musik + // sondern hier! spielt die Musik } // Benutzen Sie ein "switch" Statement anstatt eine Anreihung von if-s @@ -165,12 +166,12 @@ func learnFlowControl() { // Ab hier gilt wieder: x == 1 // For ist die einzige Schleifenform in Go, sie hat aber mehrere Formen: - for { // Endloschleife + for { // Endlosschleife break // nur ein Spaß continue // wird nie ausgeführt } - // Wie bei for, bedeutet := in einer Bedingten Anweisung zunächst die + // Wie bei for, bedeutet := in einer bedingten Anweisung zunächst die // Zuweisung und erst dann die Überprüfung der Bedingung. if y := expensiveComputation(); y > x { x = y @@ -217,8 +218,8 @@ func learnInterfaces() { // Aufruf der String Methode von i, gleiche Ausgabe wie zuvor. fmt.Println(i.String()) - // Funktionen des fmt-Packets rufen die String() Methode auf um eine - // druckbare variante des Empfängers zu erhalten. + // Funktionen des fmt-Pakets rufen die String() Methode auf um eine + // druckbare Variante des Empfängers zu erhalten. fmt.Println(p) // gleiche Ausgabe wie zuvor fmt.Println(i) // und wieder die gleiche Ausgabe wie zuvor @@ -244,75 +245,75 @@ func learnErrorHandling() { learnConcurrency() } -// c ist ein Kannal, ein sicheres Kommunikationsmedium. +// c ist ein Kanal, ein sicheres Kommunikationsmedium. func inc(i int, c chan int) { - c <- i + 1 // <- ist der "send" Operator, wenn ein Kannal auf der Linken ist + c <- i + 1 // <- ist der "send" Operator, wenn ein Kanal auf der Linken ist } // Wir verwenden "inc" um Zahlen parallel zu erhöhen. func learnConcurrency() { // Die selbe "make"-Funktion wie vorhin. Sie initialisiert Speicher für - // maps, slices und Kannäle. + // maps, slices und Kanäle. c := make(chan int) // Starte drei parallele "Goroutines". Die Zahlen werden parallel (concurrently) - // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kannal. + // erhöht. Alle drei senden ihr Ergebnis in den gleichen Kanal. go inc(0, c) // "go" ist das Statement zum Start einer neuen Goroutine go inc(10, c) go inc(-805, c) // Auslesen und dann Ausgeben der drei berechneten Werte. // Man kann nicht im voraus feststellen in welcher Reihenfolge die Werte // ankommen. - fmt.Println(<-c, <-c, <-c) // mit dem Kannal rechts ist <- der Empfangs-Operator + fmt.Println(<-c, <-c, <-c) // mit dem Kanal rechts ist <- der Empfangs-Operator - cs := make(chan string) // ein weiterer Kannal, diesmal für strings - cc := make(chan chan string) // ein Kannal für string Kannäle + cs := make(chan string) // ein weiterer Kanal, diesmal für strings + cc := make(chan chan string) // ein Kanal für string Kanäle // Start einer neuen Goroutine, nur um einen Wert zu senden go func() { c <- 84 }() - go func() { cs <- "wortreich" }() // schon wider, diesmal für + go func() { cs <- "wortreich" }() // schon wieder, diesmal für // "select" hat eine Syntax wie ein switch Statement, aber jeder Fall ist - // eine Kannaloperation. Es wählt eine Fall zufällig aus allen die - // kommunikationsbereit sind aus. + // eine Kanaloperation. Es wählt einen Fall zufällig aus allen, die + // kommunikationsbereit sind, aus. select { case i := <-c: // der empfangene Wert kann einer Variable zugewiesen werden fmt.Printf("es ist ein: %T", i) case <-cs: // oder der Wert kann verworfen werden fmt.Println("es ist eine Zeichenkette!") - case <-cc: // leerer Kannal, nicht bereit für den Empfang + case <-cc: // leerer Kanal, nicht bereit für den Empfang fmt.Println("wird nicht passieren.") } // Hier wird eine der beiden Goroutines fertig sein, die andere nicht. - // Sie wird warten bis der Wert den sie sendet von dem Kannal gelesen wird. + // Sie wird warten bis der Wert den sie sendet von dem Kanal gelesen wird. learnWebProgramming() // Go kann es und Sie hoffentlich auch bald. } -// Eine einzige Funktion aus dem http-Packet kann einen Webserver starten. +// Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { - // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse an die + // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse, an die // sich angeschlossen werden soll. // Der zweite Parameter ist ein Interface, speziell: ein http.Handler err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) // Fehler sollte man nicht ignorieren! } -// Wir lassen "pair" das http.Handler Interface erfüllen indem wir seine einzige +// Wir lassen "pair" das http.Handler Interface erfüllen, indem wir seine einzige // Methode implementieren: ServeHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Senden von Daten mit einer Methode des http.ResponseWriter - w.Write([]byte("Sie habe Go in Y Minuten gelernt!")) + w.Write([]byte("Sie haben Go in Y Minuten gelernt!")) } ``` ## Weitere Resourcen Alles zu Go finden Sie auf der [offiziellen Go Webseite](http://golang.org/). -Dort können sie der Tutorial folgen, interaktiv Quelltext ausprobieren und viel +Dort können sie dem Tutorial folgen, interaktiv Quelltext ausprobieren und viel Dokumentation lesen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und auch gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/). -Gut documentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil -verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktions- -Namen in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). +Gut dokumentiert, demonstriert sie leicht zu verstehendes und im idiomatischen Stil +verfasstes Go. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen +in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index 2c548961..d1a0008e 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Henrik Jürges", "https://github.com/santifa"] + - ["Nikolai Weh", "http://weh.hamburg"] filename: haskell-de.hs --- @@ -58,12 +59,13 @@ not False -- True -- Strings und Zeichen "Das ist ein String." 'a' -- Zeichen -'Einfache Anfuehrungszeichen gehen nicht.' -- error! +'Einfache Anführungszeichen gehen nicht.' -- error! -- Strings können konkateniert werden. "Hello " ++ "world!" -- "Hello world!" -- Ein String ist eine Liste von Zeichen. +['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!" "Das ist eine String" !! 0 -- 'D' @@ -76,11 +78,23 @@ not False -- True [1, 2, 3, 4, 5] [1..5] --- Haskell unterstuetzt unendliche Listen! -[1..] -- Die Liste aller natuerlichen Zahlen +-- Die zweite Variante nennt sich die "range"-Syntax. +-- Ranges sind recht flexibel: +['A'..'F'] -- "ABCDEF" + +-- Es ist möglich eine Schrittweite anzugeben: +[0,2..10] -- [0,2,4,6,8,10] +[5..1] -- [], da Haskell standardmässig inkrementiert. +[5,4..1] -- [5,4,3,2,1] + +-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index: +[1..10] !! 3 -- 4 + +-- Haskell unterstützt unendliche Listen! +[1..] -- Die Liste aller natürlichen Zahlen -- Unendliche Listen funktionieren in Haskell, da es "lazy evaluation" --- unterstuetzt. Haskell evaluiert erst etwas, wenn es benötigt wird. +-- unterstützt. 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 @@ -92,12 +106,9 @@ not False -- True -- Zwei Listen konkatenieren [1..5] ++ [6..10] --- Ein Element als Head hinzufuegen +-- Ein Element als Head hinzufügen 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] @@ -114,7 +125,8 @@ last [1..5] -- 5 -- Ein Tupel: ("haskell", 1) --- Auf Elemente eines Tupels zugreifen: +-- Ein Paar (Pair) ist ein Tupel mit 2 Elementen, auf die man wie folgt +-- zugreifen kann: fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -140,9 +152,9 @@ add 1 2 -- 3 (//) a b = a `div` b 35 // 4 -- 8 --- Guards sind eine einfache Möglichkeit fuer Fallunterscheidungen. +-- Guards sind eine einfache Möglichkeit für Fallunterscheidungen. fib x - | x < 2 = x + | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) -- Pattern Matching funktioniert ähnlich. @@ -174,7 +186,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- 4. Mehr Funktionen ---------------------------------------------------- --- currying: Wenn man nicht alle Argumente an eine Funktion uebergibt, +-- currying: Wenn man nicht alle Argumente an eine Funktion übergibt, -- so wird sie eine neue Funktion gebildet ("curried"). -- Es findet eine partielle Applikation statt und die neue Funktion -- nimmt die fehlenden Argumente auf. @@ -190,23 +202,28 @@ 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) +-- multipliziert dieses Ergebnis mit 4. +foo = (*4) . (+10) + +-- (5 + 10) * 4 = 60 +foo 5 -- 60 --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- Haskell hat einen Operator `$`, welcher Funktionsapplikation durchführt. +-- Im Gegenzug zu der Standard-Funktionsapplikation, welche linksassoziativ ist +-- und die höchstmögliche Priorität von "10" hat, ist der `$`-Operator +-- rechtsassoziativ und hat die Priorität 0. Dieses hat (idr.) den Effekt, +-- dass der `komplette` Ausdruck auf der rechten Seite als Parameter für die +-- Funktion auf der linken Seite verwendet wird. +-- Mit `.` und `$` kann man sich so viele Klammern ersparen. --- 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. +(even (fib 7)) -- false --- Vorher -(even (fib 7)) -- true +-- Äquivalent: +even $ fib 7 -- false --- Danach -even . fib $ 7 -- true +-- Funktionskomposition: +even . fib $ 7 -- false ---------------------------------------------------- -- 5. Typensystem @@ -221,31 +238,31 @@ even . fib $ 7 -- true True :: Bool -- Funktionen haben genauso Typen. --- `not` ist Funktion die ein Bool annimmt und ein Bool zurueckgibt: +-- `not` ist Funktion die ein Bool annimmt und ein Bool zurückgibt: -- 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: +-- Typdefinition darüber zu schreiben: double :: Integer -> Integer double x = x * 2 ---------------------------------------------------- --- 6. If-Anweisung und Kontrollstrukturen +-- 6. If-Ausdrücke und Kontrollstrukturen ---------------------------------------------------- --- If-Anweisung: +-- If-Ausdruck: 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. +-- If-Ausdrücke können auch über mehrere Zeilen verteilt sein. +-- Die Einrückung ist dabei wichtig. haskell = if 1 == 1 then "awesome" else "awful" --- Case-Anweisung: Zum Beispiel "commandline" Argumente parsen. +-- Case-Ausdruck: Am Beispiel vom Parsen von "commandline"-Argumenten. case args of "help" -> printHelp "start" -> startProgram @@ -276,7 +293,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- die Abarbeitung sieht so aus: -(2 * 3 + (2 * 2 + (2 * 1 + 4))) +(2 * 1 + (2 * 2 + (2 * 3 + 4))) ---------------------------------------------------- -- 7. Datentypen @@ -300,7 +317,7 @@ 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` +Nothing -- vom Typ `Maybe a` für jedes `a` ---------------------------------------------------- -- 8. Haskell IO @@ -309,8 +326,8 @@ Nothing -- vom Typ `Maybe a` fuer jedes `a` -- 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: +-- Wenn eine Haskell Programm ausgeführt wird, so wird `main` aufgerufen. +-- Diese muss etwas vom Typ `IO ()` zurückgeben. Zum Beispiel: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) @@ -338,10 +355,10 @@ sayHello = do -- an die Variable "name" gebunden putStrLn $ "Hello, " ++ name --- Uebung: Schreibe deine eigene Version von `interact`, +-- Übung: Schreibe deine eigene Version von `interact`, -- die nur eine Zeile einliest. --- `sayHello` wird niemals ausgefuehrt, nur `main` wird ausgefuehrt. +-- `sayHello` wird niemals ausgeführt, nur `main` wird ausgeführt. -- Um `sayHello` laufen zulassen kommentiere die Definition von `main` -- aus und ersetze sie mit: -- main = sayHello @@ -359,7 +376,7 @@ action = do input1 <- getLine input2 <- getLine -- Der Typ von `do` ergibt sich aus der letzten Zeile. - -- `return` ist eine Funktion und keine Schluesselwort + -- `return` ist eine Funktion und keine Schlüsselwort return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- Nun können wir `action` wie `getLine` benutzen: @@ -370,7 +387,7 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- Der Typ `IO` ist ein Beispiel fuer eine Monade. +-- Der Typ `IO` ist ein Beispiel für 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) @@ -387,7 +404,7 @@ main'' = do -- Starte die REPL mit dem Befehl `ghci` -- Nun kann man Haskell Code eingeben. --- Alle neuen Werte muessen mit `let` gebunden werden: +-- Alle neuen Werte müssen mit `let` gebunden werden: let foo = 5 @@ -396,7 +413,7 @@ let foo = 5 >:t foo foo :: Integer --- Auch jede `IO ()` Funktion kann ausgefuehrt werden. +-- Auch jede `IO ()` Funktion kann ausgeführt werden. > sayHello What is your name? @@ -420,6 +437,6 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater Haskell ist sehr einfach zu installieren. Hohl es dir von [hier](http://www.haskell.org/platform/). -Eine sehr viele langsamere Einfuehrung findest du unter: +Eine sehr viele langsamere Einführung findest du unter: [Learn you a Haskell](http://learnyouahaskell.com/) oder [Real World Haskell](http://book.realworldhaskell.org/). diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index a295c1c2..f3917506 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -479,9 +479,6 @@ myNumber === myNumberObj; // = false if (0){
// Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
}
-if (Number(0)){
- // Dieser Teil des Codes wird ausgeführt, weil Number(0) zu wahr evaluiert.
-}
// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen
// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen
diff --git a/de-de/json-de.html.markdown b/de-de/json-de.html.markdown new file mode 100644 index 00000000..3cf4578c --- /dev/null +++ b/de-de/json-de.html.markdown @@ -0,0 +1,65 @@ +--- +language: json +filename: learnjson-de.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Timm Albers", "https://github.com/nunull"] +lang: de-de +--- + +Da JSON ein äußerst einfaches Format für den Austausch von Daten ist, wird dieses +Dokument das vermutlich einfachste "Learn X in Y Minutes" werden. + +In seiner grundlegenden Form hat JSON keine eigentlichen Kommentare. Dennoch +akzeptieren die meisten Parser Kommentare in C-Syntax (`//`, `/* */`). Dennoch +soll für dieses Dokument nur 100% gültiges JSON verwendet werden, weshalbt keine +Kommentare verwendet werden. Glücklicherweise ist das nachfolgende Dokument +selbsterklärend. + +```json +{ + "schlüssel": "wert", + + "alle schlüssel": "müssen durch doppelte Anführungszeichen begrenzt werden", + "zahlen": 0, + "zeichenketten": "Alle Unicode-Zeichen (inklusive \"escaping\") sind erlaubt.", + "boolesche werte": true, + "nullwert": null, + + "große zahlen": 1.2e+100, + + "objekte": { + "kommentar": "Die meisten Datenstrukturen in JSON kommen aus Objekten.", + + "array": [0, 1, 2, "Arrays können Werte jeglichen Datentyps aufnehmen.", 4], + + "weiteres objekt": { + "kommentar": "Objekte können verschachtelt werden." + } + }, + + "quatsch": [ + { + "quellen von kalium": ["Bananen"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "Neo"], + [0, 0, 0, 1] + ] + ], + + "alternative formatierung": { + "kommentar": "..." + , "die position": "des Kommas ist nicht relevant - so lange es vor dem Wert steht." + , "weiterer kommentar": "wie schön" + , "übrigens": "Auch die Einrückung ist nicht relevant." + , "jede": "beliebige Anzahl von Leerzeichen / Tabs ist erlaubt.", "wirklich?":true + }, + + "das war kurz": "Und, du bist fertig. Du weißt nun (fast) alles über JSON." +} +``` diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown new file mode 100644 index 00000000..2c18b8fd --- /dev/null +++ b/de-de/latex-de.html.markdown @@ -0,0 +1,235 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +translators: + - ["Moritz Kammerer", "https://github.com/phxql"] +lang: de-de +filename: latex-de.tex +--- +``` +% Alle Kommentare starten fangen mit % an +% Es gibt keine Kommentare über mehrere Zeilen + +% LateX ist keine "What You See Is What You Get" Textverarbeitungssoftware wie z.B. +% MS Word oder OpenOffice Writer + +% Jedes LateX-Kommando startet mit einem Backslash (\) + +% LateX-Dokumente starten immer mit der Definition des Dokuments, die sie darstellen +% Weitere Dokumententypen sind z.B. book, report, presentations, etc. +% Optionen des Dokuments stehen zwischen den eckigen Klammern []. In diesem Fall +% wollen wir einen 12 Punkte-Font verwenden. +\documentclass[12pt]{article} + +% Als nächstes definieren wir die Pakete, die wir verwenden wollen. +% Wenn du z.B. Grafiken, farbigen Text oder Quelltext in dein Dokument einbetten möchtest, +% musst du die Fähigkeiten von Latex durch Hinzufügen von Paketen erweitern. +% Wir verwenden die Pakete float und caption für Bilder. +\usepackage{caption} +\usepackage{float} + +% Mit diesem Paket können leichter Umlaute getippt werden +\usepackage[utf8]{inputenc} + +% Es können durchaus noch weitere Optione für das Dokument gesetzt werden! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Nun kann's losgehen mit unserem Dokument. +% Alles vor dieser Zeile wird die Preamble genannt. +\begin{document} +% Wenn wir den Autor, das Datum und den Titel gesetzt haben, kann +% LateX für uns eine Titelseite generieren +\maketitle + +% Die meisten Paper haben ein Abstract. LateX bietet dafür einen vorgefertigen Befehl an. +% Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem +% Inhalt erscheinen. +% Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. +\begin{abstract} + LateX documentation geschrieben in LateX! Wie ungewöhnlich und garantiert nicht meine Idee! +\end{abstract} + +% Section Befehle sind intuitiv. +% Alle Titel der sections werden automatisch in das Inhaltsverzeichnis übernommen. +\section{Einleitung} +Hi, mein Name ist Moritz und zusammen werden wir LateX erforschen! + +\section{Noch eine section} +Das hier ist der Text für noch eine section. Ich glaube, wir brauchen eine subsection. + +\subsection{Das ist eine subsection} % Subsections sind auch ziemlich intuitiv. +Ich glaube, wir brauchen noch eine. + +\subsubsection{Pythagoras} +So ist's schon viel besser. +\label{subsec:pythagoras} + +% Wenn wir den Stern nach section schreiben, dann unterdrückt LateX die Nummerierung. +% Das funktioniert auch bei anderen Befehlen. +\section*{Das ist eine unnummerierte section} +Es müssen nicht alle sections nummeriert sein! + +\section{Ein paar Notizen} +LateX ist ziemlich gut darin, Text so zu platzieren, dass es gut aussieht. +Falls eine Zeile \\ mal \\ woanders \\ umgebrochen \\ werden \\ soll, füge +\textbackslash\textbackslash in den Code ein.\\ + +\section{Listen} +Listen sind eine der einfachsten Dinge in LateX. Ich muss morgen einkaufen gehen, +also lass uns eine Einkaufsliste schreiben: +\begin{enumerate} % Dieser Befehl erstellt eine "enumerate" Umgebung. + % \item bringt enumerate dazu, eins weiterzuzählen. + \item Salat. + \item 27 Wassermelonen. + \item einen Hasen. + % Wir können die Nummer des Eintrags durch [] überschreiben + \item[Wie viele?] Mittelgroße Wasserpistolen. + + Kein Listeneintrag, aber immer noch Teil von enumerate. + +\end{enumerate} % Alle Umgebungen müssen ein end haben. + +\section{Mathe} + +Einer der Haupteinsatzzwecke von LateX ist das Schreiben von akademischen +Artikeln oder Papern. Meistens stammen diese aus dem Bereich der Mathe oder +anderen Wissenschaften. Und deswegen müssen wir in der Lage sein, spezielle +Symbole zu unserem Paper hinzuzufügen! \\ + +Mathe kennt sehr viele Symbole, viel mehr als auf einer Tastatur zu finden sind; +Symbole für Mengen und relationen, Pfeile, Operatoren und Griechische Buchstaben, +um nur ein paar zu nennen.\\ + +Mengen und Relationen spielen eine sehr wichtige Rolle in vielen mathematischen +Papern. So schreibt man in LateX, dass alle y zu X gehören: $\forall$ y $\in$ X. \\ + +% Achte auf die $ Zeichen vor und nach den Symbolen. Wenn wir in LateX schreiben, +% geschieht dies standardmäßig im Textmodus. Die Mathe-Symbole existieren allerdings +% nur im Mathe-Modus. Wir können den Mathe-Modus durch das $ Zeichen aktivieren und +% ihn mit $ wieder verlassen. Variablen können auch im Mathe-Modus angezeigt werden. + +Mein Lieblingsbuchstabe im Griechischen ist $\xi$. Ich mag auch $\beta$, $\gamma$ und $\sigma$. +Bis jetzt habe ich noch keinen griechischen Buchstaben gefunden, den LateX nicht kennt! + +Operatoren sind ebenfalls wichtige Bestandteile von mathematischen Dokumenten: +Trigonometrische Funktionen ($\sin$, $\cos$, $\tan$), +Logarithmus und Exponenten ($\log$, $\exp$), +Grenzwerte ($\lim$), etc. haben vordefinierte Befehle. +Lass uns eine Gleichung schreiben: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$\\ + +Brüche (Zähler / Nenner) können so geschrieben werden: + +% 10 / 7 +$^{10}/_{7}$ + +% Komplexere Brüche können so geschrieben werden: +% \frac{Zähler}{Nenner} +$\frac{n!}{k!(n - k)!}$ \\ + +Wir können Gleichungen auch in einer equation Umgebung verwenden. + +% Dies zeigt Mathe in einer equation Umgebung an +\begin{equation} % Aktiviert automatisch den Mathe-Modus. + c^2 = a^2 + b^2. + \label{eq:pythagoras} % Pythagoras referenzieren +\end{equation} % Alle \begin Befehle müssen einen \end Befehl besitzen + +Wir können nun unsere Gleichung referenzieren! +Gleichung ~\ref{eq:pythagoras} ist auch als das Theorem des Pythagoras bekannt. Dieses wird in +Abschnitt ~\ref{subsec:pythagoras} behandelt. Es können sehr viele Sachen mit Labels versehen werden: +Grafiken, Gleichungen, Sections, etc. + +Summen und Integrale können mit den sum und int Befehlen dargestellt werden: + +% Manche LateX-Compiler beschweren sich, wenn Leerzeilen in Gleichungen auftauchen +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Grafiken} + +Lass uns eine Grafik einfügen. Das Platzieren von Grafiken kann etwas trickreich sein. +Aber keine Sorge, ich muss auch jedes mal nachschauen, welche Option wie wirkt. + +\begin{figure}[H] % H ist die Platzierungsoption + \centering % Zentriert die Grafik auf der Seite + % Fügt eine Grafik ein, die auf 80% der Seitenbreite einnimmt. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Auskommentiert, damit es nicht im Dokument auftaucht. + \caption{Dreieck mit den Seiten $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Tabellen} +Wir können Tabellen genauso wie Grafiken einfügen. + +\begin{table}[H] + \caption{Überschrift der Tabelle.} + % Die {} Argumente geben an, wie eine Zeile der Tabelle dargestellt werden soll. + % Auch hier muss ich jedes Mal nachschauen. Jedes. einzelne. Mal. + \begin{tabular}{c|cc} + Nummer & Nachname & Vorname \\ % Spalten werden durch & getrennt + \hline % Eine horizontale Linie + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Links} % Kommen bald! + +\section{Verhindern, dass LateX etwas kompiliert (z.B. Quelltext)} +Angenommen, wir wollen Quelltext in unserem LateX-Dokument. LateX soll +in diesem Fall nicht den Quelltext als LateX-Kommandos interpretieren, +sondern es einfach ins Dokument schreiben. Um das hinzubekommen, verwenden +wir eine verbatim Umgebung. + +% Es gibt noch weitere Pakete für Quelltexte (z.B. minty, lstlisting, etc.) +% aber verbatim ist das simpelste. +\begin{verbatim} + print("Hello World!") + a%b; % Schau dir das an! Wir können % im verbatim verwenden! + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Kompilieren} + +Ich vermute, du wunderst dich, wie du dieses tolle Dokument in ein PDF +verwandeln kannst. (Ja, dieses Dokument kompiliert wirklich!) \\ + +Dafür musst du folgende Schritte durchführen: + \begin{enumerate} + \item Schreibe das Dokument. (den LateX-Quelltext). + \item Kompiliere den Quelltext in ein PDF. + Das Kompilieren sieht so ähnlich wie das hier aus (Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +Manche LateX-Editoren kombinieren Schritt 1 und 2. Du siehst also nur Schritt 1 und Schritt +2 wird unsichtbar im Hintergrund ausgeführt. + +Alle Formatierungsoptionen werden in Schritt 1 in den Quelltext geschrieben. Schritt 2 verwendet +dann diese Informationen und kümmert sich drum, dass das Dokument korrekt erstellt wird. + +\section{Ende} + +Das war's erst mal! + +% Dokument beenden +\end{document} +``` +## Mehr Informationen über LateX + +* Das tolle LaTeX wikibook: [https://de.wikibooks.org/wiki/LaTeX-Kompendium](https://de.wikibooks.org/wiki/LaTeX-Kompendium) +* Ein Tutorial (englisch): [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index 5ddb6f4b..ae29d6f9 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -149,7 +149,7 @@ li[0] #=> 1 # Das letzte Element ansehen li[-1] #=> 3 -# Bei Zugriffen außerhal der Liste kommt es jedoch zu einem IndexError +# Bei Zugriffen außerhalb der Liste kommt es jedoch zu einem IndexError li[4] # Raises an IndexError # Wir können uns Ranges mit Slice-Syntax ansehen @@ -188,7 +188,7 @@ tup[:2] #=> (1, 2) # Wir können Tupel (oder Listen) in Variablen entpacken a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 -# Tuple werden standardmäßig erstellt, wenn wir uns die Klammern sparen +# Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen d, e, f = 4, 5, 6 # Es ist kinderleicht zwei Werte zu tauschen e, d = d, e # d is now 5 and e is now 4 diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown new file mode 100644 index 00000000..bdeaa30b --- /dev/null +++ b/de-de/ruby-de.html.markdown @@ -0,0 +1,613 @@ +--- +language: ruby +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-de.rb +lang: de-de +--- + +# Dies ist ein Kommentar + +=begin +Dies sind multi-line +Kommentare. Niemand benutzt +die wirklich. +=end + +# Objekte - Alles ist ein Objekt + +## Zahlen sind Objekte +``` +3.class #=> Fixnum +3.to_s #=> "3" +``` + +### Simple Arithmetik +``` +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 +``` + +// Arithmetik ist aber eigentlich nur syntaktischer Zucker +// um eine Methode eines Objekt aufzurufen +``` +1.+(3) #=> 4 +10.* 5 #=> 50 +``` + +## Special values sind Objekte +``` +nil # Nothing to see here +true # truth +false # falsehood + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass +``` + +## Objektvergleiche +### Gleicheit +``` +1 == 1 #=> true +2 == 1 #=> false +``` +### Ungleichheit +``` +1 != 1 #=> false +2 != 1 #=> true +``` +### Neben false selbst, nil ist ein anderer 'falsey' Wert +``` +!nil #=> true +!false #=> true +!0 #=> false +``` +### Weitere Vergleiche +``` +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true +``` +### Logische Operatoren +``` +true && false #=> false +true || false #=> true +!true #=> false +``` + +Es gibt alternative Versionen der logischen Operatoren mit niedrigerer +Wertigkeit. Diese werden meistens bei Flow-Control eingesetzt, um +verschiedenen Ausdrücke zu verketten bis einer true oder false zurück +liefert. + +#### and +##### `do_something_else` wird nur ausgewertet wenn `do_something` true ist. +do_something() and do_something_else() + +#### or +#####`log_error` wird nur ausgewertet wenn `do_something` false ist. +do_something() or log_error() + +## Strings sind Objekte +``` +'I am a string'.class #=> String +"I am a string too".class #=> String + + +platzhalter = 'Ruby' +"Ich kann in #{placeholder} Platzhalter mit doppelten Anführungsstrichen füllen." +``` +Einfache Anführungszeichen sollten bevorzugt werden. +Doppelte Anführungszeichen führen interne Berechnungen durch. + +### Strings können verbunden werden, aber nicht mit Zahlen +``` +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +``` +#### Zahl muss in String konvertiert werden +``` +'hello ' + 3.to_s #=> "hello 3" +``` +### Text ausgeben +``` +puts "I'm printing!" +``` +# Variablen +## Zuweisungen +### Diese Zuweisung gibt den zugeordneten Wert zurück +``` +x = 25 #=> 25 +x #=> 25 +``` +### Damit funktionieren auch mehrfache Zuweisungen +``` +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 +``` +## Benennung +### Konvention ist snake_case +``` +snake_case = true +``` +### Benutze verständliche Variablennamen +``` +path_to_project_root = '/good/name/' +path = '/bad/name/' +``` +# Symbols (sind auch Objekte) +Symbols sind unveränderliche, wiederverwendbare Konstanten, welche intern +als integer repräsentiert werden. Sie werden häufig anstelle von Strings +verwendet, um sinnvoll Werte zu übermitteln. +Symbols werden mit dem Doppelpunkt gekennzeichnet. + +``` +:pending.class #=> Symbol +status = :pending +status == :pending #=> true +status == 'pending' #=> false +status == :approved #=> false +``` +# Arrays + +## Ein Array anlegen +``` +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +``` + +## Array können verschiedene Typen beinhalten +``` +[1, 'hello', false] #=> [1, "hello", false] +``` + +## Wie bei arithmetischen Ausdrücken auch wird beim Zugriff auf +## [0] eigentlich die Methode [] des Array Objekts aufgerufen. +``` +array.[] 0 #=> 1 +array.[] 12 #=> nil +``` + +## Arrays können von vorne indiziert werden +``` +array[0] #=> 1 +array[12] #=> nil +``` + +## Arrays können von hinten indiziert werden +``` +array[-1] #=> 5 +``` + +## Arrays können mit Stard Index und Länge indiziert werden +``` +array[2, 3] #=> [3, 4, 5] +``` + +## Arrays können mit einer Range indiziert werden +``` +array[1..3] #=> [2, 3, 4] +``` + +## Einen Wert hinzufügen +``` +array << 6 #=> [1, 2, 3, 4, 5, 6] +array.push(6) #=> [1, 2, 3, 4, 5, 6] +``` + +## Testen, ob ein Element schon vorhanden ist +``` +array.include?(1) #=> true +``` + +# Hashes +Hashes sind das Hauptfeature um Key/Values zu speichern + +``` + +## Ein Hash anlegen +``` +hash = { 'color' => 'green', 'number' => 5 } +hash.keys #=> ['color', 'number'] +``` + +## Wert per key herausfinden +``` +hash['color'] #=> 'green' +hash['number'] #=> 5 +hash['nothing here'] #=> nil +// Asking a hash for a key that doesn't exist returns nil: +``` + +## Symbols können auch keys sein +``` +new_hash = { defcon: 3, action: true } +new_hash.keys #=> [:defcon, :action] +``` + +## Testen ob ein Key oder ein Value existiert +``` +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true +``` + +### Tip: Arrays und Hashes sind Enumerable +### Und haben gemeinsame, hilfreiche Methoden wie: +### each, map, count, and more + +# Kontrolstrukturen +## if +``` +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end +``` +## for - Allerdings werden for Schleifen nicht oft vewendet. +``` +for counter in 1..5 + puts "iteration #{counter}" +end +``` +## Stattdessen: "each" Methode und einen Bloch übergeben +Ein Block ist ein Codeteil, den man einer Methode übergeben kann +Ähnelt stark lambdas, anonymen Funktionen oder Closures in anderen +Programmiersprachen. + +``` +(1..5).each do |counter| + puts "iteration #{counter}" +end +``` + +Die each Methode einer Range führt den Block für jedes Element der Range aus. + +Dem Block wird ein "counter" parameter übergeben. + +### Den Block kann man auch in geschweiften Klammern schreiben +``` +(1..5).each { |counter| puts "iteration #{counter}" } +``` + +### Each kann auch über den Inhalt von Datenstrukturen iterieren +``` +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +``` + +## case +``` +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +=> "Better luck next time" +``` + +### Case können auch ranges +``` +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +=> "OK job" +``` + +# exception handling: +``` +begin + # code here that might raise an exception + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end +``` +# Funktionen +``` +def double(x) + x * 2 +end +``` +## Funktionen (und Blocks) +## geben implizit den Wert des letzten Statements zurück +``` +double(2) #=> 4 +``` + +### Klammern sind optional wenn das Ergebnis nicht mehdeutig ist +``` +double 3 #=> 6 +double double 3 #=> 12 +def sum(x, y) + x + y +end +``` + +### Methoden Parameter werden per Komma getrennt +``` +sum 3, 4 #=> 7 +sum sum(3, 4), 5 #=> 12 +``` + +## yield +### Alle Methoden haben einen impliziten, optionalen block Parameter +### Dieser wird mit dem Schlüsselword "yield" aufgerufen +``` +def surround + puts '{' + yield + puts '}' +end +surround { puts 'hello world' } +``` + +## Einen Block kann man auch einer Methoden übergeben +### "&" kennzeichnet die Referenz zum übergebenen Block +``` +def guests(&block) + block.call 'some_argument' +end +``` + +### Eine Liste von Parametern kann man auch übergeben, +### Diese wird in ein Array konvertiert +### "*" kennzeichnet dies. +``` +def guests(*array) + array.each { |guest| puts guest } +end +``` +# Klassen +## Werden mit dem class Schlüsselwort definiert +``` +class Human +``` + +### Konstruktor bzw. Initializer +``` + def initialize(name, age = 0) + # Assign the argument to the "name" instance variable for the instance + @name = name + # If no age given, we will fall back to the default in the arguments list. + @age = age + end +``` + +### setter Methode +``` + def name=(name) + @name = name + end +``` +### getter Methode +``` + def name + @name + end +``` + +#### getter können mit der attr_accessor Methode vereinfacht definiert werden +``` + attr_accessor :name + # Getter/setter methods can also be created individually like this + attr_reader :name + attr_writer :name + # A class method uses self to distinguish from instance methods. + # It can only be called on the class, not an instance. + def self.say(msg) + puts msg + end + def species + @@species + end +end +``` + +## Eine Klasse instanziieren +``` +jim = Human.new('Jim Halpert') +dwight = Human.new('Dwight K. Schrute') +``` + +## Methodenaufrufe +``` +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" +``` + +## Eine Klassenmethode aufrufen +``` +Human.say('Hi') #=> "Hi" +``` + +## Variable Gültigkeit +### Variablen die mit "$" starten, gelten global +``` +$var = "I'm a global var" +defined? $var #=> "global-variable" +``` + +### Variablen die mit "@" starten, gelten für die Instanz +``` +@var = "I'm an instance var" +defined? @var #=> "instance-variable" +``` + +### Variablen die mit "@@" starten, gelten für die Klasse +``` +@@var = "I'm a class var" +defined? @@var #=> "class variable" +``` + +### Variablen die mit einem Großbuchstaben anfangen, sind Konstanten +``` +Var = "I'm a constant" +defined? Var #=> "constant" +``` + +## Class ist auch ein Objekt +### Hat also auch Instanzvariablen +### Eine Klassenvariable wird innerhalb der Klasse und Ableitungen geteilt. + +### Basis Klasse +``` +class Human + @@foo = 0 + def self.foo + @@foo + end + def self.foo=(value) + @@foo = value + end +end +``` + +### Abgeleitete Klasse +``` +class Worker < Human +end +Human.foo # 0 +Worker.foo # 0 +Human.foo = 2 # 2 +Worker.foo # 2 +``` + +### Eine Klasseninstanzvariable wird nicht geteilt +``` +class Human + @bar = 0 + def self.bar + @bar + end + def self.bar=(value) + @bar = value + end +end +``` +``` +class Doctor < Human +end +``` +``` +Human.bar # 0 +Doctor.bar # nil +``` +``` +module ModuleExample + def foo + 'foo' + end +end +``` +### Module einbinden, heisst ihre Methoden an die Instanzen der Klasse zu binden +### Module erweitern, heisst ihre Mothden an die Klasse selbst zu binden +``` +class Person + include ModuleExample +end +``` +``` +class Book + extend ModuleExample +end +``` +``` +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' +``` +### Callbacks werden ausgeführt, wenn ein Modul eingebunden oder erweitert wird +``` + module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + module ClassMethods + def bar + 'bar' + end + end + module InstanceMethods + def qux + 'qux' + end + end + end + class Something + include ConcernExample + end +``` +``` +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Weiterführende Hinweise + +//EN + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown new file mode 100644 index 00000000..a7e1f75f --- /dev/null +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -0,0 +1,149 @@ +--- +category: tool +tool: ruby ecosystem +contributors: + - ["Jon Smock", "http://github.com/jonsmock"] + - ["Rafal Chmiel", "http://github.com/rafalchmiel"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: ruby-ecosystem-de.txt +lang: de-de +--- + +Hier gibt es einen Überblick über die gängigsten Tools zur Verwaltung +von verschiedenen Ruby Versionen, Gems und Dependencies. + +## Ruby Managers + +Einige Betriebssysteme haben bereits eine Ruby Version vorinstalliert +oder bieten sie als Package zum Download an. Die meisten Rubyisten +benutzen diese aber eher nicht und wenn, dann um damit einen Ruby +Manager zu installieren. Damit kann man komfortabel zwischen den +verschiedenen Versionen hin und herspringen. + +Dies sind die beliebtesten: + +* [RVM](https://rvm.io/) - Installiert und wechselt zwischen rubies + RVM kennt verschiedene Ruby Versionen und hat das Konzept der gemsets, + um gem Abhängigkeiten pro Projekt zu managen. +* [ruby-build](https://github.com/sstephenson/ruby-build) + Installiert nur rubies, kann diese aber sehr gut verwalten +* [rbenv](https://github.com/sstephenson/rbenv) - Wechselt Ruby Versionen. + Wird zusammen mit ruby-build benutzt. Hiermit kann man kontrollieren, + wie rubies laden. +* [chruby](https://github.com/postmodern/chruby) - Wechselt Ruby Versionen. + Ähnlich rbenv. + +## Ruby Versionen + +Ruby wurde von Yukihiro "Matz" Matsumoto vor gut 20 Jahren veröffentlicht. +Matz ist nach wie vor in die Entwicklung involviert. Daher kommt auch der +Name der Referenzimplementierung: MRI (Matz' Reference Implementation). + +Die aktuellste Version ist **2.2.3** und wurde im August 2015 veröffentlicht! + +Hier eine kurze Versionshistorie: + +* 2.0.0 - Release im Februar 2013 -- Release zum 20. Geburtstag der Sprache + [Rubies are forever](http://www.heise.de/developer/artikel/Ruby-2-0-als-Geschenk-zum-20-Geburtstag-1808109.html) +* 1.9.3 - Release im Oktober 2011 + [End of Life](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) +* 1.8.7 - Release im Juni 2006 + [End of Life](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). + +Die Veränderung zwischen 1.8.7 und 1.9.x war sehr groß und eine Migration +nicht so einfach möglich. Der Versionssprung auf 2.0.0 war verglichen dazu +weit weniger dramatisch. +Beispielsweise hat 1.9. Encodings und eine Bytecode VM eingeführt. +Es gibt immer noch Projekte die auf der stabilen Version 1.8.7 laufen, +aber diese sind mittlerweile in der Minderheit. Die meisten Projekte +laufen auf 1.9.x oder auf 2.x. + +## Ruby Implementierungen + +Das Ruby Ecosystem beinhaltet viele verschiedene Implementierungen von Ruby, +jedes mit seinen eigenen Vorteilen und verschiedenen Graden von +Kompatibilität. Auch wenn alle diese Implementierungen in verschiedenen +Sprachen geschrieben sind, sind sie doch **alle Ruby**. +Jede Implementierung bietet neben ihren speziellen Features immer auch +die Möglichkeit normale ruby Dateien auszuführen. + +Am ausgereiftesten und stabilsten: + +* [MRI](https://github.com/ruby/ruby) - Geschrieben in C, das ist die Referenz Implementierung. + Sie ist 100% kompatibel (mit sich selbst ;-). Alle anderen rubies + bleiben kompatibel mit MRI (siehe [RubySpec](#rubyspec) weiter unten). +* [JRuby](http://jruby.org/) - Geschrieben in Java and Ruby, Robust und ziemlich schnell. + Der größte Vorteil von JRuby ist die Interoperabilität mit JVM/Java und damit die + Benutzung von Ruby im Java Ecosystem. +* [Rubinius](http://rubini.us/) - Geschrieben in Ruby mit C++ bytecode VM. + Auch sehr ausgereift und schnell. + +Mittel ausgereift / kompatibel: + +* [Maglev](http://maglev.github.io/) - Baut auf Gemstone, ein Smalltalk VM. + Dieses Projekt versucht das großartige Smalltalk Tooling in die Ruby Welt + zu bringen. +* [RubyMotion](http://www.rubymotion.com/) - Ruby in der iOS Entwicklung. + +Weniger ausgereift/kompatibel: + +* [Topaz](http://topazruby.com/) - Geschrieben in RPython (via PyPy) + Topaz ist noch ziemlich jung und versucht die schnellste Implementierung + zu werden. +* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plaftform + Das letzte Release von IronRuby ist mittlerweile 5 Jahre her. + +Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber +trotzdem immer zu einer MRI Version kompatibel. +Viele können sogar zwischen verschiedenen Modi wechseln (1.8 mode -> 1.9 mode) + +## RubySpec + +Die meisten Ruby Implementierungen vertrauen der [RubySpec](http://rubyspec.org/). +sehr stark. Da Ruby keine offizielle Spezifikation hat, hat die +Community ausführbare Specs (in Ruby) geschrieben, um so die Kompatibilität +zur MRI testen zu können. + +## RubyGems + +[RubyGems](http://rubygems.org/) ist der Community Paket Manager von Ruby. +RubyGems kommt mit Ruby zusammen, so dass kein extra Tool nötig ist. + +Ruby Pakete werden "gems" genannt und könnten auf RubyGems.org +veröffentlicht werden. Jedes Gem enthält den Source Code und Meta Daten, +wie die Versionsnummer, weitere Abhängigkeiten, Autoren und Lizenzen. + +## Bundler + +[Bundler](http://bundler.io/) ist ein Tool um Abhängigkeiten zwischen +Gems aufzulösen und zu managen. Dazu werden diese in einem gemfile +zusammengefasst und Bundler kümmert sich darum die Abhängigkeiten +untereinander rekursiv aufzulösen. Entweder es klappt und alle gems +konnten runtergeladen werden, oder es wird abgebrochen und +der Konflikt gemeldet. +Zum Beispiel: +Wenn Gem A die Version 3 oder höher von Gem Z braucht, aber Gem B +von Gem Z die Version 2, dann ist das ein Konflikt. + +# Testing + +Test-Driven Development ist ein essentieller Teil der Ruby Kultur. +Ruby bringt sein eigenes Unit-Test framework mit, minitest. Darüberhinaus +gibt es noch viele weitere Testframeworks mit unterschiedlichsten Zielen: + +* [TestUnit](http://ruby-doc.org/stdlib-1.8.7/libdoc/test/unit/rdoc/Test/Unit.html) - Eingebaut in Ruby 1.8 + "Unit-style" Testframework +* [minitest](http://ruby-doc.org/stdlib-2.0.0/libdoc/minitest/rdoc/MiniTest.html) - Eingebaut in Ruby 1.9/2.0 + "Unit-style" Testframework +* [RSpec](http://rspec.info/) - Ein Testframework welches auf verständliche Testdefinition setzt +* [Cucumber](http://cukes.info/) - Ein BDD Testframework welches Gherkin tests parsen kann + +## Be Nice +Die Ruby Community ist stolz darauf eine offene, vielfältige und einladende +Community zu sein. Es gibt viele aktive Ruby User Gruppen und diverse +Ruby Konferenzen. Matz selbst ist so oft es geht dabei. + +* [Euruko](http://www.euruko2015.org) +* [User Groups](https://www.ruby-lang.org/de/community/user-groups/) + diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown new file mode 100644 index 00000000..456403a2 --- /dev/null +++ b/de-de/scala-de.html.markdown @@ -0,0 +1,840 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] + - ["Dennis Keller", "github.com/denniskeller"] +translators: + - ["Christian Albrecht", "https://github.com/coastalchief"] +filename: learnscala-de.scala +lang: de-de +--- + +Scala ist eine funktionale und objektorientierte Programmiersprache +für die Java Virtual Machine (JVM), um allgemeine Programmieraufgaben +zu erledigen. Scala hat einen akademischen Hintergrund und wurde an +der EPFL (Lausanne / Schweiz) unter der Leitung von Martin Odersky entwickelt. + +```scala +/* +Scala Umgebung einrichten: + +1. Scala binaries herunterladen- http://www.scala-lang.org/downloads +2. Unzip/untar in ein Verzeichnis +3. das bin Unterverzeichnis der `PATH` Umgebungsvariable hinzufügen +4. Mit dem Kommando `scala` wird die REPL gestartet und zeigt als Prompt: + +scala> + +Die REPL (Read-Eval-Print Loop) ist der interaktive Scala Interpreter. +Hier kann man jeden Scala Ausdruck verwenden und das Ergebnis wird direkt +ausgegeben. +Als nächstes beschäftigen wir uns mit ein paar Scala Basics. +*/ + + +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// + +// Einzeilige Kommentare beginnen mit zwei Slashes + +/* + Mehrzeilige Kommentare, starten + mit einem Slash-Stern und enden mit einem Stern-Slash +*/ + +// Einen Wert, und eine zusätzliche neue Zeile ausgeben + +println("Hello world!") +println(10) + + +// Einen Wert, ohne eine zusätzliche neue Zeile ausgeben + +print("Hello world") + +/* + Variablen werden entweder mit var oder val deklariert. + Deklarationen mit val sind immutable, also unveränderlich + Deklarationen mit var sind mutable, also veränderlich + Immutability ist gut. +*/ +val x = 10 // x ist 10 +x = 20 // error: reassignment to val +var y = 10 +y = 20 // y ist jetzt 20 + +/* +Scala ist eine statisch getypte Sprache, auch wenn wir in dem o.g. Beispiel +keine Typen an x und y geschrieben haben. +In Scala ist etwas eingebaut, was sich Type Inference nennt. Das heißt das der +Scala Compiler in den meisten Fällen erraten kann, von welchen Typ eine Variable ist, +so dass der Typ nicht jedes mal angegeben werden muss. +Einen Typ gibt man bei einer Variablendeklaration wie folgt an: +*/ +val z: Int = 10 +val a: Double = 1.0 + + +// Bei automatischer Umwandlung von Int auf Double wird aus 10 eine 10.0 + +val b: Double = 10 + + +// Boolean Werte + +true +false + + +// Boolean Operationen + +!true // false +!false // true +true == false // false +10 > 5 // true + + +// Mathematische Operationen sind wie gewohnt + +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +// Die Auswertung eines Ausdrucks in der REPL gibt den Typ +// und das Ergebnis zurück. + + scala> 1 + 7 + res29: Int = 8 + +/* +Das bedeutet, dass das Resultat der Auswertung von 1 + 7 ein Objekt +von Typ Int ist und einen Wert 0 hat. +"res29" ist ein sequentiell generierter name, um das Ergebnis des +Ausdrucks zu speichern. Dieser Wert kann bei Dir anders sein... +*/ + +"Scala strings werden in doppelten Anführungszeichen eingeschlossen" +'a' // A Scala Char +// 'Einzeln ge-quotete strings gibt es nicht!' <= This causes an error + +// Für Strings gibt es die üblichen Java Methoden + +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") + + +// Zusätzlich gibt es noch extra Scala Methoden +// siehe: scala.collection.immutable.StringOps + +"hello world".take(5) +"hello world".drop(5) + + +// String interpolation: prefix "s" + +val n = 45 +s"We have $n apples" // => "We have 45 apples" + + +// Ausdrücke im Innern von interpolierten Strings gibt es auch + +val a = Array(11, 9, 6) +val n = 100 +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" + + +// Formatierung der interpolierten Strings mit dem prefix "f" + +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" + + +// Raw Strings, ignorieren Sonderzeichen. + +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." + + +// Manche Zeichen müssen "escaped" werden, z.B. +// ein doppeltes Anführungszeichen in innern eines Strings. + +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" + + +// Dreifache Anführungszeichen erlauben es, dass ein String über mehrere Zeilen geht +// und Anführungszeichen enthalten kann. + +val html = """<form id="daform"> + <p>Press belo', Joe</p> + <input type="submit"> + </form>""" + + +///////////////////////////////////////////////// +// 2. Funktionen +///////////////////////////////////////////////// + +// Funktionen werden so definiert +// +// def functionName(args...): ReturnType = { body... } +// +// Beachte: Es gibt kein return Schlüsselwort. In Scala ist der letzte Ausdruck +// in einer Funktion der Rückgabewert. + +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + + +// Die geschweiften Klammern können weggelassen werden, wenn +// die Funktion nur aus einem einzigen Ausdruck besteht: + +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y + + +// Syntax für Funktionsaufrufe: + +sumOfSquares(3, 4) // => 25 + + +// In den meisten Fällen (mit Ausnahme von rekursiven Funktionen), können +// Rückgabetypen auch weggelassen werden, da dieselbe Typ Inference, wie bei +// Variablen, auch bei Funktionen greift: + +def sq(x: Int) = x * x // Compiler errät, dass der return type Int ist + + +// Funktionen können default parameter haben: + +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// Anonyme Funktionen sehen so aus: + +(x: Int) => x * x + + +// Im Gegensatz zu def bei normalen Funktionen, kann bei anonymen Funktionen +// sogar der Eingabetyp weggelassen werden, wenn der Kontext klar ist. +// Beachte den Typ "Int => Int", dies beschreibt eine Funktion, +// welche Int als Parameter erwartet und Int zurückgibt. + +val sq: Int => Int = x => x * x + + +// Anonyme Funktionen benutzt man ganz normal: + +sq(10) // => 100 + + +// Wenn ein Parameter einer anonymen Funktion nur einmal verwendet wird, +// bietet Scala einen sehr kurzen Weg diesen Parameter zu benutzen, +// indem die Parameter als Unterstrich "_" in der Parameterreihenfolge +// verwendet werden. Diese anonymen Funktionen werden sehr häufig +// verwendet. + +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// Es gibt einen keyword return in Scala. Allerdings ist seine Verwendung +// nicht immer ratsam und kann fehlerbehaftet sein. "return" gibt nur aus +// dem innersten def, welches den return Ausdruck umgibt, zurück. +// "return" hat keinen Effekt in anonymen Funktionen: + +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // Zeile macht z zum return Wert von foo + else + z + 2 // Zeile ist der return Wert von anonFunc + } + anonFunc(x) // Zeile ist der return Wert von foo +} + + +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// + +// Wertebereiche und Schleifen + +1 to 5 +val r = 1 to 5 +r.foreach(println) +r foreach println +(5 to 1 by -1) foreach (println) + +// Scala ist syntaktisch sehr großzügig, Semikolons am Zeilenende +// sind optional, beim Aufruf von Methoden können die Punkte +// und Klammern entfallen und Operatoren sind im Grunde austauschbare Methoden + +// while Schleife + +var i = 0 +while (i < 10) { println("i " + i); i += 1 } +i // i ausgeben, res3: Int = 10 + + +// Beachte: while ist eine Schleife im klassischen Sinne - +// Sie läuft sequentiell ab und verändert die loop-Variable. +// While in Scala läuft schneller ab als in Java und die o.g. +// Kombinatoren und Zusammenlegungen sind einfacher zu verstehen +// und zu parellelisieren. + +// Ein do while Schleife + +do { + println("x ist immer noch weniger wie 10") + x += 1 +} while (x < 10) + + +// Endrekursionen sind ideomatisch um sich wiederholende +// Dinge in Scala zu lösen. Rekursive Funtionen benötigen explizit einen +// return Typ, der Compiler kann ihn nicht erraten. +// Unit, in diesem Beispiel. + +def showNumbersInRange(a: Int, b: Int): Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1, 14) + + +// Conditionals + +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" + + +///////////////////////////////////////////////// +// 4. Daten Strukturen (Array, Map, Set, Tuples) +///////////////////////////////////////////////// + +// Array + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Exception + + +// Map - Speichert Key-Value-Paare + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Exception +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +// Set - Speichert Unikate, unsortiert (sortiert -> SortedSet) + +val s = Set(1, 3, 7) +s(0) //false +s(1) //true +val s = Set(1,1,3,3,7) +s: scala.collection.immutable.Set[Int] = Set(1, 3, 7) + +// Tuple - Speichert beliebige Daten und "verbindet" sie miteinander +// Ein Tuple ist keine Collection. + +(1, 2) +(4, 3, 2) +(1, 2, "three") +(a, 2, "three") + + +// Hier ist der Rückgabewert der Funktion ein Tuple +// Die Funktion gibt das Ergebnis, so wie den Rest zurück. + +val divideInts = (x: Int, y: Int) => (x / y, x % y) +divideInts(10, 3) + + +// Um die Elemente eines Tuples anzusprechen, benutzt man diese +// Notation: _._n wobei n der index des Elements ist (Index startet bei 1) + +val d = divideInts(10, 3) +d._1 +d._2 + + +///////////////////////////////////////////////// +// 5. Objektorientierte Programmierung +///////////////////////////////////////////////// + +/* + Bislang waren alle gezeigten Sprachelemente einfache Ausdrücke, welche zwar + zum Ausprobieren und Lernen in der REPL gut geeignet sind, jedoch in + einem Scala file selten alleine zu finden sind. + Die einzigen Top-Level Konstrukte in Scala sind nämlich: + + - Klassen (classes) + - Objekte (objects) + - case classes + - traits + + Diesen Sprachelemente wenden wir uns jetzt zu. +*/ + +// Klassen + +// Zum Erstellen von Objekten benötigt man eine Klasse, wie in vielen +// anderen Sprachen auch. + +// erzeugt Klasse mit default Konstruktor + +class Hund +scala> val t = new Hund +t: Hund = Hund@7103745 + + +// Der Konstruktor wird direkt hinter dem Klassennamen deklariert. + +class Hund(sorte: String) +scala> val t = new Hund("Dackel") +t: Hund = Hund@14be750c +scala> t.sorte //error: value sorte is not a member of Hund + + +// Per val wird aus dem Attribut ein unveränderliches Feld der Klasse +// Per var wird aus dem Attribut ein veränderliches Feld der Klasse + +class Hund(val sorte: String) +scala> val t = new Hund("Dackel") +t: Hund = Hund@74a85515 +scala> t.sorte +res18: String = Dackel + + +// Methoden werden mit def geschrieben + +def bark = "Woof, woof!" + + +// Felder und Methoden können public, protected und private sein +// default ist public +// private ist nur innerhalb des deklarierten Bereichs sichtbar + +class Hund { + private def x = ... + def y = ... +} + + +// protected ist nur innerhalb des deklarierten und aller +// erbenden Bereiche sichtbar + +class Hund { + protected def x = ... +} +class Dackel extends Hund { + // x ist sichtbar +} + +// Object +// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. +// "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so +// ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse +// benutzen ohne ein Objekt instanziieren zu müssen. +// Ein gültiges companion Objekt einer Klasse ist es aber erst dann, wenn +// es genauso heisst und in derselben Datei wie die Klasse definiert wurde. + +object Hund { + def alleSorten = List("Pitbull", "Dackel", "Retriever") + def createHund(sorte: String) = new Hund(sorte) +} + +// Case classes +// Fallklassen bzw. Case classes sind Klassen die normale Klassen um extra +// Funktionalität erweitern. Mit Case Klassen bekommt man ein paar +// Dinge einfach dazu, ohne sich darum kümmern zu müssen. Z.B. +// ein companion object mit den entsprechenden Methoden, +// Hilfsmethoden wie toString(), equals() und hashCode() und auch noch +// Getter für unsere Attribute (das Angeben von val entfällt dadurch) + +class Person(val name: String) +class Hund(val sorte: String, val farbe: String, val halter: Person) + + +// Es genügt das Schlüsselwort case vor die Klasse zu schreiben. + +case class Person(name: String) +case class Hund(sorte: String, farbe: String, halter: Person) + + +// Für neue Instanzen brauch man kein "new" + +val dackel = Hund("dackel", "grau", Person("peter")) +val dogge = Hund("dogge", "grau", Person("peter")) + + +// getter + +dackel.halter // => Person = Person(peter) + + +// equals + +dogge == dackel // => false + + +// copy +// otherGeorge == Person("george", "9876") + +val otherGeorge = george.copy(phoneNumber = "9876") + +// Traits +// Ähnlich wie Java interfaces, definiert man mit traits einen Objekttyp +// und Methodensignaturen. Scala erlaubt allerdings das teilweise +// implementieren dieser Methoden. Konstruktorparameter sind nicht erlaubt. +// Traits können von anderen Traits oder Klassen erben, aber nur von +// parameterlosen. + +trait Hund { + def sorte: String + def farbe: String + def bellen: Boolean = true + def beissen: Boolean +} +class Bernhardiner extends Hund{ + val sorte = "Bernhardiner" + val farbe = "braun" + def beissen = false +} + + + +scala> b +res0: Bernhardiner = Bernhardiner@3e57cd70 +scala> b.sorte +res1: String = Bernhardiner +scala> b.bellen +res2: Boolean = true +scala> b.beissen +res3: Boolean = false + + +// Traits können auch via Mixins (Schlüsselwort "with") eingebunden werden + +trait Bellen { + def bellen: String = "Woof" +} +trait Hund { + def sorte: String + def farbe: String +} +class Bernhardiner extends Hund with Bellen{ + val sorte = "Bernhardiner" + val farbe = "braun" +} +scala> val b = new Bernhardiner +b: Bernhardiner = Bernhardiner@7b69c6ba +scala> b.bellen +res0: String = Woof + +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// + +// Pattern matching in Scala ist ein sehr nützliches und wesentlich +// mächtigeres Feature als Vergleichsfunktionen in Java. In Scala +// benötigt ein case Statement kein "break", ein fall-through gibt es nicht. +// Mehrere Überprüfungen können mit einem Statement gemacht werden. +// Pattern matching wird mit dem Schlüsselwort "match" gemacht. + +val x = ... +x match { + case 2 => + case 3 => + case _ => +} + + +// Pattern Matching kann auf beliebige Typen prüfen + +val any: Any = ... +val gleicht = any match { + case 2 | 3 | 5 => "Zahl" + case "woof" => "String" + case true | false => "Boolean" + case 45.35 => "Double" + case _ => "Unbekannt" +} + + +// und auf Objektgleichheit + +def matchPerson(person: Person): String = person match { + case Person("George", nummer) => "George! Die Nummer ist " + number + case Person("Kate", nummer) => "Kate! Die Nummer ist " + nummer + case Person(name, nummer) => "Irgendjemand: " + name + ", Telefon: " + nummer +} + + +// Und viele mehr... + +val email = "(.*)@(.*)".r // regex +def matchEverything(obj: Any): String = obj match { + // Werte: + case "Hello world" => "Got the string Hello world" + // Typen: + case x: Double => "Got a Double: " + x + // Conditions: + case x: Int if x > 10000 => "Got a pretty big number!" + // Case Classes: + case Person(name, number) => s"Got contact info for $name!" + // RegEx: + case email(name, domain) => s"Got email address $name@$domain" + // Tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + // Strukturen: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + // Patterns kann man ineinander schachteln: + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" +} + + +// Jedes Objekt mit einer "unapply" Methode kann per Pattern geprüft werden +// Ganze Funktionen können Patterns sein + +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} + + +///////////////////////////////////////////////// +// 37. Higher-order functions +///////////////////////////////////////////////// + +Scala erlaubt, das Methoden und Funktion wiederum Funtionen und Methoden +als Aufrufparameter oder Return Wert verwenden. Diese Methoden heissen +higher-order functions +Es gibt zahlreiche higher-order functions nicht nur für Listen, auch für +die meisten anderen Collection Typen, sowie andere Klassen in Scala +Nennenswerte sind: +"filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall" + +## List + +def isGleichVier(a:Int) = a == 4 +val list = List(1, 2, 3, 4) +val resultExists4 = list.exists(isEqualToFour) + + +## map +// map nimmt eine Funktion und führt sie auf jedem Element aus und erzeugt +// eine neue Liste + +// Funktion erwartet ein Int und returned ein Int + +val add10: Int => Int = _ + 10 + + +// add10 wird auf jedes Element angewendet + +List(1, 2, 3) map add10 // => List(11, 12, 13) + + +// Anonyme Funktionen können anstatt definierter Funktionen verwendet werden + +List(1, 2, 3) map (x => x + 10) + + +// Der Unterstrich wird anstelle eines Parameters einer anonymen Funktion +// verwendet. Er wird an die Variable gebunden. + +List(1, 2, 3) map (_ + 10) + + +// Wenn der anonyme Block und die Funtion beide EIN Argument erwarten, +// kann sogar der Unterstrich weggelassen werden. + +List("Dom", "Bob", "Natalia") foreach println + + +// filter +// filter nimmt ein Prädikat (eine Funktion von A -> Boolean) und findet +// alle Elemente die auf das Prädikat passen + +List(1, 2, 3) filter (_ > 2) // => List(3) +case class Person(name: String, age: Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + +// reduce +// reduce nimmt zwei Elemente und kombiniert sie zu einem Element, +// und zwar solange bis nur noch ein Element da ist. + +// foreach +// foreach gibt es für einige Collections + +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions +// Eine for-comprehension definiert eine Beziehung zwischen zwei Datensets. +// Dies ist keine for-Schleife. + +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 + + +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// + +// **ACHTUNG:** +// Implicits sind ein sehr mächtiges Sprachfeature von Scala. +// Es sehr einfach +// sie falsch zu benutzen und Anfänger sollten sie mit Vorsicht oder am +// besten erst dann benutzen, wenn man versteht wie sie funktionieren. +// Dieses Tutorial enthält Implicits, da sie in Scala an jeder Stelle +// vorkommen und man auch mit einer Lib die Implicits benutzt nichts sinnvolles +// machen kann. +// Hier soll ein Grundverständnis geschaffen werden, wie sie funktionieren. + +// Mit dem Schlüsselwort implicit können Methoden, Werte, Funktion, Objekte +// zu "implicit Methods" werden. + +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(sorte: String) = new Hund("Golden " + sorte) + + +// implicit ändert nicht das Verhalten eines Wertes oder einer Funktion + +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").sorte // => "Golden Pitbull" + + +// Der Unterschied ist, dass diese Werte ausgewählt werden können, wenn ein +// anderer Codeteil einen implicit Wert benötigt, zum Beispiel innerhalb von +// implicit Funktionsparametern + +// Diese Funktion hat zwei Parameter: einen normalen und einen implicit + +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + + +// Werden beide Parameter gefüllt, verhält sich die Funktion wie erwartet + +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + + +// Wird der implicit Parameter jedoch weggelassen, wird ein anderer +// implicit Wert vom gleichen Typ genommen. Der Compiler sucht im +// lexikalischen Scope und im companion object nach einem implicit Wert, +// der vom Typ passt, oder nach einer implicit Methode mit der er in den +// geforderten Typ konvertieren kann. + +// Hier also: "myImplicitInt", da ein Int gesucht wird + +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + + +// bzw. "myImplicitFunction" +// Der String wird erst mit Hilfe der Funktion in Hund konvertiert, und +// dann wird die Methode aufgerufen + +"Retriever".sorte // => "Golden Retriever" + + +///////////////////////////////////////////////// +// 19. Misc +///////////////////////////////////////////////// +// Importe + +import scala.collection.immutable.List + + +// Importiere alle Unterpackages + +import scala.collection.immutable._ + + +// Importiere verschiedene Klassen mit einem Statement + +import scala.collection.immutable.{List, Map} + + +// Einen Import kann man mit '=>' umbenennen + +import scala.collection.immutable.{List => ImmutableList} + + +// Importiere alle Klasses, mit Ausnahem von.... +// Hier ohne: Map and Set: + +import scala.collection.immutable.{Map => _, Set => _, _} + +// Main + +object Application { + def main(args: Array[String]): Unit = { + // Sachen kommen hierhin + } +} + + +// I/O +// Eine Datei Zeile für Zeile lesen + +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + + +// Eine Datei schreiben + +val writer = new PrintWriter("myfile.txt") +writer.write("Schreibe Zeile" + util.Properties.lineSeparator) +writer.write("Und noch eine Zeile" + util.Properties.lineSeparator) +writer.close() + +``` + +## Weiterführende Hinweise + +// DE +* [Scala Tutorial](https://scalatutorial.wordpress.com) +* [Scala Tutorial](http://scalatutorial.de) + +// EN +* [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/) +* [Neophytes Guide to Scala](http://danielwestheide.com/scala/neophytes.html) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown new file mode 100644 index 00000000..a46c30f6 --- /dev/null +++ b/de-de/yaml-de.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Ruben M.", "https://github.com/switchhax"] +filename: learnyaml-de.yaml +lang: de-de +--- + +YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann. + +YAML ist eine Erweiterung von JSON, mit der Erweiterung von syntaktisch wichtigen Zeilenumbrüche und Einrückung sowie in Python. Anders als in Python erlaubt YAML keine Tabulator-Zeichen. + +```yaml +# Kommentare in YAML schauen so aus. + +################# +# SKALARE TYPEN # +################# + +# Unser Kernobjekt (für das ganze Dokument) wird das Assoziative Datenfeld (Map) sein, +# welches equivalent zu einem Hash oder einem Objekt einer anderen Sprache ist. +Schlüssel: Wert +nochn_Schlüssel: Hier kommt noch ein Wert hin. +eine_Zahl: 100 +wissenschaftliche_Notation: 1e+12 +boolean: true +null_Wert: null +Schlüssel mit Leerzeichen: value +# Strings müssen nicht immer mit Anführungszeichen umgeben sein, können aber: +jedoch: "Ein String in Anführungzeichen" +"Ein Schlüssel in Anführungszeichen": "Nützlich, wenn du einen Doppelpunkt im Schlüssel haben willst." + +# Mehrzeilige Strings schreibst du am besten als 'literal block' (| gefolgt vom Text) +# oder ein 'folded block' (> gefolgt vom text). +literal_block: | + Dieser ganze Block an Text ist der Wert vom Schlüssel literal_block, + mit Erhaltung der Zeilenumbrüche. + + Das Literal fährt solange fort bis dieses unverbeult ist und die vorherschende Einrückung wird + gekürzt. + + Zeilen, die weiter eingerückt sind, behalten den Rest ihrer Einrückung - + diese Zeilen sind mit 4 Leerzeichen eingerückt. +folded_style: > + Dieser ganze Block an Text ist der Wert vom Schlüssel folded_style, aber diesmal + werden alle Zeilenumbrüche durch ein Leerzeichen ersetzt. + + Freie Zeilen, wie obendrüber, werden in einen Zeilenumbruch verwandelt. + + Weiter eingerückte Zeilen behalten ihre Zeilenumbrüche - + diese Textpassage wird auf zwei Zeilen sichtbar sein. + +#################### +# COLLECTION TYPEN # +#################### + +# Verschachtelung wird duch Einrückung erzielt. +eine_verschachtelte_map: + schlüssel: wert + nochn_Schlüssel: Noch ein Wert. + noch_eine_verschachtelte_map: + hallo: hallo + +# Schlüssel müssen nicht immer String sein. +0.25: ein Float-Wert als Schlüssel + +# Schlüssel können auch mehrzeilig sein, ? symbolisiert den Anfang des Schlüssels +? | + Dies ist ein Schlüssel, + der mehrzeilig ist. +: und dies ist sein Wert + +# YAML erlaubt auch Collections als Schlüssel, doch viele Programmiersprachen +# werden sich beklagen. + +# Folgen (equivalent zu Listen oder Arrays) schauen so aus: +eine_Folge: + - Artikel 1 + - Artikel 2 + - 0.5 # Folgen können verschiedene Typen enthalten. + - Artikel 4 + - schlüssel: wert + nochn_schlüssel: nochn_wert + - + - Dies ist eine Folge + - innerhalb einer Folge + +# Weil YAML eine Erweiterung von JSON ist, können JSON-ähnliche Maps und Folgen +# geschrieben werden: +json_map: {"schlüssel": "wert"} +json_seq: [3, 2, 1, "Start"] + +############################ +# EXTRA YAML EIGENSCHAFTEN # +############################ + +# YAML stellt zusätzlich Verankerung zu Verfügung, welche es einfach machen +# Inhalte im Dokument zu vervielfältigen. Beide Schlüssel werden den selben Wert haben. +verankerter_inhalt: &anker_name Dieser String wird als Wert beider Schlüssel erscheinen. +anderer_anker: *anker_name + +# YAML hat auch Tags, mit denen man explizit Typangaben angibt. +explicit_string: !!str 0.5 +# Manche Parser implementieren sprachspezifische Tags wie dieser hier für Pythons +# komplexe Zahlen. +python_komplexe_Zahlen: !!python/komplex 1+2j + +#################### +# EXTRA YAML TYPEN # +#################### + +# Strings and Zahlen sind nicht die einzigen Skalare, welche YAML versteht. +# ISO-formatierte Datumsangaben and Zeiangaben können ebenso geparsed werden. +DatumZeit: 2001-12-15T02:59:43.1Z +DatumZeit_mit_Leerzeichen: 2001-12-14 21:59:43.10 -5 +Datum: 2002-12-14 + +# Der !!binary Tag zeigt das ein String base64 verschlüsselt ist. +# Representation des Binären Haufens +gif_datei: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML bietet auch Mengen (Sets), welche so ausschauen +menge: + ? artikel1 + ? artikel2 + ? artikel3 + +# Wie in Python sind Mengen nicht anderes als Maps nur mit null als Wert; das Beispiel oben drüber ist equivalent zu: +menge: + artikel1: null + artikel2: null + artikel3: null +``` diff --git a/edn.html.markdown b/edn.html.markdown new file mode 100644 index 00000000..d0bdddfc --- /dev/null +++ b/edn.html.markdown @@ -0,0 +1,108 @@ +--- +language: edn +filename: learnedn.edn +contributors: + - ["Jason Yeo", "https://github.com/jsyeo"] +--- + +Extensible Data Notation (EDN) is a format for serializing data. + +The notation is used internally by Clojure to represent programs. It is also +used as a data transfer format like JSON. Though it is more commonly used in +Clojure, there are implementations of EDN for many other languages. + +The main benefit of EDN over JSON and YAML is that it is extensible. We +will see how it is extended later on. + +```Clojure +; Comments start with a semicolon. +; Anything after the semicolon is ignored. + +;;;;;;;;;;;;;;;;;;; +;;; Basic Types ;;; +;;;;;;;;;;;;;;;;;;; + +nil ; also known in other languages as null + +; Booleans +true +false + +; Strings are enclosed in double quotes +"hungarian breakfast" +"farmer's cheesy omelette" + +; Characters are preceeded by backslashes +\g \r \a \c \e + +; Keywords start with a colon. They behave like enums. Kind of +; like symbols in Ruby. +:eggs +:cheese +:olives + +; Symbols are used to represent identifiers. They start with #. +; You can namespace symbols by using /. Whatever preceeds / is +; the namespace of the name. +#spoon +#kitchen/spoon ; not the same as #spoon +#kitchen/fork +#github/fork ; you can't eat with this + +; Integers and floats +42 +3.14159 + +; Lists are sequences of values +(:bun :beef-patty 9 "yum!") + +; Vectors allow random access +[:gelato 1 2 -2] + +; Maps are associative data structures that associate the key with its value +{:eggs 2 + :lemon-juice 3.5 + :butter 1} + +; You're not restricted to using keywords as keys +{[1 2 3 4] "tell the people what she wore", + [5 6 7 8] "the more you see the more you hate"} + +; You may use commas for readability. They are treated as whitespace. + +; Sets are collections that contain unique elements. +#{:a :b 88 "huat"} + +;;;;;;;;;;;;;;;;;;;;;;; +;;; Tagged Elements ;;; +;;;;;;;;;;;;;;;;;;;;;;; + +; EDN can be extended by tagging elements with # symbols. + +#MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} + +; Let me explain this with a clojure example. Suppose I want to transform that +; piece of EDN into a MenuItem record. + +(defrecord MenuItem [name rating]) + +; To transform EDN to clojure values, I will need to use the built in EDN +; reader, edn/read-string + +(edn/read-string "{:eggs 2 :butter 1 :flour 5}") +; -> {:eggs 2 :butter 1 :flour 5} + +; To transform tagged elements, define the reader function and pass a map +; that maps tags to reader functions to edn/read-string like so + +(edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} + "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") +; -> #user.MenuItem{:name "eggs-benedict", :rating 10} + +``` + +# References + +- [EDN spec](https://github.com/edn-format/edn) +- [Implementations](https://github.com/edn-format/edn/wiki/Implementations) +- [Tagged Elements](http://www.compoundtheory.com/clojure-edn-walkthrough/) diff --git a/el-gr/css-gr.html.markdown b/el-gr/css-gr.html.markdown new file mode 100644 index 00000000..327dc1a0 --- /dev/null +++ b/el-gr/css-gr.html.markdown @@ -0,0 +1,243 @@ +--- +language: css +contributors: + - ["Kostas Bariotis", "http://kostasbariotis.com"] +filename: css-gr.html.markdown +lang: el-gr +--- + +Η αρχική μορφή του Παγκόσμιου Ιστού αποτελούταν απο καθαρό κείμενο, χωρίς οπτικά αντικείμενα. Με το πέρας +του χρόνου και την εξέλιξη των Φυλλομετρητών, οι πλούσιες σελίδες, σε οπτικά και πολυμεσικά αντικείμενα, +γίναν καθημερινότητα. + +Η CSS μας βοηθάει να διαχωρήσουμε το περιεχόμενο της σελίδας μας (HTML) απο την οπτική της περιγραφή. + +Με την CSS ορίζουμε οπτικές ιδιότητες (χρώμα, μέγεθος, κλπ) σε HTML αντικείμενα (H1, div, κλπ). + +```css +/* Σχόλια εμφανίζονται εντός καθέτου-αστερίσκου, όπως εδώ. + Δεν υπάρχουν σχόλια μια γραμμής και πολλών. */ + +/* #################### + ## ΚΑΝΟΝΕΣ + #################### */ + +/* ένας κανόνας χρησιμοποιείτε για να στοχεύσουμε ένα αντικείμενο (selector). +selector { property: value; /* περισσότερες ιδιότητες...*/ } + +/* +Αυτό είναι ενα παράδειγμα αντικειμένου¨ + +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* Μπορούμε να το στοχεύσουμε με την χρήση CSS κλάσεων */ +.class1 { } + +/* Ή και με τις δύο κλάσεις! */ +.class1.class2 { } + +/* Και με το όνομα του */ +div { } + +/* Ή με το id του */ +#anID { } + +/* Ή με το γεγονός ότι περιέχει ενα attribute */ +[attr] { font-size:smaller; } + +/* Ή οτι το attribute αυτό έχει μια συγκεκριμένη τιμή */ +[attr='value'] { font-size:smaller; } + +/* Ξεκινάει απο το λεκτικό (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* Καταλήγει σε αυτο το λεκτικό (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* Περιέχει κάποιο λεκτικό */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* περιέχει το λεκτικό σε λίστα χωρισμένη με παύλες, δηλαδή: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Μπορούμε να προσθέσουμε μεταξύ τους selectors για να δημιουργήσουμε πιο αυστηρούς. + Δεν βάζουμε κενά ανάμεσα. */ +div.some-class[attr$='ue'] { } + +/* Μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται μέσα σε άλλα. */ +div.some-parent > .class-name { } + +/* Ή κάποιο αντικείμενο απόγονο ανεξαρτήτου του βάθους της σχέσης τους. */ +div.some-parent .class-name { } + +/* ΠΡΟΣΟΧΗ: ο ίδιος selector χωρίς κενά έχει άλλο νόημα. (Άσκηση προς τον αναγνώστη) */ +div.some-parent.class-name { } + +/* Μπορούμε να επιλέξουμε αντικείμενα με βάση το αμέσως επόμενο αντικείμενο στο ίδιο επίπεδο. */ +.i-am-just-before + .this-element { } + +/* Ή οποιοδήποτε αντικείμενο που προηγείται */ +.i-am-any-element-before ~ .this-element { } + +/* Με την βοήθεια των ψευδο-κλάσεων μπορούμε να επιλέξουμε αντικείμενα που βρίσκονται σε μια + ορισμένη κατάασταση. */ + +/* π.χ. όταν ο κέρσορας είναι πάνω απο ένα αντικείμενο */ +selector:hover { } + +/* ή ένας υπερσύνδεσμος που πατήθηκε */ +selector:visited { } + +/* ή που δεν πατήθηκε */ +selected:link { } + +/* ή ένα αντικείμενο που επιλέχθηκε */ +selected:focus { } + +/* οποιοδήποτε αντικείμενο είναι το πρώτο παιδί των γονέων του */ +selector:first-child {} + +/* οποιοδήποτε αντικείμενο είναι το πρώτοτελευταίο παιδί των γονέων του */ +selector:last-child {} + +/* Όπως και με τις ψευδο-κλάσεις, τα ψευδο-αντικείμενα μας επιτρέπουν τα τροποοιήσουμε συγκεκριμένα + κομμάτια της σελίδας */ + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς πριν απο το αντικείμενο */ +selector::before {} + +/* επιλέγει το ψευδο-αντικείμενο ακριβώς μετά απο τον αντικείμενο */ +selector::after {} + +/* Σε σωστά σημεία (όχι πολύ ψηλά στην ιεραρχία) ο αστερίσκος μπορείς να χρησιμοποιηθεί για να + επιλέξουμε όλα τα αντικείμενα */ +* { } /* όλα τα αντικείμενα της σελίδας */ +.parent * { } /* όλους τους απόγονους */ +.parent > * { } /* όλους τους απόγονους πρώτου επιπέδου */ + +/* #################### + ## Ιδιότητες + #################### */ + +selector { + + /* Οι μονάδες μπορούν να είναι είτε απόλυτες είτε σχετικές */ + + /* Σχετικές μονάδες */ + width: 50%; /* ποσοστό επί του πλάτους του γονέα */ + font-size: 2em; /* πολλαπλασιαστής της αρχικής τιμής του αντικειμένου */ + font-size: 2rem; /* ή της τιμής του πρώτου αντικειμένου στην ιεραρχία */ + font-size: 2vw; /* πολλαπλαστιαστής του 1% του οπτικού πλάτους */ + font-size: 2vh; /* ή τους ύψους */ + font-size: 2vmin; /* οποιοδήποτε απο αυτα τα δύο είναι το μικρότερο */ + font-size: 2vmax; /* ή το μεγαλύτερο */ + + /* Απόλυτες μονάδες */ + width: 200px; /* pixels */ + font-size: 20pt; /* στιγμες */ + width: 5cm; /* εκατοστά */ + min-width: 50mm; /* χιλιοστά */ + max-width: 5in; /* ίντσες */ + + /* Χρώματα */ + color: #F6E; /* σύντομη δεκαεξαδική μορφή */ + color: #FF66EE; /* δεκαεξαδική μορφή */ + color: tomato; /* χρώμα με το όνομα του (συγκεκριμένα χρώματα) */ + color: rgb(255, 255, 255); /* τιμή RGB */ + color: rgb(10%, 20%, 50%); /* τιμή RGB με ποσοστά */ + color: rgba(255, 0, 0, 0.3); /* τιμή RGBA (CSS3) σσ. 0 < a < 1 */ + color: transparent; /* όπως και το παραπάνω με a = 0 */ + color: hsl(0, 100%, 50%); /* τιμή hsl με ποσοστά (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* τιμή hsla με ποσοστά και a */ + + /* Εικόνες μπορούν να τοποθετηθούν στον φόντο ενός αντικειμένου */ + background-image: url(/img-path/img.jpg); + + /* Γραμματοσειρές */ + font-family: Arial; + /* εάν η γραμματοσειρα περιέχει κενά */ + font-family: "Courier New"; + /* εάν η πρώτη γραμματοσειρα δε βρεθεί εγκατεστημένη στο Λειτουργικό Σύστυμα, αυτόματα + επιλέγετε η δεύτερη, κ.κ.ε. */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Χρήση + +Αποθηκεύουμε ένα αρχείο CSS με την επέκταση `.css`. + +```xml +<!-- Πρέπει να συμπεριλάβουμε το αρχείο στην επικεφαλίδα(head) ενος HTML αρχείου. + σσ. http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Μπορούμε να το ενσωματώσουμε --> +<style> + a { color: purple; } +</style> + +<!-- Ή απευθείας σε κάποιο αντικείμενο (inline) --> +<div style="border: 1px solid red;"> +</div> +``` + +## Ειδικότητα των κανόνων (Cascading απο το αγγλικό τίτλο Cascading Style Sheets) + +Ένα αντικείμενο μπορεί να στοχευθεί απο πολλούς κανόνες και μπορεί η ίδια ιδιότητα να +περιλαμβάνετε σε πολλούς κανόνες. Σε αυτές της περιπτώσεις υπερισχύει πάντα ο πιο ειδικός +κανόνας και απο αυτούς, αυτός που εμφανίζεται τελευταίος. + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +Η σειρά θα είναι: + +* `E` έχει μεγαλύτερο βάρος λόγω του `!important`. Κάλες πρακτικές λένε να το αποφεύγουμε. +* `F` επόμενο λόγω του inline κανόνα. +* `A` επόμενο λόγω του το οτι είναι πιο ειδικό. Περιέχει τρεις selectors. +* `C` επόμενο, λόγω του οτι εμφανίζεται μετα το Β και ας έχει την ίδια ειδικότητα. +* `B` επόμενο. +* `D` τελευταίο. + +## Συμβατότητα + +Τα περισσότερα απο τα παραπάνω ήδη υποστηρίζονται απο τους γνωστούς φυλλομετρητές. Άλλα θα πρέπει +πάντα να ελέγχουμε πρωτου τους χρησιμοποιήσουμε. + +## Περισσότερα + +* Έλεγχος συμβατότητας, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## Μελέτη + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown new file mode 100644 index 00000000..589adfeb --- /dev/null +++ b/el-gr/racket-gr.html.markdown @@ -0,0 +1,745 @@ +--- +language: racket +filename: learnracket-gr.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] + - ["Keyan Zhang", "https://github.com/keyanzhang"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +lang: el-gr +--- + +H Racket είναι μια γενικού σκοπού, πολυ-υποδειγματική γλώσσα προγραμματισμού που ανήκει +στην οικογένεια της Lisp/Scheme + +```racket +#lang racket ; ορίζει την γλώσσα που χρησιμοποιόυμε + +;;; Σχόλια + +;; Τα σχόλια μιας γραμμής ξεκινούν με ερωτηματικό + +#| Τα σχόλια ολόκληρου μπλόκ + μπορούν να εκτείνονται σε πολλές γραμμές και... + #| + μπορούν να είναι εμφωλευμένα! + |# +|# + +;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την +;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να +;; κάνουμε σχόλια κάποιες εκφράσεις κατά τη διάρκεια του debugging + +#; (αυτή η έκφραση δεν θα εκτελεστεί) + +;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε +;; πολύ σύντομα!) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Πρωτογενείς τύποι μεταβλητών και τελεστές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Αριθμοί +9999999999999999999999 ; ακέραιοι +#b111 ; δυαδικοί => 7 +#o111 ; οκταδικοί => 73 +#x111 ; δεκαεξαδικοί => 273 +3.14 ; πραγματικοί +6.02e+23 +1/2 ; ρητοί +1+2i ; μιγαδικοί + +;; Οι μορφή των συναρτήσεων είναι (f x y z) +;; όπου το f είναι η συνάρτηση και τα x y z +;; είναι οι όροι που η συνάρτηση δέχεται +;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε +;; μια λίστα στην κυριολεξία από δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε από το να +;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: +'(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη +;; Τώρα , ας κάνουμε μερικές πράξεις +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; Λογικές μεταβλητές +#t ; για το true (αληθής) +#f ; για το false (ψευδής) +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; Χαρακτήρες +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήρες διαφυγής της C, + ; σε Unicode +"λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες + +;; Μπορούμε να ενώσουμε αλφαριθμητικά! +(string-append "Hello " "world!") ; => "Hello world!" + +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοποιήσουμε +;; όπως και μια λίστα από χαρακτήρες +(string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο + +;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για +;; να μορφοποιήσουμε αλφαριθμητικά +(format "~a can be ~a" "strings" "formatted") ;; => "strings can be formatted" + +;; Η εκτύπωση είναι εύκολη. +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Μεταβλητές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Μπορούμε να δημιουργήσουμε μεταβλητές +;; χρησιμοποιώντας το define. +;; Ένα όνομα μεταβλητής μπορεί να χρησιμοποιεί οποιονδήποτε +;; χαρακτήρα, εκτός από τους: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. +(define ⊆ subset?) ;; Εδώ ουσιαστικά δίνουμε στη ήδη υπάρχουσα συνάρτηση subset? + ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πριν π.χ. +(printf name) +;; θα πάρουμε το παρακάτω μήνυμα +;name: undefined; +; cannot reference undefined identifier +; context...: + +;; Η τοπική δέσμευση : `me' δεσμεύεται με το "Bob" μόνο μέσα στο (let ...) +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Δομές και συλλογές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δομές +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => #<dog> +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; Ζεύγη (αμετάβλητα) +;; Η δεσμευμένη λέξη `cons' δημιουργεί ζεύγη, +;; και το `car' και το `cdr' εξάγουν το πρώτο και +;; το δεύτερο στοιχείο αντίστοιχα. +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; Λίστες + +;; Οι λίστες είναι linked-list δομές δεδομένων, +;; που έχουν δημιουργηθεί από ζευγάρια 'cons' +;; και τελειώνουν με 'null' (ή αλλιώς '()) για να +;; δηλώσουν ότι αυτό είναι το τέλος της λίστας +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; Η δεσμευμένη λέξη 'list' είναι ένας εναλλακτικός +;; (και σαφώς πιο βολικός) τρόπος για να δημιουργούμε +;; λίστες +(list 1 2 3) ; => '(1 2 3) +;; αλλά και χρησιμοποιώντας ένα μονό εισαγωγικό το +;; το αποτέλεσμα είναι και πάλι το ίδιο +'(1 2 3) ; => '(1 2 3) + +;; Μπορούμε και πάλι όμως να χρησιμοποιούμε το 'cons' για να +;; προσθέσουμε ένα στοιχείο στην αρχή της λίστας +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Μπορούμε να χρησιμοποιούμε το 'append' για να προσθέτουμε +;; στοιχεία στο τέλος μιας λίστας. Το στοιχείο αυτό μπορεί +;; και να είναι ολόκληρη λίστα! +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Οι λίστες στην Racket είναι πολύ βασικές , οπότε υπάρχουν πολλές +;; δυνατές λειτουργίες για αυτές. Παρακάτω είναι μερικά παραδείγματα: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; Διανύσματα + +;; Τα διανύσματα είναι πίνακες σταθερού μήκους +#(1 2 3) ; => '#(1 2 3) + +;; Χρησιμοποιούμε το `vector-append' για να προσθέσουμε διανύσματα +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Σύνολα + +;; Δημιουργούμε ένα σύνολο από μία λίστα +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; Αφαιρούμε με το `set-remove' +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; Βλέπουμε αν υπάρχει ένας αριθμός στο σύνολο με το `set-member?' +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; Πίνακες κατακερματισμού (Hashes) + +;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού +(define m (hash 'a 1 'b 2 'c 3)) + +;; Παίρνουμε μια τιμή από τον πίνακα +(hash-ref m 'a) ; => 1 + +;; Αν ζητήσουμε μια τιμή που δεν υπάρχει παίρνουμε μία εξαίρεση +; (hash-ref m 'd) => no value found for key + +;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν +(hash-ref m 'd 0) ; => 0 + + +;; Χρησιμοποιούμε το 'hash-set' για να επεκτείνουμε +;; ένα πίνακα κατακερματισμού +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; Θυμηθείτε ! Αυτοί οι πίνακες κατακερματισμού +;; είναι αμετάβλητοι! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' + +;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε +;; κλειδιά +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Συναρτήσεις +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το `lambda' για να δημιουργήσουμε συναρτήσεις. +;; Μια συνάρτηση πάντα επιστρέφει την τιμή της τελευταίας της έκφρασης +(lambda () "Hello World") ; => #<procedure> +;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' +(λ () "Hello World") ; => Ίδια συνάρτηση + +;; Χρησιμοποιούμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; Εκχωρούμε σε μια μεταβλητή την συνάρτηση +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; Μπορούμε αυτό να το κάνουμε συντομότερο χρησιμοποιώντας +;; το λεγόμενο syntactic sugar : +(define (hello-world2) "Hello World") + +;; Το () στο παραπάνω είναι η λίστα από τα ορίσματα για την συνάρτηση + +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; ... ή ισοδύναμα, χρησιμοποιώντας sugared ορισμό: +(define (hello2 name) + (string-append "Hello " name)) + +;; Μπορούμε να έχουμε συναρτήσεις με πολλές μεταβλητές χρησιμοποιώντας +;; το `case-lambda' +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... ή να ορίσουμε προαιρετικά ορίσματα με μια έκφραση προκαθορισμένης τιμής +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; Οι συναρτήσεις μπορούν να πακετάρουν επιπλέον +;; ορίσματα μέσα σε μια λίστα +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... ή με unsugared μορφή `lambda': +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; Μπορούμε να εμπλέξουμε κανονικά και πακεταρισμένα ορίσματα +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... και unsugared: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; Και με λέξεις κλειδιά +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Ισότητα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; για αριθμούς χρησιμοποιούμε το `=' +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; Το `eq?' επιστρέφει #t αν δύο 2 ορίσματα αναφέρονται στο +;; ίδιο αντικείμενο (στη μνήμη),αλλιώς επιστρέφει #f. +;; Με άλλα λόγια, είναι απλή σύγκριση δεικτών. +(eq? '() '()) ; => #t, αφού υπάρχει μόνο μια άδεια λίστα στη μνήμη +(let ([x '()] [y '()]) + (eq? x y)) ; => #t, το ίδιο με πάνω + +(eq? (list 3) (list 3)) ; => #f +(let ([x (list 3)] [y (list 3)]) + (eq? x y)) ; => #f — δεν είναι η ίδια λίστα στην μνήμη! + +(let* ([x (list 3)] [y x]) + (eq? x y)) ; => #t, Αφού το x και το y τώρα δείχνουν στην ίδια θέση + +(eq? 'yes 'yes) ; => #t +(eq? 'yes 'no) ; => #f + +(eq? 3 3) ; => #t — να είστε προσεκτικοί εδώ + ; Είναι προτιμότερο να χρησιμοποιείτε `=' για την + ; σύγκριση αριθμών. +(eq? 3 3.0) ; => #f + +(eq? (expt 2 100) (expt 2 100)) ; => #f +(eq? (integer->char 955) (integer->char 955)) ; => #f + +(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `eqv?' υποστηρίζει την σύγκριση αριθμών αλλά και χαρακτήρων +;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. +(eqv? 3 3.0) ; => #f +(eqv? (expt 2 100) (expt 2 100)) ; => #t +(eqv? (integer->char 955) (integer->char 955)) ; => #t + +(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `equal?' υποστηρίζει την σύγκριση των παρακάτω τύπων μεταβλητών: +;; αλφαριθμητικά, αλφαριθμητικά από bytes, μεταβλητά ζεύγη , διανύσματα, +;; πίνακες κατακερματισμού και δομές. +;; Για άλλα ήδη τύπων μεταβλητών το `equal?' και το `eqv?' επιστρέφουν το +;; ίδιο αποτέλεσμα. +(equal? 3 3.0) ; => #f +(equal? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #t +(equal? (list 3) (list 3)) ; => #t + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Έλεγχος Ροής +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Συνθήκες (conditionals) + +(if #t ; έκφραση ελέγχου + "this is true" ; έκφραση then + "this is false") ; έκφραση else +; => "this is true" + + +;; Στα conditionals, όλες οι μη #f τιμές θεωρούνται ως #t +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; Οι αλυσίδες `cond' είναι σειρές από ελέγχους για να +;; επιλεγεί ένα αποτέλεσμα +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; Αντιστοίχιση μοτίβων + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; Βρόχοι + +;; Οι επαναλήψεις μπορούν να γίνουν μέσω αναδρομής +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; Παρομοίως με τη χρήση 'let' +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + + +;; Θα δείτε παρακάτω πως να προσθέσουμε μια νέα μορφή επανάληψης +;; αλλά η Racket έχει ήδη πολύ ευέλικτη μορφή για τους βρόχους +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; +;;; Επανάληψη μέσα σε ακολουθίες: +;; Το `for' επιτρέπει την επανάληψη μέσα σε πολλά +;; άλλα ήδη από ακολουθίες: Λίστες, διανύσματα, +;; αλφαριθμητικά, σύνολα κτλ.. + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; Πιο περίπλοκες επαναλήψεις + +;; Παράλληλη σάρωση σε πολλαπλές ακολουθίες +;; (σταματά στην πιο σύντομη) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; Εμφολευμένοι βρόχοι +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; Συνθήκες +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; Σάρωση σε λίστες +;; Παρόμοιο με τους βρόχους 'for', απλά συλλέγουμε τα αποτελέσματα + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; Υπάρχουν πολλά είδη από προϋπάρχοντες τρόπους για να συλλέγουμε +;; τιμές από τους βρόχους + +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t + +;; Και για να χρησιμοποιήσουμε ένα αυθαίρετο συνδυασμό χρησιμοποιούμε +;; το 'for/fold' +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 + +;; Αυτό συχνά μπορεί να αντικαταστήσει τους κοινούς +;; προστακτικούς βρόχους (imperative loops) + +;;; Εξαιρέσεις + +;; Για να πιάσουμε τις εξαιρέσεις χρησιμοποιούμε το +;; `with-handlers' +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", αλλά αν γίνει το break => "no time" + +;; Χρησιμοποιούμε το 'raise' για να άρουμε μια εξαίρεση +;; ή οποιαδήποτε άλλη τιμή +(with-handlers ([number? ; πιάνουμε αριθμητικές τιμές + identity]) ; και τις επιστρέφουμε σαν απλές τιμές + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Αλλαγή τιμών +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το 'set!' για να θέσουμε μια νέα τιμή +;; σε μια ήδη υπάρχουσα μεταβλητή +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβλητή +;; θα είναι mutable (θα μπορεί να αλλάξει η τιμή της) +;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + + +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι π.χ. τα ζεύγη, οι +;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή +;; π.χ. αλφαριθμητικά, διανύσματα κτλ. +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια +;; συγκεκριμένη θέση +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + + +;; Έτσι δημιουργούμε ένα άδειο μεταβλητό πίνακα κατακερματισμού +;; και τον χειριζόμαστε κατάλληλα +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Ενότητες (modules) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + +;; Οι ενότητες μας επιτρέπουν να οργανώνουμε τον κώδικα σε πολλαπλά +;; αρχεία και επαναχρησιμοποιούμενες βιβλιοθήκες +;; Εδώ χρησιμοποιούμε υπο-ενότητες, εμφωλευμένες μέσα σε μια +;; άλλη ενότητα που δημιουργεί αυτό το κείμενο (ξεκινώντας από +;; την γραμμή '#lang' ) +(module cake racket/base ; ορίζουμε μια ενότητα 'cake' βασισμένο στο + ; racket/base + + (provide print-cake) ; συνάρτηση που εξάγεται από την ενότητα + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; εσωτερική συνάρτηση + (printf fmt (make-string n ch)) + (newline))) + +;; Χρησιμοποιουμε το 'require' για να πάρουμε όλα τα +;; παρεχόμενα ονόματα από μία ενότητα +(require 'cake) ; το ' είναι για τοπική υποενότητα +(print-cake 3) +; (show "~a" 1 #\A) ; => error, το `show' δεν έχει εξαχθεί + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Κλάσεις και αντικείμενα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δημιουργούμε μια κλάση fish% (- συνήθως χρησιμοποιούμε +;; το % στο όνομα μιας κλάσης ) +(define fish% + (class object% + (init size) ; initialization argument + (super-new) ; superclass initialization + ;; Field + (define current-size size) + ;; Public methods + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; Δημιουργούμε ένα instance του fish% +(define charlie + (new fish% [size 10])) + +;; Χρησιμοποιούμε το 'send' για να καλέσουμε +;; τις μεθόδους ενός αντικειμένου +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; Το `fish%' είναι μία τιμή "πρώτης κλάσης" +;; με το οποίο μπορούμε να κάνουμε προσμείξεις +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; ή χωρίς καθόλου ονόματα : +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. Μακροεντολές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε +;; το συντακτικό μιας γλώσσας. + +;; Ας προσθέσουμε έναν βρόχο while +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; Macros are hygienic, you cannot clobber existing variables! +(define-syntax-rule (swap! x y) ; -! is idiomatic for mutation + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; Η μεταβλητή 'tmp' μετονομάζεται σε 'tmp_1' +;; για να αποφευχθεί η σύγκρουση με τα ονόματα +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ.: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουργεί ατέρμονα βρόχο +;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής +;; θα μπει στον ατέρμονα βρόχο. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. Συμβόλαια (Contracts) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Τα συμβόλαια βάζουν περιορισμούς σε τιμές που προέρχονται +;; από ενότητες (modules) +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; οι ποσότητες είναι πάντα θετικές + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; Πελάτες που προσπαθούν να καταθέσουν ένα μη θετικό ποσό παίρνουν +;; το μήνυμα (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. Είσοδος και έξοδος +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Η Racket έχει την έννοια του "port", που είναι παρόμοιο με τα +;; file descriptors σε άλλες γλώσσες. + +;; Ανοίγουμε το "/tmp/tmp.txt" και γράφουμε μέσα "Hello World" +;; Αυτό θα προκαλούσε σφάλμα αν το αρχείο υπήρχε ήδη +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; Προσθέτουμε στο τέλος του "/tmp/tmp.txt" +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; Διαβάζουμε από αρχείο ξανά +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; Εναλλακτικά, με το call-with-output-file δεν χρειάζεται να κλείσουμε +;; ρητά το αρχείο +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; Rewrite the content + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; Και το call-with-input-file κάνει το ίδιο πράγμα για την είσοδο +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) +``` + +## Επιπλέον πηγές + +Ψάχνεις για περισσότερα ; [Getting Started with Racket](http://docs.racket-lang.org/getting-started/) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown new file mode 100644 index 00000000..415fda5c --- /dev/null +++ b/el-gr/scala-gr.html.markdown @@ -0,0 +1,689 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +filename: learnscala-gr.scala +lang: el-gr +--- + +Scala - Η επεκτάσιμη γλώσσα + +```scala + +/* + Προετοιμαστείτε: + + 1) Κατεβάστε την Scala - http://www.scala-lang.org/downloads + 2) Κάνετε εξαγωγή στην επιθυμητή σας τοποθεσία και βάλτε τον υποφάκελο bin + στο path του συστήματος + 3) Ξεκινήστε ένα scala REPL γράφοντας scala. Θα πρέπει να βλέπετε το prompt: + + scala> + + Αυτό είναι το αποκαλούμενο REPL (Read-Eval-Print Loop) *. + Μπορείτε να πληκτρολογήσετε οποιαδήποτε έγκυρη έκφραση σε Scala μέσα του , + και το αποτέλεσμα θα τυπωθεί. Θα εξηγήσουμε πως μοιάζουν τα αρχεία της Scala + αργότερα μέσα στο tutorial , αλλά για τώρα ας αρχίσουμε με κάποια βασικά. + *[Βρόχος του Διάβασε - Αξιολόγησε - Τύπωσε] +*/ + + +///////////////////////////////////////////////// +// 1. Βασικές έννοιες +///////////////////////////////////////////////// + +// Τα σχόλια μίας γραμμής ξεκινούν με δύο "/" (:forward slashes) . + +/* + Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε + να δείτε , φαίνονται κάπως έτσι. +*/ + +// Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση +println("Hello world!") +println(10) + +// Εκτύπωση χωρίς νέα γραμμή στην επόμενη εκτύπωση +print("Hello world") + +// Η δήλωση μεταβλητών γίνεται χρησιμοποιώντας var ή val. +// Οι δηλώσεις val είναι αμετάβλητες, ενώ οι var είναι μεταβλητές. +// Η αμεταβλητότητα είναι συμφέρουσα και προσπαθούμε να την χρησιμοποιούμε. +val x = 10 // το x είναι τώρα 10 +x = 20 // σφάλμα: αλλαγή σε val +var y = 10 +y = 20 // το y είναι τώρα 20 + +/* + Η Scala είναι στατικού τύπου γλώσσα, εν τούτοις προσέξτε ότι στις παραπάνω + δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός + χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις + περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να + μαντέψει ποιος είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιας μεταβλητής ως εξής: +*/ +val z: Int = 10 +val a: Double = 1.0 + +/* + Προσέξτε ότι υπάρχει αυτόματη μετατροπή από ακέραιο (Int) σε διπλής + ακρίβειας (Double), και συνεπώς το αποτέλεσμα είναι 10.0 και όχι 10. +*/ +val b: Double = 10 + +// Λογικές τιμές +true +false + +// Λογικές Πράξεις +!true // false +!false // true +true == false // false +10 > 5 // true + +// Η αριθμητική είναι όπως τα συνηθισμένα +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +/* + Αξιολογώντας μια έκφραση στο REPL, σας δίνεται ο τύπος και + η τιμή του αποτελέσματος +*/ + +1 + 7 + +/* Η παραπάνω γραμμή έχει το εξής αποτέλεσμα: + + scala> 1 + 7 + res29: Int = 8 + + Αυτό σημαίνει ότι το αποτέλεσμα της αξιολόγησης του 1 + 7 είναι ένα αντικείμενο + τύπου Int με τιμή 8 + + Σημειώστε ότι το "res29" είναι ένα σειριακά δημιουργούμενο όνομα μεταβλητής + για να αποθηκεύονται τα αποτελέσματα των εκφράσεων που έχετε πληκτρολογήσει + και συνεπώς η έξοδός σας μπορεί να διαφέρει. +*/ + +"Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" +'a' // Ένας χαρακτήρας στην Scala +// res30: Char = a +// Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. + +// Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") + +// Έχουν επίσης μερικές επιπλέον μεθόδους Scala. +// Δείτε επίσης : scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) + +// Παρεμβολή αλφαριθμητικών : παρατηρήστε το πρόθεμα "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" + +// Παρατηρήστε την χρήση των '{', '}' +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" + +// Μορφοποίηση με παρεμβεβλημένα αλφαριθμητικά με το πρόθεμα "f" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" + +// Raw αλφαριθμητικά, που αγνοούν τους ειδικούς χαρακτήρες. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." + +// Μερικούς χαρακτήρες πρέπει να τους κάνουμε "escape", +// λ.χ ένα διπλό εισαγωγικό μέσα σε ένα αλφαριθμητικό : +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" + +/* + Τα τριπλά διπλά-εισαγωγικά επιτρέπουν στα αλφαριθμητικά να εκτείνονται σε + πολλαπλές γραμμές και να περιέχουν διπλά εισαγωγικά +*/ +val html = """<form id="daform"> + <p>Press belo', Joe</p> + <input type="submit"> + </form>""" + + +///////////////////////////////////////////////// +// 2. Συναρτήσεις +///////////////////////////////////////////////// + +// Οι συναρτήσεις ορίζονται ως εξής: +// +// def functionName(args...): ReturnType = { body... } +// +// Αν προέρχεστε απο πιο παραδοσιακές γλώσσες (C/C++ , Java) παρατηρήστε +// την παράλειψη του return. Στην Scala , η τελευταία έκφραση στο μπλόκ +// της συνάρτησης είναι η τιμή που επιστρέφει η συνάρτηση. +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// Τα { } μπορούν να παραλειφθούν αν η συνάρτηση αποτελείται απο μια απλή έκφραση: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y + +// Η σύνταξη για την κλήση συναρτήσεων είναι γνώριμη: +sumOfSquares(3, 4) // => 25 + +// Στις περισσότερες των περιπτώσεων (με τις αναδρομικές συναρτήσεις να αποτελούν +// την πιο αξιοπρόσεκτη εξαίρεση) , ο τύπος επιστροφής της συνάρτησης μπορεί να +// παραλειφθεί, και η ίδια συμπερασματολογία τύπων που είδαμε με τις μεταβλητές +// θα δουλεύει και με τους τύπους επιστροφής της συνάρτησης: +def sq(x: Int) = x * x // Ο μεταγλωττιστής μπορεί να μαντέψει ότι + // ο τύπος επιστροφής της συνάρτησης είναι Int + +// Οι συναρτήσεις μπορούν να έχουν προκαθορισμένες τιμές: +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// Οι ανώνυμες συναρτήσεις είναι ως εξής: +(x:Int) => x * x + +// Σε αντίθεση με τα defs , ακόμα και ο τύπος εισόδου απο τις ανώνυμες +// συναρτήσεις μπορεί να παραληφθεί αν τα συμφραζόμενα το κάνουν ξεκάθαρο. +// Προσέξτε τον τύπο "Int => Int" που σημαίνει ότι μια συνάρτηση παίρνει +// ένα Int και επιστρέφει ένα Int. +val sq: Int => Int = x => x * x + +// Οι ανώνυμες συναρτήσεις μπορούν να κληθούν όπως συνήθως: +sq(10) // => 100 + +// Αν κάθε όρισμα στην ανώνυμη συνάρτηση χρησιμοποιείται μόνο μία φορά, +// η Scala επιτρέπει έναν ακόμα πιο σύντομο τρόπο να οριστεί. Αυτές +// οι ανώνυμες συναρτήσεις αποδεικνύεται ότι είναι πολύ κοινές , +// όπως θα γίνει προφανές στο μέρος των δομών δεδομένων. +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + +// Η δεσμευμένη λέξη return υπάρχει στην Scala , αλλά επιστρέφει μόνο +// από το πιο εσωτερικό def που την περικλείει. +// ΠΡΟΣΟΧΗ: Η χρήση του return στην Scala είναι επιρρεπής σε λάθη +// και θα πρέπει να αποφεύγεται. +// Δεν έχει καμία επίδραση στις ανώνυμες συναρτήσεις. Για παράδειγμα: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // Αυτή η σειρά κάνει το z την τιμή που επιστρέφει η foo! + else + z + 2 // Αυτή η γραμμή είναι η τιμή που επιστρέφει η anonFunc + } + anonFunc(x) // Αυτή η γραμμή είναι η τιμή που επιστρέφει η foo +} + + +///////////////////////////////////////////////// +// 3. Έλεγχος ροής +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// ΠΡΟΣΟΧΗ: Η Scala είναι σχετικά επιεικής ως αναφορά τις τελείες και +// τις παρενθέσεις. Διαβάστε τους κανόνες ξεχωριστά. +// Αυτό βοηθάει στο να γράφεις DSLs και APIs που διαβάζονται σαν τα Αγγλικά. + +(5 to 1 by -1) foreach ( println ) + +// Ένας βρόχος while : +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβη; Γιατί; + +i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος + // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή + // του βρόχου. Το while είναι πολύ γρήγορο , γρηγορότερο απο τους βρόχους + // της Java , αλλά η χρήση combinators και comprehensions όπως πιο πάνω , + // είναι πιο εύκολη στην κατανόηση και στην παραλληλοποίηση. + +// Ένας βρόχος do while : +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γραφτεί +// ρητά ο τύπος που θα επιστρέψουν, αλλιώς ο μεταγλωττιστής δεν μπορεί +// αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// Έλεγχος Ροής + +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" + + +///////////////////////////////////////////////// +// 4. Δομές Δεδομένων +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // "Πετάει" exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // "Πετάει" exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Δείτε το documentation του map εδώ - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + */ + + +// Πλειάδες + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Γιατί να το έχουμε αυτό; +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα + // της ακέραιας διαίρεσης και το υπόλοιπο. + +// Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n +// όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. +val d = divideInts(10,3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Αντικειμενοστραφής Προγραμματισμός +///////////////////////////////////////////////// + +/* + Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις + (τιμές, συναρτήσεις, κτλ.). Αυτές οι εκφράσεις βολεύουν όταν τις + γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν + από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να + έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα + στοιχεία του πάνω επιπέδου που επιτρέπονται στην Scala είναι: + + - αντικείμενα (objects) + - κλάσεις (classes) + - κλάσεις περίπτωσης (case classes στην Scala) + - Χαρακτηριστικά (traits , όπως ονομάζονται στην Scala) + + Και τώρα θα εξηγήσουμε τι είναι αυτά. +*/ +// Οι κλάσεις είναι παρόμοιες με τις κλάσεις σε άλλες γλώσσες. Τα ορίσματα του +// "κατασκευαστή" (constructor) δηλώνονται μετά από το όνομα της κλάσης , +// και η αρχικοποιήση γίνεται μέσα στο σώμα της κλάσης. +class Dog(br: String) { + // Κώδικας για τον "κατασκευαστή" + var breed: String = br + + // Ορίζεται μια μέθοδος bark , που επιστρέφει ένα αλφαριθμητικό + def bark = "Woof, woof!" + + // Οι τιμές και οι μέθοδοι είναι public εκτός αν χρησιμοποιήσουμε κάποια + // απο τις λέξεις κλειδιά "protected" και "private" . + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + + // Οι abstract μέθοδοι είναι απλά μέθοδοι χωρίς σώμα. Αν βγάζαμε + // το σχόλιο απο την επόμενη γραμμή η κλάση Dog θα έπρεπε να + // δηλωθεί ως abstract class Dog(...) { ... } : + // def chaseAfter(what: String): String +} + +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" + + +// Η λέξη "object" δημιουργεί ένα type ΚΑΙ ένα singleton instance αυτού. +// Είναι κοινό για τις κλάσεις στην Scala να έχουν ένα "συντροφικό object", +// όπου η συμπεριφορά για κάθε instance αιχμαλωτίζεται μέσα στις κλάσεις +// αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances +// της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις +// μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. +// Προσέξτε ότι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} + +// Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον +// λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην +// Scala είναι πότε να χρησιμοποιούνται κλάσεις και πότε case κλάσεις. +// Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον +// πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις +// τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. +// Ο κύριος σκοπός των case classes είναι να κρατούν δεδομένα που είναι +// σταθερές(immutable). Συνήθως έχουν λίγες μεθόδους και οι μέθοδοι σπάνια +// έχουν παρενέργειες. +case class Person(name: String, phoneNumber: String) + +// Δημιουργία ενός instance. Παρατηρήστε ότι τα case classes +// δεν χρειάζονται την λέξη "new" . +val george = Person("George", "1234") +val kate = Person("Kate", "4567") + +// Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: +george.phoneNumber // => "1234" + +// Ελέγχεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// κάνουμε override στο .equals) +Person("George", "1234") == Person("Kate", "1236") // => false + +// Έυκολος τρόπος να κάνουμε αντιγραφή. Δημιουργούμε έναν νέο geroge: +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") + +// Και πολλά άλλα. Τα case classes έχουν και αντιστοίχιση προτύπων +// (pattern matching) δωρεάν, δείτε παρακάτω. + +// Τα χαρακτηριστικά (traits) έρχονται σε λίγο καιρό ! + +///////////////////////////////////////////////// +// 6. Αντιστοίχιση Προτύπων +///////////////////////////////////////////////// + +// Η αντιστοίχιση προτύπων (pattern matching) είναι ένα πολύ δυνατό και +// ευρέως χρησιμοποιούμενο χαρακτηριστικό στην Scala. Παρακάτω βλέπουμε +// πως γίνεται το pattern matching σε ένα case class. Σημείωση: Σε +// αντίθεση με άλλες γλώσσες η Scala δεν χρειάζεται breaks, γιατί γίνεται +// αυτόματα όταν γίνει κάποιο match. + +def matchPerson(person: Person): String = person match { + // Μετά προσδιορίζουμε το πρότυπο (pattern): + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} + +val email = "(.*)@(.*)".r // Ορίζουμε ένα regex για το επόμενο παράδειγμα. + // (regex <- REGular EXpression) + +// Το pattern matching μπορεί να μοιάζει γνώριμο απο τα switch statements σε +// γλώσσες που ανήκουν στην οικογένεια της C αλλά είναι πολύ πιο ισχυρό. +// Στην Scala , μπορούμε να κάνουμε match πολύ περισσότερα: +def matchEverything(obj: Any): String = obj match { + // Μπορούμε να ταιριάξουμε τιμές: + case "Hello world" => "Got the string Hello world" + + // Μπορούμε να ταιριάξουμε τύπους: + case x: Double => "Got a Double: " + x + + // Μπορούμε να βάλουμε συνθήκες: + case x: Int if x > 10000 => "Got a pretty big number!" + + // Μπορούμε να ταιριάξουμε case classes όπως πρίν: + case Person(name, number) => s"Got contact info for $name!" + + // Μπορούμε να ταιριάξουμε regex: + case email(name, domain) => s"Got email address $name@$domain" + + // Μπορούμε να ταιριάξουμε πλειάδες: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + + // Μπορούμε να ταιριάξουμε δομές δεδομένων: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + + // Μπορούμε να ταιριάξουμε πρότυπα που το ένα είναι μέσα στο άλλο: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" +} + +// Στην πραγματικότητα , μπορούμε να κάνουμε pattern matching σε όποιο αντικείμενο +// έχει την μέθοδο "unapply". Αυτό το χαρακτηριστικό είναι τόσο ισχυρό ώστε +// η Scala επιτρέπει να ορίστούν ολόκληρες συναρτήσεις σαν patterns. +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} + + +///////////////////////////////////////////////// +// 7. Συναρτησιακός Προγραμματισμός +///////////////////////////////////////////////// + +// Η Scala επιτρέπει στις μεθόδους και τις συναρτήσεις να επιστρέφουν ή να +// δέχονται ως παραμέτρους άλλες μεθόδους ή συναρτήσεις. + +val add10: Int => Int = _ + 10 // Μια συνάρτηση που δέχεται Int και επιστρέφει Int +List(1, 2, 3) map add10 // List(11, 12, 13) - το add10 εφαρμόζεται σε κάθε στοιχείο + // μέσω του map + +// Οι ανώνυμες συναρτήσεις μπορούν να χρησιμοποιηθούν αντί +// ονοματισμένων (όπως απο πάνω) : +List(1, 2, 3) map (x => x + 10) + +// Και το σύμβολο της κάτω παύλας , μπορεί να χρησιμοποιηθεί αν υπάρχει μόνο +// ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. +List(1, 2, 3) map (_ + 10) + +// Αν το μπλοκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα +// μπορείτε να παραλείψετε την κάτω παύλα. +List("Dom", "Bob", "Natalia") foreach println + + +// Συνδυαστές + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// Η συνάρτηση filter παίρνει ένα κατηγορούμενο (predicate) +// που είναι μια συνάρτηση απο το A -> Boolean και διαλέγει +// όλα τα στοιχεία που ικανοποιούν αυτό το κατηγορούμενο. +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + +// Το foreach είναι μια μέθοδος της Scala , που ορίζεται για ορισμένες +// συλλογές (collections). Παίρνει έναν τύπο και επιστρέφει Unit +// (μια μέθοδο void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions + +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 + +/* + Προσοχή : Αυτά δεν ήταν βρόχοι for. Η σημασιολογία ενός βρόχου for είναι + η επανάληψη, ενώ ένα for-comprehension ορίζει μια σχέση μεταξύ δύο + συνόλων δεδομένων. +*/ + +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// +/* + ΠΡΟΣΟΧΗ! Τα implicits είναι ένα σύνολο απο ισχυρά χαρακτηριστικά της Scala + και επομένως είναι εύκολο να γίνει κατάχρηση. Οι αρχάριοι στην Scala θα + πρέπει να αντισταθούν στον πειρασμό να τα χρησιμοποιήσουν έως ότου, όχι + μόνο καταλάβουν πως λειτουργούν, αλλά ακόμα εξασκηθούν πάνω τους. + Ο μόνος λόγος που συμπεριλάβαμε αυτό το κομμάτι στο tutorial είναι + γιατί είναι τόσο κοινό στις βιβλιοθήκες της Scala , που αδύνατο να κάνεις + οτιδήποτε σημαντικό χωρίς να χρησιμοποιήσεις μια που να έχει implicits. + +*/ + +// Κάθε τιμή (vals , συναρτήσεις , αντικείμενα , κτλ) μπορεί να δηλωθεί ως +// implicit χρησιμοποιώντας , ναι το μαντέψατε , την λέξη "implicit". +// Σημειώστε ότι χρησιμοποιούμε την κλάση Dog που δημιουργήσαμε στο +// 5ο μέρος των παραδειγμάτων. +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) + + +// Απο μόνη της, η λέξη implicit, δεν αλλάζει την συμπεριφορά μιάς τιμής +// οπότε οι παραπάνω μπορούν να χρησιμοποιοηθούν όπως συνήθως. +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" + +// Η διαφορά είναι ότι τώρα αυτές οι τιμές έχουν την δυνατότητα να +// χρησιμοποιηθούν όταν ένα άλλο κομμάτι κώδικα "χρειάζεται" μια +// implicit τιμή. Μια τέτοια περίπτωση είναι τα ορίσματα μιας implicit +// συνάρτησης: +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + +// Άν τροφοδοτήσουμε μια τιμή για το "homMany", η συνάρτηση συμπεριφέρεται +// ως συνήθως +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + +// Αλλά αν παραλείψουμε την παράμετρο implicit , μια implicit τιμή του ιδίου τύπου +// χρησιμοποιείται, στην περίπτωσή μας, το "myImplicitInt" +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + +// Οι παράμετροι implicit συναρτήσεων μας επιτρέπουν να προσομοιάζουμε +// κλάσεις τύπων (type classes) σε άλλες συναρτησιακές γλώσσες. +// Χρησιμοποιείται τόσο συχνά που έχει την δικιά του συντομογραφία. +// Οι επόμενες δύο γραμμές κώδικα σημαίνουν το ίδιο πράγμα. +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... + + + +// Μια άλλη περίπτωση στην οποία ο μεταγλωττιστής αναζητά μια implicit τιμή +// είναι αν έχετε obj.method (...) +// αλλά το "obj" δεν έχει την "method" ως μέθοδο. Σε αυτή την περίπτωση, +// αν υπάρχει μια implicit μετατροπή του τύπου Α => Β, όπου Α είναι ο τύπος +// του obj, ενώ το Β έχει μία μέθοδο που ονομάζεται «method», εφαρμόζεται η +// εν λόγω μετατροπή. Έτσι, έχοντας την MyImplicitFunction μέσα στο πεδίο +// εφαρμογής(scope), μπορούμε να πούμε: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" + +// Εδώ το String αρχικά μετατρέπεται σε Dog χρησιμοποιώντας την συνάρτησή μας +// παραπάνω, και μετά καλείται η κατάλληλη μέθοδος. Αυτό είναι ένα εξερετικά +// ισχυρό χαρακτηριστικό, αλλά δεν πρέπει να χρησιμοποιείται με ελαφριά την +// καρδιά. Μάλιστα, όταν ορίσατε την συνάρτηση implicit παραπάνω, ο μεταγλωττιστής +// θα πρέπει να σας έδωσε μια προειδοποιήση, ότι δεν πρέπει να το κάνετε αυτό +// εκτός αν πραγματικά γνωρίζετε τι κάνετε. + + +///////////////////////////////////////////////// +// 9. Διάφορα +///////////////////////////////////////////////// + +// Εισαγωγή βιβλιοθηκών κτλ +import scala.collection.immutable.List + +// Εισαγωγή των πάντων απο το scala.collection.immutable +import scala.collection.immutable._ + +// Εισαγωγή πολλών κλάσεων σε μία έκφραση +import scala.collection.immutable.{List, Map} + +// Δώστε ένα νέο όνομα στην εισαγωγή σας χρησιμοποιώντας το '=>' +import scala.collection.immutable.{ List => ImmutableList } + +// Εισαγωγή όλων των κλάσεων εκτός απο μερικές. +// Το επόμενο δεν εισάγει το Map και το Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Το σημείο εισαγωγής του προγράμματος σας ορίζεται σε ένα αρχείο scala , +// χρησιμοποιώντας ένα αντικείμενο (object), με μία μέθοδο , την main. +object Application { + def main(args: Array[String]): Unit = { + // Εδω γράφουμε ... + } +} + +// Files can contain multiple classes and objects. Compile with scalac +// Τα files μπορούν να περιέχουν περισσότερες απο μία κλάσεις και +// αντικείμενα. Το compile γίνεται με την εντολή scalac + +// Εισαγωγή και εξαγωγή. + +// Για να διβάσετε ένα αρχείο γραμμή προς γραμμή +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + +// Για να γράψετε σε ένα αρχείο +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() + +``` + +## Further resources + +[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/) + +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) + diff --git a/elisp.html.markdown b/elisp.html.markdown index 3208ffb8..3bed5d1c 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -29,7 +29,7 @@ filename: learn-emacs-lisp.el ;; I hereby decline any responsability. Have fun! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; +;; ;; Fire up Emacs. ;; ;; Hit the `q' key to dismiss the welcome message. @@ -42,9 +42,9 @@ filename: learn-emacs-lisp.el ;; The scratch buffer is the default buffer when opening Emacs. ;; You are never editing files: you are editing buffers that you ;; can save to a file. -;; +;; ;; "Lisp interaction" refers to a set of commands available here. -;; +;; ;; Emacs has a built-in set of commands available in every buffer, ;; and several subsets of commands available when you activate a ;; specific mode. Here we use the `lisp-interaction-mode', which @@ -109,7 +109,7 @@ filename: learn-emacs-lisp.el ;; The empty parentheses in the function's definition means that ;; it does not accept arguments. But always using `my-name' is ;; boring, let's tell the function to accept one argument (here -;; the argument is called "name"): +;; the argument is called "name"): (defun hello (name) (insert "Hello " name)) ;; `C-xC-e' => hello @@ -305,7 +305,7 @@ filename: learn-emacs-lisp.el (defun boldify-names () (switch-to-buffer-other-window "*test*") (goto-char (point-min)) - (while (re-search-forward "Bonjour \\([^!]+\\)!" nil 't) + (while (re-search-forward "Bonjour \\(.+\\)!" nil 't) (add-text-properties (match-beginning 1) (match-end 1) (list 'face 'bold))) @@ -318,7 +318,7 @@ filename: learn-emacs-lisp.el ;; The regular expression is "Bonjour \\(.+\\)!" and it reads: ;; the string "Bonjour ", and ;; a group of | this is the \\( ... \\) construct -;; any character not ! | this is the [^!] +;; any character | this is the . ;; possibly repeated | this is the + ;; and the "!" string. diff --git a/elixir.html.markdown b/elixir.html.markdown index 0a20e3df..720e080c 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -91,6 +91,11 @@ string. <<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> "hello " <> "world" #=> "hello world" +# Ranges are represented as `start..end` (both inclusive) +1..10 #=> 1..10 +lower..upper = 1..10 # Can use pattern matching on ranges as well +[lower, upper] #=> [1, 10] + ## --------------------------- ## -- Operators ## --------------------------- @@ -190,7 +195,7 @@ cond do "But I will" end -# It is common to see the last condition equal to `true`, which will always match. +# It is common to set the last condition equal to `true`, which will always match. cond do 1 + 1 == 3 -> "I will never be seen" @@ -338,6 +343,7 @@ rescue RuntimeError -> "rescued a runtime error" _error -> "this will rescue any error" end +#=> "rescued a runtime error" # All exceptions have a message try do @@ -346,6 +352,7 @@ rescue x in [RuntimeError] -> x.message end +#=> "some error" ## --------------------------- ## -- Concurrency @@ -364,6 +371,13 @@ spawn(f) #=> #PID<0.40.0> # messages to the process. To do message passing we use the `send` operator. # For all of this to be useful we need to be able to receive messages. This is # achieved with the `receive` mechanism: + +# The `receive do` block is used to listen for messages and process +# them when they are received. A `receive do` block will only +# process one received message. In order to process multiple +# messages, a function with a `receive do` block must recursively +# call itself to get into the `receive do` block again. + defmodule Geometry do def area_loop do receive do @@ -379,6 +393,8 @@ end # Compile the module and create a process that evaluates `area_loop` in the shell pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Alternatively +pid = spawn(Geometry, :area_loop, []) # Send a message to `pid` that will match a pattern in the receive statement send pid, {:rectangle, 2, 3} diff --git a/erlang.html.markdown b/erlang.html.markdown index 04086aeb..d6ed7b86 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -18,29 +18,32 @@ filename: learnerlang.erl % Periods (`.`) (followed by whitespace) separate entire functions and % expressions in the shell. % Semicolons (`;`) separate clauses. We find clauses in several contexts: -% function definitions and in `case`, `if`, `try..catch` and `receive` +% function definitions and in `case`, `if`, `try..catch`, and `receive` % expressions. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 1. Variables and pattern matching. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% In Erlang new variables are bound with an `=` statement. Num = 42. % All variable names must start with an uppercase letter. -% Erlang has single assignment variables, if you try to assign a different value -% to the variable `Num`, you’ll get an error. +% Erlang has single-assignment variables; if you try to assign a different +% value to the variable `Num`, you’ll get an error. Num = 43. % ** exception error: no match of right hand side value 43 % In most languages, `=` denotes an assignment statement. In Erlang, however, -% `=` denotes a pattern matching operation. `Lhs = Rhs` really means this: -% evaluate the right side (Rhs), and then match the result against the pattern -% on the left side (Lhs). +% `=` denotes a pattern-matching operation. When an empty variable is used on the +% left hand side of the `=` operator to is bound (assigned), but when a bound +% variable is used on the left hand side the following behaviour is observed. +% `Lhs = Rhs` really means this: evaluate the right side (`Rhs`), and then +% match the result against the pattern on the left side (`Lhs`). Num = 7 * 6. -% Floating point number. +% Floating-point number. Pi = 3.14159. -% Atoms, are used to represent different non-numerical constant values. Atoms +% Atoms are used to represent different non-numerical constant values. Atoms % start with lowercase letters, followed by a sequence of alphanumeric % characters or the underscore (`_`) or at (`@`) sign. Hello = hello. @@ -53,34 +56,34 @@ AtomWithSpace = 'some atom with space'. % Tuples are similar to structs in C. Point = {point, 10, 45}. -% If we want to extract some values from a tuple, we use the pattern matching +% If we want to extract some values from a tuple, we use the pattern-matching % operator `=`. {point, X, Y} = Point. % X = 10, Y = 45 % We can use `_` as a placeholder for variables that we’re not interested in. % The symbol `_` is called an anonymous variable. Unlike regular variables, -% several occurrences of _ in the same pattern don’t have to bind to the same -% value. +% several occurrences of `_` in the same pattern don’t have to bind to the +% same value. Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. {_, {_, {_, Who}, _}, _} = Person. % Who = joe % We create a list by enclosing the list elements in square brackets and % separating them with commas. % The individual elements of a list can be of any type. -% The first element of a list is the head of the list. If you imagine removing the -% head from the list, what’s left is called the tail of the list. +% The first element of a list is the head of the list. If you imagine removing +% the head from the list, what’s left is called the tail of the list. ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. % If `T` is a list, then `[H|T]` is also a list, with head `H` and tail `T`. % The vertical bar (`|`) separates the head of a list from its tail. % `[]` is the empty list. -% We can extract elements from a list with a pattern matching operation. If we +% We can extract elements from a list with a pattern-matching operation. If we % have a nonempty list `L`, then the expression `[X|Y] = L`, where `X` and `Y` % are unbound variables, will extract the head of the list into `X` and the tail % of the list into `Y`. [FirstThing|OtherThingsToBuy] = ThingsToBuy. % FirstThing = {apples, 10} -% OtherThingsToBuy = {pears, 6}, {milk, 3} +% OtherThingsToBuy = [{pears, 6}, {milk, 3}] % There are no strings in Erlang. Strings are really just lists of integers. % Strings are enclosed in double quotation marks (`"`). @@ -117,17 +120,19 @@ c(geometry). % {ok,geometry} geometry:area({rectangle, 10, 5}). % 50 geometry:area({circle, 1.4}). % 6.15752 -% In Erlang, two functions with the same name and different arity (number of arguments) -% in the same module represent entirely different functions. +% In Erlang, two functions with the same name and different arity (number of +% arguments) in the same module represent entirely different functions. -module(lib_misc). --export([sum/1]). % export function `sum` of arity 1 accepting one argument: list of integers. +-export([sum/1]). % export function `sum` of arity 1 + % accepting one argument: list of integers. sum(L) -> sum(L, 0). sum([], N) -> N; sum([H|T], N) -> sum(T, H+N). -% Funs are "anonymous" functions. They are called this way because they have no -% name. However they can be assigned to variables. -Double = fun(X) -> 2*X end. % `Double` points to an anonymous function with handle: #Fun<erl_eval.6.17052888> +% Funs are "anonymous" functions. They are called this way because they have +% no name. However, they can be assigned to variables. +Double = fun(X) -> 2 * X end. % `Double` points to an anonymous function + % with handle: #Fun<erl_eval.6.17052888> Double(2). % 4 % Functions accept funs as their arguments and can return funs. @@ -140,8 +145,9 @@ Triple(5). % 15 % The notation `[F(X) || X <- L]` means "the list of `F(X)` where `X` is taken % from the list `L`." L = [1,2,3,4,5]. -[2*X || X <- L]. % [2,4,6,8,10] -% A list comprehension can have generators and filters which select subset of the generated values. +[2 * X || X <- L]. % [2,4,6,8,10] +% A list comprehension can have generators and filters, which select subset of +% the generated values. EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] % Guards are constructs that we can use to increase the power of pattern @@ -155,17 +161,31 @@ max(X, Y) -> Y. % A guard is a series of guard expressions, separated by commas (`,`). % The guard `GuardExpr1, GuardExpr2, ..., GuardExprN` is true if all the guard -% expressions `GuardExpr1, GuardExpr2, ...` evaluate to true. +% expressions `GuardExpr1`, `GuardExpr2`, ..., `GuardExprN` evaluate to `true`. is_cat(A) when is_atom(A), A =:= cat -> true; is_cat(A) -> false. is_dog(A) when is_atom(A), A =:= dog -> true; is_dog(A) -> false. -% A `guard sequence` is either a single guard or a series of guards, separated -%by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at least -% one of the guards `G1, G2, ...` evaluates to true. -is_pet(A) when is_dog(A); is_cat(A) -> true; -is_pet(A) -> false. +% We won't dwell on the `=:=` operator here; just be aware that it is used to +% check whether two Erlang expressions have the same value *and* the same type. +% Contrast this behaviour to that of the `==` operator: +1 + 2 =:= 3. % true +1 + 2 =:= 3.0. % false +1 + 2 == 3.0. % true + +% A guard sequence is either a single guard or a series of guards, separated +% by semicolons (`;`). The guard sequence `G1; G2; ...; Gn` is true if at +% least one of the guards `G1`, `G2`, ..., `Gn` evaluates to `true`. +is_pet(A) when is_atom(A), (A =:= dog) or (A =:= cat) -> true; +is_pet(A) -> false. + +% Warning: not all valid Erlang expressions can be used as guard expressions; +% in particular, our `is_cat` and `is_dog` functions cannot be used within the +% guard sequence in `is_pet`'s definition. For a description of the +% expressions allowed in guard sequences, refer to this +% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) +% of the Erlang reference manual. % Records provide a method for associating a name with a particular element in a % tuple. @@ -188,7 +208,7 @@ X = #todo{}. X1 = #todo{status = urgent, text = "Fix errata in book"}. % #todo{status = urgent, who = joe, text = "Fix errata in book"} X2 = X1#todo{status = done}. -% #todo{status = done,who = joe,text = "Fix errata in book"} +% #todo{status = done, who = joe, text = "Fix errata in book"} % `case` expressions. % `filter` returns a list of all elements `X` in a list `L` for which `P(X)` is @@ -206,11 +226,11 @@ max(X, Y) -> if X > Y -> X; X < Y -> Y; - true -> nil; + true -> nil end. -% Warning: at least one of the guards in the `if` expression must evaluate to true; -% otherwise, an exception will be raised. +% Warning: at least one of the guards in the `if` expression must evaluate to +% `true`; otherwise, an exception will be raised. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -218,7 +238,7 @@ max(X, Y) -> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Exceptions are raised by the system when internal errors are encountered or -% explicitly in code by calling `throw(Exception)`, `exit(Exception)` or +% explicitly in code by calling `throw(Exception)`, `exit(Exception)`, or % `erlang:error(Exception)`. generate_exception(1) -> a; generate_exception(2) -> throw(a); @@ -227,7 +247,7 @@ generate_exception(4) -> {'EXIT', a}; generate_exception(5) -> erlang:error(a). % Erlang has two methods of catching an exception. One is to enclose the call to -% the function, which raised the exception within a `try...catch` expression. +% the function that raises the exception within a `try...catch` expression. catcher(N) -> try generate_exception(N) of Val -> {N, normal, Val} @@ -241,23 +261,24 @@ catcher(N) -> % exception, it is converted into a tuple that describes the error. catcher(N) -> catch generate_exception(N). -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% 4. Concurrency %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Erlang relies on the actor model for concurrency. All we need to write -% concurrent programs in erlang are three primitives: spawning processes, +% concurrent programs in Erlang are three primitives: spawning processes, % sending messages and receiving messages. -% To start a new process we use the `spawn` function, which takes a function +% To start a new process, we use the `spawn` function, which takes a function % as argument. F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768> spawn(F). % <0.44.0> -% `spawn` returns a pid (process identifier), you can use this pid to send -% messages to the process. To do message passing we use the `!` operator. -% For all of this to be useful we need to be able to receive messages. This is +% `spawn` returns a pid (process identifier); you can use this pid to send +% messages to the process. To do message passing, we use the `!` operator. +% For all of this to be useful, we need to be able to receive messages. This is % achieved with the `receive` mechanism: -module(calculateGeometry). @@ -271,15 +292,49 @@ calculateArea() -> _ -> io:format("We can only calculate area of rectangles or circles.") end. - -% Compile the module and create a process that evaluates `calculateArea` in the shell + +% Compile the module and create a process that evaluates `calculateArea` in the +% shell. c(calculateGeometry). CalculateArea = spawn(calculateGeometry, calculateArea, []). CalculateArea ! {circle, 2}. % 12.56000000000000049738 -% The shell is also a process, you can use `self` to get the current pid +% The shell is also a process; you can use `self` to get the current pid. self(). % <0.41.0> +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 5. Testing with EUnit +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Unit tests can be written using EUnits's test generators and assert macros +-module(fib). +-export([fib/1]). +-include_lib("eunit/include/eunit.hrl"). + +fib(0) -> 1; +fib(1) -> 1; +fib(N) when N > 1 -> fib(N-1) + fib(N-2). + +fib_test_() -> + [?_assert(fib(0) =:= 1), + ?_assert(fib(1) =:= 1), + ?_assert(fib(2) =:= 2), + ?_assert(fib(3) =:= 3), + ?_assert(fib(4) =:= 5), + ?_assert(fib(5) =:= 8), + ?_assertException(error, function_clause, fib(-1)), + ?_assert(fib(31) =:= 2178309) + ]. + +% EUnit will automatically export to a test() function to allow running the tests +% in the erlang shell +fib:test() + +% The popular erlang build tool Rebar is also compatible with EUnit +% ``` +% rebar eunit +% ``` + ``` ## References diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown new file mode 100644 index 00000000..7a59ddd6 --- /dev/null +++ b/es-es/amd-es.html.markdown @@ -0,0 +1,214 @@ +--- + +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] + +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +filename: learnamd-es.js +lang: es-es +--- + +## Iniciando con AMD + +El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. + +### Conceptos básicos +```javascript +// El API básico de AMD consiste en tan solo dos métodos: `define` y `require` +// y se basa en la definición y consumo de los módulos: +// `define(id?, dependencias?, fábrica)` define un módulo +// `require(dependencias, callback)` importa un conjunto de dependencias y +// las consume al invocar el callback + +// Comencemos usando define para definir un nuevo módulo +// que no posee dependencias. Lo haremos enviando un nombre +// y una función fábrica para definirla: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // El valor que regresa la función fábrica del módulo será + // lo que los otros módulos o llamados require recibirán cuando + // soliciten nuestro módulo `awesomeAMD`. + // El valor exportado puede ser cualquier cosa, funciones (constructores), + // objetos, primitivos, incluso indefinidos (aunque eso no ayuda mucho). + return isAMDAwesome; +}); + +// Ahora definamos otro módulo que dependa de nuestro módulo `awesomeAMD`. +// Observe que ahora hay un argumento adicional que define +// las dependencias de nuestro módulo: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // las dependencias serán enviadas a los argumentos de la fábrica + // en el orden que sean especificadas + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// Como ya sabemos utilizar define usemos ahora `require` para poner en marcha +// nuestro programa. La firma de `require` es `(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// Para hacer que este tutorial corra código, vamos a implementar una +// versión muy básica (no-asíncrona) de AMD justo aquí: +function define(name, deps, factory){ + // observa como son manejados los módulos sin dependencias + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // primero recuperemos todas las dependencias que necesita + // el llamado require + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // satisfacer todas las dependencias del callback + return callback.apply(null, args); +} +// puedes ver este código en acción aquí: http://jsfiddle.net/qap949pd/ +``` + +### Uso en el mundo real con require.js + +En contraste con el ejemplo introductorio, `require.js` (la librería AMD más popular) implementa la **A** de **AMD**, permitiéndote cargar los módulos y sus dependencias asincrónicamente via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // el callback es diferido hasta que la dependencia sea cargada + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // esto correrá primero +``` + +Por convención, usualmente guardas un módulo en un fichero. `require.js` puede resolver los nombres de los módulos basados en rutas de archivo, de forma que no tienes que nombrar tus módulos, simplemente referenciarlos usando su ubicación. En el ejemplo `someClass` asumimos que se ubica en la carpeta `modules`, relativa a tu `baseUrl` configurada: + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Esto significa que podemos definir `someClass` sin especificar su id de módulo: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definición de módulo, por supuesto, ocurrirá también asincrónicamente + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` + +Para alterar el comportamiento del mapeo de ruta usa `requirejs.config(configObj)` en tu `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // también puedes cargar módulos desde otras ubicaciones + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // un fichero `main` necesita llamar a require al menos una vez, + // de otra forma jamás correrá el código + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Cien etiquetas de script? Nunca más!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### Optimizar todo un proyecto usando r.js + +Muchas personas prefieren usar AMD para la organización del código durante el desarrollo, pero quieren enviar para producción un solo fichero en vez de ejecutar cientos de XHRs en las cargas de página. + +`require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. + +Instálalo usando `npm`: +```shell +$ npm install requirejs -g +``` + +Ahora puedes alimentarlo con un fichero de configuración: +```shell +$ r.js -o app.build.js +``` + +Para nuestro ejemplo anterior el archivo de configuración luciría así: +```javascript +/* file : app.build.js */ +({ + name : 'main', // nombre del punto de entrada + out : 'main-built.js', // nombre del fichero donde se escribirá la salida + baseUrl : 'app', + paths : { + // `empty:` le dice a r.js que esto aún debe ser cargado desde el CDN, usando + // la ubicación especificada en `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Para usar el fichero creado en producción, simplemente intercambia `data-main`: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +Un increíblemente detallado [resumen de opciones de generación](https://github.com/jrburke/r.js/blob/master/build/example.build.js) está disponible en el repositorio de GitHub. + +### Tópicos no cubiertos en este tutorial +* [Cargador de plugins / transformaciones](http://requirejs.org/docs/plugins.html) +* [Cargando y exportando estilos CommonJS](http://requirejs.org/docs/commonjs.html) +* [Configuración avanzada](http://requirejs.org/docs/api.html#config) +* [Configuración de Shim (cargando módulos no-AMD)](http://requirejs.org/docs/api.html#config-shim) +* [Cargando y optimizando CSS con require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Usando almond.js para construcciones](https://github.com/jrburke/almond) + +### Otras lecturas: + +* [Especificaciones oficiales](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [¿Por qué AMD?](http://requirejs.org/docs/whyamd.html) +* [Definición Universal de Módulos](https://github.com/umdjs/umd) + +### Implementaciones: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown index e33d672d..550511da 100644 --- a/es-es/brainfuck-es.html.markdown +++ b/es-es/brainfuck-es.html.markdown @@ -9,8 +9,10 @@ lang: es-es --- Brainfuck (con mayúscula sólo al inicio de una oración) es un -lenguaje de programación mínimo, computacionalmente universal -en tamaño con sólo 8 comandos. +lenguaje de programación extremadamente pequeño, Turing completo con sólo 8 comandos. + +Puedes probar brainfuck en tu navegador con [brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + ``` @@ -18,7 +20,7 @@ Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas) será ignorado. Brainfuck es representado por un arreglo de 30,000 celdas inicializadas -en cero y un apuntador en la celda actual. +en cero y un puntero apuntando la celda actual. Existen ocho comandos: @@ -26,7 +28,7 @@ Existen ocho comandos: - : Decrementa 1 al valor de la celda actual. > : Mueve el apuntador a la siguiente celda. (a la derecha) < : Mueve el apuntador a la celda anterior. (a la izquierda) -. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A') +. : Imprime el valor en ASCII de la celda actual (p.e. 65 = 'A') , : Lee un caracter como input y lo escribe en la celda actual. [ : Si el valor en la celda actual es cero mueve el apuntador hasta el primer ']' que encuentre. Si no es cero sigue a la @@ -37,7 +39,7 @@ Existen ocho comandos: [ y ] forman un while. Obviamente, deben estar balanceados. -Ahora unos ejemplos de programas escritos con brainfuck. +Estos son algunos ejemplos de programas escritos con brainfuck. ++++++ [ > ++++++++++ < - ] > +++++ . @@ -63,7 +65,7 @@ Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.). -Ten en mente que los espacios son sólo para fines de legibilidad. +Ten en cuenta que los espacios son sólo para fines de legibilidad. Es lo mismo escribir el ejemplo de arriba que esto: ,[>+<-]>. @@ -81,7 +83,7 @@ hasta la próxima vez. Para resolver este problema también incrementamos la celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene el resultado. ``` -Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir +Y eso es brainfuck. No es tan difícil, ¿verdad? Como diversión, puedes escribir tu propio intérprete de brainfuck o tu propio programa en brainfuck. El intérprete es relativamente sencillo de hacer, pero si eres masoquista, -intenta construir tu proprio intérprete de brainfuck... en brainfuck. +puedes intentar construir tu propio intérprete de brainfuck... en brainfuck. diff --git a/es-es/c++-es.html.markdown b/es-es/c++-es.html.markdown new file mode 100644 index 00000000..bcc775e5 --- /dev/null +++ b/es-es/c++-es.html.markdown @@ -0,0 +1,829 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] +translators: + - ["Gerson Lázaro", "https://gersonlazaro.com"] +lang: es-es +--- + +C++ es un lenguaje de programación de sistemas que, +[de acuerdo a su inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +fue diseñado para + +- ser un "mejor C" +- soportar abstracción de datos +- soportar programación orientada a objetos +- soportar programación genérica + +Aunque su sintaxis puede ser más difícil o compleja que los nuevos lenguajes, +es ampliamente utilizado, ya que compila instrucciones nativas que pueden ser +directamente ejecutadas por el procesador y ofrece un estricto control sobre +el hardware (como C), mientras ofrece características de alto nivel como +genericidad, excepciones, y clases. Esta combinación de velocidad y +funcionalidad hace de C ++ uno de los lenguajes de programación más utilizados. + +```c++ +//////////////////// +// Comparación con C +//////////////////// + +// C ++ es _casi_ un superconjunto de C y comparte su sintaxis básica para las +// declaraciones de variables, tipos primitivos y funciones. + +// Al igual que en C, el punto de entrada de tu programa es una función llamada +// main con un retorno de tipo entero. +// Este valor sirve como código de salida del programa. +// Mira http://en.wikipedia.org/wiki/Exit_status para mayor información. +int main(int argc, char** argv) +{ + // Los argumentos de la línea de comandos se pasan por argc y argv de la + // misma manera que en C. + // argc indica el número de argumentos, + // y argv es un arreglo de strings de estilo C (char*) + // representando los argumentos. + // El primer argumento es el nombre con el que el programa es llamado. + // argc y argv pueden omitirse si no te preocupan los argumentos, + // dejando la definición de la función como int main () + + // Un estado de salida 0 indica éxito. + return 0; +} + +// Sin embargo, C ++ varía en algunas de las siguientes maneras: + +// En C++, los caracteres literales son caracteres +sizeof('c') == sizeof(char) == 1 + +// En C, los caracteres literales son enteros +sizeof('c') == sizeof(int) + + +// C++ tiene prototipado estricto +void func(); // función que no acepta argumentos + +// En C +void func(); // función que puede aceptar cualquier número de argumentos + +// Use nullptr en lugar de NULL en C++ +int* ip = nullptr; + +// Las cabeceras (headers) estándar de C están disponibles en C ++, +// pero tienen el prefijo "c" y no tienen sufijo .h. +#include <cstdio> + +int main() +{ + printf("Hola mundo!\n"); + return 0; +} + +////////////////////////// +// Sobrecarga de funciones +////////////////////////// + +// C++ soporta sobrecarga de funciones +// siempre que cada función tenga diferentes parámetros. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("Mi entero es %d", myInt); +} + +int main() +{ + print("Hello"); // Resolves to void print(const char*) + print(15); // Resolves to void print(int) +} + +//////////////////////////////////// +// Argumentos de función por defecto +//////////////////////////////////// + +// Puedes proporcionar argumentos por defecto para una función si no son +// proporcionados por quien la llama. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Hacer algo con los enteros aqui +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Los argumentos predeterminados deben estar al final de la lista de argumentos. + +void invalidDeclaration(int a = 1, int b) // Error! +{ +} + +///////////////////// +// Espacios de nombre +///////////////////// + +// Espacios de nombres proporcionan ámbitos separados para variable, función y +// otras declaraciones. +// Los espacios de nombres se pueden anidar. + +namespace First { + namespace Nested { + void foo() + { + printf("Esto es First::Nested::foo\n"); + } + } // fin del nombre de espacio Nested +} // fin del nombre de espacio First + +namespace Second { + void foo() + { + printf("Esto es Second::foo\n") + } +} + +void foo() +{ + printf("Este es global: foo\n"); +} + +int main() +{ + + // Incluye todos los símbolos del espacio de nombre Second en el ámbito + // actual. Tenga en cuenta que simplemente foo() no funciona, ya que ahora + // es ambigua si estamos llamando a foo en espacio de nombres Second o en + // el nivel superior. + using namespace Second; + + Second::foo(); // imprime "Esto es Second::foo" + First::Nested::foo(); // imprime "Esto es First::Nested::foo" + ::foo(); // imprime "Este es global: foo" +} + +///////////////// +// Entrada/Salida +///////////////// + +// La entrada y salida de C++ utiliza flujos (streams) +// cin, cout, y cerr representan a stdin, stdout, y stderr. +// << es el operador de inserción >> es el operador de extracción. + + +#include <iostream> // Incluir para el flujo de entrada/salida + +using namespace std; // Los streams estan en std namespace (libreria estandar) + +int main() +{ + int myInt; + + // Imprime a la stdout (o terminal/pantalla) + cout << "Ingresa tu número favorito:\n"; + // Toma una entrada + cin >> myInt; + + // cout puede también ser formateado + cout << "Tu número favorito es " << myInt << "\n"; + // imprime "Tu número favorito es <myInt>" + + cerr << "Usado para mensajes de error"; +} +//////////////////// +// Cadenas (Strings) +//////////////////// + +// Las cadenas en C++ son objetos y tienen muchas funciones +#include <string> + +using namespace std; // Strings también estan en namespace std + +string myString = "Hola"; +string myOtherString = " Mundo"; + +// + es usado para concatenar. +cout << myString + myOtherString; // "Hola Mundo" + +cout << myString + " Tu"; // "Hola Tu" + +// Las cadenas en C++ son mutables y tienen valor semántico. +myString.append(" Perro"); +cout << myString; // "Hola Perro" + + +////////////// +// Referencias +////////////// + +// Además de punteros como los de C, +// C++ tiene _references_. +// Estos tipos de puntero no pueden ser reasignados una vez establecidos +// Y no pueden ser nulos. +// También tienen la misma sintaxis que la propia variable: +// No es necesaria * para eliminar la referencia y +// & (dirección) no se utiliza para la asignación. + +using namespace std; + +string foo = "Yo soy foo"; +string bar = "Yo soy bar"; + +string& fooRef = foo; // Crea una referencia a foo. +fooRef += ". Hola!"; // Modifica foo través de la referencia +cout << fooRef; // Imprime "Yo soy foo. Hola!" + +// No trate de reasignar "fooRef". Esto es lo mismo que "foo = bar", y +// foo == "Yo soy bar" +// después de esta linea. +fooRef = bar; + +const string& barRef = bar; // Crea una referencia constante a bar. +// Como en C, los valores constantes (y punteros y referencias) no pueden ser +// modificados. +barRef += ". Hola!"; // Error, referencia constante no puede ser modificada. + +// Sidetrack: Antes de hablar más sobre referencias, hay que introducir un +// concepto llamado objeto temporal. Supongamos que tenemos el siguiente código: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Lo que pasa en la segunda línea es en realidad: +// - Un objeto de cadena es retornado desde tempObjectFun +// - Una nueva cadena se construye con el objeto devuelto como argumento al +// constructor +// - El objeto devuelto es destruido +// El objeto devuelto se llama objeto temporal. Objetos temporales son +// creados cada vez que una función devuelve un objeto, y es destruido en el +// fin de la evaluación de la expresión que encierra (Bueno, esto es lo que la +// norma dice, pero los compiladores están autorizados a cambiar este +// comportamiento. Busca "return value optimization" para ver mas detalles). +// Así que en este código: +foo(bar(tempObjectFun())) + +// Suponiendo que foo y bar existen, el objeto retornado de tempObjectFun es +// pasado al bar, y se destruye antes de llamar foo. + +// Ahora, de vuelta a las referencias. La excepción a la regla "en el extremo +// de la expresión encerrada" es si un objeto temporal se une a una +// referencia constante, en cuyo caso su vida se extiende al ámbito actual: + +void constReferenceTempObjectFun() { + // ConstRef obtiene el objeto temporal, y es válido hasta el final de esta + // función. + const string& constRef = tempObjectFun(); + ... +} + +// Otro tipo de referencia introducida en C ++ 11 es específicamente para +// objetos temporales. No se puede tener una variable de este tipo, pero tiene +// prioridad en resolución de sobrecarga: + +void someFun(string& s) { ... } // Referencia regular +void someFun(string&& s) { ... } // Referencia a objeto temporal + +string foo; +someFun(foo); // Llama la función con referencia regular +someFun(tempObjectFun()); // Llama la versión con referencia temporal + +// Por ejemplo, puedes ver estas dos versiones de constructores para +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// La idea es que si estamos construyendo una nueva cadena de un objeto temporal +// (que va a ser destruido pronto de todos modos), podemos tener un constructor +// mas eficiente que "rescata" partes de esa cadena temporal. Usted verá este +// Concepto denominado "movimiento semántico". + +//////////////////////////////////////////// +// Clases y programación orientada a objetos +//////////////////////////////////////////// + +// Primer ejemplo de clases +#include <iostream> + +// Declara una clase. +// Las clases son usualmente declaradas en archivos de cabeceras (.h o .hpp) +class Dog { + // Variables y funciones de la clase son privados por defecto. + std::string name; + int weight; + +// Todos los miembros siguientes de este son públicos +// Hasta que se encuentre "private" o "protected". +// All members following this are public +// until "private:" or "protected:" is found. +public: + + // Constructor por defecto + Dog(); + + // Declaraciones de funciones de la clase (implementaciones a seguir) + // Nota que usamos std::string aquí en lugar de colocar + // using namespace std; + // arriba. + // Nunca ponga una declaración "using namespace" en un encabezado. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + // Funciones que no modifican el estado del objeto + // Deben marcarse como const. + // Esto le permite llamarlas si se envia una referencia constante al objeto. + // También tenga en cuenta que las funciones deben ser declaradas + // explícitamente como _virtual_ para que sea reemplazada en las clases + // derivadas. + // Las funciones no son virtuales por defecto por razones de rendimiento. + virtual void print() const; + + // Las funciones también se pueden definir en el interior + // del cuerpo de la clase. + // Funciones definidas como tales están entre líneas automáticamente. + void bark() const { std::cout << name << " barks!\n"; } + + // Junto a los constructores, C++ proporciona destructores. + // Estos son llamados cuando un objeto se elimina o está fuera del ámbito. + // Esto permite paradigmas potentes como RAII + // (mira abajo) + // El destructor debe ser virtual si una clase es dervada desde el; + // Si no es virtual, entonces la clase derivada destructor + // No será llamada si el objeto se destruye a través de una referencia de + // la clase base o puntero. + virtual ~Dog(); + + + +}; // Un punto y coma debe seguir la definición de clase. + +// Las funciones de una clase son normalmente implementados en archivos .cpp. +Dog::Dog() +{ + std::cout << "Un perro ha sido construido\n"; +} + +// Objetos (tales como cadenas) deben ser pasados por referencia +// Si los estas modificando o referencia constante en caso contrario. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Nota que "virtual" sólo se necesita en la declaración, no en la definición. +void Dog::print() const +{ + std::cout << "El perro es " << name << " y pesa " << weight << "kg\n"; +} + +Dog::~Dog() +{ + cout << "Adiós " << name << "\n"; +} + +int main() { + Dog myDog; // imprime "Un perro ha sido construido" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // imprime "El perro es Barkley y pesa 10 kg" + return 0; +} // imprime "Adiós Barkley" + +// Herencia: + +// Esta clase hereda todo lo público y protegido de la clase Dog +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner); + + // Reemplaza el comportamiento de la función de impresión + // de todos los OwnedDogs. Mira + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // Para una introducción más general si no está familiarizado con el + // polimorfismo de subtipo. + // La palabra clave override es opcional, pero asegura que estás + // reemplazando el método de una clase base. + void print() const override; + +private: + std::string owner; +}; + +// Mientras tanto, en el archivo .cpp correspondiente: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Llama a la función de impresión en la clase base Dog + std::cout << "El perro es de " << owner << "\n"; + // Imprime "El perro es <name> y pesa <weight>" + // "El perro es de <owner>" +} + +//////////////////////////////////////////// +// Inicialización y sobrecarga de operadores +//////////////////////////////////////////// + +// En C ++ se puede sobrecargar el comportamiento +// de los operadores como +, -, *, /, etc. +// Esto se hace mediante la definición de una función que es llamada +// cada vez que se utiliza el operador. + +#include <iostream> +using namespace std; + +class Point { +public: + // Las variables de la clase pueden dar valores por defecto de esta manera. + double x = 0; + double y = 0; + + // Define un constructor por defecto que no hace nada + // pero inicializa el punto al valor por defecto (0, 0) + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* No hace nada excepto inicializar los valores */ } + + // Sobrecarga el operador + + Point operator+(const Point& rhs) const; + + // Sobrecarga el operador += + Point& operator+=(const Point& rhs); + + // También tendría sentido añadir los operadores - y -=, + // Pero vamos a omitirlos por razones de brevedad. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Crea un nuevo punto que es la suma de este y rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // Llama al operador + de Point + // Point llama la función + con right como parámetro + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////////// +// Plantillas (Templates) +///////////////////////// + +// Las plantillas en C++ se utilizan sobre todo en la programación genérica, +// a pesar de que son mucho más poderoso que los constructores genéricos +// en otros lenguajes. Ellos también soportan especialización explícita y +// parcial y clases de tipo estilo funcional; de hecho, son un lenguaje +// funcional Turing-completo incrustado en C ++! + +// Empezamos con el tipo de programación genérica que podría estar +// familiarizado. +// Para definir una clase o función que toma un parámetro de tipo: +template<class T> +class Box { +public: + // En este caso, T puede ser usado como cualquier otro tipo. + void insert(const T&) { ... } +}; + +// Durante la compilación, el compilador realmente genera copias de cada +// plantilla con parámetros sustituidos, por lo que la definición completa +// de la clase debe estar presente en cada invocación. +// Es por esto que usted verá clases de plantilla definidas +// Enteramente en archivos de cabecera. + +//Para crear una instancia de una clase de plantilla en la pila: +Box<int> intBox; + +y puedes utilizarlo como era de esperar: +intBox.insert(123); + +// Puedes, por supuesto, anidar plantillas: +Box<Box<int> > boxOfBox; +boxOfBox.insert(intBox); + +// Hasta C++11, había que colocar un espacio entre los dos '>'s, +// de lo contrario '>>' serían analizados como el operador de desplazamiento +// a la derecha. + + +// A veces verás +// template<typename T> +// en su lugar. La palabra clave "class" y las palabras clave "typename" son +// mayormente intercambiables en este caso. Para la explicación completa, mira +// http://en.wikipedia.org/wiki/Typename +// (sí, esa palabra clave tiene su propia página de Wikipedia). + +// Del mismo modo, una plantilla de función: +template<class T> +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// Observe que no se especifica nada acerca de los tipos de parámetros aquí. +// El compilador generará y comprobará cada invocación de la plantilla, +// por lo que la función anterior funciona con cualquier tipo "T" +// que tenga un método 'bark' constante! + + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); // Imprime "Fluffy barks" 3 veces. + +Los parámetros de la plantilla no tienen que ser las clases: +template<int Y> +void printMessage() { + cout << "Aprende C++ en " << Y << " minutos!" << endl; +} + +// Y usted puede especializar explícitamente plantillas +// para código más eficiente. +// Por supuesto, la mayor parte del mundo real que utiliza una especialización +// no son tan triviales como esta. +// Tenga en cuenta que usted todavía tiene que declarar la función (o clase) +// como plantilla incluso si ha especificado de forma explícita todos +// los parámetros. + +template<> +void printMessage<10>() { + cout << "Aprende C++ rapido en solo 10 minutos!" << endl; +} + +printMessage<20>(); // Prints "Aprende C++ en 20 minutos!" +printMessage<10>(); // Prints "Aprende C++ rapido en solo 10 minutos!" + + +///////////////////// +// Manejador de excepciones +///////////////////// + +// La biblioteca estándar proporciona algunos tipos de excepción +// (mira http://en.cppreference.com/w/cpp/error/exception) +// pero cualquier tipo puede ser lanzado como una excepción +#include <exception> +#include <stdexcept> + +//Todas las excepciones lanzadas dentro del bloque _try_ pueden ser +// capturados por los siguientes manejadores _catch_. +try { + // No asignar excepciones en el heap usando _new_. + throw std::runtime_error("Ocurrió un problema"); +} + +// Captura excepciones por referencia const si son objetos +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} +******************************************************************************** +// Captura cualquier excepción no capturada por bloques _catch_ anteriores +catch (...) +{ + std::cout << "Excepción desconocida capturada"; + throw; // Re-lanza la excepción +} + +/////// +// RAII +/////// + +// RAII significa "Resource Acquisition Is Initialization" +// (Adquisición de recursos es inicialización). +// A menudo se considera el paradigma más poderoso en C++ +// Y el concepto es simple: un constructor de un objeto +// Adquiere recursos de ese objeto y el destructor les libera. + +// Para entender cómo esto es útil, +// Considere una función que utiliza un identificador de archivo C: +void doSomethingWithAFile(const char* filename) +{ + // Para empezar, asuma que nada puede fallar. + + FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Cierra el manejador de archivos +} + +// Por desgracia, las cosas se complican rápidamente por el control de errores. +// Supongamos que fopen puede fallar, y que doSomethingWithTheFile y +// DoSomethingElseWithIt retornan códigos de error si fallan. +// (Excepciones son la mejor forma de manejar los fallos, +// pero algunos programadores, especialmente los que tienen un fondo C, +// estan en desacuerdo sobre la utilidad de las excepciones). +// Ahora tenemos que comprobar cada llamado por fallos y cerrar el manejador +// del archivo si se ha producido un problema. +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abre el archivo en modo lectura + if (fh == nullptr) // El puntero retornado es nulo o falla. + return false; // Reporta el fallo a quien hizo el llamado. + + // Asume que cada función retorna falso si falla + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Cierre el manejador de archivo para que no se filtre. + return false; // Propaga el error. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Cierre el manejador de archivo para que no se filtre. + return false; // Propaga el error. + } + + fclose(fh); // Cierre el archivo. + return true; // Indica que todo funcionó correctamente. +} + +// Programadores C suelen limpiar esto un poco usando goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Cierre el archivo. + return true; // Indica que todo funcionó correctamente. + +failure: + fclose(fh); + return false; // Propagate el error +} + +// Si las funciones indican errores mediante excepciones, +// Las cosas son un poco más claras, pero pueden optimizarse mas. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abrir el archivo en modo lectura + if (fh == nullptr) + throw std::runtime_error("No puede abrirse el archivo."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Asegúrese de cerrar el archivo si se produce un error. + throw; // Luego vuelve a lanzar la excepción. + } + + fclose(fh); // Cierra el archivo +} + +// Compare esto con el uso de la clase de flujo de archivos de C++ (fstream) +// fstream utiliza su destructor para cerrar el archivo. +// Los destructores son llamados automáticamente +// cuando un objeto queda fuera del ámbito. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream es la abreviatura de el input file stream + std::ifstream fh(filename); // Abre el archivo + + // Hacer algo con el archivo + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // El archivo se cierra automáticamente aquí por el destructor + + +// Esto tiene ventajas _enormes_: +// 1. No importa lo que pase, +// El recurso (en este caso el manejador de archivo) será limpiado. +// Una vez que escribes el destructor correctamente, +// Es _imposible_ olvidar cerrar el identificador y permitir +// fugas del recurso. +// 2. Tenga en cuenta que el código es mucho más limpio. +// El destructor se encarga de cerrar el archivo detrás de cámaras +// Sin que tenga que preocuparse por ello. +// 3. El código es seguro. +// Una excepción puede ser lanzado en cualquier lugar de la función +// y la limpieza ocurrirá. + +// Todo el código idiomático C++ utiliza RAII ampliamente para todos los +// recursos. +// Otros ejemplos incluyen +// - Memoria usando unique_ptr y shared_ptr +// - Contenedores (Containers) - la biblioteca estándar linked list, +// vector (es decir, array con auto-cambio de tamaño), hash maps, etc. +// Destruimos todos sus contenidos de forma automática +// cuando quedan fuera del ámbito. +// - Mutex utilizando lock_guard y unique_lock + + +///////////////////// +// Cosas divertidas +///////////////////// + +// Aspectos de C ++ que pueden sorprender a los recién llegados +// (e incluso algunos veteranos). +// Esta sección es, por desgracia, salvajemente incompleta; +// C++ es uno de los lenguajes con los que mas facil te disparas en el pie. + +// Tu puedes sobreescribir métodos privados! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Sobreescribe Foo::bar! +}; + + +// 0 == false == NULL (La mayoria de las veces)! +bool* pt = new bool; +*pt = 0; // Establece los puntos de valor de 'pt' en falso. +pt = 0; // Establece 'pt' al apuntador nulo. Ambas lineas compilan sin error. + +// nullptr se supone que arregla un poco de ese tema: +int* pt2 = new int; +*pt2 = nullptr; // No compila +pt2 = nullptr; // Establece pt2 como null. + +// Hay una excepción para los valores bool. +// Esto es para permitir poner a prueba punteros nulos con if (!ptr), +// pero como consecuencia se puede asignar nullptr a un bool directamente! +*pt = nullptr; // Esto todavía compila, a pesar de que '*pt' es un bool! + +// '=' != '=' != '='! +// Llama Foo::Foo(const Foo&) o alguna variante (mira movimientos semanticos) +// copia del constructor. +Foo f2; +Foo f1 = f2; + +// Llama Foo::Foo(const Foo&) o variante, pero solo copia el 'Foo' parte de +// 'fooSub'. Cualquier miembro extra de 'fooSub' se descarta. Este +// comportamiento horrible se llama "Corte de objetos." +FooSub fooSub; +Foo f1 = fooSub; + +// Llama a Foo::operator=(Foo&) o variantes. +Foo f1; +f1 = f2; + + +// Cómo borrar realmente un contenedor: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); +// La siguiente línea establece el tamaño de v en 0, +// pero los destructores no son llamados y los recursos no se liberan! + +v.empty(); +v.push_back(Foo()); // Nuevo valor se copia en el primer Foo que insertamos + +// En verdad destruye todos los valores en v. +// Consulta la sección acerca de los objetos temporales para la +// explicación de por qué esto funciona. +v.swap(vector<Foo>()); + +``` +Otras lecturas: + +Una referencia del lenguaje hasta a la fecha se puede encontrar en +<http://cppreference.com/w/cpp> + +Recursos adicionales se pueden encontrar en <http://cplusplus.com> diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 5c9d3378..4e1e68ba 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -11,18 +11,18 @@ lang: es-es --- Git es un sistema de control de versiones distribuido diseñado para manejar -cualquier tipo de proyecto ya sea largos o pequeños, con velocidad y eficiencia. +cualquier tipo de proyecto, ya sea grande o pequeño, con velocidad y eficiencia. Git realiza esto haciendo "snapshots" del proyecto, con ello permite versionar y administrar nuestro código fuente. ## Versionamiento, conceptos. -### Que es el control de versiones? -El control de versiones es un sistema que guarda todos los cambios realizados a +### ¿Qué es el control de versiones? +El control de versiones es un sistema que guarda todos los cambios realizados en uno o varios archivos, a lo largo del tiempo. -### Versionamiento centralizado vs Versionamiento Distribuido. +### Versionamiento centralizado vs versionamiento distribuido. + El versionamiento centralizado se enfoca en sincronizar, rastrear, y respaldar archivos. @@ -31,15 +31,15 @@ uno o varios archivos, a lo largo del tiempo. + El versionamiento distribuido no tiene una estructura definida, incluso se puede mantener el estilo de los repositorios SVN con git. -[Informacion adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) +[Información adicional](http://git-scm.com/book/es/Empezando-Acerca-del-control-de-versiones) -### Por que usar Git? +### ¿Por qué usar Git? -* Se puede trabajar sin conexion. -* Colaborar con otros es sencillo!. -* Derivar, Crear ramas del proyecto (aka: Branching) es facil!. -* Combinar (aka: Marging) -* Git es rapido. +* Se puede trabajar sin conexión. +* ¡Colaborar con otros es sencillo!. +* Derivar, crear ramas del proyecto (aka: Branching) es fácil. +* Combinar (aka: Merging) +* Git es rápido. * Git es flexible. ## Arquitectura de Git. @@ -47,11 +47,11 @@ uno o varios archivos, a lo largo del tiempo. ### Repositorio Un repositorio es un conjunto de archivos, directorios, registros, cambios (aka: -comits), y encabezados (aka: heads). Imagina que un repositorio es una clase, -y que sus atributos otorgan acceso al historial del elemento, ademas de otras +commits), y encabezados (aka: heads). Imagina que un repositorio es una clase, +y que sus atributos otorgan acceso al historial del elemento, además de otras cosas. -Un repositorio esta compuesto por la carpeta .git y un "arbol de trabajo". +Un repositorio esta compuesto por la carpeta .git y un "árbol de trabajo". ### Directorio .git (componentes del repositorio) @@ -62,38 +62,38 @@ y mas. ### Directorio de trabajo (componentes del repositorio) -Es basicamente los directorios y archivos dentro del repositorio. La mayorioa de +Es básicamente los directorios y archivos dentro del repositorio. La mayoría de las veces se le llama "directorio de trabajo". -### Inidice (componentes del directorio .git) +### Índice (componentes del directorio .git) -El inidice es la area de inicio en git. Es basicamente la capa que separa el -directorio de trabajo, del repositorio en git. Esto otorga a los desarrolladores -mas poder sobre lo que envia y recibe en el repositorio. +El índice es el área de inicio en git. Es básicamente la capa que separa el +directorio de trabajo del repositorio en git. Esto otorga a los desarrolladores +más poder sobre lo que se envía y se recibe del repositorio. ### Commit (aka: cambios) Un commit es una captura de un conjunto de cambios, o modificaciones hechas en -el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se remueven 2, -estos cambios se almacenaran en un commit (aka: captura). Este commit puede ser o +el directorio de trabajo. Por ejemplo, si se añaden 5 archivos, se eliminan 2, +estos cambios se almacenarán en un commit (aka: captura). Este commit puede ser o no ser enviado (aka: "pusheado") hacia un repositorio. ### Branch (rama) -Un "branch", es escencialmente un apuntador hacia el ultimo commit (cambio -registrado) que se ha realizado. A medida que se realizan mas commits, este -apuntador se actualizara automaticamente hacia el ultimo commit. +Un "branch", es escencialmente un apuntador hacia el último commit (cambio +registrado) que se ha realizado. A medida que se realizan más commits, este +apuntador se actualizará automaticamente hacia el ultimo commit. -### "HEAD" y "head" (component of .git dir) +### "HEAD" y "head" (componentes del directorio .git) "HEAD" es un apuntador hacia la rama (branch) que se esta utilizando. Un repositorio solo puede tener un HEAD activo. En cambio "head", es un apuntador a -cualquier commit realizado, un repositorio puede tener cualquier numero de +cualquier commit realizado, un repositorio puede tener cualquier número de "heads". ### conceptos - recursos. -* [Git para informaticos](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para informáticos](http://eagain.net/articles/git-for-computer-scientists/) * [Git para diseñadores](http://hoth.entp.com/output/git_for_designers.html) @@ -102,8 +102,8 @@ cualquier commit realizado, un repositorio puede tener cualquier numero de ### init -Crear un repositorio de git vacio. Las configuraciones, informacion almacenada y -demas son almacenadas en el directorio ".git". +Crear un repositorio de git vacio. Las configuraciones, información almacenada y +demás son almacenadas en el directorio ".git". ```bash $ git init @@ -115,7 +115,7 @@ Se utiliza para configurar las opciones ya sea globalmente, o solamente en el repositorio. ```bash -# Imprime y guarda algunas variables de configuracion basicas. (Globalmente) +# Imprime y guarda algunas variables de configuracion básicas. (Globalmente) $ git config --global user.email $ git config --global user.name @@ -123,15 +123,15 @@ $ git config --global user.email "corre@gmail.com" $ git config --global user.name "nombre" ``` -[Mas sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git) +[Más sobre git config.](http://git-scm.com/book/es/Personalizando-Git-Configuración-de-Git) ### help -Otorga un accceso rapido a una guia extremadamente detallada de cada comando en +Otorga un accceso rápido a una guía extremadamente detallada de cada comando en git. O puede ser usada simplemente como un recordatorio de estos. ```bash -# Una vista rapido de los comandos disponibles. +# Una vista rápida de los comandos disponibles. $ git help # Chequear todos los comandos disponibles @@ -146,12 +146,12 @@ $ git help init ### status -Muestra las diferencias entre el archivo indice y el commit al cual apunta el +Muestra las diferencias entre el archivo índice y el commit al cual apunta el HEAD actualmente. ```bash -# Mostrara el "branch", archivos sin añadir a la repo, cambios y otras +# Mostrará el "branch", archivos sin añadir al repo, cambios y otras # diferencias $ git status @@ -161,9 +161,9 @@ $ git help status ### add -Para añadir archivos al arbol (directorio, repositorio) de trabajo. Si no se -utiliza `git add`, los nuevos archivos no se añadiran al arbol de trabajo, por -lo que no se incluiran en los commits (cambios). +Para añadir archivos al árbol (directorio, repositorio) de trabajo. Si no se +utiliza `git add`, los nuevos archivos no se añadirán al arbol de trabajo, por +lo que no se incluirán en los commits (cambios). ```bash # Añade un archivo en el directorio de trabajo actual. @@ -178,31 +178,31 @@ $ git add ./*.py ### branch -Administra las ramas del repositorios ("branches"). Puedes ver, editar, crear y +Administra las ramas del repositorio ("branches"). Puedes ver, editar, crear y borrar ramas ("branches"), usando este comando. ```bash # lista todas las ramas (remotas y locales) $ git branch -a -# Añada una nueva rama ("branch"). +# Añadir una nueva rama ("branch"). $ git branch branchNueva # Eliminar una rama. $ git branch -d branchFoo -# Renombra una rama. +# Renombrar una rama. # git branch -m <anterior> <nuevo> $ git branch -m youngling padawan -# Edita la descripcion de la rama. +# Editar la descripcion de la rama. $ git branch master --edit-description ``` ### checkout Actualiza todos los archivos en el directorio de trabajo para que sean igual que -las versiones almacenadas en el indice, o en un arbol de trabajo especificado. +las versiones almacenadas en el índice, o en un árbol de trabajo especificado. ```bash # Despachar un repositorio. - Por defecto la master branch. (la rama principal llamada 'master') @@ -215,8 +215,8 @@ $ git checkout -b jdei ### clone -Clona, o copia, una repo existente en un nuevo directorio. Tambien añada el -seguimiento hacia las ramas existentes del repo que ha sido clonada, lo que +Clona, o copia, un repositorio existente en un nuevo directorio. También añade el +seguimiento hacia las ramas existentes del repositorio que ha sido clonado, lo que permite subir (push) los archivos hacia una rama remota. ```bash @@ -226,60 +226,60 @@ $ git clone https://github.com/jquery/jquery.git ### commit -Almacena los cambios que almacenados en el indice en un nuevo "commit". Este -commit contiene los cambios hechos mas un resumen hecho por el desarrollador. +Almacena el contenido actual del índice en un nuevo "commit". Este +commit contiene los cambios hechos más un resumen proporcionado por el desarrollador. ```bash -# commit with a message # realizar un commit y añadirle un mensaje. $ git commit -m "jedi anakin wil be - jedis.list" ``` ### diff -Muestra las diferencias entre un archivo en el directorio de trabajo, el indice -y commits. +Muestra las diferencias entre un archivo en el directorio de trabajo, el índice +y los commits. ```bash -# Muestra la diferencia entre un directorio de trabajo y el indice. +# Muestra la diferencia entre un directorio de trabajo y el índice. $ git diff -# Muestra la diferencia entre el indice y los commits mas recientes. +# Muestra la diferencia entre el índice y los commits más recientes. $ git diff --cached -# Muestra la diferencia entre el directorio de trabajo y el commit mas reciente. +# Muestra la diferencia entre el directorio de trabajo y el commit más reciente. $ git diff HEAD ``` ### grep -Permite realizar una busqueda rapida en un repositorio. +Permite realizar una busqueda rápida en un repositorio. -Configuracion opcionales: +Configuraciones opcionales: ```bash # Gracias a Travis Jeffery por compartir lo siguiente. # Permite mostrar numeros de lineas en la salida de grep. $ git config --global grep.lineNumber true -# Realiza una busqueda mas lejible, incluyendo agrupacion. +# Realiza una búsqueda mas legible, incluyendo agrupación. $ git config --global alias.g "grep --break --heading --line-number" ``` ```bash -# Busca por "unaVariable" en todos los archivos ,java +# Busca por "unaVariable" en todos los archivos .java $ git grep 'unaVariable' -- '*.java' -# Busca por una linea que contenga "nombreArreglo" y , "agregar" o "remover" +# Busca por una línea que contenga "nombreArreglo" y "agregar" o "remover" $ git grep -e 'nombreArreglo' --and \( -e agregar -e remover \) ``` -Mas ejemplos: -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) +Más ejemplos: + +- [Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) ### log -Muestra los commits (cambios) registrados en el repositotrio. +Muestra los commits (cambios) registrados en el repositorio. ```bash # Muestra todos los commits. @@ -288,7 +288,7 @@ $ git log # Muestra un numero x de commits. $ git log -n 10 -# Muestra solo los commits que se han combinado en el hisotrial +# Muestra solo los commits que se han combinado en el historial. $ git log --merges ``` @@ -301,7 +301,7 @@ que se trabaja. # Combina la rama especificada en la rama actual. $ git merge jediMaster -# Siempre genere un solo merge commit cuando se utilizar merge. +# Siempre genere un solo merge commit cuando se utiliza merge. $ git merge --no-ff jediMaster ``` @@ -310,7 +310,7 @@ $ git merge --no-ff jediMaster Renombra o mueve un archivo ```bash -# Renombrando un archivo +# Renombrando un archivo. $ git mv HolaMundo.c AdiosMundo.c # Moviendo un archivo. @@ -322,33 +322,31 @@ $ git mv -f archivoA archivoB ### pull -Sube (Empuja) de un repositorio y lo combina en otro en una rama diferente. +Trae los cambios de un repositorio y los combina en otro en una rama diferente. ```bash -# Actualiza el repositorio local, combinando los nuevos cambios. +# Actualiza el repositorio local, combinando los nuevos cambios # de las ramas remotas "origin" y "master". -# from the remote "origin" and "master" branch. # git pull <remota> <rama> $ git pull origin master ``` ### push -Push and merge changes from a branch to a remote & branch. +Envía y combina los cambios de un repositorio local a un repositorio y rama remotos. ```bash -# Push and merge changes from a local repo to a -# Empuja y combina cambios de un repositorio local hacian un repositorio remoto +# Envía y combina cambios de un repositorio local hacia un repositorio remoto # llamados "origin" y "master", respectivamente. # git push <remota> <rama> # git push => por defecto es lo mismo que poner => git push origin master $ git push origin master ``` +### rebase Toma todos los cambios que fueron registrados en una rama, y los repite dentro -de otra rama. -*No reescribe los commits que se han empujado antes a un repositorio publico* +de otra rama. *No reescribe los commits que se han empujado antes a un repositorio público.* ```bash # Integrar ramaExperimento dentro de la rama "master" @@ -356,47 +354,47 @@ de otra rama. $ git rebase master experimentBranch ``` -[Informacion adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar) +[Información adicional.](http://git-scm.com/book/es/Ramificaciones-en-Git-Procedimientos-básicos-para-ramificar-y-fusionar) -### reset (precaucion) +### reset (precaución) -Reinicia el cabezal actual hacia un estado especificado. Esto permite desacer -combinaciones (merges), pulls, commits, adds y mas. Es un comando util, pero -tambien peligrosa si no se sabe lo que se hace. +Reinicia el HEAD actual hacia un estado especificado. Esto permite deshacer +combinaciones (merges), pulls, commits, adds y más. Es un comando útil, pero +tambien peligroso si no se sabe lo que se hace. ```bash -# Reinica el area principal, con el ultimo cambio registrado. (deja los +# Reinicia el área principal, con el último cambio registrado. (deja los # directorios sin cambios) $ git reset -# Reinica el area principal, con el ultimo cambio registrado, y reescribe el +# Reinicia el área principal, con el último cambio registrado, y reescribe el # directorio de trabajo. $ git reset --hard # Mueve la rama actual hacia el commit especificado (no realiza cambios a los -# directorios), todos los cambios aun existen el directorio. +# directorios), todos los cambios aún existen el directorio. $ git reset 31f2bb1 -# Mueve la rama actual devuelta a un commit especificado asi como el -# directorios (borra todos los cambios que no fueron registros y todos los -# cambios realizados despues del commit especificado). +# Mueve la rama actual devuelta a un commit especificado, así como el +# directorio (borra todos los cambios que no fueron registrados y todos los +# cambios realizados después del commit especificado). $ git reset --hard 31f2bb1 ``` ### rm -Lo contrario de git add, git rm remueve los archivos del directorio de trabajo +Lo contrario de git add, git rm elimina los archivos del directorio de trabajo actual. ```bash -# Remueve FooBar.c +# Elimina FooBar.c $ git rm FooBar.c -# Remueve un archivo de un directorio. +# Elimina un archivo de un directorio. $ git rm /directorio/del/archivo/FooBar.c ``` -## Informacion Adicional +## Información Adicional * [tryGit - Una forma entretenida y rapida de aprender Git.](http://try.github.io/levels/1/challenges/1) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 86de33ec..c41d693d 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -1,326 +1,450 @@ --- +name: Go +category: language language: Go lang: es-es filename: learngo-es.go contributors: - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] translators: - ["Adrian Espinosa", "http://www.adrianespinosa.com"] - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Nacho Pacheco -- Feb/2015", "https://github.com/gitnacho"] --- -Go fue creado por la necesidad de hacer el trabajo rápidamente. No es -la última tendencia en informática, pero es la forma nueva y más -rápida de resolver problemas reales. +Go fue creado por la necesidad de hacer el trabajo rápidamente. No es la +última tendencia en informática, pero es la forma nueva y más rápida de +resolver problemas reales. -Tiene conceptos familiares de lenguajes imperativos con tipado -estático. Es rápido compilando y rápido al ejecutar, añade una -concurrencia fácil de entender para las CPUs de varios núcleos de hoy -en día, y tiene características que ayudan con la programación a gran -escala. +Tiene conceptos familiares de lenguajes imperativos con tipado estático. +Es rápido compilando y rápido al ejecutar, añade una concurrencia fácil de +entender para las CPUs de varios núcleos de hoy día, y tiene +características que ayudan con la programación a gran escala. -Go viene con una librería estándar muy buena y una comunidad entusiasta. +Go viene con una biblioteca estándar muy buena y una entusiasta comunidad. ```go // Comentario de una sola línea -/* Comentario - multi línea */ +/* Comentario + multilínea */ -// La cláusula package aparece al comienzo de cada archivo fuente. -// Main es un nombre especial que declara un ejecutable en vez de una librería. +// La cláusula `package` aparece al comienzo de cada fichero fuente. +// `main` es un nombre especial que declara un ejecutable en vez de una +// biblioteca. package main -// La declaración Import declara los paquetes de librerías -// referenciados en este archivo. +// La instrucción `import` declara los paquetes de bibliotecas referidos +// en este fichero. import ( - "fmt" // Un paquete en la librería estándar de Go. - "net/http" // Sí, un servidor web! - "strconv" // Conversiones de cadenas. - m "math" // Librería matemáticas con alias local m. + "fmt" // Un paquete en la biblioteca estándar de Go. + "io/ioutil" // Implementa algunas útiles funciones de E/S. + m "math" // Biblioteca de matemáticas con alias local m. + "net/http" // Sí, ¡un servidor web! + "strconv" // Conversiones de cadenas. ) -// Definición de una función. Main es especial. Es el punto de -// entrada para el ejecutable. Te guste o no, Go utiliza llaves. +// Definición de una función. `main` es especial. Es el punto de entrada +// para el ejecutable. Te guste o no, Go utiliza llaves. func main() { - // Println imprime una línea a stdout. - // Cualificalo con el nombre del paquete, fmt. - fmt.Println("Hello world!") + // Println imprime una línea a stdout. + // Cualificalo con el nombre del paquete, fmt. + fmt.Println("¡Hola mundo!") - // Llama a otra función de este paquete. - beyondHello() + // Llama a otra función de este paquete. + másAlláDelHola() } // Las funciones llevan parámetros entre paréntesis. // Si no hay parámetros, los paréntesis siguen siendo obligatorios. -func beyondHello() { - var x int // Declaración de una variable. - // Las variables se deben declarar antes de utilizarlas. - x = 3 // Asignación de variables. - // Declaración "corta" con := para inferir el tipo, declarar y asignar. - y := 4 - sum, prod := learnMultiple(x, y) // Función devuelve dos valores. - fmt.Println("sum:", sum, "prod:", prod) // Simple salida. - learnTypes() // < y minutes, learn more! +func másAlláDelHola() { + var x int // Declaración de una variable. + // Las variables se deben declarar antes de utilizarlas. + x = 3 // Asignación de variable. + // Declaración "corta" con := para inferir el tipo, declarar y asignar. + y := 4 + suma, producto := aprendeMúltiple(x, y) // La función devuelve dos + // valores. + fmt.Println("suma:", suma, "producto:", producto) // Simple salida. + aprendeTipos() // < y minutos, ¡aprende más! } -// Las funciones pueden tener parámetros y (múltiples!) valores de retorno. -func learnMultiple(x, y int) (sum, prod int) { - return x + y, x * y // Devolver dos valores. +// Las funciones pueden tener parámetros y (¡múltiples!) valores de +// retorno. +func aprendeMúltiple(x, y int) (suma, producto int) { + return x + y, x * y // Devuelve dos valores. } // Algunos tipos incorporados y literales. -func learnTypes() { - // La declaración corta suele darte lo que quieres. - s := "Learn Go!" // tipo cadena - - s2 := ` Un tipo cadena "puro" puede incluir +func aprendeTipos() { + // La declaración corta suele darte lo que quieres. + s := "¡Aprende Go!" // tipo cadena. + s2 := `Un tipo cadena "puro" puede incluir saltos de línea.` // mismo tipo cadena - // Literal no ASCII. Los fuentes de Go son UTF-8. - g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode. - f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. - c := 3 + 4i // complex128, representado internamente por dos float64. - // Sintaxis Var con inicializadores. - var u uint = 7 // Sin signo, pero la implementación depende del - // tamaño como en int. - var pi float32 = 22. / 7 - - // Sintáxis de conversión con una declaración corta. - n := byte('\n') // byte es un alias de uint8. - - // Los Arrays tienen un tamaño fijo a la hora de compilar. - var a4 [4]int // Un array de 4 ints, inicializados a 0. - a3 := [...]int{3, 1, 5} // Un array de 3 ints, inicializados como se indica. - - // Los Slices tienen tamaño dinámico. Los arrays y slices tienen sus ventajas - // y desventajas pero los casos de uso para los slices son más comunes. - s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos. - s4 := make([]int, 4) // Asigna slices de 4 ints, inicializados a 0. - var d2 [][]float64 // Solo declaración, sin asignación. - bs := []byte("a slice") // Sintaxis de conversión de tipo. - - p, q := learnMemory() // Declara p, q para ser un tipo puntero a int. - fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. - - // Los Maps son arrays asociativos dinámicos, como los hash o - // diccionarios de otros lenguajes. - m := map[string]int{"three": 3, "four": 4} - m["one"] = 1 - - // Las variables no utilizadas en Go producen error. - // El guión bajo permite "utilizar" una variable, pero descartar su valor. - _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs - // Esto cuenta como utilización de variables. - fmt.Println(s, c, a4, s3, d2, m) - - learnFlowControl() // Vuelta al flujo. + // Literal no ASCII. Los ficheros fuente de Go son UTF-8. + g := 'Σ' // Tipo rune, un alias de int32, alberga un carácter unicode. + f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. + c := 3 + 4i // complex128, representado internamente por dos float64. + // Sintaxis Var con iniciadores. + var u uint = 7 // Sin signo, pero la implementación depende del tamaño + // como en int. + var pi float32 = 22. / 7 + + // Sintáxis de conversión con una declaración corta. + n := byte('\n') // byte es un alias para uint8. + + // Los Arreglos tienen un tamaño fijo a la hora de compilar. + var a4 [4]int // Un arreglo de 4 ints, iniciados a 0. + a3 := [...]int{3, 1, 5} // Un arreglo iniciado con un tamaño fijo de tres + // elementos, con valores 3, 1 y 5. + // Los Sectores tienen tamaño dinámico. Los arreglos y sectores tienen + // sus ventajas y desventajas pero los casos de uso para los sectores + // son más comunes. + s3 := []int{4, 5, 9} // Comparar con a3. No hay puntos suspensivos. + s4 := make([]int, 4) // Asigna sectores de 4 ints, iniciados a 0. + var d2 [][]float64 // Solo declaración, sin asignación. + bs := []byte("a sector") // Sintaxis de conversión de tipo. + // Debido a que son dinámicos, los sectores pueden crecer bajo demanda. + // Para añadir elementos a un sector, se utiliza la función incorporada + // append(). + // El primer argumento es el sector al que se está anexando. Comúnmente, + // la variable del arreglo se actualiza en su lugar, como en el + // siguiente ejemplo. + sec := []int{1, 2 , 3} // El resultado es un sector de longitud 3. + sec = append(sec, 4, 5, 6) // Añade 3 elementos. El sector ahora tiene una + // longitud de 6. + fmt.Println(sec) // El sector actualizado ahora es [1 2 3 4 5 6] + // Para anexar otro sector, en lugar de la lista de elementos atómicos + // podemos pasar una referencia a un sector o un sector literal como + // este, con elipsis al final, lo que significa tomar un sector y + // desempacar sus elementos, añadiéndolos al sector sec. + sec = append(sec, []int{7, 8, 9} ...) // El segundo argumento es un + // sector literal. + fmt.Println(sec) // El sector actualizado ahora es [1 2 3 4 5 6 7 8 9] + p, q := aprendeMemoria() // Declara p, q para ser un tipo puntero a + // int. + fmt.Println(*p, *q) // * sigue un puntero. Esto imprime dos ints. + + // Los Mapas son arreglos asociativos dinámicos, como los hash o + // diccionarios de otros lenguajes. + m := map[string]int{"tres": 3, "cuatro": 4} + m["uno"] = 1 + + // Las variables no utilizadas en Go producen error. + // El guión bajo permite "utilizar" una variable, pero descartar su + // valor. + _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs + // Esto cuenta como utilización de variables. + fmt.Println(s, c, a4, s3, d2, m) + + aprendeControlDeFlujo() // Vuelta al flujo. +} + +// Es posible, a diferencia de muchos otros lenguajes tener valores de +// retorno con nombre en las funciones. +// Asignar un nombre al tipo que se devuelve en la línea de declaración de +// la función nos permite volver fácilmente desde múltiples puntos en una +// función, así como sólo utilizar la palabra clave `return`, sin nada +// más. +func aprendeRetornosNombrados(x, y int) (z int) { + z = x * y + return // aquí z es implícito, porque lo nombramos antes. } -// Go posee recolector de basura. Tiene puntero pero no aritmética de -// punteros. Puedes cometer un errores con un puntero nil, pero no +// Go posee recolector de basura. Tiene punteros pero no aritmética de +// punteros. Puedes cometer errores con un puntero nil, pero no // incrementando un puntero. -func learnMemory() (p, q *int) { - // q y p tienen un tipo puntero a int. - p = new(int) // Función incorporada que asigna memoria. - // La asignación de int se inicializa a 0, p ya no es nil. - s := make([]int, 20) // Asigna 20 ints a un solo bloque de memoria. - s[3] = 7 // Asignar uno de ellos. - r := -2 // Declarar otra variable local. - return &s[3], &r // & toma la dirección de un objeto. +func aprendeMemoria() (p, q *int) { + // Los valores de retorno nombrados q y p tienen un tipo puntero + // a int. + p = new(int) // Función incorporada que reserva memoria. + // La asignación de int se inicia a 0, p ya no es nil. + s := make([]int, 20) // Reserva 20 ints en un solo bloque de memoria. + s[3] = 7 // Asigna uno de ellos. + r := -2 // Declara otra variable local. + return &s[3], &r // & toma la dirección de un objeto. } -func expensiveComputation() float64 { - return m.Exp(10) +func cálculoCaro() float64 { + return m.Exp(10) } -func learnFlowControl() { - // La declaración If requiere llaves, pero no paréntesis. - if true { - fmt.Println("told ya") - } - // El formato está estandarizado por el comando "go fmt." - if false { - // Pout. - } else { - // Gloat. - } - // Utiliza switch preferiblemente para if encadenados. - x := 42.0 - switch x { - case 0: - case 1: - case 42: - // Los cases no se mezclan, no requieren de "break". - case 43: - // No llega. +func aprendeControlDeFlujo() { + // La declaración If requiere llaves, pero no paréntesis. + if true { + fmt.Println("ya relatado") + } + // El formato está estandarizado por la orden "go fmt." + if false { + // Abadejo. + } else { + // Relamido. + } + // Utiliza switch preferentemente para if encadenados. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Los cases no se mezclan, no requieren de "break". + case 43: + // No llega. + } + // Como if, for no utiliza paréntesis tampoco. + // Variables declaradas en for e if son locales a su ámbito. + for x := 0; x < 3; x++ { // ++ es una instrucción. + fmt.Println("iteración", x) + } + // aquí x == 42. + + // For es la única instrucción de bucle en Go, pero tiene formas + // alternativas. + for { // Bucle infinito. + break // ¡Solo bromeaba! + continue // No llega. + } + + // Puedes usar `range` para iterar en un arreglo, un sector, una + // cadena, un mapa o un canal. + // `range` devuelve o bien, un canal o de uno a dos valores (arreglo, + // sector, cadena y mapa). + for clave, valor := range map[string]int{"uno": 1, "dos": 2, "tres": 3} { + // por cada par en el mapa, imprime la clave y el valor + fmt.Printf("clave=%s, valor=%d\n", clave, valor) + } + + // Como en for, := en una instrucción if significa declarar y asignar + // primero, luego comprobar y > x. + if y := cálculoCaro(); y > x { + x = y } - // Como if, for no utiliza paréntesis tampoco. - // Variables declaradas en for y if son locales de su ámbito local. - for x := 0; x < 3; x++ { // ++ es una sentencia. - fmt.Println("iteration", x) - } - // x == 42 aqui. + // Las funciones literales son "cierres". + granX := func() bool { + return x > 100 // Referencia a x declarada encima de la instrucción + // switch. + } + fmt.Println("granX:", granX()) // cierto (la última vez asignamos + // 1e6 a x). + x /= 1.3e3 // Esto hace a x == 1300 + fmt.Println("granX:", granX()) // Ahora es falso. + + // Es más las funciones literales se pueden definir y llamar en línea, + // actuando como un argumento para la función, siempre y cuando: + // a) la función literal sea llamada inmediatamente (), + // b) el tipo del resultado sea del tipo esperado del argumento + fmt.Println("Suma dos números + doble: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Llamada con argumentos 10 y 2 + // => Suma dos números + doble: 24 + + // Cuando lo necesites, te encantará. + goto encanto +encanto: + + aprendeFunciónFábrica() // func devolviendo func es divertido(3)(3) + aprendeADiferir() // Un rápido desvío a una importante palabra clave. + aprendeInterfaces() // ¡Buen material dentro de poco! +} - // For es la única sentencia de bucle en Go, pero tiene formas alternativas. - for { // Bucle infinito. - break // Solo bromeaba! - continue // No llega. - } - // Como en for, := en una sentencia if significa declarar y asignar primero, - // luego comprobar y > x. - if y := expensiveComputation(); y > x { - x = y - } - // Los literales de funciones son "closures". - xBig := func() bool { - return x > 100 // Referencia a x declarada encima de la sentencia switch. - } - fmt.Println("xBig:", xBig()) // verdadero (la última vez asignamos 1e6 a x). - x /= m.Exp(9) // Esto lo hace x == e. - fmt.Println("xBig:", xBig()) // Ahora es falso. +func aprendeFunciónFábrica() { + // Las dos siguientes son equivalentes, la segunda es más práctica + fmt.Println(instrucciónFábrica("día")("Un bello", "de verano")) + + d := instrucciónFábrica("atardecer") + fmt.Println(d("Un hermoso", "de verano")) + fmt.Println(d("Un maravilloso", "de verano")) +} - // Cuando lo necesites, te encantará. - goto love -love: +// Los decoradores son comunes en otros lenguajes. Lo mismo se puede hacer +// en Go con funciónes literales que aceptan argumentos. +func instrucciónFábrica(micadena string) func(antes, después string) string { + return func(antes, después string) string { + return fmt.Sprintf("¡%s %s %s!", antes, micadena, después) // nueva cadena + } +} - learnInterfaces() // Buen material dentro de poco! +func aprendeADiferir() (ok bool) { + // las instrucciones diferidas se ejecutan justo antes de que la + // función regrese. + defer fmt.Println("las instrucciones diferidas se ejecutan en orden inverso (PEPS).") + defer fmt.Println("\nEsta línea se imprime primero debido a que") + // Defer se usa comunmente para cerrar un fichero, por lo que la + // función que cierra el fichero se mantiene cerca de la función que lo + // abrió. + return true } // Define Stringer como un tipo interfaz con un método, String. type Stringer interface { - String() string + String() string } -// Define pair como un struct con dos campos int, x e y. -type pair struct { - x, y int +// Define par como una estructura con dos campos int, x e y. +type par struct { + x, y int } -// Define un método del tipo pair. Pair ahora implementa Stringer. -func (p pair) String() string { // p se llama "recibidor" - // Sprintf es otra función pública del paquete fmt. - // La sintaxis con punto referencia campos de p. - return fmt.Sprintf("(%d, %d)", p.x, p.y) +// Define un método en el tipo par. Par ahora implementa a Stringer. +func (p par) String() string { // p se conoce como el "receptor" + // Sprintf es otra función pública del paquete fmt. + // La sintaxis con punto se refiere a los campos de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) } -func learnInterfaces() { - // La sintaxis de llaves es un "literal struct". Evalúa a un struct - // inicializado. La sintaxis := declara e inicializa p a este struct. - p := pair{3, 4} - fmt.Println(p.String()) // Llamar al método String de p, de tipo pair. - var i Stringer // Declarar i como interfaz tipo Stringer. - i = p // Válido porque pair implementa Stringer. - // Llamar al metodo String de i, de tipo Stringer. Misma salida que arriba. - fmt.Println(i.String()) - - // Las funciones en el paquete fmt llaman al método String para - // preguntar a un objeto por una versión imprimible de si mismo. - fmt.Println(p) // Salida igual que arriba. Println llama al método String. - fmt.Println(i) // Salida igual que arriba. - - learnVariadicParams("great", "learning", "here!") +func aprendeInterfaces() { + // La sintaxis de llaves es una "estructura literal". Evalúa a una + // estructura iniciada. La sintaxis := declara e inicia p a esta + // estructura. + p := par{3, 4} + fmt.Println(p.String()) // Llama al método String de p, de tipo par. + var i Stringer // Declara i como interfaz de tipo Stringer. + i = p // Válido porque par implementa Stringer. + // Llama al metodo String de i, de tipo Stringer. Misma salida que + // arriba. + fmt.Println(i.String()) + + // Las funciones en el paquete fmt llaman al método String para + // consultar un objeto por una representación imprimible de si + // mismo. + fmt.Println(p) // Salida igual que arriba. Println llama al método + // String. + fmt.Println(i) // Salida igual que arriba. + aprendeNúmeroVariableDeParámetros("¡gran", "aprendizaje", "aquí!") } // Las funciones pueden tener número variable de argumentos. -func learnVariadicParams(myStrings ...interface{}) { - // Iterar cada valor de la variadic. - for _, param := range myStrings { - fmt.Println("param:", param) - } - - // Pasar valor variadic como parámetro variadic. - fmt.Println("params:", fmt.Sprintln(myStrings...)) - - learnErrorHandling() +func aprendeNúmeroVariableDeParámetros(misCadenas ...interface{}) { + // Itera en cada valor de los argumentos variables. + // El espacio en blanco aquí omite el índice del argumento arreglo. + for _, parámetro := range misCadenas { + fmt.Println("parámetro:", parámetro) + } + + // Pasa el valor de múltiples variables como parámetro variadic. + fmt.Println("parámetros:", fmt.Sprintln(misCadenas...)) + aprendeManejoDeError() } -func learnErrorHandling() { - // ", ok" forma utilizada para saber si algo funcionó o no. - m := map[int]string{3: "three", 4: "four"} - if x, ok := m[1]; !ok { // ok será falso porque 1 no está en el map. - fmt.Println("no one there") - } else { - fmt.Print(x) // x sería el valor, si estuviera en el map. - } - // Un valor de error comunica más información sobre el problema aparte de "ok". - if _, err := strconv.Atoi("non-int"); err != nil { // _ descarta el valor - // Imprime "strconv.ParseInt: parsing "non-int": invalid syntax". - fmt.Println(err) - } - // Revisarmeos las interfaces más tarde. Mientras tanto, - learnConcurrency() +func aprendeManejoDeError() { + // ", ok" forma utilizada para saber si algo funcionó o no. + m := map[int]string{3: "tres", 4: "cuatro"} + if x, ok := m[1]; !ok { // ok será falso porque 1 no está en el mapa. + fmt.Println("nada allí") + } else { + fmt.Print(x) // x sería el valor, si estuviera en el mapa. + } + // Un valor de error comunica más información sobre el problema aparte + // de "ok". + if _, err := strconv.Atoi("no-int"); err != nil { // _ descarta el + // valor + // Imprime "strconv.ParseInt: parsing "no-int": invalid syntax". + fmt.Println(err) + } + // Revisaremos las interfaces más adelante. Mientras tanto... + aprendeConcurrencia() } -// c es un canal, un objeto de comunicación de concurrencia segura. +// c es un canal, un objeto de comunicación concurrente seguro. func inc(i int, c chan int) { - c <- i + 1 // <- es el operador "enviar" cuando un canal aparece a la izquierda. + c <- i + 1 // <- es el operador "enviar" cuando aparece un canal a la + // izquierda. } // Utilizaremos inc para incrementar algunos números concurrentemente. -func learnConcurrency() { - // Misma función make utilizada antes para crear un slice. Make asigna e - // inicializa slices, maps, y channels. - c := make(chan int) - // Iniciar tres goroutines concurrentes. Los números serán incrementados - // concurrentemente, quizás en paralelo si la máquina es capaz y - // está correctamente configurada. Las tres envían al mismo channel. - go inc(0, c) // go es una sentencia que inicia una nueva goroutine. - go inc(10, c) - go inc(-805, c) - // Leer los tres resultados del channel e imprimirlos. - // No se puede saber en que orden llegarán los resultados! - fmt.Println(<-c, <-c, <-c) // Channel a la derecha, <- es el operador "recibir". - - cs := make(chan string) // Otro channel, este gestiona cadenas. - ccs := make(chan chan string) // Un channel de cadenas de channels. - go func() { c <- 84 }() // Iniciar una nueva goroutine solo para - // enviar un valor. - go func() { cs <- "wordy" }() // Otra vez, para cs en esta ocasión. - // Select tiene una sintáxis parecida a la sentencia switch pero - // cada caso involucra una operacion de channels. Selecciona un caso - // de forma aleatoria de los casos que están listos para comunicarse. - select { - case i := <-c: // El valor recibido puede ser asignado a una variable, - fmt.Printf("it's a %T", i) - case <-cs: // o el valor puede ser descartado. - fmt.Println("it's a string") - case <-ccs: // Channel vacío, no está listo para la comunicación. - fmt.Println("didn't happen.") - } - - // En este punto un valor fue devuelvto de c o cs. Uno de las dos - // goroutines que se iniciaron se ha completado, la otrá permancerá - // bloqueada. - - learnWebProgramming() // Go lo hace. Tu también quieres hacerlo. +func aprendeConcurrencia() { + // Misma función make utilizada antes para crear un sector. Make asigna + // e inicia sectores, mapas y canales. + c := make(chan int) + // Inicia tres rutinasgo concurrentes. Los números serán incrementados + // concurrentemente, quizás en paralelo si la máquina es capaz y está + // correctamente configurada. Las tres envían al mismo canal. + go inc(0, c) // go es una instrucción que inicia una nueva rutinago. + go inc(10, c) + go inc(-805, c) + // Lee los tres resultados del canal y los imprime. + // ¡No se puede saber en que orden llegarán los resultados! + fmt.Println(<-c, <-c, <-c) // Canal a la derecha, <- es el operador + // "recibe". + + cs := make(chan string) // Otro canal, este gestiona cadenas. + ccs := make(chan chan string) // Un canal de canales cadena. + go func() { c <- 84 }() // Inicia una nueva rutinago solo para + // enviar un valor. + go func() { cs <- "verboso" }() // Otra vez, para cs en esta ocasión. + // Select tiene una sintáxis parecida a la instrucción switch pero cada + // caso involucra una operacion con un canal. Selecciona un caso de + // forma aleatoria de los casos que están listos para comunicarse. + select { + case i := <-c: // El valor recibido se puede asignar a una variable, + fmt.Printf("es un %T", i) + case <-cs: // o el valor se puede descartar. + fmt.Println("es una cadena") + case <-ccs: // Canal vacío, no está listo para la comunicación. + fmt.Println("no sucedió.") + } + + // En este punto un valor fue devuelto de c o cs. Una de las dos + // rutinasgo que se iniciaron se ha completado, la otrá permancerá + // bloqueada. + + aprendeProgramaciónWeb() // Go lo hace. Tú también quieres hacerlo. } // Una simple función del paquete http inicia un servidor web. -func learnWebProgramming() { - // El primer parámetro de la direccinón TCP a la que escuchar. - // El segundo parámetro es una interfaz, concretamente http.Handler. - err := http.ListenAndServe(":8080", pair{}) - fmt.Println(err) // no ignorar errores +func aprendeProgramaciónWeb() { +// El primer parámetro es la direccinón TCP a la que escuchar. + // El segundo parámetro es una interfaz, concretamente http.Handler. + go func() { + err := http.ListenAndServe(":8080", par{}) + fmt.Println(err) // no ignora errores + }() + consultaAlServidor() } -// Haz pair un http.Handler implementando su único método, ServeHTTP. -func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Servir datos con un método de http.ResponseWriter. - w.Write([]byte("You learned Go in Y minutes!")) +// Hace un http.Handler de par implementando su único método, ServeHTTP. +func (p par) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Sirve datos con un método de http.ResponseWriter. + w.Write([]byte("¡Aprendiste Go en Y minutos!")) +} + +func consultaAlServidor() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + cuerpo, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nEl servidor web dijo: `%s`\n", string(cuerpo)) } ``` -## Para leer más +## Más información + +La raíz de todas las cosas sobre Go es el +[sitio web oficial de Go](http://golang.org/). +Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más. -La raíz de todas las cosas de Go es la [web oficial de Go](http://golang.org/). -Ahí puedes seguir el tutorial, jugar interactivamente y leer mucho. +La definición del lenguaje es altamente recomendada. Es fácil de leer y +sorprendentemente corta (como la definición del lenguaje Go en estos +días). -La propia definición del lenguaje también está altamente -recomendada. Es fácil de leer e increíblemente corta (como otras -definiciones de lenguajes hoy en día) +Puedes jugar con el código en el +[parque de diversiones Go](https://play.golang.org/p/ncRC2Zevag). ¡Trata +de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes +utilizar [https://play.golang.org]( https://play.golang.org) como un +[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar +cosas y el código en el navegador, sin ni siquiera instalar Go. -En la lista de lectura de estudiantes de Go está el código fuente de -la librería estándar. Muy bien documentada, demuestra lo mejor de Go -leíble, comprendible, estilo Go y formas Go. Pincha en el nombre de -una función en la documentación y te aparecerá el código fuente! +En la lista de lecturas para estudiantes de Go está el +[código fuente de la biblioteca estándar](http://golang.org/src/pkg/). +Ampliamente documentado, que demuestra lo mejor del legible y comprensible +Go, con su característico estilo y modismos. ¡O puedes hacer clic en un +nombre de función en [la documentación](http://golang.org/pkg/) y +aparecerá el código fuente! +Otro gran recurso para aprender Go está en +[Go con ejemplos](http://goconejemplos.com/). diff --git a/es-es/haml-es.html.markdown b/es-es/haml-es.html.markdown new file mode 100644 index 00000000..be90b8f3 --- /dev/null +++ b/es-es/haml-es.html.markdown @@ -0,0 +1,159 @@ +--- +language: haml +filename: learnhaml-es.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] +translators: + - ["Camilo Garrido", "http://www.twitter.com/hirohope"] +lang: es-es +--- + +Haml es un lenguage de marcas principalmente usado con Ruby, que de forma simple y limpia describe el HTML de cualquier documento web sin el uso de código en linea. Es una alternativa popular respecto a usar el lenguage de plantilla de Rails (.erb) y te permite embeber código Ruby en tus anotaciones. + +Apunta a reducir la repetición en tus anotaciones cerrando los tags por ti, basándose en la estructura de identación de tu código. El resultado es una anotación bien estructurada, que no se repite, lógica y fácil de leer. + +También puedes usar Haml en un proyecto independiente de Ruby, instalando la gema Haml en tu máquina y usando la línea de comandos para convertirlo en html. + +$ haml archivo_entrada.haml archivo_salida.html + + +```haml +/ ------------------------------------------- +/ Identación +/ ------------------------------------------- + +/ + Por la importancia que la identación tiene en cómo tu código es traducido, + la identación debe ser consistente a través de todo el documento. Cualquier + diferencia en la identación lanzará un error. Es una práctica común usar dos + espacios, pero realmente depende de tí, mientras sea consistente. + + +/ ------------------------------------------- +/ Comentarios +/ ------------------------------------------- + +/ Así es como un comentario se ve en Haml. + +/ + Para escribir un comentario multilínea, identa tu código a comentar de tal forma + que sea envuelto por por una barra. + + +-# Este es un comentario silencioso, significa que no será traducido al código en absoluto + + +/ ------------------------------------------- +/ Elementos Html +/ ------------------------------------------- + +/ Para escribir tus tags, usa el signo de porcentaje seguido por el nombre del tag +%body + %header + %nav + +/ Nota que no hay tags de cierre. El código anterior se traduciría como + <body> + <header> + <nav></nav> + </header> + </body> + +/ El tag div es un elemento por defecto, por lo que pueden ser escritos simplemente así +.foo + +/ Para añadir contenido a un tag, añade el texto directamente después de la declaración +%h1 Headline copy + +/ Para escribir contenido multilínea, anídalo. +%p + Esto es mucho contenido que podríamos dividirlo en dos + líneas separadas. + +/ + Puedes escapar html usando el signo ampersand y el signo igual ( &= ). + Esto convierte carácteres sensibles en html a su equivalente codificado en html. + Por ejemplo + +%p + &= "Sí & si" + +/ se traduciría en 'Sí & si' + +/ Puedes desescapar html usando un signo de exclamación e igual ( != ) +%p + != "Así es como se escribe un tag párrafo <p></p>" + +/ se traduciría como 'Así es como se escribe un tag párrafo <p></p>' + +/ Clases CSS puedes ser añadidas a tus tags, ya sea encadenando .nombres-de-clases al tag +%div.foo.bar + +/ o como parte de un hash Ruby +%div{:class => 'foo bar'} + +/ Atributos para cualquier tag pueden ser añadidos en el hash +%a{:href => '#', :class => 'bar', :title => 'Bar'} + +/ Para atributos booleanos asigna el valor verdadero 'true' +%input{:selected => true} + +/ Para escribir atributos de datos, usa la llave :dato con su valor como otro hash +%div{:data => {:attribute => 'foo'}} + + +/ ------------------------------------------- +/ Insertando Ruby +/ ------------------------------------------- + +/ + Para producir un valor Ruby como contenido de un tag, usa un signo igual + seguido por código Ruby + +%h1= libro.nombre + +%p + = libro.autor + = libro.editor + + +/ Para correr un poco de código Ruby sin traducirlo en html, usa un guión +- libros = ['libro 1', 'libro 2', 'libro 3'] + +/ Esto te permite hacer todo tipo de cosas asombrosas, como bloques de Ruby +- libros.shuffle.each_with_index do |libro, indice| + %h1= libro + + if libro do + %p Esto es un libro + +/ + Nuevamente, no hay necesidad de añadir los tags de cerrado en el código, ni siquiera para Ruby + La identación se encargará de ello por tí. + + +/ ------------------------------------------- +/ Ruby en linea / Interpolación de Ruby +/ ------------------------------------------- + +/ Incluye una variable Ruby en una línea de texto plano usando #{} +%p Tu juego con puntaje más alto es #{mejor_juego} + + +/ ------------------------------------------- +/ Filtros +/ ------------------------------------------- + +/ + Usa un signo dos puntos para definir filtros Haml, un ejemplo de filtro que + puedes usar es :javascript, el cual puede ser usado para escribir javascript en línea. + +:javascript + console.log('Este es un <script> en linea'); + +``` + +## Recusros adicionales + +- [¿Qué es HAML? (en inglés)](http://haml.info/) - Una buena introducción que hace mejor el trabajo de explicar los beneficios de usar haml. +- [Documentación Oficial (en inglés)](http://haml.info/docs/yardoc/file.REFERENCE.html) - Si deseas ir un poco más profundo. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index a1348508..9ef0c63e 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -16,8 +16,7 @@ con Java para aplicaciones más complejas. Debido a su integracion estrecha con web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. -JavaScript no sólo se limita a los navegadores web: -* Node.js: Un proyecto que provee con un ambiente para el motor V8 de Google Chrome. +Aunque JavaScript no sólo se limita a los navegadores web: Node.js, Un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. ¡La retroalimentación es bienvenida! Puedes encontrarme en: [@adambrenecki](https://twitter.com/adambrenecki), o @@ -31,7 +30,7 @@ JavaScript no sólo se limita a los navegadores web: // Cada sentencia puede ser terminada con punto y coma ; hazAlgo(); -// ... aunque no es necesario, ya que el punto y coma se agrega automaticamente +// ... aunque no es necesario, ya que el punto y coma se agrega automáticamente // cada que se detecta una nueva línea, a excepción de algunos casos. hazAlgo() @@ -49,6 +48,7 @@ hazAlgo() // Toda la aritmética básica funciona como uno esperaría. 1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 10 * 2; // = 20 35 / 5; // = 7 @@ -102,12 +102,14 @@ false; // Los tipos no importan con el operador ==... "5" == 5; // = true +null == undefined; // = true // ...a menos que uses === "5" === 5; // = false +null === undefined; // false // Los Strings funcionan como arreglos de caracteres -// Puedes accesar a cada caracter con la función charAt() +// Puedes acceder a cada caracter con la función charAt() "Este es un String".charAt(0); // = 'E' // ...o puedes usar la función substring() para acceder a pedazos más grandes @@ -122,11 +124,11 @@ undefined; // usado para indicar que un valor no está presente actualmente // (aunque undefined es un valor en sí mismo) // false, null, undefined, NaN, 0 y "" es false; todo lo demás es true. -// Note que 0 is false y "0" es true, a pesar de que 0 == "0". +// Note que 0 es false y "0" es true, a pesar de que 0 == "0". // Aunque 0 === "0" sí es false. /////////////////////////////////// -// 2. Variables, Arreglos y Objetos +// 2. Variables, Arrays y Objetos // Las variables se declaran con la palabra var. JavaScript cuenta con tipado dinámico, // así que no se necesitan aplicar tipos. La asignación se logra con el operador =. @@ -184,7 +186,7 @@ miObjeto.miLlave; // = "miValor" // agregar nuevas llaves. miObjeto.miTerceraLlave = true; -// Si intentas accesar con una llave que aún no está asignada tendrás undefined. +// Si intentas acceder con una llave que aún no está asignada tendrás undefined. miObjeto.miCuartaLlave; // = undefined /////////////////////////////////// @@ -220,7 +222,6 @@ for (var i = 0; i < 5; i++){ } // && es un "y" lógico, || es un "o" lógico -var casa = {tamano:"grande",casa:"color"}; if (casa.tamano == "grande" && casa.color == "azul"){ casa.contiene = "oso"; } @@ -300,7 +301,7 @@ i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, per //inmediatamente", que preveé variables temporales de fugarse al ámbito global (function(){ var temporal = 5; - // Podemos accesar al ámbito global asignando al 'objeto global', el cual + // Podemos acceder al ámbito global asignando al 'objeto global', el cual // en un navegador siempre es 'window'. El objeto global puede tener // un nombre diferente en ambientes distintos, por ejemplo Node.js . window.permanente = 10; @@ -320,7 +321,7 @@ function decirHolaCadaCincoSegundos(nombre){ alert(texto); } setTimeout(interna, 5000); - // setTimeout es asíncrono, así que la funcion decirHolaCadaCincoSegundos + // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos // terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos // Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene // acceso a la variable 'texto' cuando es llamada. @@ -338,7 +339,7 @@ var miObjeto = { }; miObjeto.miFuncion(); // = "¡Hola Mundo!" -// Cuando las funciones de un objeto son llamadas, pueden accesar a las variables +// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables // del objeto con la palabra clave 'this'. miObjeto = { miString: "¡Hola Mundo!", @@ -400,11 +401,11 @@ var MiConstructor = function(){ miNuevoObjeto = new MiConstructor(); // = {miNumero: 5} miNuevoObjeto.miNumero; // = 5 -// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a accesar a una +// Todos los objetos JavaScript tienen un 'prototipo'. Cuando vas a acceder a una // propiedad en un objeto que no existe en el objeto el intérprete buscará en // el prototipo. -// Algunas implementaciones de JavaScript te permiten accesar al prototipo de +// Algunas implementaciones de JavaScript te permiten acceder al prototipo de // un objeto con la propiedad __proto__. Mientras que esto es útil para explicar // prototipos, no es parte del estándar; veremos formas estándar de usar prototipos // más adelante. @@ -439,7 +440,7 @@ miPrototipo.sentidoDeLaVida = 43; miObjeto.sentidoDeLaVida; // = 43 // Mencionabamos anteriormente que __proto__ no está estandarizado, y que no -// existe una forma estándar de accesar al prototipo de un objeto. De todas formas. +// existe una forma estándar de acceder al prototipo de un objeto. De todas formas. // hay dos formas de crear un nuevo objeto con un prototipo dado. // El primer método es Object.create, el cual es una adición reciente a JavaScript, @@ -475,10 +476,7 @@ typeof miNumero; // = 'number' typeof miNumeroObjeto; // = 'object' miNumero === miNumeroObjeyo; // = false if (0){ - // Este código no se ejecutara porque 0 es false. -} -if (Number(0)){ - // Este código sí se ejecutara, puesto que Number(0) es true. + // Este código no se ejecutará porque 0 es false. } // Aún así, los objetos que envuelven y los prototipos por defecto comparten diff --git a/es-es/json-es.html.markdown b/es-es/json-es.html.markdown index fff678eb..c98049f9 100644 --- a/es-es/json-es.html.markdown +++ b/es-es/json-es.html.markdown @@ -21,22 +21,22 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "llaves": "siempre debe estar entre comillas (ya sean dobles o simples)", "numeros": 0, "strings": "Høla, múndo. Todo el unicode está permitido, así como \"escapar\".", - "soporta booleanos?": true, - "vacios": null, + "¿soporta booleanos?": true, + "vacíos": null, "numero grande": 1.2e+100, "objetos": { - "comentario": "La mayoria de tu estructura vendra de objetos.", + "comentario": "La mayoría de tu estructura vendrá de objetos.", "arreglo": [0, 1, 2, 3, "Los arreglos pueden contener cualquier cosa.", 5], "otro objeto": { - "comentario": "Estas cosas pueden estar anidadas, muy util." + "comentario": "Estas cosas pueden estar anidadas, muy útil." } }, - "tonteria": [ + "tontería": [ { "fuentes de potasio": ["bananas"] }, @@ -50,10 +50,10 @@ JSON en su forma más pura no tiene comentarios, pero la mayoría de los parsead "estilo alternativo": { "comentario": "Mira esto!" - , "posicion de la coma": "no importa - mientras este antes del valor, entonces sera valido" - , "otro comentario": "que lindo" + , "posición de la coma": "no importa - mientras este antes del valor, entonces sera válido" + , "otro comentario": "qué lindo" }, - "eso fue rapido": "Y, estas listo. Ahora sabes todo lo que JSON tiene para ofrecer." + "eso fue rapido": "Y, estás listo. Ahora sabes todo lo que JSON tiene para ofrecer." } ``` diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 203ee3bb..e4181609 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -4,757 +4,937 @@ contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: - ["Guillermo Garza", "http://github.com/ggarza"] + - ["Ismael Venegas Castelló", "https://github.com/Ismael-VC"] filename: learnjulia-es.jl lang: es-es --- -Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -Aunque que tiene todo el poder de macros homoiconic, funciones de primera -clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como -Python. +![JuliaLang](http://s13.postimg.org/z89djuwyf/julia_small.png) -Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de -2013. +[Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). -```ruby +En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario. + +### ¡Prueba Julia ahora mismo! + +* [TryJupyter](https://try.jupyter.org) +* [JuliaBox](https://juliabox.org) +* [SageMathCloud](https://cloud.sagemath.com) + +### Resumen de Características: -# Comentarios de una línea comienzan con una almohadilla (o signo gato) +* [Despacho múltiple](http://en.wikipedia.org/wiki/Multiple_dispatch): permite definir el comportamiento de las funciones a través de múltiples combinaciones de tipos de argumentos (**métodos**). +* Sistema de **tipado dinámico**: tipos para la documentación, la optimización y el despacho. +* [Buen desempeño](http://julialang.org/benchmarks), comparado al de lenguajes **estáticamente compilados** como C. +* [Gestor de paquetes](http://docs.julialang.org/en/release-0.3/stdlib/pkg) integrado. +* [Macros tipo Lisp](http://docs.julialang.org/en/release-0.3/manual/metaprogramming/#macros) y otras comodidades para la [meta programación](http://docs.julialang.org/en/release-0.3/manual/metaprogramming). +* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **Matlab** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)). +* [Llamar funciones de C y Fortran](http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code) **directamente**: sin necesidad de usar envoltorios u APIs especiales. +* Poderosas características de **línea de comandos** para [gestionar otros procesos](http://docs.julialang.org/en/release-0.3/manual/running-external-programs). +* Diseñado para la [computación paralela y distribuida](http://docs.julialang.org/en/release-0.3/manual/parallel-computing) **desde el principio**. +* [Corrutinas](http://en.wikipedia.org/wiki/Coroutine): hilos ligeros "**verdes**". +* Los [tipos definidos por el usuario](http://docs.julialang.org/en/release-0.3/manual/types) son tan **rápidos y compactos** como los tipos estándar integrados. +* [Generación automática de código](http://docs.julialang.org/en/release-0.3/stdlib/base/?highlight=%40code#internals) **eficiente y especializado** para diferentes tipos de argumentos. +* [Conversiones y promociones](http://docs.julialang.org/en/release-0.3/manual/conversion-and-promotion) para tipos numéricos y de otros tipos, **elegantes y extensibles**. +* Soporte eficiente para [Unicode](http://es.wikipedia.org/wiki/Unicode), incluyendo [UTF-8](http://es.wikipedia.org/wiki/UTF-8) pero sin limitarse solo a este. +* [Licencia MIT](https://github.com/JuliaLang/julia/blob/master/LICENSE.md): libre y de código abierto. + +Esto se basa en la versión `0.3.11`. + +```ruby +# Los comentarios de una línea comienzan con una almohadilla (o signo de gato). -#= Commentarios multilinea pueden escribirse - usando '#=' antes de el texto y '=#' - después del texto. También se pueden anidar. +#= + Los comentarios multilínea pueden escribirse + usando '#=' antes de el texto y '=#' + después del texto. También se pueden anidar. =# -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### -# Todo en Julia es una expresión. +############################################## +# 1. Tipos de datos primitivos y operadores. # +############################################## + +# Todo en Julia es una expresión (Expr). # Hay varios tipos básicos de números. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2//3 # => 2//3 (Rational{Int64}) +3 # => 3 # Int64 +3.2 # => 3.2 # Float64 +2 + 1im # => 2 + 1im # Complex{Int64} +2 // 3 # => 2//3 # Rational{Int64} # Todos los operadores infijos normales están disponibles. -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 -5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Float -div (5, 2) # => 2 # para un resultado truncado, usa div -5 \ 35 # => 7.0 -2 ^ 2 # => 4 # exponente, no es xor -12 % 10 # => 2 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 # => 8 - -# Operadores a nivel de bit -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - -# Se puede utilizar la función bits para ver la representación binaria de un -# número. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 # dividir un Int por un Int siempre resulta + # en un Float +5 / 2 # => 2.5 +div(5, 2) # => 2 # para un resultado truncado, usa la función div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # exponente, no es XOR +12 % 10 # => 2 + +# Refuerza la precedencia con paréntesis. +(1 + 3) * 2 # => 8 + +# Operadores a nivel de bit. +~2 # => -3 # bitwise NOT +3 & 5 # => 1 # bitwise AND +2 | 4 # => 6 # bitwise OR +2 $ 4 # => 6 # bitwise XOR +2 >>> 1 # => 1 # desplazamiento lógico hacia la derecha +2 >> 1 # => 1 # desplazamiento aritmético hacia la derecha +2 << 1 # => 4 # desplazamiento lógico/aritmético hacia la izquierda + +# Se puede utilizar la función bits para ver la representación +# binaria de un número. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" + bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" -# Valores 'boolean' (booleanos) son primitivos -true -false - -# Operadores Boolean (booleanos) -!true # => false -!false # => true -1 == 1 # => true -2 == 1 # => false -1 != 1 # => false -2 != 1 # => true -1 < 10 # => true -1 > 10 # => false -2 <= 2 # => true -2 >= 2 # => true +# Los valores booleanos (Bool) son primitivos. +true # => true +false # => false + +# Operadores booleanos. +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true + # ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 # => true -2 < 3 < 2 # => false +1 < 2 < 3 # => true +2 < 3 < 2 # => false -# Strings se crean con " -"Esto es un string." +# Los literales de cadenas (String) se crean con la comilla doble: " +"Esto es una cadena." -# Literales de caracteres se escriben con ' +# Los literales de caracteres (Char) se crean con la comilla simple: ' 'a' -# Una string puede ser indexado como una array de caracteres -"Esto es un string."[1] # => 'E' # Índices en Julia empiezen del 1 -# Sin embargo, esto no va a funcionar bien para strings UTF8, +# Una cadena puede ser indexada como una arreglo de caracteres. +"Esto es un string."[1] # => 'E' # Los índices en Julia comienzan en: 1 + +# Sin embargo, esto no va a funcionar bien para las cadenas UTF8 (UTF8String), # Lo que se recomienda es la iteración (map, for, etc). -# $ puede ser utilizado para la interpolación de strings: -"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# Se puede poner cualquier expresión de Julia dentro los paréntesis. +# $ puede ser utilizado para la interpolación de cadenas, se puede poner +# cualquier expresión de Julia dentro los paréntesis. +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# Otro forma de formatear strings es el macro printf -@printf "%d es menor de %f" 4.5 5.3 # 5 es menor de 5.300000 +# Otra forma para formatear cadenas es usando el macro printf. +@printf "%d es menor de %f\n" 4.5 5.3 # 5 es menor de 5.300000 -# Imprimir es muy fácil -println("Soy Julia. ¡Encantado de conocerte!") +# ¡Imprimir es muy fácil! +println("¡Hola Julia!") # ¡Hola Julia! -#################################################### -## 2. Variables y Colecciones -#################################################### + +############################## +# 2. Variables y Colecciones # +############################## # No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # => 5 -una_variable # => 5 +una_variable = 5 # => 5 +una_variable # => 5 -# Acceder a variables no asignadas previamente es una excepción. +# Acceder a una variable no asignada previamente es una excepción. try - otra_variable # => ERROR: some_other_var not defined + otra_variable # ERROR: otra_variable not defined catch e - println(e) + println(e) # UndefVarError(:otra_variable) end -# Los nombres de variables comienzan con una letra. -# Después de eso, puedes utilizar letras, dígitos, guiones y signos de +# Los nombres de variables comienzan con una letra o guion bajo: _. +# Después de eso, puedes utilizar letras, dígitos, guiones bajos y signos de # exclamación. -OtraVariable123! = 6 # => 6 +otraVariable_123! = 6 # => 6 + +# También puedes utilizar caracteres Unicode. +☃ = 8 # => 8 -# También puede utilizar caracteres unicode -☃ = 8 # => 8 # Estos son especialmente útiles para la notación matemática -2 * π # => 6.283185307179586 - -# Una nota sobre las convenciones de nomenclatura de Julia: -# -# * Los nombres de las variables aparecen en minúsculas, con separación de -# palabra indicado por underscore ('\ _'). -# -# * Los nombres de los tipos comienzan con una letra mayúscula y separación de -# palabras se muestra con CamelCase en vez de underscore. -# -# * Los nombres de las funciones y los macros están en minúsculas, sin -# underscore. -# -# * Funciones que modifican sus inputs tienen nombres que terminan en!. Estos -# funciones a veces se llaman mutating functions o in-place functions. - -# Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n -a = Int64[] # => 0-element Int64 Array - -# Literales de arrays 1-dimensionales se pueden escribir con valores separados -# por comas. -b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] -b[1] # => 4 -b[end] # => 6 - -# Los arrays 2-dimensionales usan valores separados por espacios y filas -# separados por punto y coma. -matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] - -# Añadir cosas a la final de una lista con push! y append! -push!(a,1) # => [1] -push!(a,2) # => [1,2] -push!(a,4) # => [1,2,4] -push!(a,3) # => [1,2,4,3] -append!(a,b) # => [1,2,4,3,4,5,6] - -# Eliminar de la final con pop -pop!(b) # => 6 y b ahora es [4,5] - -# Vamos a ponerlo de nuevo -push!(b, 6) # b es ahora [4,5,6] de nuevo. - -a[1] # => 1 # recuerdan que los índices de Julia empiezan desde 1, no desde 0! - -# end es una abreviatura para el último índice. Se puede utilizar en cualquier -# expresión de indexación -a[end] # => 6 - -# tambien hay shift y unshift -shift!(a) # => 1 y a es ahora [2,4,3,4,5,6] -unshift!(a,7) # => [7,2,4,3,4,5,6] - -# Nombres de funciónes que terminan en exclamaciones indican que modifican -# su argumento. -arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] -sort(arr) # => [4,5,6]; arr es todavía [5,4,6] -sort!(arr) # => [4,5,6]; arr es ahora [4,5,6] - -# Buscando fuera de límites es un BoundsError +# (multiplicación implicita). +2π # => 6.283185307179586 + +#= + Una nota sobre las convenciones de nomenclatura de Julia: + + * Los nombres de las variables aparecen en minúsculas, con separación de + palabra indicado por un guion bajo: + + otra_variable + + * Los nombres de los tipos comienzan con una letra mayúscula y separación de + palabras se muestra con CamelCase en vez de guión bajo: + + OtroTipo + + * Los nombres de las funciones y los macros están en minúsculas, sin + underscore: + + otromacro + + * Funciones que modifican sus entradas tienen nombres que terminan en: !. + Estas funciones a veces se les llaman funciones transformadoras o + funciones in situ: + + otra_funcion! +=# + +# Los arreglos (Array) almacenan una secuencia de valores indexados de entre 1 hasta n. +a = Int64[] # => 0-element Array{Int64,1} + +# Los literales de arregos unidimensionales se pueden escribir con valores +# separados por comas. +b = [4, 5, 6] +#= + => 3-element Array{Int64,1}: + 4 + 5 + 6 +=# +b[1] # => 4 +b[end] # => 6 + +# Los arreglos bidimensionales usan valores separados por espacios y filas +# separadas por punto y coma. +matrix = [1 2; 3 4] +#= + => 2x2 Array{Int64,2}: + 1 2 + 3 4 +=# + +# Añadir cosas al final de un arreglo con push! y append!. +push!(a, 1) # => [1] +push!(a, 2) # => [1,2] +push!(a, 4) # => [1,2,4] +push!(a, 3) # => [1,2,4,3] +append!(a, b) # => [1,2,4,3,4,5,6] + +# Eliminar del final con pop!. +pop!(b) # => 6 y b ahora es: [4,5] + +# Vamos a ponerlo de nuevo. +push!(b, 6) # b es ahora [4,5,6] de nuevo + +a[1] # => 1 # recuerda, los índices de Julia empiezan desde 1, no desde 0! + +# end es una abreviatura para el último índice. Se puede utilizar en cualquier +# expresión de indexación. +a[end] # => 6 + +# También hay shift! y unshift!. +shift!(a) # => 1 y a es ahora: [2,4,3,4,5,6] +unshift!(a, 7) # => [7,2,4,3,4,5,6] + +# Los nombres de funciones que terminan en exclamaciones indican que modifican +# su o sus argumentos de entrada. +arr = [5, 4, 6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] y arr es todavía: [5,4,6] +sort!(arr) # => [4,5,6] y arr es ahora: [4,5,6] + +# Buscando fuera de límites es un BoundsError. try - a[0] # => ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 + a[0] # ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # ERROR: BoundsError() in getindex at array.jl:270 catch e - println(e) + println(e) # BoundsError() end -# Errors dan la línea y el archivo de su procedencia, aunque sea en el standard -# library. Si construyes Julia de source, puedes buscar en el source para -# encontrar estos archivos. +# Las excepciones y los errores dan la línea y el archivo de su procedencia, +# aunque provenga de la librería estándar. Si compilas Julia del código fuente, +# puedes buscar en el código para encontrar estos archivos. -# Se puede inicializar arrays de un range -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +# Se puede inicializar un arreglo con un rango (Range). +a = [1:5] # => 5-element Array{Int64,1}: [1,2,3,4,5] -# Puedes mirar en ranges con sintaxis slice. -a[1:3] # => [1, 2, 3] -a[2:end] # => [2, 3, 4, 5] +# Puedes mirar en los rangos con la sintaxis de rebanada. +a[1:3] # => [1,2,3] +a[2:end] # => [2,3,4,5] -# Eliminar elementos de una array por índice con splice! -arr = [3,4,5] -splice!(arr,2) # => 4 ; arr es ahora [3,5] +# Eliminar elementos de un arreglo por índice con splice! +arr = [3, 4, 5] +splice!(arr, 2) # => 4 y arr es ahora: [3,5] -# Concatenar listas con append! -b = [1,2,3] -append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] +# Concatenar arreglos con append! +b = [1, 2, 3] +append!(a, b) # a ahora es: [1,2,3,4,5,1,2,3] -# Comprueba la existencia en una lista con in -in(1, a) # => true +# Comprueba la existencia de un elemento en un arreglo con in. +in(1, a) # => true -# Examina la longitud con length -length(a) # => 8 +# Examina la longitud con length. +length(a) # => 8 + +# Las tuplas (Tuple) son inmutables. +tup = (1, 2, 3) # => (1,2,3) # una tupla tipo (Int64,Int64,Int64) +tup[1] # => 1 -# Tuples son immutable. -tup = (1, 2, 3) # => (1,2,3) # un (Int64,Int64,Int64) tuple. -tup[1] # => 1 try: - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 # ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e - println(e) + println(e) # MethodError(setindex!,(:tup,3,1)) end -# Muchas funciones de lista también trabajan en las tuples -length(tup) # => 3 -tup[1:2] # => (1,2) -in(2, tup) # => true +# Muchas funciones de arreglos también trabajan en con las tuplas. +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# Se pueden desempacar las tuplas en variables individuales. +a, b, c = (1, 2, 3) # => (1,2,3) # ahora a es 1, b es 2 y c es 3 + +# Los tuplas se crean, incluso si se omiten los paréntesis. +d, e, f = 4, 5, 6 # => (4,5,6) -# Se puede desempacar tuples en variables -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# Una tupla de un elemento es distinta del valor que contiene. +(1,) == 1 # => false +(1) == 1 # => true -# Los tuples se crean, incluso si se omite el paréntesis -d, e, f = 4, 5, 6 # => (4,5,6) +# Mira que fácil es cambiar dos valores! +e, d = d, e # => (5,4) # ahora d es 5 y e es 4 -# Un tuple 1-elemento es distinto del valor que contiene -(1,) == 1 # => false -(1) == 1 # => true +# Los diccionarios (Dict) son arreglos asociativos. +dicc_vacio = Dict() # => Dict{Any,Any} with 0 entries -# Mira que fácil es cambiar dos valores -e, d = d, e # => (5,4) # d is now 5 and e is now 4 +# Se puede crear un diccionario usando una literal. +dicc_lleno = ["uno" => 1, "dos" => 2, "tres" => 3] +#= + => Dict{ASCIIString,Int64} with 3 entries: + "tres" => 3 + "dos" => 2 + "uno" => 1 +=# +# Busca valores con: []. +dicc_lleno["uno"] # => 1 -# Dictionaries almanecan mapeos -dict_vacio = Dict() # => Dict{Any,Any}() +# Obtén todas las claves con. +keys(dicc_lleno) +#= + => KeyIterator for a Dict{ASCIIString,Int64} with 3 entries. Keys: + "tres" + "dos" + "uno" +=# -# Se puede crear un dictionary usando un literal -dict_lleno = ["one"=> 1, "two"=> 2, "three"=> 3] -# => Dict{ASCIIString,Int64} +# Nota: los elementos del diccionario no están ordenados y no se guarda el orden +# en que se insertan. -# Busca valores con [] -dict_lleno["one"] # => 1 +# Obtén todos los valores. +values(dicc_lleno) +#= + => ValueIterator for a Dict{ASCIIString,Int64} with 3 entries. Values: + 3 + 2 + 1 +=# -# Obtén todas las claves -keys(dict_lleno) -# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - claves del dictionary no están ordenados ni en el orden en que se -# insertan. +# Nota: igual que el anterior en cuanto a ordenamiento de los elementos. -# Obtén todos los valores -values(dict_lleno) -# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - Igual que el anterior en cuanto a ordenamiento de claves. +# Comprueba si una clave existe en un diccionario con in y haskey. +in(("uno", 1), dicc_lleno) # => true +in(("tres", 3), dicc_lleno) # => false -# Compruebe si hay existencia de claves en un dictionary con in y haskey -in(("uno", 1), dict_lleno) # => true -in(("tres", 3), dict_lleno) # => false -haskey(dict_lleno, "one") # => true -haskey(dict_lleno, 1) # => false +haskey(dicc_lleno, "uno") # => true +haskey(dicc_lleno, 1) # => false -# Tratando de buscar una clave que no existe producirá un error +# Tratar de obtener un valor con una clave que no existe producirá un error. try - dict_lleno["dos"] # => ERROR: key not found: dos in getindex at dict.jl:489 + # ERROR: key not found: cuatro in getindex at dict.jl:489 + dicc_lleno["cuatro"] catch e - println(e) + println(e) # KeyError("cuatro") end -# Utilice el método get para evitar ese error proporcionando un valor -# predeterminado -# get(dictionary,key,default_value) -get(dict_lleno,"one",4) # => 1 -get(dict_lleno,"four",4) # => 4 +# Utiliza el método get para evitar este error proporcionando un valor +# predeterminado: get(diccionario, clave, valor_predeterminado). +get(dicc_lleno, "uno", 4) # => 1 +get(dicc_lleno, "cuatro", 4) # => 4 -# Usa Sets para representar colecciones (conjuntos) de valores únicos, no -# ordenadas -conjunto_vacio = Set() # => Set{Any}() -# Iniciar una set de valores -conjunto_lleno = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# Usa conjuntos (Set) para representar colecciones de valores únicos, no +# ordenados. +conjunto_vacio = Set() # => Set{Any}({}) -# Añadir más valores a un conjunto -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) +# Iniciar una conjunto de valores. +conjunto_lleno = Set(1, 2, 2, 3, 4) # => Set{Int64}({4,2,3,1}) -# Compruebe si los valores están en el conjunto -in(2, conjunto_lleno) # => true -in(10, conjunto_lleno) # => false +# Añadir más valores a un conjunto. +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) -# Hay funciones de intersección de conjuntos, la unión, y la diferencia. -conjunto_otro= Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) -intersect(conjunto_lleno, conjunto_otro) # => Set{Int64}(3,4,5) -union(conjunto_lleno, conjunto_otro) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +# Comprobar si los valores están en el conjunto. +in(2, conjunto_lleno) # => true +in(10, conjunto_lleno) # => false +# Hay funciones de intersección, unión y diferencia de conjuntos. +otro_conjunto = Set(3, 4, 5, 6) # => Set{Int64}({6,4,5,3}) +intersect(conjunto_lleno, otro_conjunto) # => Set{Int64}({3,4,5}) +union(conjunto_lleno, otro_conjunto) # => Set{Int64}({1,2,3,4,5,6}) +setdiff(Set(1, 2, 3, 4), Set(2, 3, 5)) # => Set{Int64}({1,4}) -#################################################### -## 3. Control de Flujo -#################################################### -# Hagamos una variable +####################### +# 3. Control de Flujo # +####################### + +# Hagamos una variable. una_variable = 5 -# Aquí está una declaración de un 'if'. La indentación no es significativa en -# Julia +# Aquí está la declaración de un if. La indentación no es significativa en +# Julia. if una_variable > 10 - println("una_variable es completamente mas grande que 10.") -elseif una_variable < 10 # Este condición 'elseif' es opcional. - println("una_variable es mas chica que 10.") -else # Esto también es opcional. - println("una_variable es de hecho 10.") + println("una_variable es completamente mayor que 10.") +elseif una_variable < 10 # esta condición elseif es opcional + println("una_variable es menor que 10.") +else # esto también es opcional + println("De echo una_variable es 10.") end -# => imprime "una_variable es mas chica que 10." +# imprime: una_variable es menor que 10. -# For itera sobre tipos iterables -# Tipos iterables incluyen Range, Array, Set, Dict, y String. -for animal=["perro", "gato", "raton"] - println("$animal es un mamifero") - # Se puede usar $ para interpolar variables o expresiónes en strings +# El bucle for itera sobre tipos iterables, ie. Range, Array, Set, +# Dict y String. +for animal in ["perro", "gato", "ratón"] + # Se puede usar $ para interpolar variables o expresiones en ls cadenas. + println("$animal es un mamífero.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for a in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] - println("$(a[1]) es un $(a[2])") +for a in ["perro" => "mamífero", "gato" => "mamífero", "ratón" => "mamífero"] + println("$(a[1]) es un $(a[2]).") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for (k,v) in ["perro"=>"mamifero", "gato"=>"mamifero", "raton"=>"mamifero"] - println("$k es un $v") +for (k,v) in ["perro"=>"mamífero", "gato"=>"mamífero", "ratón"=>"mamífero"] + println("$k es un $v.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -# While itera hasta que una condición no se cumple. +# El bucle while itera hasta que una condición se deje de cumplir. x = 0 while x < 4 println(x) - x += 1 # versión corta de x = x + 1 + x += 1 # versión corta de: x = x + 1 end -# imprime: -# 0 -# 1 -# 2 -# 3 +#= +imprime: + 0 + 1 + 2 + 3 +=# -# Maneja excepciones con un bloque try/catch -try - error("ayuda") +# Maneja excepciones con un bloque try/catch. +try # intentar + error("Ooops!") catch e - println("capturando $e") + println("capturando: $e") # capturando: ErrorException("Ooops!") end -# => capturando ErrorException("ayuda") -#################################################### -## 4. Funciones -#################################################### +################ +# 4. Funciones # +################ -# Usa 'function' para crear nuevas funciones +# Usa function para crear nuevas funciones. -#function nombre(arglist) -# cuerpo... -#end +#= + function nombre(arglist) + cuerpo... + end +=# function suma(x, y) println("x es $x e y es $y") - # Las funciones devuelven el valor de su última declaración + # las funciones devuelven el valor de su última expresión x + y end +# => suma (generic function with 1 method) + +suma(5, 6) # => 11 # después de imprimir: x es 5 e y es 6 -suma(5, 6) # => 11 # después de imprimir "x es 5 e y es de 6" +# También puedes usar esta otra sintaxis para definir funciones! +resta(x, y) = x - y # => resta (generic function with 1 method) # Puedes definir funciones que toman un número variable de -# argumentos posicionales +# argumentos posicionales (el ... se llama un splat). function varargs(args...) + # Usa la palabra clave return para regresar desde cualquier + # lugar de la función. return args - # Usa la palabra clave return para devolver en cualquier lugar de la función end # => varargs (generic function with 1 method) -varargs(1,2,3) # => (1,2,3) +varargs(1, 2, 3) # => (1,2,3) +varargs([1, 2, 3]) # => ([1,2,3],) -# El ... se llama un splat. -# Acabamos de utilizar lo en una definición de función. -# También se puede utilizar en una llamada de función, -# donde va splat un Array o el contenido de un Tuple en la lista de argumentos. -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # Produce un Set de Arrays -Set([1,2,3]...) # => Set{Int64}(1,2,3) # esto es equivalente a Set(1,2,3) +# Acabamos de utilizar el splat (...) en la definición de una función. También +# se puede utilizar al llamar a una función, donde se esparce un arreglo, tupla +# o en general una secuencia iterable en la tupla de argumentos. +varargs([1, 2, 3]...) # => (1,2,3) # igual que: varargs(1, 2, 3) -x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # un Set de Tuples -Set(x...) # => Set{Int64}(2,3,1) +x = (1, 2, 3) # => (1,2,3) +varargs(x) # => ((1,2,3),) +varargs(x...) # => (1,2,3) +varargs("abc"...) # => ('a','b','c') -# Puede definir funciones con argumentos posicionales opcionales -function defaults(a,b,x=5,y=6) +# Puedes definir funciones con argumentos posicionales opcionales. +function defaults(a, b, x=5, y=6) return "$a $b y $x $y" end +# => defaults (generic function with 3 methods) + +defaults('h', 'g') # => "h g y 5 6" +defaults('h', 'g', 'j') # => "h g y j 6" +defaults('h', 'g', 'j', 'k') # => "h g y j k" -defaults('h','g') # => "h g y 5 6" -defaults('h','g','j') # => "h g y j 6" -defaults('h','g','j','k') # => "h g y j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # ERROR: `defaults` has no method matching defaults(::Char) + defaults() # ERROR: `defaults` has no method matching defaults() catch e - println(e) + println(e) # MethodError(defaults,('h',)) end -# Puedes definir funciones que toman argumentos de palabra clave -function args_clave(;k1=4,nombre2="hola") # note the ; - return ["k1"=>k1,"nombre2"=>nombre2] +# Puedes definir funciones que tomen argumentos de palabras clave. +function args_clave(;k1=4, nombre2="hola") # nota el punto y coma: ; + return ["k1" => k1, "nombre2" => nombre2] end +# => args_clave (generic function with 1 method) -args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] -args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] -args_clave() # => ["nombre2"=>"hola","k1"=>4] +args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] +args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] +args_clave() # => ["nombre2"=>"hola","k1"=>4] -# Puedes combinar todo tipo de argumentos en la misma función -function todos_los_args(arg_normal, arg_posicional_opcional=2; arg_clave="foo") - println("argumento normal: $arg_normal") - println("argumento optional: $arg_posicional_opcional") - println("argumento de clave: $arg_clave") +# Puedes combinar todo tipo de argumentos en la misma función. +function todos_los_args(arg_posicional, arg_opcional=2; arg_clave="foo") + println("argumento posicional: $arg_posicional") + println(" argumento opcional: $arg_opcional") + println(" argumento clave: $arg_clave") end +# => todos_los_args (generic function with 2 methods) +# No se necesita punto y coma ; al llamar la función usando un argumento clave, +# esto solo es necesario en la definición de la función. todos_los_args(1, 3, arg_clave=4) -# imprime: -# argumento normal: 1 -# argumento optional: 3 -# argumento de clave: 4 +#= + imprime: + argumento posicional: 1 + argumento opcional: 3 + argumento clave: 4 +=# -# Julia tiene funciones de primera clase +# Julia tiene funciones de primera clase. function crear_suma(x) - suma = function (y) + suma = function (y) # función anónima return x + y end return suma end +# => crear_suma (generic function with 1 method) -# Esta es el sintaxis "stabby lambda" para crear funciones anónimas -(x -> x > 2)(3) # => true +# Esta es otra sintaxis (estilo cálculo lambda), para crear funciones anónimas. +(x -> x > 2)(3) # => true # Esta función es idéntica a la crear_suma implementación anterior. -function crear_suma(x) - y -> x + y -end +crear_suma(x) = y -> x + y -# También puedes nombrar la función interna, si quieres +# También puedes nombrar la función interna, si quieres. function crear_suma(x) function suma(y) x + y end suma end +# => crear_suma (generic function with 1 method) -suma_10 = crear_suma(10) -suma_10(3) # => 13 +suma_10 = crear_suma(10) # => suma (generic function with 1 method) +suma_10(3) # => 13 +# Hay funciones integradas de orden superior. +map(suma_10, [1, 2, 3]) # => [11,12,13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6,7] -# Hay funciones integradas de orden superior -map(suma_10, [1,2,3]) # => [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# Se puede pasar un bloque a las funciones cuyo primer argumento posicional +# es otra función, como en map y filter. +map([1, 2, 3]) do arr + suma_10(arr) +end +#= + => 3-element Array{Int64,1}: + 11 + 12 + 13 +=# -# Podemos usar listas por comprensión para mapeos -[suma_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +filter([3, 4, 5, 6, 7]) do arr + (x -> x > 5)(arr) +end +#= + => 2-element Array{Int64,1}: + 6 + 7 +=# -#################################################### -## 5. Tipos -#################################################### +# Podemos usar comprensiones de listas multidimensionales. +[suma_10(i) for i = [1, 2, 3]] # => [11, 12, 13] # 1D +[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +[i*j for i = [1:3], j in [1:3]] # 2D +#= + => 3x3 Array{Int64,2}: + 1 2 3 + 2 4 6 + 3 6 9 +=# + +[i*j/k for i = [1:3], j = [1:3], k in [1:3]] # 3D +#= + => 3x3x3 Array{Float64,3}: + [:, :, 1] = + 1.0 2.0 3.0 + 2.0 4.0 6.0 + 3.0 6.0 9.0 + + [:, :, 2] = + 0.5 1.0 1.5 + 1.0 2.0 3.0 + 1.5 3.0 4.5 + + [:, :, 3] = + 0.333333 0.666667 1.0 + 0.666667 1.33333 2.0 + 1.0 2.0 3.0 +=# + + +############ +# 5. Tipos # +############ -# Julia tiene sistema de tipos. # Cada valor tiene un tipo y las variables no tienen propios tipos. -# Se puede utilizar la función `typeof` para obtener el tipo de un valor. -typeof(5) # => Int64 +# Se puede utilizar la función typeof para obtener el tipo de un valor. +typeof(5) # => Int64 # en un sistema de 64 bits, de lo contrario: Int32 -# Los tipos son valores de primera clase -typeof(Int64) # => DataType -typeof(DataType) # => DataType -# DataType es el tipo que representa los tipos, incluyéndose a sí mismo. +# Los tipos son valores de primera clase, DataType es el tipo que representa a +# los tipos, incluyéndose a sí mismo. +typeof(Int64) # => DataType +typeof(DataType) # => DataType -# Los tipos se usan para la documentación, optimizaciones, y envio. -# No están comprobados estáticamente. +# Los tipos se usan para la documentación, para optimizaciones +# y el despacho múltiple. No están comprobados estáticamente. -# Los usuarios pueden definir tipos -# Son como registros o estructuras en otros idiomas. -# Nuevos tipos se definen utilizado la palabra clave `type`. +# Los usuarios pueden definir sus propios tipos. +# Son como registros o estructuras en otros idiomas. +# Un nuevo tipos se define utilizado la palabra clave type. # type Nombre -# field::OptionalType +# atributo::UnTipo # las anotaciones de tipos son opcionales # ... # end type Tigre - longituddecola::Float64 - colordelpelaje # no incluyendo una anotación de tipo es el mismo que `::Any` + longitud_cola::Float64 + color_pelaje # sin una anotación de tipo, es lo mismo que `::Any` end -# Los argumentos del constructor por default son las propiedades -# del tipo, en el orden en que están listados en la definición -tigger = Tigre(3.5,"anaranjado") # => Tiger(3.5,"anaranjado") +# Los argumentos del constructor por defecto son los atributos +# del tipo, en el orden en que están listados en la definición. +tigre = Tigre(3.5, "anaranjado") # => Tigre(3.5,"anaranjado") -# El tipo funciona como la función constructora de valores de ese tipo -sherekhan = typeof(tigger)(5.6,"fuego") # => Tiger(5.6,"fuego") +# El tipo funciona como método constructor para los valores de ese tipo. +sherekhan = typeof(tigre)(5.6, "fuego") # => Tigre(5.6,"fuego") -# Este estilo de tipos son llamados tipos concrete -# Se pueden crear instancias, pero no pueden tener subtipos. -# La otra clase de tipos es tipos abstractos (abstract types). +# Este estilo de tipos son llamados tipos concretos. +# Se pueden crear instancias de estos, pero no pueden tener subtipos. +# La otra clase de tipos son los tipos abstractos. # abstract Nombre -abstract Gato # sólo un nombre y un punto en la jerarquía de tipos - -# De los tipos Abstract no se pueden crear instancias, pero pueden tener -# subtipos. Por ejemplo, Number es un tipo abstracto. -subtypes(Number) # => 6-element Array{Any,1}: - # Complex{Float16} - # Complex{Float32} - # Complex{Float64} - # Complex{T<:Real} - # Real -subtypes(Gato) # => 0-element Array{Any,1} - -# Cada tipo tiene un supertipo, utilice la función `súper` para conseguirlo. -typeof(5) # => Int64 -super(Int64) # => Signed -super(Signed) # => Real -super(Real) # => Number -super(Number) # => Any -super(super(Signed)) # => Number -super(Any) # => Any -# Todo de estos tipos, a excepción de Int64, son abstractos. - -# <: es el operador de subtipos -type Leon <: Gato # Leon es un subtipo de Gato - color_de_crin - rugido::String -end +abstract Gato # sólo un nombre y un punto en la jerarquía de tipos + +# No se pueden crear instancias de los tipos abstractos, pero pueden tener +# subtipos. Por ejemplo, Number es un tipo abstracto. +subtypes(Number) +#= + => 2-element Array{Any,1}: + Complex{T<:Real} + Real +=# + +subtypes(Gato) # => 0-element Array{Any,1} -# Se puede definir más constructores para su tipo. -# Sólo defina una función del mismo nombre que el tipo -# y llame a un constructor existente para obtener un valor del tipo correcto -Leon(rugido::String) = Leon("verde",rugido) -# Este es un constructor externo porque es fuera de la definición del tipo - -type Pantera <: Gato # Pantera tambien es un a subtipo de Cat - color_de_ojos - Pantera() = new("verde") - # Panteras sólo tendrán este constructor, y ningún constructor - # predeterminado. +# Cada tipo tiene un supertipo, utiliza la función súper para conseguirlo. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Integer +super(Integer) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Real +super(Any) # => Any + +# Todos estos tipos, a excepción de Int64, son abstractos. + +# <: es el operador de subtipos. +type Leon <: Gato # Leon es un subtipo de Gato + color_crin + rugido::String end -# Utilizar constructores internos, como Panther hace, te da control sobre cómo -# se pueden crear valores del tipo. Cuando sea posible, debes utilizar -# constructores exteriores en lugar de los internos. -#################################################### -## 6. Envio múltiple -#################################################### +# Se pueden definir más constructores para un tipo. +# Sólo define una función del mismo nombre que el tipo y llama al constructor +# existente para obtener un valor del tipo correcto. -# En Julia, todas las funciones nombradas son funciones genéricas. -# Esto significa que se construyen a partir de muchos métodos pequeños -# Cada constructor de Leon es un método de la función genérica Leon. +# Este es un constructor externo porque está fuera de la definición del tipo. +Leon(rugido::String) = Leon("verde", rugido) -# Por ejemplo, vamos a hacer un maullar función: +type Pantera <: Gato # Pantera también es un a subtipo de Gato + color_ojos -# Definiciones para Leon, Pantera, y Tigre -function maullar(animal::Leon) - animal.rugido # acceso utilizando notación de puntos + # Pantera sólo tendrá este constructor, y ningún constructor predeterminado. + Pantera() = new("verde") end -function maullar(animal::Pantera) - "grrr" -end +# Utilizar constructores internos, como se hace en Pantera, te da control sobre +# cómo se pueden crear valores de este tipo. Cuando sea posible, debes utilizar +# constructores externos en lugar de internos. -function maullar(animal::Tigre) - "rawwwr" -end -# Prueba de la función maullar -maullar(tigger) # => "rawwr" -maullar(Leon("cafe","ROAAR")) # => "ROAAR" -maullar(Pantera()) # => "grrr" +######################## +# 6. Despacho Múltiple # +######################## -# Revisar la jerarquía de tipos locales -issubtype(Tigre,Gato) # => false -issubtype(Leon,Gato) # => true -issubtype(Pantera,Gato) # => true +# En Julia, todas las funciones nombradas son funciones genéricas. +# Esto significa que se construyen a partir de muchos métodos más pequeños. +# Cada constructor de Leon es un método de la función genérica Leon. -# Definición de una función que toma Gatos -function mascota(gato::Gato) - println("El gato dice $(maullar(gato))") -end +# Por ejemplo, vamos a hacer métodos para Leon, Pantera, y Tigre de una +# función genérica maullar: + +# acceso utilizando notación de puntos +maullar(animal::Leon) = animal.rugido +# => maullar (generic function with 1 method) +maullar(animal::Pantera) = "grrr" +# => maullar (generic function with 2 methods) +maullar(animal::Tigre) = "rawwwr" +# => maullar (generic function with 3 methods) + +# Se puede obtener una lista de métodos con la función methods. +methods(maullar) +#= + # 3 methods for generic function "maullar": + maullar(animal::Leon) at none:1 + maullar(animal::Pantera) at none:1 + maullar(animal::Tigre) at none:1 +=# + +# Prueba de la función maullar. +maullar(tigre) # => "rawwwr" +maullar(Leon("cafe", "ROAAR")) # => "ROAAR" +maullar(Pantera()) # => "grrr" + +# Revisar la jerarquía de tipos locales. +issubtype(Tigre, Gato) # => false # igual que: Tigre <: Gato +issubtype(Leon, Gato) # => true # igual que: Leon <: Gato +issubtype(Pantera, Gato) # => true + +# Definición de una función que acepta argumentos de tipo Gato. +mascota(gato::Gato) = println("El gato dice $(maullar(gato))") + +mascota(Leon("42")) # El gato dice 42 -mascota(Leon("42")) # => imprime "El gato dice 42" try - mascota(tigger) # => ERROR: no method mascota(Tigre)) + mascota(tigre) # ERROR: `mascota` has no method matching mascota(::Tigre) catch e - println(e) + println(e) # MethodError(mascota,(Tigre(3.5,"anaranjado"),)) end -# En los lenguajes orientados a objetos, expedición única es común. Esto -# significa que el método se recogió basándose en el tipo del primer argumento. -# En Julia, todos los tipos de argumentos contribuyen a seleccionar el mejor -# método. +# En los lenguajes orientados a objetos, el despacho simple es común. Esto +# significa que la implementación del método a llamar se selecciona en base +# al tipo del primer argumento. + +# En Julia, los tipos de todos los argumentos contribuyen a seleccionar método +# más específico. # Vamos a definir una función con más argumentos, para que podamos ver la # diferencia -function pelear(t::Tigre,c::Gato) - println("¡El tigre $(t.colordelpelaje) gana!") -end +pelear(t::Tigre, c::Gato) = println("¡El tigre $(t.color_pelaje) gana!") # => pelear (generic function with 1 method) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => ¡El tigre anaranjado gana! +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # ¡El tigre anaranjado gana! -# Vamos a cambiar el comportamiento cuando el Gato es específicamente un Leon -pelear(t::Tigre,l::Leon) = println("El león con melena $(l.color_de_crin) gana") +# Vamos a cambiar el comportamiento cuando el Gato sea específicamente un Leon. +pelear(t::Tigre, l::Leon) = println("El león con melena $(l.color_crin) gana.") # => pelear (generic function with 2 methods) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => imprime El león con melena verde gana +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # El león con melena verde gana. -# No necesitamos un tigre para poder luchar -pelear(l::Leon,c::Gato) = println("El gato victorioso dice $(maullar(c))") -# => fight (generic function with 3 methods) +# No necesitamos un tigre para poder luchar. +pelear(l::Leon, c::Gato) = println("El gato victorioso dice $(maullar(c)).") +# => pelear (generic function with 3 methods) -pelear(Leon("balooga!"),Pantera()) # => imprime El gato victorioso dice grrr +methods(pelear) +#= + # 3 methods for generic function "pelear": + pelear(t::Tigre,l::Leon) at none:2 + pelear(t::Tigre,c::Gato) at none:1 + pelear(l::Leon,c::Gato) at none:2 +=# + +pelear(Leon("balooga!"), Pantera()) # El gato victorioso dice grrr. try - pelear(Pantera(),Leon("RAWR")) # => ERROR: no method pelear(Pantera, Leon)) -catch + # ERROR: `pelear` has no method matching pelear(::Pantera, ::Leon) + pelear(Pantera(),Leon("RAWR")) +catch # no hacer nada con la excepción atrapada end -# Un metodo con el gato primero +# Un metodo con el tipo Gato primero. pelear(c::Gato,l::Leon) = println("El gato le gana al León") -# Warning: New definition -# pelear(Gato,Leon) at none:1 -# is ambiguous with: -# pelear(Leon,Gato) at none:1. -# To fix, define -# pelear(Leon,Leon) -# before the new definition. -# pelear (generic function with 4 methods) - -# Esta advertencia se debe a que no está claro que metodo de pelear será llamado -# en: -pelear(Leon("RAR"),Leon("cafe","rar")) # => imprime El gato victorioso dice rar -# El resultado puede ser diferente en otras versiones de Julia +#= + Warning: New definition + pelear(Gato,Leon) at none:1 + is ambiguous with: + pelear(Leon,Gato) at none:1. + To fix, define + pelear(Leon,Leon) + before the new definition. + pelear (generic function with 4 methods) +=# +# Esta advertencia se debe a que no está claro que método de pelear +# será llamado en: +pelear(Leon("RAR"),Leon("cafe","rar")) # El gato victorioso dice rar. + +# El resultado puede ser diferente en otras versiones de Julia pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") -pelear(Leon("GR"),Leon("cafe","rar")) # => imprime Los leones llegan a un empate - - -# Un vistazo al nivel bajo -# Se puede echar un vistazo a la LLVM y el código ensamblador generado. - -area_cuadrada(l) = l * l # area_cuadrada (generic function with 1 method) - -area_cuadrada(5) # => 25 - -# ¿Qué sucede cuando damos area_cuadrada diferentes argumentos? -code_native(area_cuadrada, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX - -code_native(area_cuadrada, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret - -code_native(area_cuadrada, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # - -# Ten en cuenta que Julia usará instrucciones de "floating point" si alguno de -# los argumentos son "floats" -# Vamos a calcular el área de un círculo -area_circulo(r) = pi * r * r # circle_area (generic function with 1 method) -area_circulo(5) # 78.53981633974483 + +pelear(Leon("GR"),Leon("cafe","rar")) # Los leones llegan a un empate + + +################################ +# 7. Un vistazo de bajo nivel. # +################################ + +# Se puede echar un vistazo al código IR de LLVM y al código +# ensamblador generado. +area_cuadrado(l) = l * l # => area_cuadrado (generic function with 1 method) + +area_cuadrado(5) # => 25 + +# ¿Qué sucede cuando damos area_cuadrada diferentes tipos de argumentos? +code_native(area_cuadrado, (Int32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 # prólogo + push RBP + mov RBP, RSP + Source line: 1 + imul RDI, RDI # elevar l al cuadrado + mov RAX, RDI # almacenar el resultado en RAX + pop RBP # restaurar el puntero base anterior + ret # el resultado estará en RAX +=# + +code_native(area_cuadrado, (Float32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulss XMM0, XMM0 # multiplicación escalar de presición simple (AVX) + pop RBP + ret +=# + +code_native(area_cuadrado, (Float64,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulsd XMM0, XMM0 # multiplicación escalar de presición doble (AVX) + pop RBP + ret +=# + +# Ten en cuenta que Julia usará instrucciones de punto flotante si el tipo de +# alguno de los argumentos es flotante. + +# Vamos a calcular el área de un círculo. +area_circulo(r) = π * r * r # area_circulo (generic function with 1 method) +area_circulo(5) # 78.53981633974483 code_native(area_circulo, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + cvtsi2sd XMM1, EDI # cargar entero r de la memoria + movabs RAX, 4477117456 # cargar constante matemática π + movsd XMM0, QWORD PTR [RAX] + mulsd XMM0, XMM1 # π * r + mulsd XMM0, XMM1 # (π * r) * r + pop RBP + ret +=# code_native(area_circulo, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + movabs RAX, 4477120336 + movsd XMM1, QWORD PTR [RAX] + Source line: 1 + mulsd XMM1, XMM0 + mulsd XMM1, XMM0 + movaps XMM0, XMM1 + pop RBP + ret +=# ``` -## ¿Listo para más? +![Julia-tan](http://s27.postimg.org/x37ndhz0j/julia_tan_small.png) -Puedes obtener muchos más detalles en [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +## ¿Listo para más? -El mejor lugar para obtener ayuda con Julia es el (muy amable) [lista de correos](https://groups.google.com/forum/#!forum/julia-users). +Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3). +El mejor lugar para obtener ayuda con Julia, es en su amigable [lista de correos](https://groups.google.com/forum/#!forum/julia-users). diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown index d90e3eb5..bc481df7 100644 --- a/es-es/markdown-es.html.markdown +++ b/es-es/markdown-es.html.markdown @@ -11,7 +11,7 @@ lang: es-es Markdown fue creado por John Gruber en 2004. Su propósito es ser una sintaxis fácil de leer y escribir que se convierta fácilmente a HTML (y, actualmente, otros formatos también). -¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! +¡Denme toda la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests! ```markdown @@ -44,7 +44,7 @@ Esto es un h2 ------------- <!-- Estilos para texto plano --> -<!-- El texto puede ser fácilmente estilizaedo con italicas, negritas o tachado +<!-- El texto puede ser fácilmente estilizado con italicas, negritas o tachado usando markdown --> *Este texto está en itálicas.* @@ -62,7 +62,7 @@ Markdown en Github, también tenemos: --> ~~Este texto está tachado.~~ -<!-- Los párrafos son una o múltuples líneas de texto adyacentes separadas por +<!-- Los párrafos son una o múltiples líneas de texto adyacentes separadas por una o múltiples líneas en blanco--> Este es un párrafo. Estoy escribiendo un párrafo, ¿No es divertido? diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index f7a0ec02..4930eebc 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Fabio Souto", "http://fabiosouto.me"] lang: es-es filename: learnpython-es.py --- @@ -30,27 +31,47 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Tienes números 3 #=> 3 -# Matemática es lo que esperarías -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +# Evidentemente puedes realizar operaciones matemáticas +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 # La división es un poco complicada. Es división entera y toma la parte entera # de los resultados automáticamente. -5 / 2 #=> 2 +5 / 2 #=> 2 # Para arreglar la división necesitamos aprender sobre 'floats' # (números de coma flotante). 2.0 # Esto es un 'float' -11.0 / 4.0 #=> 2.75 ahhh...mucho mejor +11.0 / 4.0 #=> 2.75 ahhh...mucho mejor + +# Resultado de la división de enteros truncada para positivos y negativos +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona con números en coma flotante +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# El operador módulo devuelve el resto de una división entre enteros +7 % 3 # => 1 + +# Exponenciación (x elevado a y) +2**4 # => 16 # Refuerza la precedencia con paréntesis -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 #=> 8 + +# Operadores booleanos +# Nota: "and" y "or" son sensibles a mayúsculas +True and False #=> False +False or True #=> True -# Valores 'boolean' (booleanos) son primitivos -True -False +# Podemos usar operadores booleanos con números enteros +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True # Niega con 'not' not True #=> False @@ -90,7 +111,7 @@ not False #=> True # Una forma más reciente de formatear strings es el método 'format'. # Este método es la forma preferida "{0} pueden ser {1}".format("strings", "formateados") -# Puedes usar palabras claves si no quieres contar. +# Puedes usar palabras clave si no quieres contar. "{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") # None es un objeto @@ -107,8 +128,8 @@ None is None #=> True # None, 0, y strings/listas vacíos(as) todas se evalúan como False. # Todos los otros valores son True -0 == False #=> True -"" == False #=> True +bool(0) #=> False +bool("") #=> False #################################################### @@ -130,16 +151,16 @@ otra_variable # Levanta un error de nombre # 'if' puede ser usado como una expresión "yahoo!" if 3 > 2 else 2 #=> "yahoo!" -# Listas almacenan secuencias +# Las listas almacenan secuencias lista = [] # Puedes empezar con una lista prellenada otra_lista = [4, 5, 6] # Añadir cosas al final de una lista con 'append' -lista.append(1) #lista ahora es [1] -lista.append(2) #lista ahora es [1, 2] -lista.append(4) #lista ahora es [1, 2, 4] -lista.append(3) #lista ahora es [1, 2, 4, 3] +lista.append(1) # lista ahora es [1] +lista.append(2) # lista ahora es [1, 2] +lista.append(4) # lista ahora es [1, 2, 4] +lista.append(3) # lista ahora es [1, 2, 4, 3] # Remueve del final de la lista con 'pop' lista.pop() #=> 3 y lista ahora es [1, 2, 4] # Pongámoslo de vuelta @@ -173,11 +194,11 @@ lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] # Chequea la existencia en una lista con 1 in lista #=> True -# Examina el largo de una lista con 'len' +# Examina el tamaño de una lista con 'len' len(lista) #=> 6 -# Tuplas son como listas pero son inmutables. +# Las tuplas son como las listas, pero son inmutables. tupla = (1, 2, 3) tupla[0] #=> 1 tupla[0] = 3 # Levanta un error TypeError @@ -266,7 +287,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Hagamos sólo una variable una_variable = 5 -# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! # imprime "una_variable es menor que 10" if una_variable > 10: print "una_variable es completamente mas grande que 10." @@ -400,12 +421,12 @@ class Humano(object): # Un atributo de clase es compartido por todas las instancias de esta clase especie = "H. sapiens" - # Constructor basico + # Constructor básico, se llama al instanciar la clase. def __init__(self, nombre): # Asigna el argumento al atributo nombre de la instancia self.nombre = nombre - # Un metodo de instancia. Todos los metodos toman self como primer argumento + # Un método de instancia. Todos los metodos toman self como primer argumento def decir(self, msg): return "%s: %s" % (self.nombre, msg) @@ -470,6 +491,56 @@ import math dir(math) +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores permiten evaluación perezosa +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha +# En vez de generar y devolver todos los valores de una vez, crea un valor +# en cada iteración. En este ejemplo los valores mayores que 15 no serán +# procesados en duplicar_numeros. +# Nota: xrange es un generador que hace lo mismo que range. +# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio. +# xrange crea un generador, mientras que range crea toda la lista. +# Añadimos un guion bajo a los nombres de variable que coinciden con palabras +# reservadas de python. +xrange_ = xrange(1, 900000000) + +# duplica todos los números hasta que encuentra un resultado >= 30 +for i in duplicar_numeros(xrange_): + print i + if i >= 30: + break + +# Decoradores +# en este ejemplo pedir rodea a hablar +# Si por_favor es True se cambiará el mensaje. +from functools import wraps + + +def pedir(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, por_favor = target_function(*args, **kwargs) + if por_favor: + return "{} {}".format(msg, "¡Por favor! Soy pobre :(") + return msg + + return wrapper + + +@pedir +def hablar(por_favor=False): + msg = "¿Me puedes comprar una cerveza?" + return msg, por_favor + +print hablar() # ¿Me puedes comprar una cerveza? +print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :( ``` ## ¿Listo para más? @@ -481,6 +552,7 @@ dir(math) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Encuadernados diff --git a/es-es/ruby-es.html.markdown b/es-es/ruby-es.html.markdown index 66a5d0fe..d8b67fe7 100644 --- a/es-es/ruby-es.html.markdown +++ b/es-es/ruby-es.html.markdown @@ -5,8 +5,18 @@ contributors: - ["David Underwood", "http://theflyingdeveloper.com"] - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Erick Bernal", "http://www.twitter.com/billowkib"] lang: es-es --- @@ -33,6 +43,8 @@ Tu tampoco deberías 8 - 1 #=> 7 10 * 2 #=> 20 35 / 5 #=> 7 +2**5 #=> 32 +5 % 3 #=> 2 # La aritmética es sólo azúcar sintáctico # para llamar un método de un objeto @@ -55,8 +67,6 @@ false.class #=> FalseClass # Desigualdad 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true # Además de 'false', 'nil' es otro valor falso @@ -70,14 +80,29 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Operadores lógicos +true && false #=> false +true || false #=> true +!true #=> false + +# Existen versiones alternativas de los operadores lógicos con menor prioridad +# Estos son usados como constructores controladores de flujo que encadenan +# sentencias hasta que una de ellas retorne verdadero o falso + +# `has_otra_cosa` solo se llama si `has_algo` retorna verdadero. +has_algo() and has_otra_cosa() +# `registra_error` solo se llama si `has_algo` falla +has_algo() or registra_error() + + # Los strings son objetos 'Soy un string'.class #=> String "Soy un string también".class #=> String -referente = "usar interpolacion de strings" +referente = "usar interpolación de strings" "Yo puedo #{referente} usando strings de comillas dobles" -#=> "Yo puedo usar interpolacion de strings usando strings de comillas dobles" +#=> "Yo puedo usar interpolación de strings usando strings de comillas dobles" # Imprime a la salida estándar @@ -119,15 +144,16 @@ status == :aprovado #=> false # Arreglos # Esto es un arreglo -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +arreglo = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arreglos pueden contener elementos de distintos tipos -arreglo = [1, "hola", false] #=> => [1, "hola", false] +[1, "hola", false] #=> => [1, "hola", false] # Arreglos pueden ser indexados # Desde el frente arreglo[0] #=> 1 +arreglo.first #=> 1 arreglo[12] #=> nil # Tal como la aritmética, el acceso como variable[índice] @@ -138,15 +164,25 @@ arreglo.[] 12 #=> nil # Desde el final arreglo[-1] #=> 5 +arreglo.last #=> 5 + +# Con un índice de inicio y longitud +arreglo[2, 3] #=> [3, 4, 5] -# Con un índice de inicio y final -arreglo[2, 4] #=> [3, 4, 5] +# Invertir un arreglo +a = [1, 2, 3] +a.reverse! #=> [3, 2, 1] # O con rango arreglo[1..3] #=> [2, 3, 4] # Añade elementos a un arreglo así arreglo << 6 #=> [1, 2, 3, 4, 5, 6] +# O así +arreglo.push(6) #=> [1, 2, 3, 4, 5, 6] + +#Verifica si un elemento ya existe en ese arreglo +arreglo.include?(1) #=> true # Hashes son los diccionarios principales de Ruby con pares llave/valor. # Hashes se denotan con llaves: @@ -161,17 +197,16 @@ hash['numero'] #=> 5 # Preguntarle a un hash por una llave que no existe retorna 'nil': hash['nada aqui'] #=> nil -# Itera sobre un hash con el método 'each': -hash.each do |k, v| - puts "#{k} is #{v}" -end - # Desde Ruby 1.9, hay una sintaxis especial cuando se usa un símbolo como llave: nuevo_hash = { defcon: 3, accion: true} nuevo_hash.keys #=> [:defcon, :accion] +# Verifica la existencia de llaves y valores en el hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Tanto los arreglos como los hashes son Enumerable (enumerables) # Comparten muchos métodos útiles tales como 'each', 'map', 'count', y más @@ -194,9 +229,15 @@ end #=> iteracion 4 #=> iteracion 5 -# Aunque -# Nadie usa los ciclos `for` -# Usa `each`, así: +# SIN EMBARGO, nadie usa ciclos `for` +# En su lugar debes usar el método "each" y pasarle un block (bloque). +# Un bloque es un fragmento código que puedes pasar a métodos como `each`. +# Es símilar a las funciones lambda, funciones anónimas o `closures` en otros +# lenguajes de programación. +# +# El método `each` de un Range (rango) ejecuta el bloque una vez por cada elemento. +# Al bloque se le pasa un contador como parametro. +# Usar el método `each` con un bloque se ve así: (1..5).each do |contador| puts "iteracion #{contador}" @@ -207,10 +248,27 @@ end #=> iteracion 4 #=> iteracion 5 -counter = 1 -while counter <= 5 do - puts "iteracion #{counter}" - counter += 1 +# También puedes envolver el bloque entre llaves: +(1..5).each { |counter| puts "iteración #{contador}" } + +#El contenido de las estructuras de datos en ruby puede ser iterado usando `each`. +arreglo.each do |elemento| + puts "#{elemento} es parte del arreglo" +end +hash.each do |llave, valor| + puts "#{llave} es #{valor}" +end + +# Si aún necesitas un índice puedes usar "each_with_index" y definir una variable +# índice. +arreglo.each_with_index do |element, index| + puts "#{element} tiene la posición #{index} en el arreglo" +end + +contador = 1 +while contador <= 5 do + puts "iteracion #{contador}" + contador += 1 end #=> iteracion 1 #=> iteracion 2 @@ -218,6 +276,19 @@ end #=> iteracion 4 #=> iteracion 5 +# Hay una gran variedad de otras funciones iterativas útiles en Ruby, +# por ejemplo `map`, `reduce`, `inject`, entre otras. Map, por ejemplo, +# toma el arreglo sobre el cuál está iterando, le hace cambios +# definidos en el bloque, y retorna un arreglo completamente nuevo. +arreglo = [1,2,3,4,5] +duplicado = array.map do |elemento| + elemento * 2 +end +puts duplicado +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + nota = 'B' case nota @@ -234,6 +305,34 @@ when 'F' else puts "Sistema alternativo de notas, ¿eh?" end +#=> "Mejor suerte para la proxima" + +# Los casos también pueden usar rangos +nota = 82 + +case nota +when 90..100 + puts 'Excelente!' +when 80..100 + puts 'Buen trabajo' +else + puts '¡Reprobaste!' +end +#=> "Buen trabajo" + +# Manejo de excepciones +begin + # código que podría causar excepción + raise NoMemoryError, 'Se te acabó la memoria' +rescue NoMemoryError => variable_de_excepcion + puts 'El error NoMemoryError ocurrió', variable_de_excepcion +rescue RuntimeError => otra_variable_de_excepcion + puts 'El error RuntimeError ocurrió' +else + puts 'Esto se ejecuta si ningun error ocurrió' +ensure + puts 'Este código siempre se ejecuta, sin importar que' +end # Funciones @@ -244,7 +343,7 @@ end # Funciones (y todos los bloques) implícitamente retornan el valor de la última instrucción doble(2) #=> 4 -# Paréntesis son opcionales cuando el resultado es ambiguo +# Paréntesis son opcionales cuando el resultado no es ambiguo doble 3 #=> 6 doble doble 3 #=> 12 @@ -259,7 +358,7 @@ suma 3, 4 #=> 7 suma suma(3,4), 5 #=> 12 # yield -# Todos los métodos tienen un parámetro de bloqueo opcional e implícitp +# Todos los métodos tienen un parámetro bloque opcional e implícito # puede llamarse con la palabra clave 'yield' def alrededor @@ -274,6 +373,17 @@ alrededor { puts 'hola mundo' } # hola mundo # } +# Puedes pasar un bloque a una función +# '&' representa una referencia a un bloque +def visitantes(&bloque) + bloque.call +end + +# Puedes pasar una lista de argumentos, que serán convertidos en un arreglo +# Para eso sirve el operador ('*') +def visitantes(*arreglo) + arreglo.each { |visitante| puts visitante } +end # Define una clase con la palabra clave 'class' class Humano @@ -299,16 +409,26 @@ class Humano @nombre end + # La funcionalidad anterior puede ser encapsulada usando el método attr_accessor + # de la siguiente manera + + attr_accessor :name + + # Los métodos de tipo getter y setter también se pueden crear de manera individual + # de la siguiente manera + + attr_reader :name + attr_writer :name + # Un método de clase usa 'self' (sí mismo) para distinguirse de métodos de instancia. # Sólo puede ser llamado en la clase, no por una instancia. def self.decir(mensaje) - puts "#{mensaje}" + puts mensaje end def especie @@especie end - end @@ -328,6 +448,23 @@ dwight.nombre #=> "Dwight K. Schrute" # Llama el método de clase Humano.decir("Hi") #=> "Hi" +# El alcance de las variables es definido por la manera en que las nombramos. +# Las variables que inician con $ tienen un alcance global +$var = "Soy una variable global" +defined? $var #=> "global-variable" + +# Las variables que empiezan con @ tienen un alcance de instancia +@var = "Soy una variable de instancia" +defined? @var #=> "instance-variable" + +# Variables que empiezan con @@ tienen un alcance de clase +@@var = "Soy una variable de clase" +defined? @@var #=> "class variable" + +# Las variables que empiezan con letra mayuscula son constantes +Var = "Soy una constante" +defined? Var #=> "constant" + # Las clases también son un objeto en ruby. Por lo cual, las clases también pueden tener variables de instancia. # Variables de clase son compartidas a través de la clase y todos sus descendientes. @@ -371,7 +508,67 @@ end class Doctor < Humano end -Human.bar # 0 +Humano.bar # 0 Doctor.bar # nil +module ModuloEjemplo + def foo + 'foo' + end +end + +# Al incluir un módulo sus métodos se comparten con las instancias de la clase +# Al extender un módulo sus métodos se comparten con la clase misma + +class Persona + include ModuloEjemplo +end + +class Libro + extend ModuloEjemplo +end + +Persona.foo # => NoMethodError: undefined method `foo' for Persona:Class +Persona.new.foo # => 'foo' +Libro.foo # => 'foo' +Libro.new.foo # => NoMethodError: undefined method `foo' + +# Las llamadas de retorno (callbacks) son ejecutadas cuando se incluye o +# extiende un módulo +module EjemploConcern + def self.incluido(base) + base.extend(MetodosClase) + base.send(:include, MetodosInstancia) + end + + module MetodosClase + def bar + 'bar' + end + end + + module MetodosInstancia + def qux + 'qux' + end + end +end + +class Algo + include EjemploConcern +end + +Algo.bar #=> 'bar' +Algo.qux #=> NoMethodError: undefined method `qux' +Algo.new.bar # => NoMethodError: undefined method `bar' +Algo.new.qux # => 'qux' ``` + +## Recursos adicionales +- [Aprende Ruby Mediante Ejemplo con Ejercicios](http://www.learneroo.com/modules/61/nodes/338) - Una variante de +esta referencia con ejercicios en navegador. +- [Documentación Oficial](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby desde otros lenguajes](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programando Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - Una +[edición antigua](http://ruby-doc.com/docs/ProgrammingRuby/) gratuita disponible en línea. +- [Guía de estilo de Ruby](https://github.com/bbatsov/ruby-style-guide) - Guía de estilo creada por la comunidad. diff --git a/es-es/swift-es.html.markdown b/es-es/swift-es.html.markdown new file mode 100644 index 00000000..c04ab02b --- /dev/null +++ b/es-es/swift-es.html.markdown @@ -0,0 +1,596 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] +translators: + - ["David Hsieh", "http://github.com/deivuh"] +lang: es-es +filename: learnswift-es.swift +--- + +Swift es un lenguaje de programación para el desarrollo en iOS y OS X creado +por Apple. Diseñado para coexistir con Objective-C y ser más resistente contra +el código erroneo, Swift fue introducido en el 2014 en el WWDC, la conferencia +de desarrolladores de Apple. + +Véase también la guía oficial de Apple, [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), el cual tiene un completo tutorial de Swift. + + +```swift +// Importar un módulo +import UIKit + +// +// MARK: Básicos +// + +// XCode soporta referencias para anotar tu código y agregarlos a lista de la +// barra de saltos. +// MARK: Marca de sección +// TODO: Hacer algo pronto +// FIXME: Arreglar este código + +// En Swift 2, println y print fueron combinados en un solo método print. +// Print añade una nueva línea automáticamente. +print("Hola, mundo") // println ahora es print +print("Hola, mundo", appendNewLine: false) // print sin agregar nueva línea + +// Valores de variables (var) pueden cambiar después de ser asignados +// Valores de constrantes (let) no pueden cambiarse después de ser asignados + +var myVariable = 42 +let øπΩ = "value" // nombres de variable unicode +let π = 3.1415926 +let convenience = "keyword" // nombre de variable contextual +// Las declaraciones pueden ser separadas por punto y coma (;) +let weak = "keyword"; let override = "another keyword" +// Los acentos abiertos (``) permiten utilizar palabras clave como nombres de +// variable +let `class` = "keyword" +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Conversión (casting) +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolación de string + +// Valores específicos de la compilación (build) +// utiliza la configuración -D +#if false + print("No impreso") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Las opcionales son un aspecto del lenguaje Swift que permite el + almacenamiento de un valor `Some` (algo) o `None` (nada). + + Debido a que Swift requiere que cada propiedad tenga un valor, + hasta un valor 'nil' debe de ser explicitamente almacenado como un + valor opcional. + + Optional<T> es un enum. +*/ +var someOptionalString: String? = "opcional" // Puede ser nil +// Al igual que lo anterior, pero ? es un operador postfix (sufijo) +var someOptionalString2: Optional<String> = "opcional" + +if someOptionalString != nil { + // No soy nil + if someOptionalString!.hasPrefix("opt") { + print("Tiene el prefijo") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// Opcional implícitamente desenvuelto +var unwrappedString: String! = "Un valor esperado." +// Al igual que lo anterior, pero ! es un operador postfix (sufijo) +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Un valor esperado." + +if let someOptionalStringConstant = someOptionalString { + // tiene valor `Some` (algo), no nil + if !someOptionalStringConstant.hasPrefix("ok") { + // No tiene el prefijo + } +} + +// Swift tiene soporte de almacenamiento para cualquier tipo de valor. +// AnyObject == id +// A diferencia de Objective-C `id`, AnyObject funciona con cualquier +// valor (Class, Int, struct, etc) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Cambiado a un valor string, no es buena práctica, pero posible." + +/* + Comentar aquí + + /* + Comentarios anidados también son soportados + */ +*/ + +// +// MARK: Colecciones +// + +/* + Tipos Array (arreglo) y Dictionary (diccionario) son structs (estructuras). + Así que `let` y `var` también indican si son mudables (var) o + inmutables (let) durante la declaración de sus tipos. +*/ + +// Array (arreglo) +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = [String]() // let == inmutable +let emptyArray2 = Array<String>() // igual que lo anterior +var emptyMutableArray = [String]() // var == mudable + + +// Dictionary (diccionario) +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = [String: Float]() // let == inmutable +let emptyDictionary2 = Dictionary<String, Float>() // igual que lo anterior +var emptyMutableDictionary = [String: Float]() // var == mudable + + +// +// MARK: Flujo de control +// + +// Ciclo for (array) +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + print("Uno!") + } else { + print("No es uno!") + } +} + +// Ciclo for (dictionary) +var dict = ["uno": 1, "dos": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// Ciclo for (range) +for i in -1...shoppingList.count { + print(i) +} +shoppingList[1...2] = ["steak", "peacons"] +// Utilizar ..< para excluir el último valor + +// Ciclo while +var i = 1 +while i < 1000 { + i *= 2 +} + +// Ciclo do-while +do { + print("Hola") +} while 1 == 2 + +// Switch +// Muy potente, se puede pensar como declaraciones `if` con _azúcar sintáctico_ +// Soportan String, instancias de objetos, y primitivos (Int, Double, etc) +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // obligatorio (se debe cumplir con todos los posibles valores de entrada) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// MARK: Funciones +// + +// Funciones son un tipo de primera-clase, quiere decir que pueden ser anidados +// en funciones y pueden ser pasados como parámetros + +// Función en documentación de cabeceras Swift (formato reStructedText) + +/** + Una operación de saludo + + - Una viñeta en la documentación + - Otra viñeta en la documentación + + :param: name Un nombre + :param: day Un día + :returns: Un string que contiene el valor de name y day +*/ +func greet(name: String, day: String) -> String { + return "Hola \(name), hoy es \(day)." +} +greet("Bob", "Martes") + +// Similar a lo anterior, a excepción del compartamiento de los parámetros +// de la función +func greet2(requiredName: String, externalParamName localParamName: String) -> String { + return "Hola \(requiredName), hoy es el día \(localParamName)" +} +greet2(requiredName:"John", externalParamName: "Domingo") + +// Función que devuelve múltiples valores en una tupla +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Ignorar tupla (u otros) valores utilizando _ (guión bajo) +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// Cantidad variable de argumentos +func setup(numbers: Int...) { + // Es un arreglo + let number = numbers[0] + let argCount = numbers.count +} + +// Pasando y devolviendo funciones +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// Pasando como referencia +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closures (Clausuras) +// +var numbers = [1, 2, 6] + +// Las funciones son un caso especial de closure ({}) + +// Ejemplo de closure. +// `->` Separa los argumentos del tipo de retorno +// `in` Separa la cabecera del cuerpo del closure +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Cuando se conoce el tipo, como en lo anterior, se puede hacer esto +numbers = numbers.map({ number in 3 * number }) +// o esto +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Closure restante +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Bastante corto, debido a que el operador < infiere los tipos + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Estructuras +// + +// Las estructuras y las clases tienen capacidades similares +struct NamesTable { + let names = [String]() + + // Subscript personalizado + subscript(index: Int) -> String { + return names[index] + } +} + +// Las estructuras tienen un inicializador designado autogenerado (implícitamente) +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: Clases +// + +// Las clases, las estructuras y sus miembros tienen tres niveles de control de acceso +// Éstos son: internal (predeterminado), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Todos los métodos y las propiedades de una clase son public (públicas) +// Si solo necesitas almacenar datos en un objecto estructurado, +// debes de utilizar `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Getter y setter personalizado + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` es una variable implícita disponible para los setters + sideLength = newValue / 4 + } + } + + // Lazily loading (inicialización bajo demanda) a una propiedad + // subShape queda como nil (sin inicializar) hasta que getter es llamado + lazy var subShape = Rect(sideLength: 4) + + // Si no necesitas un getter y setter personalizado + // pero aún quieres ejecutar código antes y después de hacer get o set + // a una propiedad, puedes utilizar `willSet` y `didSet` + var identifier: String = "defaultID" { + // El argumento `willSet` será el nombre de variable para el nuevo valor + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // Siempre poner super.init de último al momento de inicializar propiedades + // personalizadas + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// Una clase simple `Square` que extiende de `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// Conversión de tipo de instancia +let aShape = mySquare as Shape + +// Comparar instancias, no es igual a == que compara objetos (equal to) +if mySquare === mySquare { + print("Yep, it's mySquare") +} + +// Inicialización (init) opcional +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Un signo de interrogación como sufijo después de `init` es un init opcional + // que puede devolver nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // no será ejecutado debido a que myEmptyCircle es nil + print("circle is not nil") +} + + +// +// MARK: Enums +// + + +// Los enums pueden ser opcionalmente de un tipo específico o de su propio tipo +// Al igual que las clases, pueden contener métodos + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Los valores de enum permite la sintaxis corta, sin necesidad de poner +// el tipo del enum cuando la variable es declarada de manera explícita +var suitValue: Suit = .Hearts + +// Enums de tipo no-entero requiere asignaciones de valores crudas directas +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// Enum con valores asociados +enum Furniture { + // Asociación con Int + case Desk(height: Int) + // Asociación con String e Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" + + +// +// MARK: Protocolos +// + +// `protocol` puede requerir que los tipos tengan propiedades +// de instancia específicas, métodos de instancia, métodos de tipo, +// operadores, y subscripts + + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Protocolos declarados con @objc permiten funciones opcionales, +// que te permite evaluar conformidad +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // Pon un signo de interrogación después de la propiedad opcional, + // método, o subscript para ignorar un valor nil y devolver nil + // en lugar de tirar un error de tiempo de ejecución + // ("optional chaining") + if let allow = self.delegate?.canReshape?() { + // test for delegate then for method + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Otros +// + +// `extension`: Agrega funcionalidades a tipos existentes + +// Square ahora se "conforma" al protocolo `Printable` +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") + +// También puedes hacer extend a tipos prefabricados (built-in) +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// Generics: Similar Java y C#. Utiliza la palabra clave `where` para +// especificar los requerimientos de los genéricos. + +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// Operadores: +// Operadores personalizados puede empezar con los siguientes caracteres: +// / = - + * % < > ! & | ^ . ~ +// o +// Caracteres unicode: math, symbol, arrow, dingbat, y line/box. +prefix operator !!! {} + +// Un operador prefix que triplica la longitud del lado cuando es utilizado +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// Valor actual +print(mySquare.sideLength) // 4 + +// Cambiar la longitud del lado utilizando el operador !!!, +// incrementa el tamaño por 3 +!!!mySquare +print(mySquare.sideLength) // 12 +``` diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown new file mode 100644 index 00000000..a7354be1 --- /dev/null +++ b/es-es/tmux-es.html.markdown @@ -0,0 +1,253 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +filename: LearnTmux-es.txt +translators: + - ["Damaso Sanoja", "https://github.com/damasosanoja"] +lang: es-es +--- + + +[tmux](http://tmux.sourceforge.net) +es un terminal multiplexor: habilita la creación, acceso y control +de múltiples terminales controlados desde una sola pantalla. tmux +puede ser separado de una pantalla y continuar corriendo en el fondo +y luego ser insertado nuevamente. + + +``` + + tmux [command] # Corre un comando + # 'tmux' sin comandos creará una nueva sesión + + new # Crea una nueva sesión + -s "Session" # Crea sesión con nombre + -n "Window" # Crea ventana con nombre + -c "/dir" # Comienza en el directorio destino + + attach # Adjunta sesión última/disponible + -t "#" # Adjunta sesión destino + -d # Separa la sesión de otras instancias + + ls # Lista las sesiones abiertas + -a # Lista todas las sesiones abiertas + + lsw # Lista las ventanas + -a # Lista todas las ventanas + -s # Lista todas las ventanas en la sesión + + lsp # Lista los páneles + -a # Lista todos los páneles + -s # Lista todos los páneles de la sesión + -t # Lista los páneles de aplicación en el destino + + kill-window # Cierra la ventana actual + -t "#" # Cierra la ventana destino + -a # Cierra todas las ventanas + -a -t "#" # Cierra todas las ventanas menos el destino + + kill-session # Cierra la sesión actual + -t "#" # Cierra la sesión destino + -a # Cierra todas las sesiones + -a -t "#" # Cierra todas las sesiones menos el destino + +``` + + +### Atajos de Teclado + +El método para controlar una sesión adjunta tmux es mediante +combinaciones de teclas llamadas teclas 'Prefijo'. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # combinación 'Prefijo' necesaria para usar atajos + + (M-1) = Meta + 1 -o- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos los atajos de teclado + : # Entra en la línea de comandos tmux + r # Fuerza el redibujado del cliente adjuntado + c # Crea una nueva ventana + + ! # Separa el panel actual fuera de la ventana. + % # Separa el panel actual en dos, izquierdo y derecho + " # Separa el panel actual en dos, superior e inferior + + n # Cambia a la siguiente ventana + p # Cambia a la ventana previa + { # Intercambia el panel actual con el anterior + } # Intercambia el panel actual con el próximo + + s # Selecciona una nueva sesión para el cliente adjuntado + interactivamente + w # Elegir la ventana actual interactivamente + 0 al 9 # Seleccionar ventanas 0 al 9 + + d # Separa el cliente actual + D # Elige un cliente para separar + + & # Cierra la ventana actual + x # Cierra el panel actual + + Up, Down # Cambia al panel superior, inferior, izquierdo, o derecho + Left, Right + + M-1 to M-5 # Organizar páneles: + # 1) uniformes horizontales + # 2) uniformes verticales + # 3) principal horizontal + # 4) principal vertical + # 5) mozaico + + C-Up, C-Down # Redimensiona el panel actual en pasos de una celda + C-Left, C-Right + + M-Up, M-Down # Redimensiona el panel actual en pasos de cinco celdas + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. + +``` +# Ejemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Fuera de pantalla/Historia límite +set -g history-limit 2048 + +# Comienzo de índice +set -g base-index 1 + +# Ratón +set-option -g mouse-select-pane on + +# Forza recarga de fichero de configuración +unbind r +bind r source-file ~/.tmux.conf + + +### Atajos de teclado +########################################################################### + +# Desvincula C-b como el prefijo por defecto +unbind C-b + +# Establece el nuevo prefijo +set-option -g prefix ` + +# Regresa a la ventana previa cuando el prefijo es accionado dos veces +bind C-a last-window +bind ` last-window + +# Permite intercambiar C-a y ` usando F11/F12 +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencias de atajos +setw -g mode-keys vi +set-option -g status-keys vi + +# Moviéndose entre paneles con movimientos de teclas vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Ciclo/Intercambio de Ventana +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# División rápida de paneles +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Activar sesión mas interna (cuando se anida tmux) para enviar comandos +bind a send-prefix + + +### Temas +########################################################################### + +# Paleta de Colores de la Barra de estado +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de Colores del Borde del Panel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Paleta de Colores de Mensajes +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de Colores de la Ventana +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificación +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Establece automáticamente títulos de ventanas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes de barra de estado +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Muestra indicadores de rendimiento en barra de estado +# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referencias + +[Tmux | Inicio](http://tmux.sourceforge.net) + +[Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown new file mode 100644 index 00000000..c7f581c0 --- /dev/null +++ b/es-es/visualbasic-es.html.markdown @@ -0,0 +1,286 @@ +--- +language: Visual Basic +contributors: + - ["Brian Martin", "http://brianmartin.biz"] +translators: + - ["Adolfo Jayme Barrientos", "https://github.com/fitojb"] +author: Brian Martin +author_url: https://github.com/fitojb +filename: learnvisualbasic-es.vb +lang: es-es +--- + +```vb +Module Module1 + + Sub Main() + ' Un vistazo rápido a las aplicaciones de consola de Visual Basic antes + ' de que profundicemos en el tema. + ' El apóstrofo inicia una línea de comentario. + ' Para explorar este tutorial dentro del Compilador de Visual Basic, + ' he creado un sistema de navegación. + ' Dicho sistema se explicará a medida que avancemos en este + ' tutorial; gradualmente entenderás lo que significa todo. + Console.Title = ("Aprende X en Y minutos") + Console.WriteLine("NAVEGACIÓN") 'Mostrar + Console.WriteLine("") + Console.ForegroundColor = ConsoleColor.Green + Console.WriteLine("1. Salida «Hola, mundo»") + Console.WriteLine("2. Entrada «Hola, mundo»") + Console.WriteLine("3. Calcular números enteros") + Console.WriteLine("4. Calcular números decimales") + Console.WriteLine("5. Una calculadora funcional") + Console.WriteLine("6. Uso de bucles «Do While»") + Console.WriteLine("7. Uso de bucles «For While»") + Console.WriteLine("8. Declaraciones condicionales") + Console.WriteLine("9. Selecciona una bebida") + Console.WriteLine("50. Acerca de") + Console.WriteLine("Elige un número de la lista anterior") + Dim selection As String = Console.ReadLine + Select Case selection + Case "1" 'Salida «hola, mundo» + Console.Clear() 'Limpia la consola y abre la subrutina privada + SalidaHolaMundo() 'Abre la subrutina privada nombrada + Case "2" 'Entrada «hola, mundo» + Console.Clear() + EntradaHolaMundo() + Case "3" 'Calcular números enteros + Console.Clear() + CalcularNumerosEnteros() + Case "4" 'Calcular números decimales + Console.Clear() + CalcularNumerosDecimales() + Case "5" 'Una calculadora funcional + Console.Clear() + CalculadoraFuncional() + Case "6" 'Uso de bucles «Do While» + Console.Clear() + UsoBuclesDoWhile() + Case "7" 'Uso de bucles «For While» + Console.Clear() + UsoBuclesFor() + Case "8" 'Declaraciones condicionales + Console.Clear() + DeclaracionCondicional() + Case "9" 'Declaración «If/Else» + Console.Clear() + DeclaracionIfElse() 'Selecciona una bebida + Case "50" 'Cuadro de mensaje «Acerca de» + Console.Clear() + Console.Title = ("Aprende X en Y minutos :: Acerca de") + MsgBox("Tutorial escrito por Brian Martin (@BrianMartinn") + Console.Clear() + Main() + Console.ReadLine() + + End Select + End Sub + + 'Uno - He usado números para guiarme por el sistema de navegación anterior + 'cuando regrese posteriormente a implementarlo. + + 'Usamos subrutinas privadas para separar distintas secciones del programa. + Private Sub SalidaHolaMundo() + 'Título de la aplicación de consola + Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos" + 'Usa Console.Write("") o Console.WriteLine("") para mostrar salidas. + 'Seguido por Console.Read(), o bien, Console.Readline() + 'Console.ReadLine() muestra la salida en la consola. + Console.WriteLine("Hola, mundo") + Console.ReadLine() + End Sub + + 'Dos + Private Sub EntradaHolaMundo() + Console.Title = "«Hola, mundo, soy...» | Aprende X en Y minutos" + ' Variables + ' Los datos que introduzca un usuario deben almacenarse. + ' Las variables también empiezan por Dim y terminan por As VariableType. + + ' En este tutorial queremos conocer tu nombre y hacer que el programa + ' responda a este. + Dim nombredeusuario As String + 'Usamos «string» porque es una variable basada en texto. + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeusuario = Console.ReadLine() 'Almacenar nombre del usuario. + Console.WriteLine("Hola, " + nombredeusuario) 'La salida es Hola, nombre + Console.ReadLine() 'Muestra lo anterior. + 'El código anterior te hará una pregunta y mostrará la respuesta. + 'Entre otras variables está Integer, la cual usaremos para números enteros. + End Sub + + 'Tres + Private Sub CalcularNumerosEnteros() + Console.Title = "Calcular números enteros | Aprende X en Y minutos" + Console.Write("Primer número: ") 'Escribe un núm. entero, 1, 2, 104, etc + Dim a As Integer = Console.ReadLine() + Console.Write("Segundo número: ") 'Escribe otro número entero. + Dim b As Integer = Console.ReadLine() + Dim c As Integer = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Lo anterior es una calculadora sencilla + End Sub + + 'Cuatro + Private Sub CalcularNumerosDecimales() + Console.Title = "Calcular con tipo doble | Aprende X en Y minutos" + 'Por supuesto, nos gustaría sumar decimales. + 'Por ello podríamos cambiar del tipo Integer al Double. + + 'Escribe un número fraccionario, 1.2, 2.4, 50.1, 104.9 etc + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") 'Escribe el segundo número. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Console.WriteLine(c) + Console.ReadLine() + 'Este programa puede sumar 1.1 y 2.2 + End Sub + + 'Cinco + Private Sub CalculadoraFuncional() + Console.Title = "La calculadora funcional | Aprende X en Y minutos" + 'Pero si quieres que la calculadora reste, divida, multiplique y + 'sume. + 'Copia y pega lo anterior. + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + 'Mediante las líneas siguientes podremos restar, + 'multiplicar y dividir los valores a y b + Console.Write(a.ToString() + " + " + b.ToString()) + 'Queremos dar un margen izquierdo de 3 espacios a los resultados. + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + + End Sub + + 'Seis + Private Sub UsoBuclesDoWhile() + 'Igual que la subrutina privada anterior + 'Esta vez preguntaremos al usuario si quiere continuar (¿sí o no?) + 'Usamos el bucle Do While porque no sabemos si el usuario quiere + 'usar el programa más de una vez. + Console.Title = "Uso de bucles «Do While» | Aprende X en Y minutos" + Dim respuesta As String 'Usamos la variable «String» porque la resp. es texto + Do 'Comenzamos el programa con + Console.Write("Primer número: ") + Dim a As Double = Console.ReadLine + Console.Write("Segundo número: ") + Dim b As Integer = Console.ReadLine + Dim c As Integer = a + b + Dim d As Integer = a * b + Dim e As Integer = a - b + Dim f As Integer = a / b + + Console.Write(a.ToString() + " + " + b.ToString()) + Console.WriteLine(" = " + c.ToString.PadLeft(3)) + Console.Write(a.ToString() + " * " + b.ToString()) + Console.WriteLine(" = " + d.ToString.PadLeft(3)) + Console.Write(a.ToString() + " - " + b.ToString()) + Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.Write(a.ToString() + " / " + b.ToString()) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) + Console.ReadLine() + 'Preguntar si el usuario quiere continuar. Desafortunadamente, + 'distingue entre mayúsculas y minúsculas. + Console.Write("¿Quieres continuar? (s / n)") + 'El programa toma la variable, la muestra y comienza de nuevo. + respuesta = Console.ReadLine + 'La orden que hará funcionar esta variable es en este caso «s» + Loop While respuesta = "s" + + End Sub + + 'Siete + Private Sub UsoBuclesFor() + 'A veces el programa debe ejecutarse solo una vez. + 'En este programa contaremos a partir de 10. + + Console.Title = "Uso de bucles «For» | Aprende X en Y minutos" + 'Declarar Variable y desde qué número debe contar en Step -1, + 'Step -2, Step -3, etc. + For i As Integer = 10 To 0 Step -1 + Console.WriteLine(i.ToString) 'Muestra el valor del contador + Next i 'Calcular el valor nuevo + Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!! + Console.ReadLine() '¡¡ZAS!! - Quizá me he emocionado bastante :) + End Sub + + 'Ocho + Private Sub DeclaracionCondicional() + Console.Title = "Declaraciones condicionales | Aprende X en Y minutos" + Dim nombredeUsuario As String = Console.ReadLine + Console.WriteLine("Hola, ¿cómo te llamas? ") 'Preguntar nombre de usuario. + nombredeUsuario = Console.ReadLine() 'Almacena el nombre de usuario. + If nombredeUsuario = "Adam" Then + Console.WriteLine("Hola, Adam") + Console.WriteLine("Gracias por crear este útil sitio web") + Console.ReadLine() + Else + Console.WriteLine("Hola, " + nombredeUsuario) + Console.WriteLine("¿Has visitado www.learnxinyminutes.com?") + Console.ReadLine() 'Termina y muestra la declaración anterior. + End If + End Sub + + 'Nueve + Private Sub DeclaracionIfElse() + Console.Title = "Declaración «If / Else» | Aprende X en Y minutos" + 'A veces es importante considerar más de dos alternativas. + 'A veces, algunas de estas son mejores. + 'Cuando esto sucede, necesitaríamos más de una declaración «if». + 'Una declaración «if» es adecuada para máquinas expendedoras. + 'En las que el usuario escribe un código (A1, A2, A3) para elegir. + 'Pueden combinarse todas las elecciones en una sola declaración «if». + + Dim seleccion As String = Console.ReadLine 'Valor de la selección + Console.WriteLine("A1. para 7Up") + Console.WriteLine("A2. para Fanta") + Console.WriteLine("A3. para Dr. Pepper") + Console.WriteLine("A4. para Coca-Cola") + Console.ReadLine() + If selection = "A1" Then + Console.WriteLine("7up") + Console.ReadLine() + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + Console.ReadLine() + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + Console.ReadLine() + ElseIf selection = "A4" Then + Console.WriteLine("coca-cola") + Console.ReadLine() + Else + Console.WriteLine("Selecciona un producto") + Console.ReadLine() + End If + + End Sub + +End Module + +``` + +## Referencias + +Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad. + +He creado un <a href="http://www.vbbootcamp.co.uk/" Title="Tutorial de Visual Basic">tutorial de Visual Basic</a> más exhaustivo para quienes quieran saber más. + +Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa. diff --git a/fa-ir/brainfuck.html.markdown b/fa-ir/brainfuck-fa.html.markdown index ef2bcba3..ef2bcba3 100644 --- a/fa-ir/brainfuck.html.markdown +++ b/fa-ir/brainfuck-fa.html.markdown diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript-fa.html.markdown index 5c64d24a..fe3555af 100644 --- a/fa-ir/javascript.html.markdown +++ b/fa-ir/javascript-fa.html.markdown @@ -499,9 +499,6 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } -if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. -} ``` diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown new file mode 100644 index 00000000..9ed4e0d2 --- /dev/null +++ b/fi-fi/go-fi.html.markdown @@ -0,0 +1,441 @@ +--- +name: Go +category: language +language: Go +filename: learngo-fi.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] +translators: + - ["Timo Virkkunen", "https://github.com/ComSecNinja"] +lang: fi-fi +--- + +Go luotiin työn tekemistä varten. Se ei ole tietojenkäsittelyn uusin trendi, +mutta se on uusin nopein tapa ratkaista oikean maailman ongelmia. + +Sillä on staattisesti tyypitetyistä imperatiivisista kielistä tuttuja +konsepteja. Se kääntyy ja suorittuu nopeasti, lisää helposti käsitettävän +samanaikaisten komentojen suorittamisen nykyaikaisten moniytimisten +prosessoreiden hyödyntämiseksi ja antaa käyttäjälle ominaisuuksia suurten +projektien käsittelemiseksi. + +Go tuo mukanaan loistavan oletuskirjaston sekä innokkaan yhteisön. + +```go +// Yhden rivin kommentti +/* Useamman + rivin kommentti */ + +// Package -lausekkeella aloitetaan jokainen lähdekooditiedosto. +// Main on erityinen nimi joka ilmoittaa +// suoritettavan tiedoston kirjaston sijasta. +package main + +// Import -lauseke ilmoittaa tässä tiedostossa käytetyt kirjastot. +import ( + "fmt" // Paketti Go:n oletuskirjastosta. + "io/ioutil" // Implementoi hyödyllisiä I/O -funktioita. + m "math" // Matematiikkakirjasto jolla on paikallinen nimi m. + "net/http" // Kyllä, web-palvelin! + "strconv" // Kirjainjonojen muuntajia. +) + +// Funktion määrittelijä. Main on erityinen: se on ohjelman suorittamisen +// aloittamisen alkupiste. Rakasta tai vihaa sitä, Go käyttää aaltosulkeita. +func main() { + // Println tulostaa rivin stdoutiin. + // Se tulee paketin fmt mukana, joten paketin nimi on mainittava. + fmt.Println("Hei maailma!") + + // Kutsu toista funktiota tämän paketin sisällä. + beyondHello() +} + +// Funktioilla voi olla parametrejä sulkeissa. +// Vaikkei parametrejä olisikaan, sulkeet ovat silti pakolliset. +func beyondHello() { + var x int // Muuttujan ilmoittaminen: ne täytyy ilmoittaa ennen käyttöä. + x = 3 // Arvon antaminen muuttujalle. + // "Lyhyet" ilmoitukset käyttävät := joka päättelee tyypin, ilmoittaa + // sekä antaa arvon muuttujalle. + y := 4 + sum, prod := learnMultiple(x, y) // Funktio palauttaa kaksi arvoa. + fmt.Println("summa:", sum, "tulo:", prod) // Yksinkertainen tuloste. + learnTypes() // < y minuuttia, opi lisää! +} + +/* <- usean rivin kommentti +Funktioilla voi olla parametrejä ja (useita!) palautusarvoja. +Tässä `x`, `y` ovat argumenttejä ja `sum`, `prod` ovat ne, mitä palautetaan. +Huomaa että `x` ja `sum` saavat tyyin `int`. +*/ +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Palauta kaksi arvoa. +} + +// Sisäänrakennettuja tyyppejä ja todellisarvoja. +func learnTypes() { + // Lyhyt ilmoitus antaa yleensä haluamasi. + str := "Opi Go!" // merkkijonotyyppi. + + s2 := `"raaka" todellisarvoinen merrkijono +voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi. + + // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8. + g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen. + + f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku. + c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla. + + // var -syntaksi alkuarvoilla. + var u uint = 7 // Etumerkitön, toteutus riippuvainen koosta kuten int. + var pi float32 = 22. / 7 + + // Muuntosyntaksi lyhyellä ilmoituksella. + n := byte('\n') // byte on leminimi uint8:lle. + + // Listoilla on kiinteä koko kääntöhetkellä. + var a4 [4]int // 4 int:in lista, alkiot ovat alustettu nolliksi. + a3 := [...]int{3, 1, 5} // Listan alustaja jonka kiinteäksi kooksi tulee 3 + // alkiota, jotka saavat arvot 3, 1, ja 5. + + // Siivuilla on muuttuva koko. Sekä listoilla että siivuilla on puolensa, + // mutta siivut ovat yleisempiä käyttötapojensa vuoksi. + s3 := []int{4, 5, 9} // Vertaa a3: ei sananheittoa (...). + s4 := make([]int, 4) // Varaa 4 int:n siivun, alkiot alustettu nolliksi. + var d2 [][]float64 // Vain ilmoitus, muistia ei varata. + bs := []byte("a slice") // Tyypinmuuntosyntaksi. + + // Koska siivut ovat dynaamisia, niitä voidaan yhdistellä sellaisinaan. + // Lisätäksesi alkioita siivuun, käytä sisäänrakennettua append()-funktiota. + // Ensimmäinen argumentti on siivu, johon alkoita lisätään. + s := []int{1, 2, 3} // Tuloksena on kolmen alkion pituinen lista. + s = append(s, 4, 5, 6) // Lisätty kolme alkiota. Siivun pituudeksi tulee 6. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6] + + // Lisätäksesi siivun toiseen voit antaa append-funktiolle referenssin + // siivuun tai todellisarvoiseen siivuun lisäämällä sanaheiton argumentin + // perään. Tämä tapa purkaa siivun alkiot ja lisää ne siivuun s. + s = append(s, []int{7, 8, 9}...) // 2. argumentti on todellisarvoinen siivu. + fmt.Println(s) // Päivitetty siivu on nyt [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Ilmoittaa p ja q olevan tyyppiä osoittaja int:iin. + fmt.Println(*p, *q) // * seuraa osoittajaa. Tämä tulostaa kaksi int:ä. + + // Kartat ovat dynaamisesti kasvavia assosiatiivisia listoja, kuten hash tai + // dictionary toisissa kielissä. + m := map[string]int{"three": 3, "four": 4} + m["one"] = 1 + + // Käyttämättömät muuttujat ovat virheitä Go:ssa. + // Alaviiva antaa sinun "käyttää" muuttujan mutta hylätä sen arvon. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + // Tulostaminen tietysti lasketaan muuttujan käyttämiseksi. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // Takaisin flowiin. +} + +// Go:ssa on useista muista kielistä poiketen mahdollista käyttää nimettyjä +// palautusarvoja. +// Nimen antaminen palautettavan arvon tyypille funktion ilmoitusrivillä +// mahdollistaa helpon palaamisen useasta eri funktion suorituskohdasta sekä +// pelkän return-lausekkeen käytön ilman muita mainintoja. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z on epäsuorasti tässä, koska nimesimme sen aiemmin. +} + +// Go kerää kaikki roskansa. Siinä on osoittajia mutta ei niiden laskentoa. +// Voit tehdä virheen mitättömällä osoittajalla, mutta et +// kasvattamalla osoittajaa. +func learnMemory() (p, q *int) { + // Nimetyillä palautusarvoilla p ja q on tyyppi osoittaja int:iin. + p = new(int) // Sisäänrakennettu funktio new varaa muistia. + // Varattu int on alustettu nollaksi, p ei ole enää mitätön. + s := make([]int, 20) // Varaa 20 int:ä yhteen kohtaan muistissa. + s[3] = 7 // Anna yhdelle niistä arvo. + r := -2 // Ilmoita toinen paikallinen muuttuja. + return &s[3], &r // & ottaa asian osoitteen muistissa. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // If -lausekkeet vaativat aaltosulkeet mutta ei tavallisia sulkeita. + if true { + fmt.Println("mitä mä sanoin") + } + // Muotoilu on standardoitu käyttämällä komentorivin komentoa "go fmt". + if false { + // Nyrpistys. + } else { + // Nautinto. + } + // Käytä switch -lauseketta ketjutettujen if -lausekkeiden sijasta. + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Tapaukset eivät "tipu läpi". + /* + Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso: + https://github.com/golang/go/wiki/Switch#fall-through + */ + case 43: + // Saavuttamaton. + default: + // Oletustapaus (default) on valinnainen. + } + // Kuten if, for -lauseke ei myöskään käytä tavallisia sulkeita. + // for- ja if- lausekkeissa ilmoitetut muuttujat ovat paikallisia niiden + // piireissä. + for x := 0; x < 3; x++ { // ++ on lauseke. Sama kuin "x = x + 1". + fmt.Println("iteraatio", x) + } + // x == 42 tässä. + + // For on kielen ainoa silmukkalauseke mutta sillä on vaihtoehtosia muotoja. + for { // Päättymätön silmukka. + break // Kunhan vitsailin. + continue // Saavuttamaton. + } + + // Voit käyttää range -lauseketta iteroidaksesi listojen, siivujen, merkki- + // jonojen, karttojen tai kanavien läpi. range palauttaa yhden (kanava) tai + // kaksi arvoa (lista, siivu, merkkijono ja kartta). + for key, value := range map[string]int{"yksi": 1, "kaksi": 2, "kolme": 3} { + // jokaista kartan paria kohden, tulosta avain ja arvo + fmt.Printf("avain=%s, arvo=%d\n", key, value) + } + + // Kuten for -lausekkeessa := if -lausekkeessa tarkoittaa ilmoittamista ja + // arvon asettamista. + // Aseta ensin y, sitten testaa onko y > x. + if y := expensiveComputation(); y > x { + x = y + } + // Todellisarvoiset funktiot ovat sulkeumia. + xBig := func() bool { + return x > 10000 // Viittaa ylempänä ilmoitettuun x:ään. + } + fmt.Println("xBig:", xBig()) // tosi (viimeisin arvo on e^10). + x = 1.3e3 // Tämä tekee x == 1300 + fmt.Println("xBig:", xBig()) // epätosi nyt. + + // Lisäksi todellisarvoiset funktiot voidaan samalla sekä ilmoittaa että + // kutsua, jolloin niitä voidaan käyttää funtioiden argumentteina kunhan: + // a) todellisarvoinen funktio kutsutaan välittömästi (), + // b) palautettu tyyppi vastaa odotettua argumentin tyyppiä. + fmt.Println("Lisää ja tuplaa kaksi numeroa: ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Kutsuttu argumenteilla 10 ja 2 + // => Lisää ja tuplaa kaksi numeroa: 24 + + // Kun tarvitset sitä, rakastat sitä. + goto love +love: + + learnFunctionFactory() // Funktioita palauttavat funktiot + learnDefer() // Nopea kiertoreitti tärkeään avainsanaan. + learnInterfaces() // Hyvää kamaa tulossa! +} + +func learnFunctionFactory() { + // Seuraavat kaksi ovat vastaavia, mutta toinen on käytännöllisempi + fmt.Println(sentenceFactory("kesä")("Kaunis", "päivä!")) + + d := sentenceFactory("kesä") + fmt.Println(d("Kaunis", "päivä!")) + fmt.Println(d("Laiska", "iltapäivä!")) +} + +// Somisteet ovat yleisiä toisissa kielissä. Sama saavutetaan Go:ssa käyttämällä +// todellisarvoisia funktioita jotka ottavat vastaan argumentteja. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // uusi jono + } +} + +func learnDefer() (ok bool) { + // Lykätyt lausekkeet suoritetaan juuri ennen funktiosta palaamista. + defer fmt.Println("lykätyt lausekkeet suorittuvat") + defer fmt.Println("käänteisessä järjestyksessä (LIFO).") + defer fmt.Println("\nTämä rivi tulostuu ensin, koska") + // Defer -lauseketta käytetään yleisesti tiedoston sulkemiseksi, jotta + // tiedoston sulkeva funktio pysyy lähellä sen avannutta funktiota. + return true +} + +// Määrittele Stringer rajapintatyypiksi jolla on +// yksi jäsenfunktio eli metodi, String. +type Stringer interface { + String() string +} + +// Määrittele pair rakenteeksi jossa on kaksi kenttää, x ja y tyyppiä int. +type pair struct { + x, y int +} + +// Määrittele jäsenfunktio pair:lle. Pair tyydyttää nyt Stringer -rajapinnan. +func (p pair) String() string { // p:tä kutsutaan nimellä "receiver" + // Sprintf on toinen julkinen funktio paketissa fmt. + // Pistesyntaksilla viitataan P:n kenttiin. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // Aaltosuljesyntaksi on "todellisarvoinen rakenne". Se todentuu alustetuksi + // rakenteeksi. := -syntaksi ilmoittaa ja alustaa p:n täksi rakenteeksi. + p := pair{3, 4} + fmt.Println(p.String()) // Kutsu p:n (tyyppiä pair) jäsenfunktiota String. + var i Stringer // Ilmoita i Stringer-rajapintatyypiksi. + i = p // Pätevä koska pair tyydyttää rajapinnan Stringer. + // Kutsu i:n (Stringer) jäsenfunktiota String. Tuloste on sama kuin yllä. + fmt.Println(i.String()) + + // Funktiot fmt-paketissa kutsuvat argumenttien String-jäsenfunktiota + // selvittääkseen onko niistä saatavilla tulostettavaa vastinetta. + fmt.Println(p) // Tuloste on sama kuin yllä. Println kutsuu String-metodia. + fmt.Println(i) // Tuloste on sama kuin yllä. + + learnVariadicParams("loistavaa", "oppimista", "täällä!") +} + +// Funktioilla voi olla muuttuva eli variteettinen +// määrä argumentteja eli parametrejä. +func learnVariadicParams(myStrings ...interface{}) { + // Iteroi jokaisen argumentin läpi. + // Tässä alaviivalla sivuutetaan argumenttilistan kunkin kohdan indeksi. + for _, param := range myStrings { + fmt.Println("param:", param) + } + + // Luovuta variteettinen arvo variteettisena parametrinä. + fmt.Println("params:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // "; ok" -muotoa käytetään selvittääksemme toimiko jokin vai ei. + m := map[int]string{3: "kolme", 4: "neljä"} + if x, ok := m[1]; !ok { // ok on epätosi koska 1 ei ole kartassa. + fmt.Println("ei ketään täällä") + } else { + fmt.Print(x) // x olisi arvo jos se olisi kartassa. + } + // Virhearvo voi kertoa muutakin ongelmasta. + if _, err := strconv.Atoi("ei-luku"); err != nil { // _ sivuuttaa arvon + // tulostaa strconv.ParseInt: parsing "ei-luku": invalid syntax + fmt.Println(err) + } + // Palaamme rajapintoihin hieman myöhemmin. Sillä välin, + learnConcurrency() +} + +// c on kanava, samanaikaisturvallinen viestintäolio. +func inc(i int, c chan int) { + c <- i + 1 // <- on "lähetysoperaattori" kun kanava on siitä vasemmalla. +} + +// Käytämme inc -funktiota samanaikaiseen lukujen lisäämiseen. +func learnConcurrency() { + // Sama make -funktio jota käytimme aikaisemmin siivun luomiseksi. Make + // varaa muistin ja alustaa siivut, kartat ja kanavat. + c := make(chan int) + // Aloita kolme samanaikaista gorutiinia (goroutine). Luvut kasvavat + // samanaikaisesti ja ehkäpä rinnakkain jos laite on kykenevä ja oikein + // määritelty. Kaikki kolme lähettävät samalle kanavalle. + go inc(0, c) // go -lauseke aloittaa uuden gorutiinin. + go inc(10, c) + go inc(-805, c) + // Lue kolme palautusarvoa kanavalta ja tulosta ne. + // Niiden saapumisjärjestystä ei voida taata! + // <- on "vastaanotto-operaattori" jos kanava on oikealla + fmt.Println(<-c, <-c, <-c) + + cs := make(chan string) // Toinen kanava joka käsittelee merkkijonoja. + ccs := make(chan chan string) // Kanava joka käsittelee merkkijonokanavia. + go func() { c <- 84 }() // Aloita uusi gorutiini arvon lähettämiseksi. + go func() { cs <- "sanaa" }() // Uudestaan, mutta cs -kanava tällä kertaa. + // Select -lausekkeella on syntaksi kuten switch -lausekkeella mutta + // jokainen tapaus sisältää kanavaoperaation. Se valitsee satunnaisen + // tapauksen niistä kanavista, jotka ovat kommunikaatiovalmiita + select { + case i := <-c: // Vastaanotettu arvo voidaan antaa muuttujalle + fmt.Printf("se on %T", i) + case <-cs: // tai vastaanotettu arvo voidaan sivuuttaa. + fmt.Println("se on merkkijono") + case <-ccs: // Tyhjä kanava; ei valmis kommunikaatioon. + fmt.Println("ei tapahtunut.") + } + // Tässä vaiheessa arvo oli otettu joko c:ltä tai cs:ltä. Yksi kahdesta + // ylempänä aloitetusta gorutiinista on valmistunut, toinen pysyy tukossa. + + learnWebProgramming() // Go tekee sitä. Sinäkin haluat tehdä sitä. +} + +// Yksittäinen funktio http -paketista aloittaa web-palvelimen. +func learnWebProgramming() { + + // ListenAndServe:n ensimmäinen parametri on TCP-osoite, jota kuunnellaan. + // Toinen parametri on rajapinta, http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // älä sivuuta virheitä. + }() + + requestServer() +} + +// Tee pair:sta http.Handler implementoimalla sen ainoa metodi, ServeHTTP. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Tarjoa dataa metodilla http.ResponseWriter. + w.Write([]byte("Opit Go:n Y minuutissa!")) +} + +func requestServer() { + resp, err := http.Get("http://localhost:8080") + fmt.Println(err) + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + fmt.Printf("\nWeb-palvelin sanoo: `%s`", string(body)) +} +``` + +## Lisää luettavaa + +Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). +Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. +Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa +siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. + +Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja +yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) + +Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). +Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) +[REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. + +Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). +Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, +-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja +lähdekoodi tulee esille! + +Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). + +Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia +Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile). diff --git a/forth.html.markdown b/forth.html.markdown index 570e12ed..b4a5581b 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -12,7 +12,7 @@ such as Open Firmware. It's also used by NASA. Note: This article focuses predominantly on the Gforth implementation of Forth, but most of what is written here should work elsewhere. -```forth +``` \ This is a comment ( This is also a comment but it's only used when defining words ) @@ -117,7 +117,7 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok : threes ( n n -- ) ?do i . 3 +loop ; \ ok 15 0 threes \ 0 3 6 9 12 ok -\ Indefinite loops with `begin` <stuff to do> <flag> `unil`: +\ Indefinite loops with `begin` <stuff to do> <flag> `until`: : death ( -- ) begin ." Are we there yet?" 0 until ; \ ok \ ---------------------------- Variables and Memory ---------------------------- @@ -133,7 +133,7 @@ variable age \ ok age @ . \ 21 ok age ? \ 21 ok -\ Constants are quite simiar, except we don't bother with memory addresses: +\ Constants are quite similar, except we don't bother with memory addresses: 100 constant WATER-BOILING-POINT \ ok WATER-BOILING-POINT . \ 100 ok diff --git a/fr-fr/HTML-fr.html.markdown b/fr-fr/HTML-fr.html.markdown new file mode 100644 index 00000000..fdde9107 --- /dev/null +++ b/fr-fr/HTML-fr.html.markdown @@ -0,0 +1,115 @@ +--- +language: html +filename: learnhtml-fr.html +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +lang: fr-fr +--- +HTML signifie HyperText Markup Language. +C'est un langage (format de fichiers) qui permet d'écrire des pages internet. +C’est un langage de balisage, il nous permet d'écrire des pages HTML au moyen de balises (Markup, en anglais). +Les fichiers HTML sont en réalité de simple fichier texte. +Qu'est-ce que le balisage ? C'est une façon de hiérarchiser ses données en les entourant par une balise ouvrante et une balise fermante. +Ce balisage sert à donner une signification au texte ainsi entouré. +Comme tous les autres langages, HTML a plusieurs versions. Ici, nous allons parlons de HTML5. + +**NOTE :** Vous pouvez tester les différentes balises que nous allons voir au fur et à mesure du tutoriel sur des sites comme [codepen](http://codepen.io/pen/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. +Cet article porte principalement sur la syntaxe et quelques astuces. + + +```HTML +<!-- Les commentaires sont entouré comme cette ligne! --> + +<!-- #################### Les balises #################### --> + +<!-- Voici un exemple de fichier HTML que nous allons analyser --> +<!-- Venez voir ce que ça donne --> + +<!doctype html> + <html> + <head> + <title>Mon Site</title> + </head> + <body> + <h1>Hello, world!</h1> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> + <p>Ceci est un paragraphe</p> + <p>Ceci est un autre paragraphe</p> + <ul> + <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> + <li>Ceci est un autre item</li> + <li>Et ceci est le dernier item de la liste</li> + </ul> + </body> + </html> + +<!-- Un fichier HTML débute toujours par indiquer au navigateur que notre page est faite en HTML --> + +<!doctype html> + +<!-- Après ça on commence par ouvrir une balise <html> --> +<html> +</html> +<!-- Et puis on la referme à la fin du fichier avec </html> --> +<!-- après cette balise de fin, plus rien ne doit apparaître. --> + +<!-- À l'intérieur (entre la balise ouvrant et fermante <html></html>), on trouve : --> + +<!-- Un entête (<head> en anglais ; il faut le refermer avec </head>) --> +<!-- L'entête contient des descriptions et informations annexes qui ne sont pas affichées : se sont les métadonnées --> + +<head> + <title>Mon Site</title><!-- La balise <title> permet d'indiquer au navigateur le titre à afficher dans la barre de l'onglet de la fenêtre --> +</head> + +<!-- Après la balise <head>, on trouve la balise <body> --> +<!-- Pour le moment, rien n'est encore affiché dans la fenêtre du navigateur. --> +<!-- Il faut ensuite remplir le corps (balise <body>) avec du contenu --> + +<body> + <h1>Hello, world!</h1> <!-- La balise h1 permet de structurer le texte, c'est un titre --> + <!-- Il exite différents sous-titres à <h1> qui sont hiérarchisés du plus important (h2) au plus précis (h6) --> + <a href = "http://codepen.io/anon/pen/xwjLbZ">Venez voir ce que ça donne</a> <!-- Lien vers la source cible indiqué dans href="" --> + <p>Ceci est un paragraphe </p> <!-- La balise <p> permet d'inclure du texte à la page html --> + <p>Ceci est un autre paragraphe</p> + <ul> <!-- La balise <ul> permet d'introduire une liste à puces --> + <!-- Si on souhaite une liste ordonnée : <ol> liste numérotée, 1. pour le premier élément, 2. pour le second, etc --> + <li>Ceci est un item d'une liste non ordonnée (liste à puces)</li> + <li>Ceci est un autre item</li> + <li>Et ceci est le dernier item de la liste</li> + </ul> +</body> + +<!-- Voilà comment créer un fichier HTML simple --> + +<!-- Mais il est possible d'ajouter encore des balises plus spécifiques --> + +<!-- Pour insérer une image --> +<img src="http://i.imgur.com/XWG0O.gif"/> <!-- On indique la source de l'image dans src="" --> +<!-- La source peut-être un URL ou encore la destination d'un fichier de votre ordinateur --> + +<!-- Il est possible de réaliser des tableaux également --> + +<table> <!-- On ouvre la balise <table> --> + <tr> <!-- <tr> permet de créer une ligne --> + <th>First Header</th> <!-- <th> permet de créer un titre au tableau --> + <th>Second Header</th> + </tr> + <tr> + <td>Première ligne, première cellule</td> <!-- <td> permet de créer une cellule --> + <td>Première ligne, deuxième cellule</td> + </tr> + <tr> + <td>Deuxième ligne, première cellule</td> + <td>Deuxième ligne, deuxième cellule</td> + </tr> +</table> + +## Utilisation + +Le HTML s'écrit dans des fichiers `.html`. + +## En savoir plus + +* [Tutoriel HTML](http://slaout.linux62.org/html_css/html.html) +* [W3School](http://www.w3schools.com/html/html_intro.asp) diff --git a/fr-fr/clojure-fr.html.markdown b/fr-fr/clojure-fr.html.markdown index d3c5a67b..63bc25b5 100644 --- a/fr-fr/clojure-fr.html.markdown +++ b/fr-fr/clojure-fr.html.markdown @@ -248,7 +248,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Il y a encore d'autres fonctions dans l'espace de nom clojure.sets. -; Formes utiles +; Formes et macros utiles ;;;;;;;;;;;;;;; ; Les constructions logiques en Clojure sont juste des macros, et @@ -275,6 +275,33 @@ ressemblent à toutes les autres formes: (let [name "Urkel"] (print "Saying hello to " name) (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Utilisez les Threading Macros (-> et ->>) pour exprimer plus +; clairement vos transformations, en y pensant de manière multi-niveaux. + +; La "flèche simple" ou "Thread-first", insère, à chaque niveau +; de la transformation, la forme courante en la seconde position +; de la forme suivante, constituant à chaque fois un nouvel étage +; de transformation. Par exemple: +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> Génère ici (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> Génère ici (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; Cette expression est ré-écrite en: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; et est évaluée en : {:a 1 :c 3} + +; La "flèche double" ou "Thread-last" procède de la même manière +; que "->", mais insère le résultat de la réécriture de chaque +; étage en dernière position. Par exemple: +(->> + (range 10) + (map inc) ;=> Génère ici (map inc (range 10) + (filter odd?) ;=> Génère ici (filter odd? (map inc (range 10)) + (into [])) ;=> Génère ici (into [] (filter odd? (map inc (range 10))), ce qui est évalué au final à; + ; [1 3 5 7 9] + ; Modules ;;;;;;;;;;;;;;; diff --git a/fr-fr/csharp-fr.html.markdown b/fr-fr/csharp-fr.html.markdown index e51eacc8..58b3f386 100644 --- a/fr-fr/csharp-fr.html.markdown +++ b/fr-fr/csharp-fr.html.markdown @@ -239,7 +239,8 @@ sur une nouvelle ligne! ""Wow!"", quel style"; // Opérateur ternaire // Un simple if/else peut s'écrire : // <condition> ? <valeur si true> : <valeur si false> - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // Boucle while int fooWhile = 0; diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown index bdab9715..35673c47 100644 --- a/fr-fr/css-fr.html.markdown +++ b/fr-fr/css-fr.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs, +Au début du web, il n'y avait pas d'élements visuels, simplement du texte pur. Mais avec le dévelopement des navigateurs, des pages avec du contenu visuel sont arrivées. CSS est le langage standard qui existe et permet de garder une séparation entre le contenu (HTML) et le style d'une page web. @@ -16,8 +16,8 @@ le contenu (HTML) et le style d'une page web. En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents sur une page HTML afin de leur donner des propriétés visuelles différentes. -Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0 -qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur. +Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parler de CSS2.0 +qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateurs. **NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage. Cet article porte principalement sur la syntaxe et quelques astuces. @@ -33,7 +33,7 @@ Cet article porte principalement sur la syntaxe et quelques astuces. /* Généralement, la première déclaration en CSS est très simple */ selecteur { propriete: valeur; /* autres proprietés...*/ } -/* Le sélécteur sert à cibler un élément du HTML +/* Le sélecteur sert à cibler un élément du HTML Vous pouvez cibler tous les éléments d'une page! */ * { color:red; } diff --git a/fr-fr/d.html.markdown b/fr-fr/d.html.markdown new file mode 100644 index 00000000..d9bd9b48 --- /dev/null +++ b/fr-fr/d.html.markdown @@ -0,0 +1,264 @@ +--- +language: D +filename: learnd-fr.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +translators: + - ["Quentin Ladeveze", "aceawan.eu"] +lang: fr-fr +--- + +```d +// Commençons par un classique +module hello; + +import std.stdio; + +// args n'est pas obligatoire +void main(string[] args) { + writeln("Bonjour le monde !"); +} +``` + +Si vous êtes comme moi et que vous passez beaucoup trop de temps sur internet, il y a +de grandes chances pour que vous ayez déjà entendu parler du [D](http://dlang.org/). +D est un langage de programmation moderne, généraliste, multi-paradigmes qui contient +des fonctionnalités aussi bien de bas niveau que de haut niveau. + +D est activement développé par de nombreuses personnes très intelligents, guidées par +[Walter Bright](https://fr.wikipedia.org/wiki/Walter_Bright))) et +[Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). +Après cette petite introduction, jetons un coup d'oeil à quelques exemples. + +```d +import std.stdio; + +void main() { + //Les conditions et les boucles sont classiques. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + // On peut utiliser auto pour inférer automatiquement le + // type d'une variable. + auto n = 1; + + // On peut faciliter la lecture des valeurs numériques + // en y insérant des `_`. + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For et while sont très utiles, mais en D, on préfère foreach. + // Les deux points : '..', créent un intervalle continue de valeurs + // incluant la première mais excluant la dernière. + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + // On peut également utiliser foreach_reverse pour itérer à l'envers. + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("Non !"); + } + } +} +``` +On peut définir de nouveaux types avec les mots-clés `struct`, `class`, +`union` et `enum`. Ces types sont passés au fonction par valeur (ils sont copiés) +De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. + +```d +// Ici, 'T' est un paramètre de type. Il est similaire au <T> de C++/C#/Java. +struct LinkedList(T) { + T data = null; + + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '<T>' + LinkedList!(T)* next; +} + +class BinTree(T) { + T data = null; + + // Si il n'y a qu'un seul paramètre de template, + // on peut s'abstenir de mettre des parenthèses. + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Utilisez alias pour créer des abreviations pour les types. +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// On peut tout aussi bien créer des templates de function ! +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// On peut utiliser le mot-clé ref pour s'assurer que quelque chose est passé +// par référence, et ceci, même si a et b sont d'ordinaire passés par valeur. +// Ici ils seront toujours passés par référence à 'swap()'. +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// Avec les templates, on peut également passer des valeurs en paramètres. +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // T est 'int' par défaut + +``` +À propos de classes, parlons des propriétés. Une propriété est, en gros, +une méthode qui peut se comporter comme une lvalue. On peut donc utiliser +la syntaxe des structures classiques (`struct.x = 7`) comme si il +s'agissait de méthodes getter ou setter. + +```d +// Considérons une classe paramétrée avec les types 'T' et 'U' +class MyClass(T, U) { + T _data; + U _other; +} + +// Et des méthodes "getter" et "setter" comme suit: +class MyClass(T, U) { + T _data; + U _other; + + // Les constructeurs s'apellent toujours 'this'. + this(T t, U u) { + // Ceci va appeller les setters ci-dessous. + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} + +// Et on l'utilise de cette façon: +void main() { + auto mc = new MyClass!(int, string)(7, "seven"); + + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) + import std.stdio; + + // On appelle les getters pour obtenir les valeurs. + writefln("Earlier: data = %d, str = %s", mc.data, mc.other); + + // On appelle les setter pour assigner de nouvelles valeurs. + mc.data = 8; + mc.other = "eight"; + + // On appelle les setter pour obtenir les nouvelles valeurs. + writefln("Later: data = %d, str = %s", mc.data, mc.other); +} +``` +Avec les propriétés, on peut constuire nos setters et nos getters +comme on le souhaite, tout en gardant un syntaxe très propre, +comme si on accédait directement à des membres de la classe. + +Les autres fonctionnalités orientées objets à notre disposition +incluent les interfaces, les classes abstraites, et la surcharge +de méthodes. D gère l'héritage comme Java: On ne peut hériter que +d'une seule classe et implémenter autant d'interface que voulu. + +Nous venons d'explorer les fonctionnalités objet du D, mais changeons +un peu de domaine. D permet la programmation fonctionelle, avec les fonctions +de premier ordre, les fonctions `pure` et les données immuables. +De plus, tout vos algorithmes fonctionelles favoris (map, reduce, filter) +sont disponibles dans le module `std.algorithm`. + +```d +import std.algorithm : map, filter, reduce; +import std.range : iota; // construit un intervalle excluant la dernière valeur. + +void main() { + // On veut un algorithm qui affiche la somme de la listes des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! + + // On se content de passer des expressions lambda en paramètre à des templates. + // On peut fournier au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Vous voyez comme on a calculé `num` comme on le ferait en haskell par exemple ? +C'est grâce à une innvoation de D qu'on appelle "Uniform Function Call Syntax". +Avec l'UFCS, on peut choisir d'écrire un appelle à une fonction de manière +classique, ou comme un appelle à une méthode. Walter Brighter a écrit un +article en anglais sur l'UFCS [ici.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +Pour faire court, on peut appeller une fonction dont le premier paramètre +est de type A, comme si c'était une méthode de A. + +J'aime le parallélisme. Vous aimez les parallélisme ? Bien sur que vous aimez ça +Voyons comment on le fait en D ! + +```d +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // On veut calculer la racine carré de tous les nombres + // dans notre tableau, et profiter de tous les coeurs + // à notre disposition. + auto arr = new double[1_000_000]; + + // On utilise un index et une référence à chaque élément du tableau. + // On appelle juste la fonction parallel sur notre tableau ! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/fr-fr/erlang-fr.html.markdown b/fr-fr/erlang-fr.html.markdown new file mode 100644 index 00000000..55453c56 --- /dev/null +++ b/fr-fr/erlang-fr.html.markdown @@ -0,0 +1,327 @@ +--- +language: erlang +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Julien Cretel", "https://github.com/Jubobs"] +filename: learnerlang-fr.erl +lang: fr-fr +--- + +```erlang +% Un signe pour cent marque le début d'un commentaire de fin de ligne. + +%% Deux signes pour cent sont utilisés pour commenter les fonctions. + +%%% Trois signes pour cent sont utilisés pour commenter les modules. + +% Trois symboles de ponctuation sont utilisés en Erlang. +% Les virgules (`,`) servent à séparer les paramètres dans les appels de +% fonctions, les contructeurs, et les motifs. +% Les points (`.`) (suivis par des blancs) servent à séparer les fonctions et +% les expressions dans l'interpréteur. +% Les points-virgules (`;`) servent à séparer les clauses. Ces dernières +% apparaissent dans différent cas de figure : définitions de fonctions et +% expressions `case`, `if`, `try..catch`, `receive`. + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. Variables et filtrage par motif +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +(L'équivalent anglais de *filtrage par motif* est *pattern patching*.) + +Nb = 42. % Chaque nom de variable doit commencer par une lettre majuscule. + +% Les variables Erlang ne peuvent être affectées qu'une seule fois ; si vous +% essayez d'affecter une autre valeur à la variable `Nb`, vous obtiendrez +% une erreur. +Nb = 43. % ** exception error: no match of right hand side value 43 + +% Dans la plupart des languages, `=` indique une affectation. En Erlang, +% cependant, `=` indique un filtrage par motif. En fait, `Gauche = Droit` +% signifie ce qui suit : évalue le côté droit (`Droit`), et ensuite filtre le +% résultat à l'aide du motif du côté gauche (`Gauche`). +Nb = 7 * 6. + +% Nombre en virgule flottante. +Pi = 3.14159. + +% Les atomes représentent des valeurs constantes non-numériques. Un atome +% commence par une lettre minuscule, suivie d'une séquence composée de +% caractères alphanumériques, de tirets bas (`_`), ou d'arobases (`@`). +Bonjour = bonjour. +AutreNoeud = exemple@noeud. + +% Les atomes de valeur autre qu'alphanumérique peuvent être délimités par +% des guillemets droits simples. +AtomeAvecEspace = 'un atome contenant des espaces'. + +% Les tuples sont similaires aux enregistrements du language C. +Point = {point, 10, 45}. + +% Pour extraire des valeurs d'un tuple, on filtre par motif avec +% l'opérateur `=`. +{point, X, Y} = Point. % X = 10, Y = 45 + +% On peut utiliser `_` comme caractère joker pour les variables qui ne nous +% intéressent pas. Le symbol `_` est appelé variable muette. Contrairement +% aux variables normales, de multiples apparitions de `_` dans un même motif +% ne lient pas nécessairement à la même valeur. +Personne = {personne, {nom, {prenom, joe}, {famille, armstrong}}, + {pointure, 42}}. +{_, {_, {_, Qui}, _}, _} = Personne. % Qui = joe + +% Pour créer une liste, on écrit les éléments de la liste entre crochets, en +% les séparant par des virgules. +% Les éléments d'une liste peuvent avoir n'importe quel type. +% Le premier élément d'une liste est appelé la tête de la liste. Si on retire +% la tête d'une liste, ce qui reste est appelée la queue de la liste. +Articles = [{pommes, 10}, {poires, 6}, {lait, 3}]. + +% Si `Q` est une liste, alors `[T|Q]` est aussi une liste dont la tête est `T` +% et dont la queue est `Q`. La barre verticale (`|`) sépare la tête d'une +% liste de sa queue. +% `[]` est la liste vide. +% On peut extraire des éléments d'une liste par filtrage de motif. Si `L` est +% une liste non vide, alors l'expression `[X|Y] = L`, où `X` et `Y` sont des +% variables non affectées, va extraire la tête de la liste dans `X` et la +% queue de la liste dans `Y`. +[PremierArticle|AutresArticles] = Articles. +% PremierArticle = {pommmes, 10} +% AutresArticles = [{poires, 6}, {lait, 3}] + +% Il n'y a pas de chaînes de caractères en Erlang. Les chaînes de caractères +% ne sont rien de plus que des listes d'entiers. +% Les chaînes de caractères sont délimitées par des guillemets droits doubles +% (`"`). +Nom = "Bonjour". +[66, 111, 110, 106, 111, 117, 114] = "Bonjour". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. Programmation séquentielle. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Les modules constituent l'unité de base d'un programme Erlang. Toutes les +% fonctions que l'on écrit sont enregistrées dans des modules. Les modules sont +% enregistrés dans des fichiers avec une extension `.erl`. +% Les modules doivent être compilés afin d'éxecuter le programme. +% Un module compilé a une extension `.beam`. +-module(geometrie). +-export([aire/1]). % la liste des fonctions exportées par le module. + +% La fonction `aire` est composée de deux clauses. Les clauses sont séparées +% par un point-virgule, et la dernière clause est suivie d'un point et un +% espace blanc. Chaque clause a une en-tête et un corps ; l'en-tête consiste +% en un nom de fonction suivi d'un motif (entre parenthèses), et le corps +% consiste en une séquence d'expressions, qui sont évaluées si le motif de +% l'en-tête est cohérent par rapport à la valeur des paramètres d'appel. +% L'expression est filtrée séquentiellement par les différents motifs, dans +% l'ordre dans lequel ils apparaissent dans la définition de la fonction. +aire({rectangle, Largeur, Hauteur}) -> Largeur * Hauteur; +aire({cercle, R}) -> 3.14159 * R * R. + +% Compilation du code du fichier geometrie.erl. +c(geometrie). % {ok,geometrie} + +% Le nom du module doit être inclus avec le nom de la fonction afin +% d'identifier précisément quelle fonction on souhaite appeler. +geometrie:aire({rectangle, 10, 5}). % 50 +geometrie:area({cercle, 1.4}). % 6.15752 + +% En Erlang, deux fonctions portant le même nom mais ayant des arités +% différentes (c'est à dire ne prenant pas le même nombre de paramètres) +% au sein d'un même module représentent des fonctions complètement +% différentes. +-module(lib_divers). +-export([somme/1]). % exporte la fonction `somme` d'arité 1 + % acceptant un paramètre : une liste d'entiers. +somme(L) -> somme(L, 0). +somme([], N) -> N; +somme([T|Q], N) -> somme(Q, T+N). + +% Les `fun`s sont des fonctions "anonymes" ; elles sont appelées ainsi parce +% qu'elles n'ont pas de nom. Cependant, elles peuvent être affectées à des +% variables. +Doubler = fun(X) -> 2 * X end. % `Doubler` pointe vers une fonction anonyme + % dont le handle est : #Fun<erl_eval.6.17052888> +Doubler(2). % 4 + +% Les fonctions peuvent prendre des `fun`s comme paramètres et peuvent renvoyer +% des `fun`s. +Mult = fun(Fois) -> ( fun(X) -> X * Fois end ) end. +Tripler = Mult(3). +Tripler(5). % 15 + +% Les listes en compréhension sont des expressions qui créent des listes sans +% requérir ni `fun`s, ni maps, ni filters. +% La notation `[F(X) || X <- L]` signifie "la liste des `F(X)` où `X` est +% extrait de la liste `L`." +L = [1,2,3,4,5]. +[2 * X || X <- L]. % [2,4,6,8,10] +% Une liste en compréhension peut être constituée de générateurs, ainsi que de +% gardes, qui sélectionnent un sous-ensemble des valeurs générées. +NombresPairs = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% La garde est un élément syntaxique qui rend le filtrage par motif encore +% plus puissant. Les gardes permettent de d'effectuer de simple tests et +% comparaisons sur les variables d'un motif. Les gardes peuvent être +% utilisées dans les en-têtes de fonctions, au sein desquelles elles sont +% introduites par le mot-clé `when`, ou encore à n'importe quel endroit où +% une expression est autorisée. +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% Une garde est une série d'expressions gardes, séparées par des virgules (`,`). +% La garde `ExprGarde1, ExprGarde2, ..., ExprGardeN` est vraie si toutes les +% expressions gardes `ExprGarde1`, `ExprGarde2, ..., `ExprGardeN` ont pour +% valeur `true`. +est_chat(A) when is_atom(A), A =:= chat -> true; +est_chat(A) -> false. +est_chien(A) when is_atom(A), A =:= chien -> true; +est_chien(A) -> false. + +% Une séquence de gardes est composée soit d'une seule garde ou bien d'une +% série de gardes, séparées par des points-virgules (`;`). La séquence de +% gardes `G1; G2; ...; Gn` est vraie si au moins l'une des gardes `G1`, `G2`, +% ..., `Gn` a pour valeur `true`. +est_animal(A) when is_atom(A), (A =:= chien) or (A =:= chat) -> true; +est_animal(A) -> false. + +% Attention : toutes les expressions Erlang valides ne peuvent pas être +% utilisées comme expressions gardes ; en particulier, nos fonctions +% `est_chat` et `est_chien` ne sont pas autorisées au sein de la séquence de +% gardes dans la définition de `est_animal`. Pour plus de détails sur les +% expressions autorisées ands les séquences de gardes, voir cette +% [section](http://erlang.org/doc/reference_manual/expressions.html#id81912) +% du manuel Erlang. + +% Les enregistrements permettent d'associer un nom à un certain élément dans +% un tuple. +% Les enregistrements peuvent être définis dans des fichiers sources Erlang +% ou bien dans des fichiers avec une extension `.hrl`, qui sont ensuite inclus +% dans des fichiers sources Erlang. +-record(afaire, { + statut = rappel, % Valeur par défaut + qui = joe, + texte +}). + +% Les définitions d'enregistrements doivent être lues dans l'interpreteur +% pour qu'on puisse définir un enregistrement. On utilise la fonction `rr` +% (abbréviation de *read records* en anglais, ou *lire enregistrements* en +% français) pour ça. +rr("enregistrements.hrl"). % [afaire] + +% Création et mise à jour d'enregistrements : +X = #afaire{}. +% #afaire{statut = rappel, qui = joe, texte = undefined} +X1 = #afaire{statut = urgent, texte = "Corriger erreurs dans livre"}. +% #afaire{statut = urgent, qui = joe, texte = "Corriger erreurs dans livre"} +X2 = X1#afaire{statut = fini}. +% #afaire{statut = fini, qui = joe, texte = "Corriger erreurs dans livre"} + +% Expressions `case`. +% `filter` renvoie une liste de tous les éléments `X` d'une liste `L` pour +% lesquels `P(X)` est vrai. +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% Expressions `if`. +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil + end. + +% Attention : au moins l'une des gardes dans l'expression `if` doit avoir pour +% valeur `true` ; autrement, une exception sera lancée. + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. Exceptions. +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Des exceptions sont lancées par le système quand des erreurs internes +% surviennent, ou de manière explicite dans le programme en appelant +% `throw(Exception)`, `exit(Exception)`, ou `erlang:error(Exception)`. +generer_exception(1) -> a; +generer_exception(2) -> throw(a); +generer_exception(3) -> exit(a); +generer_exception(4) -> {'EXIT', a}; +generer_exception(5) -> erlang:error(a). + +% Erlang dispose de deux méthodes pour capturer une exception. La première +% consiste à inclure l'appel de de la fonction qui lance l'exception dans une +% expression `try...catch`. +catcher(N) -> + try generer_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% L'autre méthode consiste à inclure l'appel dans une expression `catch`. +% Quand une exception est capturée, elle est convertie en un tuple qui décrit +% l'erreur. +catcher(N) -> catch generer_exception(N). + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. Concurrence +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang est basé sur le modèle d'acteur pour la concurrence. Seulement trois +% opérations sont requises pour écrire des programmes concurrents en Erlang : +% la création de processus, l'envoi de messages, et la réception de messages. + +% Pour démarrer un nouveau processus, on utilise la fonction `spawn`, qui +% prend une fonction comme paramètre. + +F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768> +spawn(F). % <0.44.0> + +% `spawn` renvoie un pid (*process identifier* en anglais, ou *identifiant de +% processus* en français), qui peut être utilisé pour envoyer des messages au +% processus en question. Pour passer des messages, on utilise l'opérateur `!`. +% Pour que cela soit utile, on doit aussi être en mesure de recevoir des +% messages, ce qui est accompli grâce à une clause `receive` : + +-module(calculerGeometrie). +-compile(export_all). +calculerAire() -> + receive + {rectangle, W, H} -> + W * H; + {cercle, R} -> + 3.14 * R * R; + _ -> + io:format("Seule l'aire d'un rectangle / cercle peut etre calculee.") + end. + +% Compilation du module and création d'un processus qui évalue `calculerAire` +% dans l'interpréteur. +c(calculerGeometrie). +CalculerAire = spawn(calculerGeometrie, calculerAire, []). +CalculerAire ! {cercle, 2}. % 12.56000000000000049738 + +% L'interpréteur est lui-même un processus ; on peut utiliser `self` pour +% obtenir le pid actuel. +self(). % <0.41.0> + +``` + +## Ressources (en anglais) + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown new file mode 100644 index 00000000..16558e7e --- /dev/null +++ b/fr-fr/go-fr.html.markdown @@ -0,0 +1,439 @@ +--- +name: Go +category: language +language: Go +lang: fr-fr +filename: learngo.go +contributors: + - ["Sonia Keys", "https://github.com/soniakeys"] + - ["Christopher Bess", "https://github.com/cbess"] + - ["Jesse Johnson", "https://github.com/holocronweaver"] + - ["Quint Guvernator", "https://github.com/qguv"] + - ["Jose Donizetti", "https://github.com/josedonizetti"] + - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Jean-Philippe Monette", "http://blogue.jpmonette.net/"] +--- + +Go a été créé dans l'optique de développer de façon efficace. Ce n'est pas la +dernière tendance en ce qui est au développement, mais c'est la nouvelle façon +de régler des défis réels de façon rapide. + +Le langage possède des concepts familiers à la programmation impérative avec +typage. Il est rapide à compiler et exécuter, ajoute une concurrence facile à +comprendre, pour les processeurs multi coeurs d'aujourd'hui et apporte des +fonctionnalités facilitant le développement à grande échelle. + +Développer avec Go, c'est bénéficier d'une riche bibliothèque standard et d'une +communauté active. + +```go +// Commentaire ligne simple +/* Commentaire + multiligne */ + +// Un paquet débute avec une clause "package" +// "Main" est un nom spécial déclarant un paquet de type exécutable plutôt +// qu'une bibliothèque +package main + +// "Import" déclare les paquets référencés dans ce fichier. +import ( + "fmt" // Un paquet dans la bibliothèque standard. + "io/ioutil" // Implémente des fonctions utilitaires I/O. + m "math" // Bibliothèque mathématique utilisant un alias local "m". + "net/http" // Un serveur Web! + "strconv" // Bibliothèque pour convertir les chaînes de caractères. +) + +// Une définition de fonction. La fonction "main" est spéciale - c'est le point +// d'entrée du binaire. +func main() { + // Println retournera la valeur à la console. + // Associez la fonction avec son paquet respectif, fmt. + fmt.Println("Hello world!") + + // Appelez une fonction différente à partir de ce paquet. + beyondHello() +} + +// Les fonctions ont des paramètres entre parenthèses. +// Les parenthèses sont nécessaires avec ou sans paramètre. +func beyondHello() { + var x int // Déclaration de variable. Les variables doivent être déclarées + // avant leur utilisation. + x = 3 // Assignation de valeur. + // Les déclarations courtes utilisent := pour inférer le type, déclarer et + // assigner. + y := 4 + sum, prod := learnMultiple(x, y) // La fonction retourne deux valeurs. + fmt.Println("sum:", sum, "prod:", prod) // Affichage simple. + learnTypes() // < y minutes, en savoir plus! +} + +// Les fonctions peuvent avoir des paramètres et plusieurs valeurs retournées. +func learnMultiple(x, y int) (sum, prod int) { + return x + y, x * y // Deux valeurs retournées. +} + +// Quelques types inclus et littéraux. +func learnTypes() { + // Une déclaration courte infère généralement le type désiré. + str := "Learn Go!" // Type string. + + s2 := `Une chaîne de caractères peut contenir des +sauts de ligne.` // Chaîne de caractère. + + // Littéral non-ASCII. Les sources Go utilisent le charset UTF-8. + g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère + // unicode. + + f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. + c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur. + + // Syntaxe "var" avec une valeur d'initialisation. + var u uint = 7 // Non signé, mais la taille dépend selon l'entier. + var pi float32 = 22. / 7 + + // Conversion avec syntaxe courte. + n := byte('\n') // byte est un alias du type uint8. + + // Les tableaux ont une taille fixe déclarée à la compilation. + var a4 [4]int // Un tableau de 4 ints, tous initialisés à 0. + a3 := [...]int{3, 1, 5} // Un tableau initialisé avec une taille fixe de 3 + // éléments, contenant les valeurs 3, 1 et 5. + + // Les slices ont des tailles dynamiques. Les tableaux et slices ont chacun + // des avantages, mais les cas d'utilisation des slices sont plus fréquents. + s3 := []int{4, 5, 9} // Comparable à a3. + s4 := make([]int, 4) // Alloue un slice de 4 ints, initialisés à 0. + var d2 [][]float64 // Déclaration seulement, sans allocation de mémoire. + bs := []byte("a slice") // Conversion d'une chaîne en slice de bytes. + + // Parce qu'elles sont dynamiques, les slices peuvent être jointes sur + // demande. Pour joindre un élément à une slice, la fonction standard append() + // est utilisée. Le premier argument est la slice à utiliser. Habituellement, + // la variable tableau est mise à jour sur place, voir ci-bas. + s := []int{1, 2, 3} // Le résultat est une slice de taille 3. + s = append(s, 4, 5, 6) // Ajout de 3 valeurs. La taille est de 6. + fmt.Println(s) // La valeur est de [1 2 3 4 5 6] + + // Pour ajouter une slice à une autre, au lieu d'utiliser une liste de valeurs + // atomiques, il est possible de mettre en argument une référence de + // slice littérale grâce aux points de suspension. + s = append(s, []int{7, 8, 9}...) // Le deuxième argument est une slice + // littérale. + fmt.Println(s) // La slice contient [1 2 3 4 5 6 7 8 9] + + p, q := learnMemory() // Déclare p, q comme étant des pointeurs de type int. + fmt.Println(*p, *q) // * suit un pointeur. Ceci retourne deux ints. + + // Les maps sont des tableaux associatifs de taille dynamique, comme les + // hash ou les types dictionnaires de certains langages. + m := map[string]int{"trois": 3, "quatre": 4} + m["un"] = 1 + + // Les valeurs inutilisées sont considérées comme des erreurs en Go. + // Un tiret bas permet d'ignorer une valeur inutilisée, évitant une erreur. + _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs + + // Cependant, son affichage en console est considéré comme une utilisation, + // ce qui ne sera pas considéré comme une erreur à la compilation. + fmt.Println(s, c, a4, s3, d2, m) + + learnFlowControl() // De retour dans le flux. +} + +// Il est possible, à l'opposé de plusieurs autres langages, de retourner des +// variables par leur nom à partir de fonctions. +// Assigner un nom à un type retourné par une fonction permet de retrouver sa +// valeur ainsi que d'utiliser le mot-clé "return" uniquement, sans plus. +func learnNamedReturns(x, y int) (z int) { + z = x * y + return // z est implicite, car la variable a été définie précédemment. +} + +// La récupération de la mémoire est automatique en Go. Le langage possède des +// pointeurs, mais aucune arithmétique des pointeurs (*(a + b) en C). Vous +// pouvez produire une erreur avec un pointeur nil, mais pas en incrémentant un +// pointeur. +func learnMemory() (p, q *int) { + // Les valeurs retournées p et q auront le type pointeur int. + p = new(int) // Fonction standard "new" alloue la mémoire. + // Le int alloué est initialisé à 0, p n'est plus nil. + s := make([]int, 20) // Alloue 20 ints en un seul bloc de mémoire. + s[3] = 7 // Assigne l'un des entiers. + r := -2 // Déclare une autre variable locale. + return &s[3], &r // & retourne l'adresse d'un objet. +} + +func expensiveComputation() float64 { + return m.Exp(10) +} + +func learnFlowControl() { + // Bien que les "if" requièrent des accolades, les parenthèses ne sont pas + // nécessaires pour contenir le test booléen. + if true { + fmt.Println("voilà!") + } + // Le formatage du code est standardisé par la commande shell "go fmt." + if false { + // bing. + } else { + // bang. + } + // Utilisez "switch" au lieu des "if" en chaîne + x := 42.0 + switch x { + case 0: + case 1: + case 42: + // Les "case" n'ont pas besoin de "break;". + case 43: + // Non-exécuté. + } + // Comme les "if", les "for" n'utilisent pas de parenthèses. + // Les variables déclarées dans les "for" et les "if" sont locales à leur + // portée. + for x := 0; x < 3; x++ { // ++ est une incrémentation. + fmt.Println("itération ", x) + } + // x == 42 ici. + + // "For" est le seul type de boucle en Go, mais possède différentes formes. + for { // Boucle infinie + break // C'est une farce + continue // Non atteint. + } + + // Vous pouvez utiliser une "range" pour itérer dans un tableau, une slice, une + // chaîne, une map ou un canal. Les "range" retournent un canal ou deux + // valeurs (tableau, slice, chaîne et map). + for key, value := range map[string]int{"une": 1, "deux": 2, "trois": 3} { + // pour chaque pair dans une map, affichage de la valeur et clé + fmt.Printf("clé=%s, valeur=%d\n", key, value) + } + + // À l'opposé du "for", := dans un "if" signifie la déclaration et + // l'assignation y en premier, et ensuite y > x + if y := expensiveComputation(); y > x { + x = y + } + // Les fonctions littérales sont des fermetures. + xBig := func() bool { + return x > 10000 + } + fmt.Println("xBig:", xBig()) // true (la valeur e^10 a été assignée à x). + x = 1.3e3 // Ceci fait x == 1300 + fmt.Println("xBig:", xBig()) // Maintenant false. + + // De plus, les fonctions littérales peuvent être définies et appelées + // sur la même ligne, agissant comme argument à cette fonction, tant que: + // a) la fonction littérale est appelée suite à (), + // b) le résultat correspond au type de l'argument. + fmt.Println("Ajoute + multiplie deux nombres : ", + func(a, b int) int { + return (a + b) * 2 + }(10, 2)) // Appelle la fonction avec les arguments 10 et 2 + // => Ajoute + double deux nombres : 24 + + // Quand vous en aurez besoin, vous allez l'adorer. + goto love +love: + + learnFunctionFactory() // func retournant func correspondant à fun(3)(3). + learnDefer() // Un survol de cette instruction importante. + learnInterfaces() // Incontournable ! +} + +func learnFunctionFactory() { + // Les deux syntaxes sont identiques, bien que la seconde soit plus pratique. + fmt.Println(sentenceFactory("été")("Une matinée d'", "agréable!")) + + d := sentenceFactory("été") + fmt.Println(d("Une matinée d'", "agréable!")) + fmt.Println(d("Une soirée d'", "relaxante!")) +} + +// Le décorateur est un patron de conception commun dans d'autres langages. +// Il est possible de faire de même en Go avec des fonctions littérales +// acceptant des arguments. +func sentenceFactory(mystring string) func(before, after string) string { + return func(before, after string) string { + return fmt.Sprintf("%s %s %s", before, mystring, after) // nouvelle chaîne + } +} + +func learnDefer() (ok bool) { + // Les déclarations différées sont exécutées avant la sortie d'une fonction. + defer fmt.Println("les déclarations différées s'exécutent en ordre LIFO.") + defer fmt.Println("\nCette ligne est affichée en premier parce que") + // Les déclarations différées sont utilisées fréquemment pour fermer un + // fichier, afin que la fonction ferme le fichier en fin d'exécution. + return true +} + +// Défini Stringer comme étant une interface avec une méthode, String. +type Stringer interface { + String() string +} + +// Défini pair comme étant une structure contenant deux entiers, x et y. +type pair struct { + x, y int +} + +// Défini une méthode associée au type pair. Pair implémente maintenant Stringer +func (p pair) String() string { // p s'appelle le "destinataire" + // Sprintf est une autre fonction publique dans le paquet fmt. + // La syntaxe avec point permet de faire référence aux valeurs de p. + return fmt.Sprintf("(%d, %d)", p.x, p.y) +} + +func learnInterfaces() { + // La syntaxe avec accolade défini une "structure littérale". Celle-ci + // s'évalue comme étant une structure. La syntaxe := déclare et initialise p + // comme étant une instance. + p := pair{3, 4} + fmt.Println(p.String()) // Appelle la méthode String de p, de type pair. + var i Stringer // Déclare i instance de l'interface Stringer. + i = p // Valide, car pair implémente Stringer. + // Appelle la méthode String de i, de type Stringer. Retourne la même valeur + // que ci-haut. + fmt.Println(i.String()) + + // Les fonctions dans le paquet fmt appellent la méthode String, demandant + // aux objets d'afficher une représentation de leur structure. + fmt.Println(p) // Affiche la même chose que ci-haut. Println appelle la + // méthode String. + fmt.Println(i) // Affiche la même chose que ci-haut. + + learnVariadicParams("apprentissage", "génial", "ici!") +} + +// Les fonctions peuvent être définie de façon à accepter un ou plusieurs +// paramètres grâce aux points de suspension, offrant une flexibilité lors de +// son appel. +func learnVariadicParams(myStrings ...interface{}) { + // Itère chaque paramètre dans la range. + // Le tiret bas sert à ignorer l'index retourné du tableau. + for _, param := range myStrings { + fmt.Println("paramètre:", param) + } + + // Passe une valeur variadique comme paramètre variadique. + fmt.Println("paramètres:", fmt.Sprintln(myStrings...)) + + learnErrorHandling() +} + +func learnErrorHandling() { + // ", ok" idiome utilisée pour définir si l'opération s'est déroulée avec + // succès ou non + m := map[int]string{3: "trois", 4: "quatre"} + if x, ok := m[1]; !ok { // ok sera faux, car 1 n'est pas dans la map. + fmt.Println("inexistant") + } else { + fmt.Print(x) // x serait la valeur, si elle se trouvait dans la map. + } + // Une erreur ne retourne qu'un "ok", mais également plus d'information + // par rapport à un problème survenu. + if _, err := strconv.Atoi("non-int"); err != nil { // _ discarte la valeur + // retourne: 'strconv.ParseInt: parsing "non-int": invalid syntax' + fmt.Println(err) + } + // Nous réviserons les interfaces un peu plus tard. Pour l'instant, + learnConcurrency() +} + +// c est un canal, un objet permettant de communiquer en simultané de façon +// sécurisée. +func inc(i int, c chan int) { + c <- i + 1 // <- est l'opérateur "envoi" quand un canal apparaît à + // gauche. +} + +// Nous utiliserons inc pour incrémenter des nombres en même temps. +func learnConcurrency() { + // La fonction "make" utilisée précédemment pour générer un slice. Elle + // alloue et initialise les slices, maps et les canaux. + c := make(chan int) + // Démarrage de trois goroutines simultanées. Les nombres seront incrémentés + // simultanément, peut-être en paralèle si la machine le permet et configurée + // correctement. Les trois utilisent le même canal. + go inc(0, c) // go est une instruction démarrant une nouvelle goroutine. + go inc(10, c) + go inc(-805, c) + // Lis et affiche trois résultats du canal - impossible de savoir dans quel + // ordre ! + fmt.Println(<-c, <-c, <-c) // Canal à droite, <- est l'opérateur de + // "réception". + + cs := make(chan string) // Un autre canal, celui-ci gère des chaînes. + ccs := make(chan chan string) // Un canal de canaux de chaînes. + go func() { c <- 84 }() // Démarre une nouvelle goroutine, pour + // envoyer une valeur. + go func() { cs <- "wordy" }() // De nouveau, pour cs cette fois-ci. + // Select possède une syntaxe similaire au switch, mais chaque cas requiert + // une opération impliquant un canal. Il sélectionne un cas aléatoirement + // prêt à communiquer. + select { + case i := <-c: // La valeur reçue peut être assignée à une variable, + fmt.Printf("c'est un %T", i) + case <-cs: // ou la valeur reçue peut être ignorée. + fmt.Println("c'est une chaîne") + case <-ccs: // Un canal vide, indisponible à la communication. + fmt.Println("ne surviendra pas.") + } + // À ce point, une valeur a été prise de c ou cs. L'une des deux goroutines + // démarrée plus haut a complétée, la seconde restera bloquée. + + learnWebProgramming() // Go permet la programmation Web. +} + +// Une seule fonction du paquet http démarre un serveur Web. +func learnWebProgramming() { + + // Le premier paramètre de ListenAndServe est une adresse TCP à écouter. + // Le second est une interface, de type http.Handler. + go func() { + err := http.ListenAndServe(":8080", pair{}) + fmt.Println(err) // n'ignorez pas les erreurs ! + }() + + requestServer() +} + +// Implémente la méthode ServeHTTP de http.Handler à pair, la rendant compatible +// avec les opérations utilisant l'interface http.Handler. +func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // Répondez à une requête à l'aide de la méthode http.ResponseWriter. + w.Write([]byte("Vous avez appris Go en 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("\nLe serveur Web a dit: `%s`", string(body)) +} +``` + +## En savoir plus + +La référence Go se trouve sur [le site officiel de Go](http://golang.org/). +Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. + +Une lecture de la documentation du langage est grandement conseillée. C'est +facile à lire et très court (comparé aux autres langages). + +Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. + +Sur la liste de lecteur des étudiants de Go se trouve le [code source de la +librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre +le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous +pouvez cliquer sur le nom d'une fonction dans [la +documentation](http://golang.org/pkg/) et le code source apparaît! + +Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/). diff --git a/fr-fr/haml-fr.html.markdown b/fr-fr/haml-fr.html.markdown new file mode 100644 index 00000000..24be8bf9 --- /dev/null +++ b/fr-fr/haml-fr.html.markdown @@ -0,0 +1,157 @@ +--- +language: haml +filename: learnhaml.haml +contributors: + - ["Simon Neveu", "https://github.com/sneveu"] + - ["Thibault", "https://github.com/iTech-"] +lang: fr-fr +--- + +Haml est un langage de balisage utilisé majoritairement avec Ruby, qui décrit de manière simple et propre le HTML de n'importe quelle page web sans l'utilisation des traditionnelles lignes de code. Le langage est une alternative très populaire au langage de templates Rails (.erb) et permet d'intégrer du code en Ruby dans votre balisage. + +Son but est de réduire le nombre de répétitions dans le balisage en fermant des balises pour vous en se basant sur l'indentation de votre code. Finalement, le balisage est bien structuré, ne contient pas de répétition, est logique et facile à lire. + +Vous pouvez aussi utiliser Haml sur un projet indépendant de Ruby, en installant les gems de Haml et en le convertissant en html grâce aux commandes. + +$ haml fichier_entree.haml fichier_sortie.html + + +```haml +/ ------------------------------------------- +/ Indentation +/ ------------------------------------------- + +/ + A cause de l'importance de l'indentation sur la manière dont votre code sera + converti, l'indentation doit être constante à travers votre document. Un + simple changement d'indentation entrainera une erreur. En général, on utilise + deux espaces, mais ce genre de décision sur l'indentation vous appartient, du + moment que vous vous y tenez. + +/ ------------------------------------------- +/ Commentaires +/ ------------------------------------------- + +/ Ceci est un commentaire en Haml. + +/ + Pour écrire un commentaire sur plusieurs lignes, indentez votre code + commenté en le commençant par un slash + +-# Ceci est un commentaire silencieux, qui n'apparaîtra pas dans le fichier + + +/ ------------------------------------------- +/ Eléments HTML +/ ------------------------------------------- + +/ Pour écrire vos balises, utilisez un pourcentage suivi du nom de votre balise +%body + %header + %nav + +/ Remarquez qu'il n'y a aucunes balises fermées. Le code produira alors ceci + <body> + <header> + <nav></nav> + </header> + </body> + +/ La balise div est l'élément par défaut, vous pouvez donc l'écrire comme ceci +.balise + +/ Pour ajouter du contenu à votre balise, ajoutez le texte après sa déclaration +%h1 Titre contenu + +/ Pour écrire du contenu sur plusieurs lignes, imbriquez le +%p + Ce paragraphe contient beaucoup de contenu qui pourrait + probablement tenir sur deux lignes séparées. + +/ + Vous pouvez utiliser des caractères html spéciaux en utilisant &=. Cela va + convertir les caractères comme &, /, : en leur équivalent HTML. Par exemple + +%p + &= "Oui & oui" + +/ Produira 'Oui & oui' + +/ Vous pouvez écrire du contenu html sans qu'il soit converti en utilisant != +%p + != "Voici comment écrire une balise de paragraphe <p></p>" + +/ Cela produira 'Voici comment écrire une balise de paragraphe <p></p>' + +/ Une classe CSS peut être ajouté à votre balise en chainant le nom de la classe +%div.truc.machin + +/ ou en utilisant un hash de Ruby +%div{:class => 'truc machin'} + +/ Des attributs pour n'importe quelles balises peuvent être ajoutés au hash +%a{:href => '#', :class => 'machin', :title => 'Titre machin'} + +/ Pour affecter une valeur à un booléen, utilisez 'true' +%input{:selected => true} + +/ Pour écrire des data-attributes, utilisez le :data avec la valeur d'un hash +%div{:data => {:attribute => 'machin'}} + + +/ ------------------------------------------- +/ Insérer du Ruby +/ ------------------------------------------- + +/ + Pour transférer une valeur de Ruby comme contenu d'une balise, utilisez le + signe égal suivi du code Ruby + +%h1= livre.titre + +%p + = livre.auteur + = livre.editeur + + +/ Pour lancer du code Ruby sans le convertir en HTML, utilisez un trait d'union +- livres = ['livre 1', 'livre 2', 'livre 3'] + +/ Ceci vous permet de faire des choses géniales comme des blocs Ruby +- livre.shuffle.each_with_index do |livre, index| + %h1= livre + + if livre do + %p Ceci est un livre + +/ + Encore une fois il n'est pas nécessaire d'ajouter une balise fermante, même + pour Ruby. + L'indentation le fera pour vous. + + +/ ------------------------------------------- +/ Ruby en-ligne / Interpolation en Ruby +/ ------------------------------------------- + +/ Inclure une variable Ruby dans une ligne en utilisant #{} +%p Votre meilleur score est #{record} + + +/ ------------------------------------------- +/ Filtres +/ ------------------------------------------- + +/ + Utilisez les deux points pour définir un filtre Haml, vous pouvez par exemple + utiliser un filtre :javascript pour écrire du contenu en-ligne js + +:javascript + console.log('Ceci est la balise en-ligne <script>'); + +``` + +## Lectures complémentaires + +- [Qu'est-ce que HAML ?](http://haml.info/) - Une bonne introduction qui explique très bien les avantages d'utiliser HAML. +- [Documentation officielle](http://haml.info/docs/yardoc/file.REFERENCE.html) - Si vous souhaitez en apprendre plus et aller plus loin. diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 2e18d0be..15478cdb 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -469,9 +469,6 @@ myNumber === myNumberObj; // = false if (0){ // 0 est falsy, le code ne fonctionnera pas. } -if (Number(0)){ - // Parce que Number(0) est truthy, le code fonctionnera -} // Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à // cette particularité. diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown new file mode 100644 index 00000000..49c95820 --- /dev/null +++ b/fr-fr/json-fr.html.markdown @@ -0,0 +1,62 @@ +--- +language: json +filename: learnjson-fr.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Alois de Gouvello","https://github.com/aloisdg"] +lang: fr-fr +--- + +Comme JSON est un format d'échange de données extrêmement simple, ce Apprendre X en Y minutes +est susceptible d'être le plus simple jamais réalisé. + +JSON dans son état le plus pur n'a aucun commentaire, mais la majorité des parseurs accepterons +les commentaires du langage C (`//`, `/* */`). Pour les besoins de ce document, cependant, +tout sera du JSON 100% valide. Heureusement, il s'explique par lui-même. + + +```json +{ + "Clé": "valeur", + + "Clés": "devront toujours être entourées par des guillemets", + "nombres": 0, + "chaînes de caractères": "Hellø, wørld. Tous les caractères Unicode sont autorisés, accompagné d'un \"caractère d'échappement\".", + "a des booléens ?": true, + "rien": null, + + "grand nombre": 1.2e+100, + + "objets": { + "commentaire": "La majorité de votre strucutre sera des objets.", + + "tableau": [0, 1, 2, 3, "Les tableaux peuvent contenir n'importe quoi.", 5], + + "un autre objet": { + "commentaire": "Ces choses peuvent être imbriquées. C'est très utile." + } + }, + + "bêtises": [ + { + "sources de potassium": ["bananes"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "style alternatif": { + "commentaire": "regarde ça !" + , "position de la virgule": "n'a pas d'importance - aussi longtemps qu'elle est avant la valeur, alors elle est valide." + , "un autre commentaire": "comme c'est gentil" + }, + + "C'était court": "Et, vous avez terminé. Maintenant, vous savez tout ce que JSON a à offrir." +} +``` diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown new file mode 100644 index 00000000..13bbffe5 --- /dev/null +++ b/fr-fr/livescript-fr.html.markdown @@ -0,0 +1,360 @@ +--- +language: LiveScript +filename: learnLivescript-fr.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: + - ["Morgan Bohn", "https://github.com/dotmobo"] +lang: fr-fr +--- + +LiveScript est un langage qui compile en JavaScript. Il a un rapport direct +avec JavaScript, et vous permet d'écrire du JavaScript plus simplement, plus +efficacement et sans répétitivité. LiveScript ajoute non seulement des +fonctionnalités pour écrire du code fonctionnel, mais possède aussi nombre +d'améliorations pour la programmation orientée objet et la programmation +impérative. + +LiveScript est un descendant direct de [Coco][], indirect de [CoffeeScript][], +avec lequel il a beaucoup plus de compatibilité. + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +Vous pouvez contacter l'auteur du guide original en anglais ici : +[@kurisuwhyte](https://twitter.com/kurisuwhyte) + + +```coffeescript +# Comme son cousin CoffeeScript, LiveScript utilise le symbole dièse pour les +# commentaires sur une ligne. + +/* + Les commentaires sur plusieurs lignes utilisent la syntaxe du C. Utilisez-les + si vous voulez préserver les commentaires dans la sortie JavaScript. + */ +``` +```coffeescript +# LiveScript utilise l'indentation pour délimiter les blocs de code plutôt que +# les accolades, et les espaces pour appliquer les fonctions (bien que les +# parenthèses soient utilisables). + + +######################################################################## +## 1. Valeurs basiques +######################################################################## + +# Les valeurs non définies sont représentées par le mot clé `void` à la place de +# `undefined` +void # comme `undefined` mais plus sûr (ne peut pas être redéfini) + +# Une valeur non valide est représentée par Null. +null + + +# Les booléens s'utilisent de la façon suivante: +true +false + +# Et il existe divers alias les représentant également: +on; off +yes; no + + +# Puis viennent les nombres entiers et décimaux. +10 +0.4 # Notez que le `0` est requis + +# Dans un souci de lisibilité, vous pouvez utiliser les tirets bas et les +# suffixes sur les nombres. Il seront ignorés à la compilation. +12_344km + + +# Les chaînes sont des séquences immutables de caractères, comme en JS: +"Christina" # Les apostrophes fonctionnent également! +"""Multi-line + strings + are + okay + too.""" + +# De temps à autre, vous voulez encoder un mot clé; la notation en backslash +# rend cela facile: +\keyword # => 'keyword' + + +# Les tableaux sont des collections ordonnées de valeurs. +fruits = + * \apple + * \orange + * \pear + +# Il peuvent être écrits de manière plus consises à l'aide des crochets: +fruits = [ \apple, \orange, \pear ] + +# Vous pouvez également utiliser la syntaxe suivante, à l'aide d'espaces, pour +# créer votre liste de valeurs: +fruits = <[ apple orange pear ]> + +# Vous pouvez récupérer une entrée à l'aide de son index: +fruits[0] # => "apple" + +# Les objets sont une collection non ordonnées de paires clé/valeur, et +# d'autres choses (que nous verrons plus tard). +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# A nouveau, vous pouvez utiliser une expression plus consise à l'aide des +# accolades: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# Vous pouvez récupérer une entrée via sa clé: +person.name # => "Christina" +person["name"] # => "Christina" + + +# Les expressions régulières utilisent la même syntaxe que JavaScript: +trailing-space = /\s$/ # les mots-composés deviennent motscomposés + +# A l'exception que vous pouvez pouvez utiliser des expressions sur plusieurs +# lignes! +# (les commentaires et les espaces seront ignorés) +funRE = // + function\s+(.+) # nom + \s* \((.*)\) \s* # arguments + { (.*) } # corps + // + + +######################################################################## +## 2. Les opérations basiques +######################################################################## + +# Les opérateurs arithmétiques sont les mêmes que pour JavaScript: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# Les comparaisons sont presque identiques, à l'exception que `==` équivaut au +# `===` de JS, là où le `==` de JS est `~=` en LiveScript, et `===` active la +# comparaison d'objets et de tableaux, ainsi que les comparaisons strictes +# (sans conversion de type) +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# Les opérateurs suivants sont également disponibles: <, <=, > et >= + +# Les valeurs logiques peuvent être combinéees grâce aux opérateurs logiques +# `or`, `and` et `not` +true and false # => false +false or true # => true +not false # => true + + +# Les collections ont également des opérateurs additionnels +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. Fonctions +######################################################################## + +# Puisque LiveScript est fonctionnel, vous vous attendez à une bonne prise en +# charge des fonctions. En LiveScript, il est encore plus évident que les +# fonctions sont de premier ordre: +add = (left, right) -> left + right +add 1, 2 # => 3 + +# Les fonctions qui ne prennent pas d'arguments peuvent être appelées avec un +# point d'exclamation! +two = -> 2 +two! + +# LiveScript utilise l'environnement de la fonction, comme JavaScript. +# A l'inverse de JavaScript, le `=` fonctionne comme un opérateur de +# déclaration, et il déclarera toujours la variable située à gauche (sauf si +# la variable a été déclarée dans l'environnement parent). + +# L'opérateur `:=` est disponible pour réutiliser un nom provenant de +# l'environnement parent. + + +# Vous pouvez extraire les arguments d'une fonction pour récupérer +# rapidement les valeurs qui vous intéressent dans une structure de données +# complexe: +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# Vous pouvez également transformer les arguments en utilisant les opérateurs +# binaires et unaires. Définir des arguments par défaut est aussi possible. +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# You pouvez utiliser cela pour cloner un argument en particulier pour éviter +# les effets secondaires. Par exemple: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# Une fonction peut être curryfiée en utilisant une longue flèche à la place +# d'une courte: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# Les fonctions ont un argument `it` implicite si vous n'en déclarez pas: +identity = -> it +identity 1 # => 1 + +# Les opérateurs ne sont pas des fonctions en LiveScript, mais vous pouvez +# facilement les transformer en fonction: +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two).reduce (+) + +# Comme dans tout bon langage fonctionnel, vous pouvez créer des fonctions +# composées d'autres fonctions: +double-minus-one = (- 1) . (* 2) + +# En plus de la formule mathématique `f . g`, vous avez les opérateurs `>>` +# et `<<`, qui décrivent l'ordre d'application des fonctions composées. +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# Pour appliquer une valeur à une fonction, vous pouvez utiliser les opérateurs +# `|>` et `<|`: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# La version sans pipe correspond à: +((map (* 2)) [1, 2, 3]) + +# You pouvez aussi choisir où vous voulez que la valeur soit placée, en +# marquant la position avec un tiret bas (_): +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# Le tiret bas est également utilisé pour l'application partielle, +# que vous pouvez utiliser pour toute fonction: +div = (left, right) -> left / right +div-by-two = div _, 2 +div-by-two 4 # => 2 + + +# Pour conclure, LiveScript vous permet d'utiliser les fonctions de rappel. +# (mais vous devriez essayer des approches plus fonctionnelles, comme +# Promises). +# Un fonction de rappel est une fonction qui est passée en argument à une autre +# fonction: +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# Equivalent à: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. Conditionnalités +######################################################################## + +# Vous pouvez faire de la conditionnalité à l'aide de l'expression `if...else`: +x = if n > 0 then \positive else \negative + +# A la place de `then`, vous pouvez utiliser `=>` +x = if n > 0 => \positive + else \negative + +# Pour les conditions complexes, il vaut mieux utiliser l'expresssion `switch`: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` et `_` correspondent. + +# Le corps des fonctions, les déclarations et les assignements disposent d'un +# `switch` implicite, donc vous n'avez pas besoin de le réécrire: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. Compréhensions +######################################################################## + +# Comme en python, vous allez pouvoir utiliser les listes en compréhension, +# ce qui permet de générer rapidement et de manière élégante une liste de +# valeurs: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# `when` et `unless` peuvent être utilisés comme des filtres. + +# Cette technique fonctionne sur les objets de la même manière. Vous allez +# pouvoir générer l'ensemble de paires clé/valeur via la syntaxe suivante: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 4. Programmation orientée objet +######################################################################## + +# Bien que LiveScript soit un langage fonctionnel, il dispose d'intéressants +# outils pour la programmation objet. La syntaxe de déclaration d'une classe +# est héritée de CoffeeScript: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# En plus de l'héritage classique, vous pouvez utiliser autant de mixins +# que vous voulez pour votre classe. Les mixins sont juste des objets: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## Lectures complémentaires + +Il y a beaucoup plus de choses à dire sur LiveScript, mais ce guide devrait +suffire pour démarrer l'écriture de petites fonctionnalités. +Le [site officiel](http://livescript.net/) dispose de beaucoup d'information, +ainsi que d'un compilateur en ligne vous permettant de tester le langage! + +Jetez également un coup d'oeil à [prelude.ls](http://gkz.github.io/prelude-ls/), +et consultez le channel `#livescript` sur le réseau Freenode. diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index b4e2a161..1f592320 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -434,9 +434,9 @@ les librairies standard: Autres références complémentaires: -* <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">Lua for programmers</a> -* <a href="lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Courte de référence de Lua</a> -* <a href="http://www.lua.org/pil/contents.html">Programming In Lua</a> +* <a href="http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/">Lua pour programmeurs</a> +* <a href="lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf">Référence condensée de Lua</a> +* <a href="http://www.lua.org/pil/contents.html">Programmer en Lua</a> * <a href="http://www.lua.org/manual/">Les manuels de référence Lua</a> A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et @@ -446,4 +446,4 @@ Ce tutoriel a été originalement écrit pour <a href="tylerneylon.com">tylerney disponible en tant que <a href="https://gist.github.com/tylerneylon/5853042">gist</a>. Il a été traduit en français par Roland Yonaba (voir son <a href="http://github.com/Yonaba">github</a>). -Amusez-vous bien avec Lua!
\ No newline at end of file +Amusez-vous bien avec Lua! diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 29c0d65d..66f0efbe 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -2,7 +2,7 @@ language: markdown contributors: - ["Andrei Curelaru", "http://www.infinidad.fr"] -filename: markdown.md +filename: markdown-fr.md lang: fr-fr --- @@ -177,7 +177,7 @@ des syntaxes spécifiques --> \`\`\`ruby <!-- mais enlevez les backslashes quand vous faites ça, -gardez juste ```ruby ( ou nom de la synatxe correspondant à votre code )--> +gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )--> def foobar puts "Hello world!" end diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown index 69f4d8f9..4e31c4bf 100644 --- a/fr-fr/objective-c-fr.html.markdown +++ b/fr-fr/objective-c-fr.html.markdown @@ -14,7 +14,7 @@ lang: fr-fr L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch. -```objective_c +```objective-c // Les commentaires sur une seule ligne commencent par // /* diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown new file mode 100644 index 00000000..e737b7aa --- /dev/null +++ b/fr-fr/perl-fr.html.markdown @@ -0,0 +1,174 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-fr.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] + - ["Matteo Taroli", "http://www.matteotaroli.be"] +translators: + - ["Matteo Taroli", "http://www.matteotaroli.be"] +lang: fr-fr +--- +Perl 5 est un langage de programmation riche en fonctionnalité, avec plus de 25 ans de développement. + +Perl 5 fonctionne sur plus de 100 plateformes, allant des pc portables aux mainframes et +est autant adapté à un prototypage rapide qu'à des projets de grande envergure. + +```perl +# Les commentaires en une ligne commencent par un dièse + + +#### Types de variables de Perl + +# Les variables comment par un symbole précisant le type. +# Un nom de variable valide commence par une lettre ou un underscore, +# suivi d'un nombre quelconque de lettres, chiffres ou underscores. + +### Perl a trois types principaux de variables: $scalaire, @tableau and %hash + +## Scalaires +# Un scalaire représente une valeur unique : +my $animal = "chameau"; +my $reponse = 42; + +# Les valeurs scalaires peuvent être des strings, des entiers ou des nombres à virgule flottante +# et Perl les convertira automatiquement entre elles quand nécessaire. + +## Tableaux +# Un tableau représente une liste de valeurs : +my @animaux = ("chameau", "lama", "chouette"); +my @nombres = (23, 42, 69); +my @melange = ("chameau", 42, 1.23); + +## Hashes +# Un hash représente un ensemble de paires de clé/valeur : +my %fruit_couleur = ("pomme", "rouge", "banane", "jaune"); + +# Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment : + +my %fruit_couleur = ( + pomme => "rouge", + banane => "jaune" +); + +# Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata +# (perldoc perldata) + +# Des types de données plus complexes peuvent être construits en utilisant des références, +# vous permettant de construire des listes et des hashes à l'intérieur d'autres listes et hashes. + +#### Conditions et boucles + +# Perl possède la plupart des conditions et boucles habituelles. + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (condition) { + ... +} +# Ceci est fourni en tant que version plus lisible de "if (!condition)" + +# la postcondition à la sauce Perl + +print "Yow!" if $zippy; +print "Nous n'avons pas de banane." unless $bananes; + +# while +while (condition) { + ... +} + +# boucle for et iteration +for (my $i = 0; $i < $max; $i++) { + print "l'index est $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "L'élément courant est " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# implicitement + +# La variable de contexte scalaire $_ est utilisée par défaut dans différentes +# situations, comme par exemple dans la boucle foreach ou en argument par défaut +# de la plupart des fonctions pour en simplifier l'écriture. + +# Dans l'exemple suivant, $_ prends successivement la valeur de +# chaque élément de la liste. + +for (@elements) { + print; # affiche le contenu de $_ +} + + +#### Expressions régulières + +# Le support des expressions régulières par Perl est aussi large que profond +# et est sujet à une longue documentation sur perlrequick, perlretut et ailleurs. +# Cependant, pour faire court : + +# Simple correspondance +if (/foo/) { ... } # vrai si $_ contient "foo" +if ($a =~ /foo/) { ... } # vrai si $a contient "foo" + +# Simple substitution + +$a =~ s/foo/bar/; # remplace le premier foo par bar dans $a +$a =~ s/foo/bar/g; # remplace TOUTES LES INSTANCES de foo par bar dans $a + + +#### Fichiers et E/S + +# Vous pouvez ouvrir un fichier pour y écrire ou pour le lire avec la fonction "open()". + +open(my $in, "<", "input.txt") or die "Impossible d'ouvrir input.txt: $!"; +open(my $out, ">", "output.txt") or die "Impossible d'ouvrir output.txt: $!"; +open(my $log, ">>", "my.log") or die "Impossible d'ouvrir my.log: $!"; + +# Vous pouvez lire depuis un descripteur de fichier grâce à l'opérateur "<>". +# Dans un contexte scalaire, il lit une seule ligne depuis le descripteur de fichier +# et dans un contexte de liste, il lit le fichier complet, assignant chaque ligne à un +# élément de la liste : + +my $ligne = <$in> +my $lignes = <$in> + +#### Ecrire des fonctions + +# Ecrire des fonctions est facile : + +sub logger { + my $logmessage = shift; + + open my $logfile, ">>", "my.log" or die "Impossible d'ouvrir my.log: $!"; + + print $logfile $logmessage; +} + +# Maintenant, nous pouvons utiliser cette fonction comme n'importe quelle fonction intégrée : + +logger("On a une fonction de logging!!"); +``` + +#### Utiliser des modules Perl + +Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl. + +Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser. + +#### Pour en savoir plus + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` diff --git a/fr-fr/php.html.markdown b/fr-fr/php.html.markdown new file mode 100644 index 00000000..f4eaf396 --- /dev/null +++ b/fr-fr/php.html.markdown @@ -0,0 +1,696 @@ +--- +language: PHP +contributors: + - ["Malcolm Fell", "http://emarref.net/"] + - ["Trismegiste", "https://github.com/Trismegiste"] +translators: + - ["Pascal Boutin", "http://pboutin.net/"] +lang: fr-fr +--- + +This document describes PHP 5+. + +```php + // Le code PHP doit être placé à l'intérieur de balises '<?php' + +// Si votre fichier php ne contient que du code PHP, il est +// généralement recommandé de ne pas fermer la balise '?>' + +// Deux barres obliques amorcent un commentaire simple. + +# Le dièse aussi, bien que les barres obliques soient plus courantes + +/* + Les barres obliques et les astérisques peuvent être utilisés + pour faire un commentaire multi-lignes. +*/ + +// Utilisez "echo" ou "print" afficher une sortie +print('Hello '); // Affiche "Hello " sans retour à la ligne + +// Les parenthèses sont facultatives pour print et echo +echo "World\n"; // Affiche "World" avec un retour à la ligne + +// toutes les instructions doivent se terminer par un point-virgule + +// Tout ce qui se trouve en dehors des <?php ?> est automatiquement +// affiché en sortie +Hello World Again! +<?php + + +/************************************ + * Types & Variables + */ + +// Les noms de variables débutent par le symbole $ +// Un nom de variable valide commence par une lettre ou un souligné, +// suivi de n'importe quelle lettre, nombre ou de soulignés. + +// Les valeurs booléenes ne sont pas sensibles à la casse +$boolean = true; // ou TRUE ou True +$boolean = false; // ou FALSE ou False + +// Entiers (integers) +$int1 = 12; // => 12 +$int2 = -12; // => -12 +$int3 = 012; // => 10 (un 0 devant la valeur désigne une valeur octale) +$int4 = 0x0F; // => 15 (un 0x devant la valeur désigne une valeur hexadécimale) + +// Réels (floats, doubles) +$float = 1.234; +$float = 1.2e3; +$float = 7E-10; + +// Suppression d'une variable +unset($int1); + +// Arithmétique +$sum = 1 + 1; // 2 (addition) +$difference = 2 - 1; // 1 (soustraction) +$product = 2 * 2; // 4 (produit) +$quotient = 2 / 1; // 2 (division) + +// Arithmétique (raccourcis) +$number = 0; +$number += 2; // Incrémente $number de 2 +echo $number++; // Affiche 2 (incrémente après l'évaluation) +echo ++$number; // Affiche 4 (incrémente avant l'évaluation) +$number /= $float; // Divise et assigne le quotient à $number + +// Les chaînes de caractères (strings) doivent être à +// l'intérieur d'une paire d'apostrophes +$sgl_quotes = '$String'; // => '$String' + +// Évitez les guillemets sauf pour inclure le contenu d'une autre variable +$dbl_quotes = "This is a $sgl_quotes."; // => 'This is a $String.' + +// Les caractères spéciaux sont seulement échappés avec des guillemets +$escaped = "This contains a \t tab character."; +$unescaped = 'This just contains a slash and a t: \t'; + +// En cas de besoin, placez la variable dans des accolades +$money = "I have $${number} in the bank."; + +// Depuis PHP 5.3, Nowdoc peut être utilisé pour faire des chaînes +// multi-lignes non-interprétées +$nowdoc = <<<'END' +Multi line +string +END; + +// Heredoc peut être utilisé pour faire des chaînes multi-lignes interprétées +$heredoc = <<<END +Multi line +$sgl_quotes +END; + +// La concaténation de chaînes se fait avec un . +echo 'This string ' . 'is concatenated'; + + +/******************************** + * Constantes + */ + +// Une constante est déclarée avec define() +// et ne peut jamais être changée durant l'exécution + +// un nom valide de constante commence par une lettre ou un souligné, +// suivi de n'importe quelle lettre, nombre ou soulignés. +define("FOO", "something"); + +// on peut accéder à une constante en utilisant directement son nom +echo 'This outputs '.FOO; + + +/******************************** + * Tableaux (array) + */ + +// Tous les tableaux en PHP sont associatifs (hashmaps), + +// Fonctionne dans toutes les versions de PHP +$associative = array('One' => 1, 'Two' => 2, 'Three' => 3); + +// PHP 5.4 a introduit une nouvelle syntaxe +$associative = ['One' => 1, 'Two' => 2, 'Three' => 3]; + +echo $associative['One']; // affiche 1 + +// Dans une liste simple, l'index est automatiquement attribué en tant que clé +$array = ['One', 'Two', 'Three']; +echo $array[0]; // => "One" + +// Ajoute un élément à la fin du tableau +$array[] = 'Four'; + +// Retrait d'un élément du tableau +unset($array[3]); + +/******************************** + * Affichage + */ + +echo('Hello World!'); +// Affiche Hello World! dans stdout. +// Stdout est la page web si on exécute depuis un navigateur. + +print('Hello World!'); // Pareil à "écho" + +// Pour écho, vous n'avez pas besoin des parenthèses +echo 'Hello World!'; +print 'Hello World!'; // Pour print non plus + +$paragraph = 'paragraph'; + +echo 100; // Affichez un scalaire directement +echo $paragraph; // ou des variables + +// Si le raccourci de sortie est configuré, ou si votre version de PHP est +// 5.4.0+, vous pouvez utiliser ceci: +?> +<p><?= $paragraph ?></p> +<?php + +$x = 1; +$y = 2; +$x = $y; // $x contient maintenant la même valeur que $y +$z = &$y; +// $z contient une référence vers $y. Changer la valeur de +// $z changerait également la valeur de $y, et vice-versa. +// $x resterait inchangé comme la valeur initiale de $y + +echo $x; // => 2 +echo $z; // => 2 +$y = 0; +echo $x; // => 2 +echo $z; // => 0 + +// Affiche le type et la valeur de la variable dans stdout +var_dump($z); // prints int(0) + +// Affiche la variable dans stdout dans un format plus convivial +print_r($array); // prints: Array ( [0] => One [1] => Two [2] => Three ) + +/******************************** + * Logique + */ +$a = 0; +$b = '0'; +$c = '1'; +$d = '1'; + +// assert affiche un avertissement dans son argument n'est pas vrai + +// Ces comparaisons vont toujours être vraies, même si leurs +// types ne sont pas les mêmes. +assert($a == $b); // égalité +assert($c != $a); // inégalité +assert($c <> $a); // inégalité (moins courant) +assert($a < $c); +assert($c > $b); +assert($a <= $b); +assert($c >= $d); + +// Ces comparaisons vont seulement être vraies si les types concordent. +assert($c === $d); +assert($a !== $d); +assert(1 === '1'); +assert(1 !== '1'); + +// Opérateur 'spaceship' depuis PHP 7 +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 car ils sont égaux +echo $a <=> $b; // -1 car $a < $b +echo $b <=> $a; // 1 car $b > $a + +// Les variables peuvent être transtypées dépendamment de leur usage. + +$integer = 1; +echo $integer + $integer; // => 2 + +$string = '1'; +echo $string + $string; // => 2 + +$string = 'one'; +echo $string + $string; // => 0 +// Donne 0 car l'opérateur + ne peut pas transtyper la chaîne 'one' en un nombre + +// On peut également transtyper manuellement pour utiliser +// une variable dans un autre type + +$boolean = (boolean) 1; // => true + +$zero = 0; +$boolean = (boolean) $zero; // => false + +// Il y a également des fonctions dédiées pour transtyper +$integer = 5; +$string = strval($integer); + +$var = null; // Valeur nulle + + +/******************************** + * Structures de contrôle + */ + +if (true) { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne le suis pas'; +} else { + print 'Je suis affiché'; +} + +if (false) { + print 'Je ne suis pas affiché'; +} elseif (true) { + print 'Je le suis'; +} + +// Opérateur ternaire +print (false ? 'N\'est pas affiché' : 'L\'est'); + +// Opérateur ternaire depuis PHP 5.3 +// équivalent de $x ? $x : 'Does' +$x = false; +print($x ?: 'Does'); + +// depuis PHP 7, on peut facilement vérifier si une valeur est nulle +$a = null; +$b = 'Hello World'; +echo $a ?? 'a is not set'; // Affiche 'a is not set' +echo $b ?? 'b is not set'; // Affiche 'Hello World' + + +$x = 0; +if ($x === '0') { + print 'Pas affiché'; +} elseif($x == '1') { + print 'Pas affiché'; +} else { + print 'Affiché'; +} + + +// Cette syntaxe alternative est particulièrement utile avec du HTML: +?> + +<?php if ($x): ?> +<p>Ceci est affiché si $x est vrai</p> +<?php else: ?> +<p>Ceci est affiché si $x est faux</p> +<?php endif; ?> + +<?php + +// On peut également utiliser une condition multiple (switch case) +switch ($x) { + case '0': + print 'Les switch font du transtypage implicite'; + break; // Il est important de déclaré un 'break', sinon les cas + // 'two' et 'three' seront évalués + case 'two': + case 'three': + // Si $x == 'two' || $x == 'three' + break; + default: + // Si aucun cas n'a été vrai +} + +// Structures itératives (for, while, do while) +$i = 0; +while ($i < 5) { + echo $i++; +}; // Affiche "01234" + +echo "\n"; + +$i = 0; +do { + echo $i++; +} while ($i < 5); // Affiche "01234" + +echo "\n"; + +for ($x = 0; $x < 10; $x++) { + echo $x; +} // Affiche "0123456789" + +echo "\n"; + +$wheels = ['bicycle' => 2, 'car' => 4]; + +// Les boucles 'foreach' sont utiles pour parcourir les tableaux +foreach ($wheels as $wheel_count) { + echo $wheel_count; +} // Affiche "24" + +echo "\n"; + +// Il est également possible d'accéder aux clés du tableau +foreach ($wheels as $vehicle => $wheel_count) { + echo "The $vehicle have $wheel_count wheels"; +} + +echo "\n"; + +$i = 0; +while ($i < 5) { + if ($i === 3) { + break; // Permet d'arrêter la boucle + } + echo $i++; +} // Affiche "012" + +for ($i = 0; $i < 5; $i++) { + if ($i === 3) { + continue; // Permet de passer immédiatement à l'itération suivante + } + echo $i; +} // Affiche "0124" + + +/******************************** + * Fonctions + */ + +// On peut déclarer une fonction avec le mot clé 'function' +function my_function () { + return 'Hello'; +} + +echo my_function(); // => "Hello" + + +// Les noms de fonction débutent par le symbole $ +// Un nom de variable valide commence par une lettre ou un souligné, +// suivi de n'importe quelle lettre, nombre ou de soulignés. + +function add ($x, $y = 1) { // $y est facultatif et sa valeur par défaut est 1 + $result = $x + $y; + return $result; +} + +echo add(4); // => 5 +echo add(4, 2); // => 6 + +// $result n'est pas accessible en dehors de la fonction +// print $result; // Retourne un avertissement + +// Depuis PHP 5.3 on peut déclarer des fonctions anonymes +$inc = function ($x) { + return $x + 1; +}; + +echo $inc(2); // => 3 + +function foo ($x, $y, $z) { + echo "$x - $y - $z"; +} + +// Une fonction peut retourner une fonction +function bar ($x, $y) { + // On peut utiliser 'use' pour passer des variables externes + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; +} + +$bar = bar('A', 'B'); +$bar('C'); // Affiche "A - B - C" + +// On peut exécuter une fonction par son nom en chaîne de caractères +$function_name = 'add'; +echo $function_name(1, 2); // => 3 +// Utile pour déterminer par programmation quelle fonction exécuter. + +// On peut également utiliser +call_user_func(callable $callback [, $parameter [, ... ]]); + +/******************************** + * Insertions + */ + +<?php +// Le PHP se trouvant dans un fichier inclus doit +// également commencer par une balise PHP. + +include 'my-file.php'; +// Le code se trouvant dans my-file.php est maintenant disponible dans +// le contexte courant. Si le fichier ne peut pas être inclus +// (ex. non trouvé), un avertissement sera émit. + +include_once 'my-file.php'; +// Si le code dans my-file.php a déjà été inclus ailleur, il ne va pas +// être inclus de nouveau. + +require 'my-file.php'; +require_once 'my-file.php'; +// Même comportement que include() mais déclenche une érreur fatale si le fichier ne peux pas être inclus. + +// Contenu de my-include.php: +<?php + +return 'Anything you like.'; +// Fin de my-include.php + +// include() et require() peuvent également retourner une valeur +$value = include('my-include.php'); + +// Les fichiers sont inclus depuis le chemin donné ou, si aucun chemin n'est donné, +// la configuration 'include_path'. Si le fichier n'est pas trouvé dans le 'include_path', +// include va finalement vérifier dans le répertoire courant avant d'échouer. + +/******************************** + * Classes + */ + +// Les classes sont définies avec le mot clé 'class' + +class MyClass +{ + const MY_CONST = 'value'; // Une constante + + static $staticVar = 'static'; + + // Variables statiques et leur visibilité + public static $publicStaticVar = 'publicStatic'; + // Accessible à l'intérieur de la classe seulement + private static $privateStaticVar = 'privateStatic'; + // Accessible à l'intérieur de la classe et des classes enfants + protected static $protectedStaticVar = 'protectedStatic'; + + // Les attributs doivent définir leur visibilité + public $property = 'public'; + public $instanceProp; + protected $prot = 'protected'; + private $priv = 'private'; + + // Déclaration d'un constructeur avec __construct + public function __construct($instanceProp) { + // Access instance variables with $this + $this->instanceProp = $instanceProp; + } + + // Les méthodes sont déclarés par des fonctions au sein de la classe + public function myMethod() + { + print 'MyClass'; + } + + // le mot clé 'final' rend la function impossible à surcharger + final function youCannotOverrideMe() + { + } + +/* + * Les attributs et méthodes statiques peuvent être accédés sans devoir + * instancier la classe. Les attributs statiques ne sont pas accessibles depuis + * une instance, même si les méthodes statiques le sont. + */ + + public static function myStaticMethod() + { + print 'I am static'; + } +} + +// Les constantes d'une classe peuvent toujours être utilisé de façon statique +echo MyClass::MY_CONST; // Outputs 'value'; + +echo MyClass::$staticVar; // Retourne 'static'; +MyClass::myStaticMethod(); // Retourne 'I am static'; + +// On peut instancier une classe en utilisant le mot clé 'new' +$my_class = new MyClass('An instance property'); + +// On peut accéder aux attributs/méthodes d'une instance avec -> +echo $my_class->property; // => "public" +echo $my_class->instanceProp; // => "An instance property" +$my_class->myMethod(); // => "MyClass" + + +// On peut hériter d'une classe en utilisant 'extends' +class MyOtherClass extends MyClass +{ + function printProtectedProperty() + { + echo $this->prot; + } + + // Surcharge d'une méthode + function myMethod() + { + parent::myMethod(); + print ' > MyOtherClass'; + } +} + +$my_other_class = new MyOtherClass('Instance prop'); +$my_other_class->printProtectedProperty(); // => Retourne "protected" +$my_other_class->myMethod(); // Retourne "MyClass > MyOtherClass" + +// On peut empêcher qu'une classe soit héritée +final class YouCannotExtendMe +{ +} + +// On peut utiliser des "méthodes magiques" pour se faire des accesseurs +class MyMapClass +{ + private $property; + + public function __get($key) + { + return $this->$key; + } + + public function __set($key, $value) + { + $this->$key = $value; + } +} + +$x = new MyMapClass(); +echo $x->property; // Va utiliser la méthode __get() +$x->property = 'Something'; // Va utiliser la méthode __set() + +// Les classes peuvent être abstraites (en utilisant le mot clé 'abstract'), ou +// elle peuvent implémenter une interface (en utilisant le mot clé 'implement'). + +// Une interface peut être déclarée avec le mot clé 'interface' + +interface InterfaceOne +{ + public function doSomething(); +} + +interface InterfaceTwo +{ + public function doSomethingElse(); +} + +// Les interfaces peuvent hériter d'autres interfaces +interface InterfaceThree extends InterfaceTwo +{ + public function doAnotherContract(); +} + +abstract class MyAbstractClass implements InterfaceOne +{ + public $x = 'doSomething'; +} + +class MyConcreteClass extends MyAbstractClass implements InterfaceTwo +{ + public function doSomething() + { + echo $x; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + + +// Les classes peuvent implémenter plusieurs interfaces à la fois +class SomeOtherClass implements InterfaceOne, InterfaceTwo +{ + public function doSomething() + { + echo 'doSomething'; + } + + public function doSomethingElse() + { + echo 'doSomethingElse'; + } +} + +/******************************** + * Espaces de noms (namespaces) + */ + +// Cette section est séparée, car une déclaration d'espace de nom doit être +// la première chose que l'on retrouve dans un fichier PHP, +// imaginons que c'est le cas + +<?php + +// Par défaut, les classes existent dans l'espace de nom global et peuvent +// être appelé explicitement avec un antislash. + +$cls = new \MyClass(); + + + +// On peut spécifier l'espace de nom d'un fichier comme cela +namespace My\Namespace; + +class MyClass +{ +} + +// (depuis un autre fichier...) +$cls = new My\Namespace\MyClass; + +// Ou depuis un autre espace de nom +namespace My\Other\Namespace; + +use My\Namespace\MyClass; + +$cls = new MyClass(); + +// On peut également utiliser un alias sur un espace de nom + +namespace My\Other\Namespace; + +use My\Namespace as SomeOtherNamespace; + +$cls = new SomeOtherNamespace\MyClass(); + +*/ + +``` + +## Pour plus d'informations + +Visitez la [documentation officielle](http://www.php.net/manual/fr). + +Si vous êtes intéressé par les bonnes pratiques, visitez +[PHP The Right Way](http://www.phptherightway.com/) (anglais seulement). + +Si vous êtes habitué à utiliser de bons gestionaires de dépendances, regardez +[Composer](http://getcomposer.org/). + +Pour consulter les standards, visitez "the PHP Framework Interoperability Groups" +[PSR standards](https://github.com/php-fig/fig-standards). diff --git a/fr-fr/python-fr.html.markdown b/fr-fr/python-fr.html.markdown index 58a036ba..d78291be 100644 --- a/fr-fr/python-fr.html.markdown +++ b/fr-fr/python-fr.html.markdown @@ -14,12 +14,11 @@ Je suis tombé amoureux de Python de par la clarté de sa syntaxe. C'est pratiqu Vos retours sont grandement appréciés. Vous pouvez me contacter sur Twitter [@louiedinh](http://twitter.com/louiedinh) ou par e-mail: louiedinh [at] [google's email service] -NB: Cet artice s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x -Vous pourrez bientôt trouver un article pour Python 3! +N.B. : Cet article s'applique spécifiquement à Python 2.7, mais devrait s'appliquer pour toute version Python 2.x. Python 2.7 est en fin de vie et ne sera plus maintenu à partir de 2020, il est donc recommandé d'apprendre Python avec Python 3. Pour Python 3.x, il existe un autre [tutoriel pour Python 3](http://learnxinyminutes.com/docs/fr-fr/python3-fr/). ```python # Une ligne simple de commentaire commence par un dièse -""" Les lignes de commenatires multipes peuvent être écrites +""" Les lignes de commentaires multipes peuvent être écrites en utilisant 3 guillemets ("), et sont souvent utilisées pour les commentaires """ diff --git a/fr-fr/python3-fr.html.markdown b/fr-fr/python3-fr.html.markdown new file mode 100644 index 00000000..04d0a55d --- /dev/null +++ b/fr-fr/python3-fr.html.markdown @@ -0,0 +1,723 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] +translators: + - ["Gnomino", "https://github.com/Gnomino"] +filename: learnpython3-fr.py +lang: fr-fr +--- + +Python a été créé par Guido Van Rossum au début des années 90. C'est maintenant un des +langages les populaires. Je suis tombé amoureux de Python pour la clarté de sa syntaxe. +C'est tout simplement du pseudo-code exécutable. + +L'auteur original apprécierait les retours (en anglais): vous pouvez le contacter sur Twitter à [@louiedinh](http://twitter.com/louiedinh) ou par mail à l'adresse louiedinh [at] [google's email service] + +Note : Cet article s'applique spécifiquement à Python 3. Jettez un coup d'oeil [ici](http://learnxinyminutes.com/docs/fr-fr/python-fr/) pour apprendre le vieux Python 2.7 + +```python + +# Un commentaire d'une ligne commence par un dièse + +""" Les chaînes de caractères peuvent être écrites + avec 3 guillemets doubles ("), et sont souvent + utilisées comme des commentaires. +""" + +#################################################### +## 1. Types de données primaires et opérateurs +#################################################### + +# On a des nombres +3 # => 3 + +# Les calculs sont ce à quoi on s'attend +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Sauf pour la division qui retourne un float (nombre à virgule flottante) +35 / 5 # => 7.0 + +# Résultats de divisions entières tronqués pour les nombres positifs et négatifs +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Quand on utilise un float, le résultat est un float +3 * 2.0 # => 6.0 + +# Modulo (reste de la division) +7 % 3 # => 1 + +# Exponentiation (x**y, x élevé à la puissance y) +2**4 # => 16 + +# Forcer la priorité de calcul avec des parenthèses +(1 + 3) * 2 # => 8 + +# Les valeurs booléennes sont primitives +True +False + +# Négation avec not +not True # => False +not False # => True + +# Opérateurs booléens +# On note que "and" et "or" sont sensibles à la casse +True and False #=> False +False or True #=> True + +# Utilisation des opérations booléennes avec des entiers : +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# On vérifie une égalité avec == +1 == 1 # => True +2 == 1 # => False + +# On vérifie une inégalité avec != +1 != 1 # => False +2 != 1 # => True + +# Autres opérateurs de comparaison +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# On peut enchaîner les comparaisons +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is vs. ==) is vérifie si deux variables pointent sur le même objet, mais == vérifie +# si les objets ont la même valeur. +a = [1, 2, 3, 4] # a pointe sur une nouvelle liste, [1, 2, 3, 4] +b = a # b pointe sur a +b is a # => True, a et b pointent sur le même objet +b == a # => True, les objets a et b sont égaux +b = [1, 2, 3, 4] # b pointe sur une nouvelle liste, [1, 2, 3, 4] +b is a # => False, a et b ne pointent pas sur le même objet +b == a # => True, les objets a et b ne pointent pas sur le même objet + +# Les chaînes (ou strings) sont créées avec " ou ' +"Ceci est une chaine" +'Ceci est une chaine aussi.' + +# On peut additionner des chaînes aussi ! Mais essayez d'éviter de le faire. +"Hello " + "world!" # => "Hello world!" +# On peut aussi le faire sans utiliser '+' +"Hello " "world!" # => "Hello world!" + +# On peut traîter une chaîne comme une liste de caractères +"This is a string"[0] # => 'T' + +# .format peut être utilisé pour formatter des chaînes, comme ceci: +"{} peuvent etre {}".format("Les chaînes", "interpolées") + +# On peut aussi réutiliser le même argument pour gagner du temps. +"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") +#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" + +# On peut aussi utiliser des mots clés pour éviter de devoir compter. +"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" + +# Si votre code doit aussi être compatible avec Python 2.5 et moins, +# vous pouvez encore utiliser l'ancienne syntaxe : +"Les %s peuvent être %s avec la %s méthode" % ("chaînes", "interpolées", "vieille") + + +# None est un objet +None # => None + +# N'utilisez pas "==" pour comparer des objets à None +# Utilisez plutôt "is". Cela permet de vérifier l'égalité de l'identité des objets. +"etc" is None # => False +None is None # => True + +# None, 0, and les strings/lists/dicts (chaînes/listes/dictionnaires) valent False lorsqu'ils sont convertis en booléens. +# Toutes les autres valeurs valent True +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Variables et Collections +#################################################### + +# Python a une fonction print pour afficher du texte +print("I'm Python. Nice to meet you!") + +# Par défaut, la fonction print affiche aussi une nouvelle ligne à la fin. +# Utilisez l'argument optionnel end pour changer ce caractère de fin. +print("Hello, World", end="!") # => Hello, World! + +# Pas besoin de déclarer des variables avant de les définir. +# La convention est de nommer ses variables avec des minuscules_et_underscores +some_var = 5 +some_var # => 5 + +# Tenter d'accéder à une variable non définie lève une exception. +# Voir Structures de contrôle pour en apprendre plus sur le traitement des exceptions. +une_variable_inconnue # Lève une NameError + +# Les listes permettent de stocker des séquences +li = [] +# On peut initialiser une liste pré-remplie +other_li = [4, 5, 6] + +# On ajoute des objets à la fin d'une liste avec .append +li.append(1) # li vaut maintenant [1] +li.append(2) # li vaut maintenant [1, 2] +li.append(4) # li vaut maintenant [1, 2, 4] +li.append(3) # li vaut maintenant [1, 2, 4, 3] +# On enlève le dernier élément avec .pop +li.pop() # => 3 et li vaut maintenant [1, 2, 4] +# Et on le remet +li.append(3) # li vaut de nouveau [1, 2, 4, 3] + +# Accès à un élément d'une liste : +li[0] # => 1 +# Accès au dernier élément : +li[-1] # => 3 + +# Accéder à un élément en dehors des limites lève une IndexError +li[4] # Lève une IndexError + +# On peut accéder à une intervalle avec la syntaxe "slice" +# (c'est un rang du type "fermé/ouvert") +li[1:3] # => [2, 4] +# Omettre les deux premiers éléments +li[2:] # => [4, 3] +# Prendre les trois premiers +li[:3] # => [1, 2, 4] +# Sélectionner un élément sur deux +li[::2] # =>[1, 4] +# Avoir une copie de la liste à l'envers +li[::-1] # => [3, 4, 2, 1] +# Pour des "slices" plus élaborées : +# li[debut:fin:pas] + +# Faire une copie d'une profondeur de un avec les "slices" +li2 = li[:] # => li2 = [1, 2, 4, 3] mais (li2 is li) vaut False. + +# Enlever des éléments arbitrairement d'une liste +del li[2] # li is now [1, 2, 3] + +# On peut additionner des listes +# Note: les valeurs de li et other_li ne sont pas modifiées. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Concaténer des listes avec "extend()" +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] + +# Vérifier la présence d'un objet dans une liste avec "in" +1 in li # => True + +# Examiner la longueur avec "len()" +len(li) # => 6 + + +# Les tuples sont comme des listes mais sont immuables. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Lève une TypeError + +# Note : un tuple de taille un doit avoir une virgule après le dernier élément, +# mais ce n'est pas le cas des tuples d'autres tailles, même zéro. +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> + +# On peut utiliser la plupart des opérations des listes sur des tuples. +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Vous pouvez décomposer des tuples (ou des listes) dans des variables +a, b, c = (1, 2, 3) # a vaut 1, b vaut 2 et c vaut 3 +# Les tuples sont créés par défaut sans parenthèses +d, e, f = 4, 5, 6 +# Voyez comme il est facile d'intervertir deux valeurs : +e, d = d, e # d vaut maintenant 5 et e vaut maintenant 4 + + +# Créer un dictionnaire : +empty_dict = {} +# Un dictionnaire pré-rempli : +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Note : les clés des dictionnaires doivent être de types immuables. +# Elles doivent être convertibles en une valeur constante pour une recherche rapide. +# Les types immuables incluent les ints, floats, strings et tuples. +invalid_dict = {[1,2,3]: "123"} # => Lève une TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Par contre, les valeurs peuvent être de tout type. + +# On trouve une valeur avec [] +filled_dict["one"] # => 1 + +# On obtient toutes les clés sous forme d'un itérable avec "keys()" Il faut l'entourer +# de list() pour avoir une liste Note: l'ordre n'est pas garanti. +list(filled_dict.keys()) # => ["three", "two", "one"] + + +# On obtient toutes les valeurs sous forme d'un itérable avec "values()". +# Là aussi, il faut utiliser list() pour avoir une liste. +# Note : l'ordre n'est toujours pas garanti. +list(filled_dict.values()) # => [3, 2, 1] + + +# On vérifie la présence d'une clé dans un dictionnaire avec "in" +"one" in filled_dict # => True +1 in filled_dict # => False + +# L'accès à une clé non-existente lève une KeyError +filled_dict["four"] # KeyError + +# On utilise "get()" pour éviter la KeyError +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# La méthode get accepte une valeur de retour par défaut en cas de valeur non-existante. +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 + +# "setdefault()" insère une valeur dans un dictionnaire si la clé n'est pas présente. +filled_dict.setdefault("five", 5) # filled_dict["five"] devient 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] est toujours 5 + +# Ajouter à un dictionnaire +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # une autre méthode + +# Enlever des clés d'un dictionnaire avec del +del filled_dict["one"] # Enlever la clé "one" de filled_dict. + + +# Les sets stockent des ensembles +empty_set = set() +# Initialiser un set avec des valeurs. Oui, ça ressemble aux dictionnaires, désolé. +some_set = {1, 1, 2, 2, 3, 4} # some_set est maintenant {1, 2, 3, 4} + +# Comme les clés d'un dictionnaire, les éléments d'un set doivent être immuables. +invalid_set = {[1], 1} # => Lève une TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# On peut changer un set : +filled_set = some_set + +# Ajouter un objet au set : +filled_set.add(5) # filled_set vaut maintenant {1, 2, 3, 4, 5} + +# Chercher les intersections de deux sets avec & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# On fait l'union de sets avec | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# On fait la différence de deux sets avec - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# On vérifie la présence d'un objet dans un set avec in +2 in filled_set # => True +10 in filled_set # => False + + + +#################################################### +## 3. Structures de contrôle et Itérables +#################################################### + +# On crée juste une variable +some_var = 5 + +# Voici une condition "si". L'indentation est significative en Python! +# Affiche: "some_var is smaller than 10" +if some_var > 10: + print("some_var is totally bigger than 10.") +elif some_var < 10: # La clause elif ("sinon si") est optionelle + print("some_var is smaller than 10.") +else: # La clause else ("sinon") l'est aussi. + print("some_var is indeed 10.") + + +""" +Les boucles "for" itèrent sur une liste +Affiche: + chien est un mammifère + chat est un mammifère + souris est un mammifère +""" +for animal in ["chien", "chat", "souris"]: + # On peut utiliser format() pour interpoler des chaînes formattées + print("{} est un mammifère".format(animal)) + +""" +"range(nombre)" retourne un itérable de nombres +de zéro au nombre donné +Affiche: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(debut, fin)" retourne un itérable de nombre +de debut à fin. +Affiche: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(debut, fin, pas)" retourne un itérable de nombres +de début à fin en incrémentant de pas. +Si le pas n'est pas indiqué, la valeur par défaut est 1. +Affiche: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + +Les boucles "while" bouclent jusqu'à ce que la condition devienne fausse. +Affiche: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Raccourci pour x = x + 1 + +# On gère les exceptions avec un bloc try/except +try: + # On utilise "raise" pour lever une erreur + raise IndexError("Ceci est une erreur d'index") +except IndexError as e: + pass # Pass signifie simplement "ne rien faire". Généralement, on gère l'erreur ici. +except (TypeError, NameError): + pass # Si besoin, on peut aussi gérer plusieurs erreurs en même temps. +else: # Clause optionelle des blocs try/except. Doit être après tous les except. + print("Tout va bien!") # Uniquement si aucune exception n'est levée. +finally: # Éxécuté dans toutes les circonstances. + print("On nettoie les ressources ici") + +# Au lieu de try/finally pour nettoyer les ressources, on peut utiliser with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Python offre une abstraction fondamentale : l'Iterable. +# Un itérable est un objet pouvant être traîté comme une séquence. +# L'objet retourné par la fonction range() est un itérable. + +filled_dict = {"one": 1, "two": 2, "three": 3} +our_iterable = filled_dict.keys() +print(our_iterable) #=> range(1,10). C'est un objet qui implémente l'interface Iterable + +# On peut boucler dessus +for i in our_iterable: + print(i) # Affiche one, two, three + +# Cependant, on ne peut pas accéder aux éléments par leur adresse. +our_iterable[1] # Lève une TypeError + +# Un itérable est un objet qui sait créer un itérateur. +our_iterator = iter(our_iterable) + +# Notre itérateur est un objet qui se rappelle de notre position quand on le traverse. +# On passe à l'élément suivant avec "next()". +next(our_iterator) #=> "one" + +# Il garde son état quand on itère. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" + +# Après que l'itérateur a retourné toutes ses données, il lève une exception StopIterator +next(our_iterator) # Lève une StopIteration + +# On peut mettre tous les éléments d'un itérateur dans une liste avec list() +list(filled_dict.keys()) #=> Returns ["one", "two", "three"] + + +#################################################### +## 4. Fonctions +#################################################### + +# On utilise "def" pour créer des fonctions +def add(x, y): + print("x est {} et y est {}".format(x, y)) + return x + y # On retourne une valeur avec return + +# Appel d'une fonction avec des paramètres : +add(5, 6) # => affiche "x est 5 et y est 6" et retourne 11 + +# Une autre manière d'appeller une fonction : avec des arguments +add(y=6, x=5) # Les arguments peuvent être dans n'importe quel ordre. + +# Définir une fonction qui prend un nombre variable d'arguments +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# On peut aussi définir une fonction qui prend un nombre variable de paramètres. +def keyword_args(**kwargs): + return kwargs + +# Appelons la pour voir ce qu'il se passe : +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# On peut aussi faire les deux à la fois : +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) affiche: + (1, 2) + {"a": 3, "b": 4} +""" + +# En appelant des fonctions, on peut aussi faire l'inverse : +# utiliser * pour étendre un tuple de paramètres +# et ** pour étendre un dictionnaire d'arguments. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # équivalent à foo(1, 2, 3, 4) +all_the_args(**kwargs) # équivalent à foo(a=3, b=4) +all_the_args(*args, **kwargs) # équivalent à foo(1, 2, 3, 4, a=3, b=4) + +# Retourne plusieurs valeurs (avec un tuple) +def swap(x, y): + return y, x # Retourne plusieurs valeurs avec un tuple sans parenthèses. + # (Note: on peut aussi utiliser des parenthèses) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Là aussi, rien ne nous empêche d'ajouter des parenthèses + +# Portée des fonctions : +x = 5 + +def setX(num): + # La variable locale x n'est pas la même que la variable globale x + x = num # => 43 + print (x) # => 43 + +def setGlobalX(num): + global x + print (x) # => 5 + x = num # la variable globale x est maintenant 6 + print (x) # => 6 + +setX(43) +setGlobalX(6) + + +# Python a des fonctions de première classe +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Mais aussi des fonctions anonymes +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# TODO - Fix for iterables +# Il y a aussi des fonctions de base +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# On peut utiliser les compréhensions de listes pour de jolies maps et filtres. +# Une compréhension de liste stocke la sortie comme une liste qui peut elle même être une liste imbriquée. +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Classes +#################################################### + + +# On utilise l'opérateur "classe" pour définir une classe +class Human: + + # Un attribut de la classe. Il est partagé par toutes les instances de la classe. + species = "H. sapiens" + + # L'initialiseur de base. Il est appelé quand la classe est instanciée. + # Note : les doubles underscores au début et à la fin sont utilisés pour + # les fonctions et attributs utilisés par Python mais contrôlés par l'utilisateur. + # Les méthodes (ou objets ou attributs) comme: __init__, __str__, + # __repr__ etc. sont appelés méthodes magiques. + # Vous ne devriez pas inventer de noms de ce style. + def __init__(self, name): + # Assigner l'argument à l'attribut de l'instance + self.name = name + + # Une méthode de l'instance. Toutes prennent "self" comme premier argument. + def say(self, msg): + return "{name}: {message}".format(name=self.name, message=msg) + + # Une méthode de classe est partagée avec entre les instances + # Ils sont appelés avec la classe comme premier argument + @classmethod + def get_species(cls): + return cls.species + + # Une méthode statique est appelée sans référence à une instance ni à une classe. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instantier une classe +i = Human(name="Ian") +print(i.say("hi")) # affiche "Ian: hi" + +j = Human("Joel") +print(j.say("hello")) # affiche "Joel: hello" + +# Appeller notre méthode de classe +i.get_species() # => "H. sapiens" + +# Changer les attributs partagés +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Appeller la méthode statique +Human.grunt() # => "*grunt*" + + +#################################################### +## 6. Modules +#################################################### + +# On peut importer des modules +import math +print(math.sqrt(16)) # => 4 + +# On peut importer des fonctions spécifiques d'un module +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# On peut importer toutes les fonctions d'un module +# Attention: ce n'est pas recommandé. +from math import * + +# On peut raccourcir un nom de module +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Les modules Python sont juste des fichiers Python. +# Vous pouvez écrire les vôtres et les importer. Le nom du module +# est le nom du fichier. + +# On peut voir quels fonctions et objets un module définit +import math +dir(math) + + +#################################################### +## 7. Avancé +#################################################### + +# Les générateurs aident à faire du code paresseux (lazy) +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Un générateur crée des valeurs à la volée. +# Au lieu de générer et retourner toutes les valeurs en une fois, il en crée une à chaque +# itération. Cela signifie que les valeurs supérieures à 15 ne seront pas traîtées par +# double_numbers. +# Note : range est un générateur aussi. +# Créer une liste 1-900000000 prendrait beaucoup de temps +# On met un underscore à la fin d'un nom de variable normalement réservé par Python. +range_ = range(1, 900000000) +# Double tous les nombres jusqu'à ce qu'un nombre >=30 soit trouvé +for i in double_numbers(range_): + print(i) + if i >= 30: + break + + +# Decorateurs +# Dans cet exemple, beg enveloppe say +# Beg appellera say. Si say_please vaut True le message retourné sera changé +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Please! I am poor :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Can you buy me a beer?" + return msg, say_please + + +print(say()) # affiche Can you buy me a beer? +print(say(say_please=True)) # affiche Can you buy me a beer? Please! I am poor :( +``` + +## Prêt pour encore plus ? + +### En ligne et gratuit (en anglais) + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) + +### Livres (en anglais) + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) diff --git a/fr-fr/r-fr.html.markdown b/fr-fr/r-fr.html.markdown new file mode 100644 index 00000000..7d30a48d --- /dev/null +++ b/fr-fr/r-fr.html.markdown @@ -0,0 +1,747 @@ +--- +language: R +contributors: + - ["e99n09", "http://github.com/e99n09"] + - ["isomorphismes", "http://twitter.com/isomorphisms"] +translators: + - ["Anne-Catherine Dehier", "https://github.com/spellart"] +filename: learnr-fr.r +lang: fr-fr +--- + +R est un langage de programmation statistique. Il dispose de nombreuses +bibliothèques pour le téléchargement et le nettoyage d'ensembles de données, +l'exécution de procédures statistiques, et la réalisation de graphiques. +On peut également exécuter des commmandes `R` au sein d'un document LaTeX. + + +```r + +# Les commentaires commencent avec des symboles numériques. + +# Il n'est pas possible de faire des commentaires multilignes, +# mais on peut placer plusieurs commentaires les uns en dessous +# des autres comme ceci. + +# Sur Mac, taper COMMAND-ENTER pour exécuter une ligne +# et sur Windows taper CTRL-ENTER + + + +######################################################################## +# Les choses que vous pouvez faire sans rien comprendre +# à la programmation +######################################################################## + +# Dans cette section, nous vous montrons quelques trucs cools que vous +# pouvez faire avec R sans rien comprendre à la programmation. +# Ne vous inquiétez pas si vous ne comprenez pas tout ce que le code fait. +# Profitez simplement ! + +data() # parcours les ensembles de données préchargées +data(rivers) # récupère ceci : "Lengths of Major North American Rivers" +ls() # notez que "rivers" apparaît maintenant dans votre espace de travail +head(rivers) # donne un aperçu des données +# 735 320 325 392 524 450 + +length(rivers) # Combien de rivers ont été mesurées ? +# 141 +summary(rivers) # Quelles sont les principales données statistiques ? +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 + +# Fait un diagramme à tiges et à feuilles (visualisation de données de +# types histogramme) +stem(rivers) + + +# Le point décimal est de 2 chiffres à droite du | +# +# 0 | 4 +# 2 | 011223334555566667778888899900001111223333344455555666688888999 +# 4 | 111222333445566779001233344567 +# 6 | 000112233578012234468 +# 8 | 045790018 +# 10 | 04507 +# 12 | 1471 +# 14 | 56 +# 16 | 7 +# 18 | 9 +# 20 | +# 22 | 25 +# 24 | 3 +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | +# 36 | 1 + +stem(log(rivers)) # Notez que les données ne sont ni normales +# ni lognormales ! +# Prenez-ça, la courbe en cloche + +# Le point décimal est à 1 chiffre à gauche du | +# +# 48 | 1 +# 50 | +# 52 | 15578 +# 54 | 44571222466689 +# 56 | 023334677000124455789 +# 58 | 00122366666999933445777 +# 60 | 122445567800133459 +# 62 | 112666799035 +# 64 | 00011334581257889 +# 66 | 003683579 +# 68 | 0019156 +# 70 | 079357 +# 72 | 89 +# 74 | 84 +# 76 | 56 +# 78 | 4 +# 80 | +# 82 | 2 + +# Fait un histogramme : +hist(rivers, col="#333333", border="white", breaks=25) # amusez-vous avec ces paramètres +hist(log(rivers), col="#333333", border="white", breaks=25) # vous ferez plus de tracés plus tard + +# Ici d'autres données qui viennent préchargées. R en a des tonnes. +data(discoveries) +plot(discoveries, col="#333333", lwd=3, xlab="Year", + main="Number of important discoveries per year") +plot(discoveries, col="#333333", lwd=3, type = "h", xlab="Year", + main="Number of important discoveries per year") + +# Plutôt que de laisser l'ordre par défaut (par année) +# Nous pourrions aussi trier pour voir ce qu'il y a de typique +sort(discoveries) +# [1] 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 +# [26] 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 +# [51] 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 +# [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 + +stem(discoveries, scale=2) +# +# Le point décimale est à la | +# +# 0 | 000000000 +# 1 | 000000000000 +# 2 | 00000000000000000000000000 +# 3 | 00000000000000000000 +# 4 | 000000000000 +# 5 | 0000000 +# 6 | 000000 +# 7 | 0000 +# 8 | 0 +# 9 | 0 +# 10 | 0 +# 11 | +# 12 | 0 + +max(discoveries) +# 12 +summary(discoveries) +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 + +# Lance un dé plusieurs fois +round(runif(7, min=.5, max=6.5)) +# 1 4 6 1 4 6 4 +# Vos numéros diffèreront des miens à moins que nous mettions +# le même random.seed(31337) + +# Dessine à partir d'une normale Gaussienne 9 fois +rnorm(9) +# [1] 0.07528471 1.03499859 1.34809556 -0.82356087 0.61638975 -1.88757271 +# [7] -0.59975593 0.57629164 1.08455362 + + + +############################################################## +# les types de données et l'arithmétique de base +############################################################## + +# Maintenant pour la partie orientée programmation du tutoriel. +# Dans cette section vous rencontrerez les types de données importants de R : +# les entiers, les numériques, les caractères, les logiques, et les facteurs. + +# LES ENTIERS +# Les entiers de type long sont écrits avec L +5L # 5 +class(5L) # "integer" +# (Essayez ?class pour plus d'informations sur la fonction class().) +# Avec R, chaque valeur seule, comme 5L, est considérée comme +# un vecteur de longueur 1 +length(5L) # 1 +# On peut avoir un vecteur d'entiers avec une longueur > 1 : +c(4L, 5L, 8L, 3L) # 4 5 8 3 +length(c(4L, 5L, 8L, 3L)) # 4 +class(c(4L, 5L, 8L, 3L)) # "integer" + +# LES NUMÉRIQUES +# Un "numeric" est un nombre à virgule flottante d'une précision double +5 # 5 +class(5) # "numeric" +# Encore une fois, tout dans R est un vecteur ; +# Vous pouvez faire un vecteur numérique avec plus d'un élément +c(3,3,3,2,2,1) # 3 3 3 2 2 1 +# Vous pouvez aussi utiliser la notation scientifique +5e4 # 50000 +6.02e23 # nombre d'Avogadro +1.6e-35 # longueur de Planck +# Vous pouvez également avoir des nombres infiniments grands ou petits +class(Inf) # "numeric" +class(-Inf) # "numeric" +# Vous pouvez utiliser "Inf", par exemple, dans integrate(dnorm, 3, Inf); +# Ça permet d'éviter de réaliser une table de la loi normale. + +# ARITHMÉTIQUES DE BASE +# Vous pouvez faire de l'arithmétique avec des nombres +# Faire des opérations arithmétiques en mixant des entiers +# et des numériques +# donne un autre numérique +10L + 66L # 76 # un entier plus un entier donne un entier +53.2 - 4 # 49.2 # un numérique moins un numérique donne un numérique +2.0 * 2L # 4 # un numérique multiplié par un entier donne un numérique +3L / 4 # 0.75 # un entier sur un numérique donne un numérique +3 %% 2 # 1 # le reste de deux numériques est un autre numérique +# Les opérations arithmétiques illégales donnent un "Not A Number" : +0 / 0 # NaN +class(NaN) # "numeric" +# Vous pouvez faire des opérations arithmétiques avec deux vecteurs d'une +# longueur plus grande que 1, à condition que la longueur du plus grand +# vecteur soit un multiple entier du plus petit +c(1,2,3) + c(1,2,3) # 2 4 6 + +# LES CARACTÈRES +# Il n'y a pas de différences entre les chaînes de caractères et +# les caractères en R +"Horatio" # "Horatio" +class("Horatio") # "character" +class('H') # "character" +# Ceux-ci sont tous les deux des vecteurs de longueur 1 +# Ici un plus long : +c('alef', 'bet', 'gimmel', 'dalet', 'he') +# => +# "alef" "bet" "gimmel" "dalet" "he" +length(c("Call","me","Ishmael")) # 3 +# Vous pouvez utiliser des expressions rationnelles sur les vecteurs de caractères : +substr("Fortuna multis dat nimis, nulli satis.", 9, 15) # "multis " +gsub('u', 'ø', "Fortuna multis dat nimis, nulli satis.") # "Fortøna møltis dat nimis, nølli satis." +# R possède plusieurs vecteurs de caractères préconstruits : +letters +# => +# [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" +# [20] "t" "u" "v" "w" "x" "y" "z" +month.abb # "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" + +# LES TYPES BOOLÉENS +# En R, un "logical" est un booléen +class(TRUE) # "logical" +class(FALSE) # "logical" +# Leur comportement est normal +TRUE == TRUE # TRUE +TRUE == FALSE # FALSE +FALSE != FALSE # FALSE +FALSE != TRUE # TRUE +# Les données manquantes (NA) sont logiques également +class(NA) # "logical" +# On utilise | et & pour les operations logiques. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Vous pouvez tester si x est TRUE +isTRUE(TRUE) # TRUE +# Ici nous avons un vecteur de type logique avec plusieurs éléments : +c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE +c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE + +# LES FACTEURS +# Les facteurs sont généralement utilisés pour y stocker des +# variables qualitatives (catégorielles). +# Les facteurs peuvent être ordonnés (comme le niveau scolaire +# des enfants) ou non ordonnés (comme le sexe) +factor(c("female", "female", "male", NA, "female")) +# female female male <NA> female +# Les niveaux : female male +# Les facteurs possèdent un attribut appelé niveau ("level"). +# Les niveaux sont des vecteurs contenant toutes les valeurs +# que peuvent prendre les données catégorielles. +# Notez que les données manquantes n'entrent pas dans le niveau +levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male" +# Si le vecteur de facteurs a une longueur 1, ses niveaux seront +# de longueur 1 également +length(factor("male")) # 1 +length(levels(factor("male"))) # 1 +# On rencontre communément des facteurs dans des "data frame", +# un type de données que nous couvrirons plus tard +data(infert) # "Infertility after Spontaneous and Induced Abortion" +levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" + +# NULL +# "NULL" est bizarre ; on l'utilise pour effacer un vecteur +class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") +parakeet +# => +# [1] "beak" "feathers" "wings" "eyes" +parakeet <- NULL +parakeet +# => +# NULL + +# LES CONVERSIONS DE TYPES +# Les conversions de types servent à forcer une valeur à prendre +# un type différent +as.character(c(6, 8)) # "6" "8" +as.logical(c(1,0,1,1)) # TRUE FALSE TRUE TRUE +# Si vous mettez des éléments de différents types dans un vecteur, +# des coercitions bizarres se produisent : +c(TRUE, 4) # 1 4 +c("dog", TRUE, 4) # "dog" "TRUE" "4" +as.numeric("Bilbo") +# => +# [1] NA +# Message d'avertissement : +# NAs est introduit par coercition + +# Notez également : ce n'étaient que des types de données basiques +# Il y a beaucoup d'autres types de données, comme les dates, +# les séries temporelles, etc ... + + + +####################################### +# Variables, boucles , if/else +####################################### + +# Une variable est comme une boîte dans laquelle on garde une valeur +# pour l'utiliser plus tard. +# Nous appellons ça "assigner" une valeur à une variable. +# Avoir des variables nous permet d'écrire des boucles, des fonctions, et +# des instructions conditionnelles (if/else) + +# LES VARIABLES +# Beaucoup de façons d'assigner des choses : +x = 5 # c'est correct +y <- "1" # c'est préféré +TRUE -> z # ça marche mais c'est bizarre + +# LES BOUCLES +# Il y a les boucles for : +for (i in 1:4) { + print(i) +} +# Il y a les boucles while : +a <- 10 +while (a > 4) { + cat(a, "...", sep = "") + a <- a - 1 +} +# Gardez à l'esprit que les boucles for et while s'exécutent lentement +# en R. +# Des opérations sur la totalité d'un vecteur (ex une ligne entière, +# une colonne entière), +# ou les fonctions de type apply() (nous en parlerons plus tard), +# sont préférées. + +# IF/ELSE +# Encore une fois assez standard +if (4 > 3) { + print("4 is greater than 3") +} else { + print("4 is not greater than 3") +} +# => +# [1] "4 is greater than 3" + +# LES FONCTIONS +# se définissent comme ceci : +jiggle <- function(x) { + x = x + rnorm(1, sd=.1) # ajoute un peu de bruit (contrôlé) + return(x) +} +# Appelées comme n'importe quelles autres fonction R : +jiggle(5) # 5±ε. After set.seed(2716057), jiggle(5)==5.005043 + + + +########################################################################## +# Les structures de données : les vecteurs, les matrices, +# les data frames et les tableaux +########################################################################## + +# À UNE DIMENSION + +# Commençons par le tout début, et avec quelque chose que +# vous connaissez déjà : les vecteurs. +vec <- c(8, 9, 10, 11) +vec # 8 9 10 11 +# Nous demandons des éléments spécifiques en les mettant entre crochets +# (Notez que R commence à compter à partir de 1) +vec[1] # 8 +letters[18] # "r" +LETTERS[13] # "M" +month.name[9] # "September" +c(6, 8, 7, 5, 3, 0, 9)[3] # 7 +# Nous pouvons également rechercher des indices de composants spécifiques, +which(vec %% 2 == 0) # 1 3 +# Récupèrer seulement les premières ou dernières entrées du vecteur, +head(vec, 1) # 8 +tail(vec, 2) # 10 11 +# ou vérifier si un certaine valeur est dans le vecteur +any(vec == 10) # TRUE +# Si un index "dépasse" vous obtiendrez NA : +vec[6] # NA +# Vous pouvez trouver la longueur de votre vecteur avec length() +length(vec) # 4 +# Vous pouvez réaliser des opérations sur des vecteurs entiers ou des +# sous-ensembles de vecteurs +vec * 4 # 16 20 24 28 +vec[2:3] * 5 # 25 30 +any(vec[2:3] == 8) # FALSE +# Et R a beaucoup de méthodes statistiques pré-construites pour les vecteurs : +mean(vec) # 9.5 +var(vec) # 1.666667 +sd(vec) # 1.290994 +max(vec) # 11 +min(vec) # 8 +sum(vec) # 38 +# Quelques fonctions préconstruites sympas supplémentaires : +5:15 # 5 6 7 8 9 10 11 12 13 14 15 +seq(from=0, to=31337, by=1337) +# => +# [1] 0 1337 2674 4011 5348 6685 8022 9359 10696 12033 13370 14707 +# [13] 16044 17381 18718 20055 21392 22729 24066 25403 26740 28077 29414 30751 + +# À DEUX DIMENSIONS (TOUT DANS UNE CLASSE) + +# Vous pouvez créer une matrice à partir d'entrées du même type comme ceci : +mat <- matrix(nrow = 3, ncol = 2, c(1,2,3,4,5,6)) +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Différemment du vecteur, la classe d'une matrice est "matrix", +# peut importe ce qu'elle contient +class(mat) # => "matrix" +# Récupérer la première ligne +mat[1,] # 1 4 +# Réaliser une opération sur la première colonne +3 * mat[,1] # 3 6 9 +# Demander une cellule spécifique +mat[3,2] # 6 + +# Transposer la matrice entière +t(mat) +# => +# [,1] [,2] [,3] +# [1,] 1 2 3 +# [2,] 4 5 6 + +# La multiplication de matrices +mat %*% t(mat) +# => +# [,1] [,2] [,3] +# [1,] 17 22 27 +# [2,] 22 29 36 +# [3,] 27 36 45 + +# cbind() colle des vecteurs ensemble en colonne pour faire une matrice +mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) +mat2 +# => +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" +# [4,] "4" "dog" +class(mat2) # matrix +# Encore une fois regardez ce qui se passe ! +# Parce que les matrices peuvent contenir des entrées de toutes sortes de +# classes, tout sera converti en classe caractère +c(class(mat2[,1]), class(mat2[,2])) + +# rbind() colle des vecteurs ensemble par lignes pour faire une matrice +mat3 <- rbind(c(1,2,4,5), c(6,7,0,4)) +mat3 +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 2 4 5 +# [2,] 6 7 0 4 +# Ah, tout de la même classe. Pas de coercitions. Beaucoup mieux. + +# À DEUX DIMENSIONS (DE CLASSES DIFFÉRENTES) + +# Pour des colonnes de différents types, utiliser une data frame +# Cette structure de données est si utile pour la programmation statistique, +# qu'une version a été ajoutée à Python dans le paquet "pandas". + +students <- data.frame(c("Cedric","Fred","George","Cho","Draco","Ginny"), + c(3,2,2,1,0,-1), + c("H", "G", "G", "R", "S", "G")) +names(students) <- c("name", "year", "house") # name the columns +class(students) # "data.frame" +students +# => +# name year house +# 1 Cedric 3 H +# 2 Fred 2 G +# 3 George 2 G +# 4 Cho 1 R +# 5 Draco 0 S +# 6 Ginny -1 G +class(students$year) # "numeric" +class(students[,3]) # "factor" +# Trouver les dimensions +nrow(students) # 6 +ncol(students) # 3 +dim(students) # 6 3 +# La fonction data.frame() convertit les vecteurs caractères en vecteurs de +# facteurs par défaut; désactiver cette fonction en règlant +# stringsAsFactors = FALSE quand vous créer la data.frame +?data.frame + +# Il y a plusieurs façons de subdiviser les data frames, +# toutes subtilement différentes +students$year # 3 2 2 1 0 -1 +students[,2] # 3 2 2 1 0 -1 +students[,"year"] # 3 2 2 1 0 -1 + +# Une version améliorée de la structure data.frame est data.table. +# Si vous travaillez avec des données volumineuses ou des panels, ou avez +# besoin de fusionner quelques ensembles de données, data.table peut être +# un bon choix. Ici un tour éclair : +install.packages("data.table") # télécharge le paquet depuis CRAN +require(data.table) # le charge +students <- as.data.table(students) +students # regardez la différence à l'impression +# => +# name year house +# 1: Cedric 3 H +# 2: Fred 2 G +# 3: George 2 G +# 4: Cho 1 R +# 5: Draco 0 S +# 6: Ginny -1 G +students[name=="Ginny"] # obtiens les lignes avec name == "Ginny" +# => +# name year house +# 1: Ginny -1 G +students[year==2] # obtiens les lignes avec year == 2 +# => +# name year house +# 1: Fred 2 G +# 2: George 2 G +# data.table facilite la fusion entre deux ensembles de données +# Faisons une autre data.table pour fusionner students +founders <- data.table(house=c("G","H","R","S"), + founder=c("Godric","Helga","Rowena","Salazar")) +founders +# => +# house founder +# 1: G Godric +# 2: H Helga +# 3: R Rowena +# 4: S Salazar +setkey(students, house) +setkey(founders, house) +students <- founders[students] # merge les deux ensembles de données qui matchent "house" +setnames(students, c("house","houseFounderName","studentName","year")) +students[,order(c("name","year","house","houseFounderName")), with=F] +# => +# studentName year house houseFounderName +# 1: Fred 2 G Godric +# 2: George 2 G Godric +# 3: Ginny -1 G Godric +# 4: Cedric 3 H Helga +# 5: Cho 1 R Rowena +# 6: Draco 0 S Salazar + +# data.table facilite le résumé des tableaux +students[,sum(year),by=house] +# => +# house V1 +# 1: G 3 +# 2: H 3 +# 3: R 1 +# 4: S 0 + +# Pour supprimer une colonne d'une data.frame ou data.table, +# assignez-lui la valeur NULL +students$houseFounderName <- NULL +students +# => +# studentName year house +# 1: Fred 2 G +# 2: George 2 G +# 3: Ginny -1 G +# 4: Cedric 3 H +# 5: Cho 1 R +# 6: Draco 0 S + +# Supprimer une ligne en subdivisant +# En utilisant data.table : +students[studentName != "Draco"] +# => +# house studentName year +# 1: G Fred 2 +# 2: G George 2 +# 3: G Ginny -1 +# 4: H Cedric 3 +# 5: R Cho 1 +# En utilisant data.frame : +students <- as.data.frame(students) +students[students$house != "G",] +# => +# house houseFounderName studentName year +# 4 H Helga Cedric 3 +# 5 R Rowena Cho 1 +# 6 S Salazar Draco 0 + +# MULTI-DIMENSIONNELLE (TOUS ÉLÉMENTS D'UN TYPE) + +# Les arrays créent des tableaux de n dimensions. +# Tous les éléments doivent être du même type. +# Vous pouvez faire un tableau à 2 dimensions (une sorte de matrice) +array(c(c(1,2,4,5),c(8,9,3,6)), dim=c(2,4)) +# => +# [,1] [,2] [,3] [,4] +# [1,] 1 4 8 3 +# [2,] 2 5 9 6 +# Vous pouvez aussi utiliser array pour faire des matrices à 3 dimensions : +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) +# => +# , , 1 +# +# [,1] [,2] +# [1,] 2 8 +# [2,] 300 9 +# [3,] 4 0 +# +# , , 2 +# +# [,1] [,2] +# [1,] 5 66 +# [2,] 60 7 +# [3,] 0 847 + +# LES LISTES (MULTI-DIMENSIONNELLES, ÉVENTUELLEMMENT DÉCHIRÉES, +# DE DIFFÉRENTS TYPES) + +# Enfin, R a des listes (de vecteurs) +list1 <- list(time = 1:40) +list1$price = c(rnorm(40,.5*list1$time,4)) # random +list1 +# Vous pouvez obtenir des éléments de la liste comme ceci +list1$time # une façon +list1[["time"]] # une autre façon +list1[[1]] # encore une façon différente +# => +# [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 +# [34] 34 35 36 37 38 39 40 +# Vous pouvez subdiviser les éléments d'une liste comme n'importe quel vecteur +list1$price[4] + +# Les listes ne sont pas les structures de données les plus efficaces +# à utiliser avec R ; +# À moins d'avoir une très bonne raison, vous devriez utiliser data.frames +# Les listes sont souvent retournées par des fonctions qui effectuent +# des régressions linéaires. + +########################################## +# La famille de fonction apply() +########################################## + +# Vous vous rappelez mat ? +mat +# => +# [,1] [,2] +# [1,] 1 4 +# [2,] 2 5 +# [3,] 3 6 +# Utilisez apply(X, MARGIN, FUN) pour appliquer la fonction FUN à la matrice X +# sur les lignes (MAR = 1) ou les colonnes (MAR = 2) +# R exécute FUN à chaque lignes (ou colonnes) de X, beaucoup plus rapidement +# que le ferait une boucle for ou while +apply(mat, MAR = 2, jiggle) +# => +# [,1] [,2] +# [1,] 3 15 +# [2,] 7 19 +# [3,] 11 23 +# D'autres fonctions : ?lapply, ?sapply + +# Ne soyez pas trop intimidé ; tout le monde reconnaît que c'est un peu déroutant + +# Le paquet plyr vise à remplacer (et améliorer !) la famille *apply(). +install.packages("plyr") +require(plyr) +?plyr + + + +############################ +# Charger des données +############################ + +# "pets.csv" est un fichier sur internet +# (mais il pourrait être tout aussi facilement sur votre ordinateur) +pets <- read.csv("http://learnxinyminutes.com/docs/pets.csv") +pets +head(pets, 2) # first two rows +tail(pets, 1) # last row + +# Pour sauvegarder une data frame ou une matrice en fichier .csv +write.csv(pets, "pets2.csv") # to make a new .csv file +# définir le répertoire de travail avec setwd(), le récupérer avec getwd() + +# Essayez ?read.csv et ?write.csv pour plus d'informations + + + +################ +# Les tracés +################ + +# LES FONCTIONS DE TRACÉ PRÉCONSTRUITES +# Les diagrammes de dispersion ! +plot(list1$time, list1$price, main = "fake data") +# Les régressions ! +linearModel <- lm(price ~ time, data = list1) +linearModel # sort le résultat de la régression +# Tracer une ligne de regression sur une tracé existant +abline(linearModel, col = "red") +# Obtenir une variété de diagnostiques sympas +plot(linearModel) +# Les histogrammes ! +hist(rpois(n = 10000, lambda = 5), col = "thistle") +# Les diagrammes en bâtons ! +barplot(c(1,4,5,1,2), names.arg = c("red","blue","purple","green","yellow")) + +# GGPLOT2 +# Mais ceux-ci ne sont même pas les plus jolis tracés de R +# Essayez le paquet ggplot2 pour d'avantages de graphiques +install.packages("ggplot2") +require(ggplot2) +?ggplot2 +pp <- ggplot(students, aes(x=house)) +pp + geom_histogram() +ll <- as.data.table(list1) +pp <- ggplot(ll, aes(x=time,price)) +pp + geom_point() +# ggplot2 a une documentation excellente +#(disponible sur http://docs.ggplot2.org/current/) + + + +``` + +## Comment obtenir R ? + +* Obtiens R et R GUI depuis [http://www.r-project.org/](http://www.r-project.org/) +* [RStudio](http://www.rstudio.com/ide/) est un autre GUI diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown index 75c8d0d3..1564d2b6 100644 --- a/fr-fr/ruby-fr.html.markdown +++ b/fr-fr/ruby-fr.html.markdown @@ -268,7 +268,7 @@ end # implicitement la valeur de la dernière instruction évaluée double(2) #=> 4 -# Les paranthèses sont facultative +# Les parenthèses sont facultatives # lorsqu'il n'y a pas d'ambiguïté sur le résultat double 3 #=> 6 diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index a43edf16..c6d06361 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -208,6 +208,7 @@ 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) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -217,6 +218,7 @@ List( // Scala a une méthode foreach définie pour certaines collections // qui prend en argument une fonction renvoyant Unit (une méthode void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique. // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus // facile pour comprendre et pour faire la parallélisation +i = 0 // La boucle do while do { println("x is still less then 10"); - x += 1 -} while (x < 10) + i += 1 +} while (i < 10) // La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. @@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com" "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 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 diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown new file mode 100644 index 00000000..b8807104 --- /dev/null +++ b/fr-fr/typescript-fr.html.markdown @@ -0,0 +1,174 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"] +translators: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +filename: learntypescript-fr.ts +lang: fr-fr +--- + +TypeScript est un langage visant à faciliter le développement d'applications larges et scalables, écrites en JavaScript. +TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript. +C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur. + +Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/). + +Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript. + +```js +// Il y a 3 types basiques en TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +// Si nous ne pouvons pas déterminer le type, on utilise `Any` +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // ok, définitivement un booléen + +// Pour les collections, il y a les tableaux typés et les tableaux génériques +var list: number[] = [1, 2, 3]; // Un tableaux typé +var list: Array<number> = [1, 2, 3]; // un tableau générique + +// Pour les énumeration +enum Color { Red, Green, Blue }; +var c: Color = Color.Green; + +// Enfin, `void` est utilisé dans le cas spécifique +// d'une fonction ne retournant rien +function bigHorribleAlert(): void { + alert("Je suis une petite boîte ennuyeuse !"); +} + +// Les fonctions sont des entités de première classe. Le langage supporte +// les expressions lambda et utilise l'inférence de type + +// Les fonctions ci-dessous sont équivalentes, une signature identique +// sera inférée par le compilateur, et le même JavaScript sera généré +var f1 = function(i: number): number { return i * i; } +// Retourne un type inféré +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Retourne un type inféré +var f4 = (i: number) => { return i * i; } +// Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire +var f5 = (i: number) => i * i; + +// Les interfaces sont structurées, tout les objets qui ont ces propriétés +// sont compatible avec l'interface +interface Person { + name: string; + // Les propriétés optionnelles sont identifiées avec un "?" + age?: number; + // Et bien sûr, les fonctions + move(): void; +} + +// Un objet implémentant l'interface "Person" peut être traité comme +// une Person car il a les propriétés "name" et "move" +var p: Person = { name: "Bobby", move: () => {} }; +// Des objets implémentants la propriété optionnelle : +// valide car "age" est un nombre +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// invalide car "age" n'est pas un nombre +var invalidPerson: Person = { name: "Bobby", age: true }; + +// Les interfaces peuvent aussi décrire un type de fonction +interface SearchFunc { + (source: string, subString: string): boolean; +} + +// Seul les types des paramètres sont importants. Les noms ne le sont pas. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + return src.search(sub) != -1; +} + +// Les membres des classes sont publiques par défaut. +class Point { + // Propriétés + x: number; + + // Constructeur - Les mots clés "public" et "private" dans ce contexte + // génèrent le code de la propriété et son initialisation dans le + // constructeur. Ici, "y" sera défini de la même façon que "x", + // mais avec moins de code. Les valeurs par défaut sont supportées. + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Fonctions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Membres statiques + static origin = new Point(0, 0); +} + +var p1 = new Point(10 ,20); +var p2 = new Point(25); // y sera 0 + +// Héritage +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + // Un appel explicite au constructeur de la super classe + // est obligatoire. + super(x, y); + } + + // Redéfinition + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +// Modules, "." peut être utilisé comme un séparateur de sous modules. +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +// Alias local pour référencer un module +import G = Geometry; + +var s2 = new G.Square(10); + +// Génériques +// Classes +class Tuple<T1, T2> { + constructor(public item1: T1, public item2: T2) { + } +} + +// Interfaces +interface Pair<T> { + item1: T; + item2: T; +} + +// Et fonctions +var pairToTuple = function<T>(p: Pair<T>) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); + +// Inclure des références à un fichier : +/// <reference path="jquery.d.ts" /> + +``` + +## Lectures complémentaires + * [Site officiel de TypeScript] (http://www.typescriptlang.org/) + * [Spécification du langage TypeScript (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Code source sur GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 43b1df54..1e8296d3 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -8,113 +8,117 @@ lang: fr-fr Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de représentation de données par sérialisation, conçu pour être aisément -éditable et lisible par nous même, les humains. +modifiable et lisible par nous-mêmes, les humains. -YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages. +YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le +découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont +il est un parent naturel. Toutefois, YAML emprunte également des idées et +concepts de Python, et s'intègre bien avec bon nombre de langages. +Contrairement à ce dernier, YAML interdit l'utilisation des tabulations. ```yaml -# les Commentaires sont précédés d'un signe "#", comme cette ligne. +# Les commentaires sont précédés d'un signe "#", comme cette ligne. ############# # SCALAIRES # ############# -# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections -# ( listes ou tableaux associatifs ). +# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections +# (listes ou tableaux associatifs). -# Notre objet root ( racine ), sera une map ( carte ) et englobera -# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire, +# Notre objet root (racine), sera une map (carte) et englobera +# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire, # hash ou objet dans d'autres langages. clé: valeur -aurtre_clé: une autre valeur +autre_clé: une autre valeur valeur_numérique: 100 notation_scientifique: 1e+12 -boolean: true +booléen: true valeur_null: null clé avec espaces: valeur -# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères +# Bien qu'il ne soit pas nécessaire de mettre les chaînes de caractères # entre guillemets, cela reste possible, et parfois utile. toutefois: "Une chaîne, peut être contenue entre guillemets." -"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé." +"Une clé entre guillemets.": "Utile si l'on veut utiliser ':' dans la clé." -# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix, -# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ). +# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix, +# comme un "bloc littéral" (avec '|') ou bien un "bloc replié" (avec '>'). bloc_littéral: | - Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral', - avec préservation des retours à la ligne. ( chaque ligne vide à - l'intérieur du même bloc, sera remplacée par "\n\n" ) + Tout ce bloc de texte sera la valeur de la clé "bloc_littéral", + avec préservation des retours à la ligne. Le littéral continue jusqu'à ce que l'indentation soit annulée. - Toutes lignes qui serait "d'avantage indentées" conservent leur + Toutes lignes qui seraient "davantage indentées" conservent leur indentation, constituée de 4 espaces. bloc_replié: > - Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais - cette fois ci, toutes les nouvelles lignes deviendront un simple espace. + Tout ce bloc de texte sera la valeur de la clé "bloc_replié", mais + cette fois-ci, toutes les nouvelles lignes deviendront un simple espace. - Les lignes vides, comme ci-dessus, seront converties en caractère "\n". + Les lignes vides, comme ci-dessus, seront converties en caractère de + nouvelle ligne. - Les lignes 'plus-indentées' gardent leurs retours à la ligne - + Les lignes "plus-indentées" gardent leurs retours à la ligne - ce texte apparaîtra sur deux lignes. ############### # COLLECTIONS # ############### -# l'Imbrication est créée par indentation. +# L'imbrication est créée par indentation. une_map_imbriquée: clé: valeur autre_clé: autre valeur autre_map_imbriquée: bonjour: bonjour -# les Clés des Maps ne sont pas nécessairement des chaînes de caractères. -0.25: une clé de type float +# Les clés des maps ne sont pas nécessairement des chaînes de caractères. +0.25: une clé de type flottant -# les Clés peuvent également être des objets s'étendant sur plusieurs lignes, +# Les clés peuvent également être des objets s'étendant sur plusieurs lignes, # en utilisant le signe "?" pour indiquer le début de la clé. ? | - ceci est une Clé + ceci est une clé sur de multiples lignes -: et ceci est sa Valeur +: et ceci est sa valeur # YAML autorise aussi l'usage des collections à l'intérieur des clés, # mais certains langages de programmation ne le tolère pas si bien. -# les Séquences (équivalent des listes ou tableaux) ressemblent à cela: +# Les séquences (équivalent des listes ou tableaux) ressemblent à cela : une_séquence: - - Item 1 - - Item 2 + - Objet 1 + - Objet 2 - 0.5 # les séquences peuvent contenir des types variés. - - Item 4 + - Objet 4 - clé: valeur autre_clé: autre_valeur - - Ceci est une séquence - dans une autre séquence -# YAML étant un proche parent de JSON, vous pouvez écrire directement +# YAML étant un proche parent de JSON, vous pouvez écrire directement # des maps et séquences façon JSON json_map: {"clé": "valeur"} json_seq: [1, 2, 3, "soleil"] -################################# +################################ # AUTRES FONCTIONNALITÉES YAML # -################################# +################################ -# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci +# YAML possède une fonctionnalité fort utile nommée "ancres". Celle-ci # vous permet de dupliquer aisément du contenu au sein de votre document. -# Les deux clés suivantes auront la même valeur: +# Les deux clés suivantes auront la même valeur : contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés. autre_ancre: *nom_ancre -# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données. +# Avec les tags YAML, vous pouvez explicitement déclarer des types de données. chaine_explicite: !!str 0.5 -# Certains parsers implémentent des tags spécifiques à d'autres langages, -# comme par exemple le "complex number" de Python. +# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à +# d'autres langages, comme par exemple celui des nombres complexes de Python. python_complex_number: !!python/complex 1+2j ##################### @@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j ##################### # YAML interprète également les données formatées ISO de type date et datetime, -# pas seulement les chaînes et nombres. +# pas seulement les chaînes et nombres. datetime: 2001-12-15T02:59:43.1Z datetime_avec_espaces: 2001-12-14 21:59:43.10 -5 date: 2002-12-14 @@ -135,14 +139,14 @@ fichier_gif: !!binary | +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= -# YAML a de même un type "set", qui ressemble à cela: +# YAML a de même un type "set", semblable à ceci : set: ? item1 ? item2 ? item3 # Comme dans Python, les sets ne sont que des maps contenant des valeurs null ; -# le set précédent est l'équivalent du suivant: +# le set précédent est l'équivalent du suivant : set2: item1: null item2: null @@ -152,6 +156,6 @@ set2: Quelques références et outils : -- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, +- Documentation officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*, - Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire, -- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. +- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples. diff --git a/fsharp.html.markdown b/fsharp.html.markdown index 49951c78..809a1da2 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnfsharp.fs --- -F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more. +F# is a general purpose functional/OO programming language. It's free and open source, and runs on Linux, Mac, Windows and more. It has a powerful type system that traps many errors at compile time, but it uses type inference so that it reads more like a dynamic language. @@ -31,14 +31,14 @@ If you want to try out the code below, you can go to [tryfsharp.org](http://www. // The "let" keyword defines an (immutable) value let myInt = 5 let myFloat = 3.14 -let myString = "hello" //note that no types needed +let myString = "hello" // note that no types needed // ------ Lists ------ -let twoToFive = [2;3;4;5] // Square brackets create a list with +let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. let oneToFive = 1 :: twoToFive // :: creates list with new 1st element -// The result is [1;2;3;4;5] -let zeroToFive = [0;1] @ twoToFive // @ concats two lists +// The result is [1; 2; 3; 4; 5] +let zeroToFive = [0; 1] @ twoToFive // @ concats two lists // IMPORTANT: commas are never used as delimiters, only semicolons! @@ -53,7 +53,7 @@ add 2 3 // Now run the function. // to define a multiline function, just use indents. No semicolons needed. let evens list = - let isEven x = x%2 = 0 // Define "isEven" as a sub function + let isEven x = x % 2 = 0 // Define "isEven" as a sub function List.filter isEven list // List.filter is a library function // with two parameters: a boolean function // and a list to work on @@ -75,7 +75,7 @@ let sumOfSquaresTo100piped = // you can define lambdas (anonymous functions) using the "fun" keyword let sumOfSquaresTo100withFun = - [1..100] |> List.map (fun x -> x*x) |> List.sum + [1..100] |> List.map (fun x -> x * x) |> List.sum // In F# there is no "return" keyword. A function always // returns the value of the last expression used. @@ -90,7 +90,7 @@ let simplePatternMatch = | _ -> printfn "x is something else" // underscore matches anything // F# doesn't allow nulls by default -- you must use an Option type -// and then pattern match. +// and then pattern match. // Some(..) and None are roughly analogous to Nullable wrappers let validValue = Some(99) let invalidValue = None @@ -109,103 +109,103 @@ optionPatternMatch invalidValue // The printf/printfn functions are similar to the // Console.Write/WriteLine functions in C#. printfn "Printing an int %i, a float %f, a bool %b" 1 2.0 true -printfn "A string %s, and something generic %A" "hello" [1;2;3;4] +printfn "A string %s, and something generic %A" "hello" [1; 2; 3; 4] // There are also sprintf/sprintfn functions for formatting data // into a string, similar to String.Format in C#. // ================================================ -// More on functions +// More on functions // ================================================ // F# is a true functional language -- functions are first -// class entities and can be combined easy to make powerful +// class entities and can be combined easily to make powerful // constructs // Modules are used to group functions together // Indentation is needed for each nested module. -module FunctionExamples = +module FunctionExamples = // define a simple adding function let add x y = x + y - + // basic usage of a function let a = add 1 2 - printfn "1+2 = %i" a - + printfn "1 + 2 = %i" a + // partial application to "bake in" parameters let add42 = add 42 let b = add42 1 - printfn "42+1 = %i" b - + printfn "42 + 1 = %i" b + // composition to combine functions let add1 = add 1 let add2 = add 2 let add3 = add1 >> add2 let c = add3 7 - printfn "3+7 = %i" c - + printfn "3 + 7 = %i" c + // higher order functions [1..10] |> List.map add3 |> printfn "new list is %A" - + // lists of functions, and more let add6 = [add1; add2; add3] |> List.reduce (>>) let d = add6 7 - printfn "1+2+3+7 = %i" d + printfn "1 + 2 + 3 + 7 = %i" d // ================================================ // Lists and collection // ================================================ // There are three types of ordered collection: -// * Lists are most basic immutable collection. -// * Arrays are mutable and more efficient when needed. -// * Sequences are lazy and infinite (e.g. an enumerator). +// * Lists are most basic immutable collection. +// * Arrays are mutable and more efficient when needed. +// * Sequences are lazy and infinite (e.g. an enumerator). // // Other collections include immutable maps and sets // plus all the standard .NET collections -module ListExamples = +module ListExamples = - // lists use square brackets - let list1 = ["a";"b"] + // lists use square brackets + let list1 = ["a"; "b"] let list2 = "c" :: list1 // :: is prepending let list3 = list1 @ list2 // @ is concat - + // list comprehensions (aka generators) - let squares = [for i in 1..10 do yield i*i] + let squares = [for i in 1..10 do yield i * i] // prime number generator let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] let primes = sieve [2..50] - printfn "%A" primes - + printfn "%A" primes + // pattern matching for lists - let listMatcher aList = + let listMatcher aList = match aList with - | [] -> printfn "the list is empty" - | [first] -> printfn "the list has one element %A " first - | [first; second] -> printfn "list is %A and %A" first second - | _ -> printfn "the list has more than two elements" + | [] -> printfn "the list is empty" + | [first] -> printfn "the list has one element %A " first + | [first; second] -> printfn "list is %A and %A" first second + | _ -> printfn "the list has more than two elements" - listMatcher [1;2;3;4] - listMatcher [1;2] + listMatcher [1; 2; 3; 4] + listMatcher [1; 2] listMatcher [1] - listMatcher [] + listMatcher [] // recursion using lists - let rec sum aList = + let rec sum aList = match aList with | [] -> 0 | x::xs -> x + sum xs sum [1..10] - - // ----------------------------------------- - // Standard library functions + + // ----------------------------------------- + // Standard library functions // ----------------------------------------- - + // map let add3 x = x + 3 [1..10] |> List.map add3 @@ -213,102 +213,102 @@ module ListExamples = // filter let even x = x % 2 = 0 [1..10] |> List.filter even - + // many more -- see documentation - -module ArrayExamples = + +module ArrayExamples = // arrays use square brackets with bar - let array1 = [| "a";"b" |] + let array1 = [| "a"; "b" |] let first = array1.[0] // indexed access using dot - + // pattern matching for arrays is same as for lists - let arrayMatcher aList = + let arrayMatcher aList = match aList with - | [| |] -> printfn "the array is empty" - | [| first |] -> printfn "the array has one element %A " first - | [| first; second |] -> printfn "array is %A and %A" first second - | _ -> printfn "the array has more than two elements" + | [| |] -> printfn "the array is empty" + | [| first |] -> printfn "the array has one element %A " first + | [| first; second |] -> printfn "array is %A and %A" first second + | _ -> printfn "the array has more than two elements" - arrayMatcher [| 1;2;3;4 |] + arrayMatcher [| 1; 2; 3; 4 |] // Standard library functions just as for List - - [| 1..10 |] - |> Array.map (fun i -> i+3) - |> Array.filter (fun i -> i%2 = 0) + + [| 1..10 |] + |> Array.map (fun i -> i + 3) + |> Array.filter (fun i -> i % 2 = 0) |> Array.iter (printfn "value is %i. ") - - -module SequenceExamples = + + +module SequenceExamples = // sequences use curly braces let seq1 = seq { yield "a"; yield "b" } - - // sequences can use yield and + + // sequences can use yield and // can contain subsequences let strange = seq { - // "yield! adds one element + // "yield" adds one element yield 1; yield 2; - + // "yield!" adds a whole subsequence - yield! [5..10] + yield! [5..10] yield! seq { - for i in 1..10 do - if i%2 = 0 then yield i }} - // test - strange |> Seq.toList - + for i in 1..10 do + if i % 2 = 0 then yield i }} + // test + strange |> Seq.toList + // Sequences can be created using "unfold" // Here's the fibonacci series let fib = Seq.unfold (fun (fst,snd) -> Some(fst + snd, (snd, fst + snd))) (0,1) - // test + // test let fib10 = fib |> Seq.take 10 |> Seq.toList - printf "first 10 fibs are %A" fib10 - - + printf "first 10 fibs are %A" fib10 + + // ================================================ -// Data Types +// Data Types // ================================================ -module DataTypeExamples = +module DataTypeExamples = // All data is immutable by default // Tuples are quick 'n easy anonymous types // -- Use a comma to create a tuple - let twoTuple = 1,2 - let threeTuple = "a",2,true - + let twoTuple = 1, 2 + let threeTuple = "a", 2, true + // Pattern match to unpack - let x,y = twoTuple //sets x=1 y=2 + let x, y = twoTuple // sets x = 1, y = 2 - // ------------------------------------ - // Record types have named fields - // ------------------------------------ + // ------------------------------------ + // Record types have named fields + // ------------------------------------ // Use "type" with curly braces to define a record type type Person = {First:string; Last:string} - - // Use "let" with curly braces to create a record + + // Use "let" with curly braces to create a record let person1 = {First="John"; Last="Doe"} // Pattern match to unpack - let {First=first} = person1 //sets first="john" + let {First = first} = person1 // sets first="John" - // ------------------------------------ + // ------------------------------------ // Union types (aka variants) have a set of choices // Only case can be valid at a time. - // ------------------------------------ + // ------------------------------------ // Use "type" with bar/pipe to define a union type - type Temp = + type Temp = | DegreesC of float | DegreesF of float - + // Use one of the cases to create one let temp1 = DegreesF 98.6 let temp2 = DegreesC 37.0 @@ -317,29 +317,29 @@ module DataTypeExamples = let printTemp = function | DegreesC t -> printfn "%f degC" t | DegreesF t -> printfn "%f degF" t - - printTemp temp1 + + printTemp temp1 printTemp temp2 - // ------------------------------------ + // ------------------------------------ // Recursive types - // ------------------------------------ + // ------------------------------------ - // Types can be combined recursively in complex ways + // Types can be combined recursively in complex ways // without having to create subclasses - type Employee = + type Employee = | Worker of Person | Manager of Employee list - let jdoe = {First="John";Last="Doe"} + let jdoe = {First="John"; Last="Doe"} let worker = Worker jdoe - - // ------------------------------------ - // Modelling with types - // ------------------------------------ - - // Union types are great for modelling state without using flags - type EmailAddress = + + // ------------------------------------ + // Modeling with types + // ------------------------------------ + + // Union types are great for modeling state without using flags + type EmailAddress = | ValidEmailAddress of string | InvalidEmailAddress of string @@ -350,68 +350,68 @@ module DataTypeExamples = // The combination of union types and record types together // provide a great foundation for domain driven design. - // You can create hundreds of little types that accurately + // You can create hundreds of little types that accurately // reflect the domain. type CartItem = { ProductCode: string; Qty: int } type Payment = Payment of float type ActiveCartData = { UnpaidItems: CartItem list } type PaidCartData = { PaidItems: CartItem list; Payment: Payment} - - type ShoppingCart = + + type ShoppingCart = | EmptyCart // no data | ActiveCart of ActiveCartData - | PaidCart of PaidCartData + | PaidCart of PaidCartData - // ------------------------------------ + // ------------------------------------ // Built in behavior for types - // ------------------------------------ + // ------------------------------------ // Core types have useful "out-of-the-box" behavior, no coding needed. // * Immutability // * Pretty printing when debugging // * Equality and comparison // * Serialization - + // Pretty printing using %A - printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" + printfn "twoTuple=%A,\nPerson=%A,\nTemp=%A,\nEmployee=%A" twoTuple person1 temp1 worker // Equality and comparison built in. // Here's an example with cards. type Suit = Club | Diamond | Spade | Heart - type Rank = Two | Three | Four | Five | Six | Seven | Eight - | Nine | Ten | Jack | Queen | King | Ace + type Rank = Two | Three | Four | Five | Six | Seven | Eight + | Nine | Ten | Jack | Queen | King | Ace - let hand = [ Club,Ace; Heart,Three; Heart,Ace; - Spade,Jack; Diamond,Two; Diamond,Ace ] + let hand = [ Club, Ace; Heart, Three; Heart, Ace; + Spade, Jack; Diamond, Two; Diamond, Ace ] // sorting List.sort hand |> printfn "sorted hand is (low to high) %A" List.max hand |> printfn "high card is %A" List.min hand |> printfn "low card is %A" - + // ================================================ // Active patterns // ================================================ -module ActivePatternExamples = +module ActivePatternExamples = - // F# has a special type of pattern matching called "active patterns" - // where the pattern can be parsed or detected dynamically. + // F# has a special type of pattern matching called "active patterns" + // where the pattern can be parsed or detected dynamically. // "banana clips" are the syntax for active patterns - + // for example, define an "active" pattern to match character types... - let (|Digit|Letter|Whitespace|Other|) ch = + let (|Digit|Letter|Whitespace|Other|) ch = if System.Char.IsDigit(ch) then Digit else if System.Char.IsLetter(ch) then Letter else if System.Char.IsWhiteSpace(ch) then Whitespace - else Other + else Other // ... and then use it to make parsing logic much clearer - let printChar ch = + let printChar ch = match ch with | Digit -> printfn "%c is a Digit" ch | Letter -> printfn "%c is a Letter" ch @@ -419,57 +419,57 @@ module ActivePatternExamples = | _ -> printfn "%c is something else" ch // print a list - ['a';'b';'1';' ';'-';'c'] |> List.iter printChar + ['a'; 'b'; '1'; ' '; '-'; 'c'] |> List.iter printChar // ----------------------------------- // FizzBuzz using active patterns // ----------------------------------- - + // You can create partial matching patterns as well - // Just use undercore in the defintion, and return Some if matched. + // Just use underscore in the defintion, and return Some if matched. let (|MultOf3|_|) i = if i % 3 = 0 then Some MultOf3 else None let (|MultOf5|_|) i = if i % 5 = 0 then Some MultOf5 else None // the main function - let fizzBuzz i = + let fizzBuzz i = match i with - | MultOf3 & MultOf5 -> printf "FizzBuzz, " - | MultOf3 -> printf "Fizz, " - | MultOf5 -> printf "Buzz, " + | MultOf3 & MultOf5 -> printf "FizzBuzz, " + | MultOf3 -> printf "Fizz, " + | MultOf5 -> printf "Buzz, " | _ -> printf "%i, " i - + // test - [1..20] |> List.iter fizzBuzz - + [1..20] |> List.iter fizzBuzz + // ================================================ -// Conciseness +// Conciseness // ================================================ -module AlgorithmExamples = +module AlgorithmExamples = - // F# has a high signal/noise ratio, so code reads + // F# has a high signal/noise ratio, so code reads // almost like the actual algorithm // ------ Example: define sumOfSquares function ------ - let sumOfSquares n = + let sumOfSquares n = [1..n] // 1) take all the numbers from 1 to n |> List.map square // 2) square each one |> List.sum // 3) sum the results - // test - sumOfSquares 100 |> printfn "Sum of squares = %A" - - // ------ Example: define a sort function ------ + // test + sumOfSquares 100 |> printfn "Sum of squares = %A" + + // ------ Example: define a sort function ------ let rec sort list = match list with - // If the list is empty - | [] -> + // If the list is empty + | [] -> [] // return an empty list - // If the list is not empty - | firstElem::otherElements -> // take the first element - let smallerElements = // extract the smaller elements + // If the list is not empty + | firstElem::otherElements -> // take the first element + let smallerElements = // extract the smaller elements otherElements // from the remaining ones - |> List.filter (fun e -> e < firstElem) + |> List.filter (fun e -> e < firstElem) |> sort // and sort them let largerElements = // extract the larger ones otherElements // from the remaining ones @@ -479,13 +479,13 @@ module AlgorithmExamples = List.concat [smallerElements; [firstElem]; largerElements] // test - sort [1;5;23;18;9;1;3] |> printfn "Sorted = %A" + sort [1; 5; 23; 18; 9; 1; 3] |> printfn "Sorted = %A" // ================================================ // Asynchronous Code // ================================================ -module AsyncExample = +module AsyncExample = // F# has built-in features to help with async code // without encountering the "pyramid of doom" @@ -495,23 +495,23 @@ module AsyncExample = open System.Net open System open System.IO - open Microsoft.FSharp.Control.CommonExtensions + open Microsoft.FSharp.Control.CommonExtensions // Fetch the contents of a URL asynchronously - let fetchUrlAsync url = - async { // "async" keyword and curly braces + let fetchUrlAsync url = + async { // "async" keyword and curly braces // creates an "async" object - let req = WebRequest.Create(Uri(url)) - use! resp = req.AsyncGetResponse() + let req = WebRequest.Create(Uri(url)) + use! resp = req.AsyncGetResponse() // use! is async assignment - use stream = resp.GetResponseStream() + use stream = resp.GetResponseStream() // "use" triggers automatic close() // on resource at end of scope - use reader = new IO.StreamReader(stream) - let html = reader.ReadToEnd() - printfn "finished downloading %s" url + use reader = new IO.StreamReader(stream) + let html = reader.ReadToEnd() + printfn "finished downloading %s" url } - + // a list of sites to fetch let sites = ["http://www.bing.com"; "http://www.google.com"; @@ -520,90 +520,90 @@ module AsyncExample = "http://www.yahoo.com"] // do it - sites + sites |> List.map fetchUrlAsync // make a list of async tasks |> Async.Parallel // set up the tasks to run in parallel |> Async.RunSynchronously // start them off // ================================================ -// .NET compatability +// .NET compatibility // ================================================ -module NetCompatibilityExamples = +module NetCompatibilityExamples = // F# can do almost everything C# can do, and it integrates // seamlessly with .NET or Mono libraries. // ------- work with existing library functions ------- - - let (i1success,i1) = System.Int32.TryParse("123"); + + let (i1success, i1) = System.Int32.TryParse("123"); if i1success then printfn "parsed as %i" i1 else printfn "parse failed" // ------- Implement interfaces on the fly! ------- - + // create a new object that implements IDisposable - let makeResource name = - { new System.IDisposable + let makeResource name = + { new System.IDisposable with member this.Dispose() = printfn "%s disposed" name } - let useAndDisposeResources = + let useAndDisposeResources = use r1 = makeResource "first resource" - printfn "using first resource" + printfn "using first resource" for i in [1..3] do let resourceName = sprintf "\tinner resource %d" i - use temp = makeResource resourceName - printfn "\tdo something with %s" resourceName + use temp = makeResource resourceName + printfn "\tdo something with %s" resourceName use r2 = makeResource "second resource" - printfn "using second resource" - printfn "done." + printfn "using second resource" + printfn "done." // ------- Object oriented code ------- - + // F# is also a fully fledged OO language. // It supports classes, inheritance, virtual methods, etc. // interface with generic type - type IEnumerator<'a> = + type IEnumerator<'a> = abstract member Current : 'a - abstract MoveNext : unit -> bool + abstract MoveNext : unit -> bool // abstract base class with virtual methods [<AbstractClass>] - type Shape() = - //readonly properties + type Shape() = + // readonly properties abstract member Width : int with get abstract member Height : int with get - //non-virtual method + // non-virtual method member this.BoundingArea = this.Height * this.Width - //virtual method with base implementation - abstract member Print : unit -> unit + // virtual method with base implementation + abstract member Print : unit -> unit default this.Print () = printfn "I'm a shape" - // concrete class that inherits from base class and overrides - type Rectangle(x:int, y:int) = + // concrete class that inherits from base class and overrides + type Rectangle(x:int, y:int) = inherit Shape() override this.Width = x override this.Height = y override this.Print () = printfn "I'm a Rectangle" - //test - let r = Rectangle(2,3) + // test + let r = Rectangle(2, 3) printfn "The width is %i" r.Width printfn "The area is %i" r.BoundingArea - r.Print() + r.Print() // ------- extension methods ------- - - //Just as in C#, F# can extend existing classes with extension methods. + + // Just as in C#, F# can extend existing classes with extension methods. type System.String with member this.StartsWithA = this.StartsWith "A" - //test + // test let s = "Alice" - printfn "'%s' starts with an 'A' = %A" s s.StartsWithA - + printfn "'%s' starts with an 'A' = %A" s s.StartsWithA + // ------- events ------- - + type MyButton() = let clickEvent = new Event<_>() @@ -615,11 +615,11 @@ module NetCompatibilityExamples = // test let myButton = new MyButton() - myButton.OnClick.Add(fun (sender, arg) -> + myButton.OnClick.Add(fun (sender, arg) -> printfn "Click event with arg=%O" arg) myButton.TestEvent("Hello World!") - + ``` ## More Information diff --git a/git.html.markdown b/git.html.markdown index 04350dd5..e7ca07d6 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -5,20 +5,22 @@ contributors: - ["Jake Prather", "http://github.com/JakeHP"] - ["Leo Rudberg" , "http://github.com/LOZORD"] - ["Betsy Lorton" , "http://github.com/schbetsy"] + - ["Bruno Volcov", "http://github.com/volcov"] + - ["Andrew Taylor", "http://github.com/andrewjt71"] filename: LearnGit.txt --- -Git is a distributed version control and source code management system. +Git is a distributed version control and source code management system. -It does this through a series of snapshots of your project, and it works -with those snapshots to provide you with functionality to version and +It does this through a series of snapshots of your project, and it works +with those snapshots to provide you with functionality to version and manage your source code. ## Versioning Concepts ### What is version control? -Version control is a system that records changes to a file, or set of files, over time. +Version control is a system that records changes to a file(s), over time. ### Centralized Versioning VS Distributed Versioning @@ -42,8 +44,9 @@ Version control is a system that records changes to a file, or set of files, ove ### Repository -A set of files, directories, historical records, commits, and heads. Imagine it as a source code data structure, -with the attribute that each source code "element" gives you access to its revision history, among other things. +A set of files, directories, historical records, commits, and heads. Imagine it +as a source code data structure, with the attribute that each source code +"element" gives you access to its revision history, among other things. A git repository is comprised of the .git directory & working tree. @@ -54,31 +57,42 @@ The .git directory contains all the configurations, logs, branches, HEAD, and mo ### Working Tree (component of repository) -This is basically the directories and files in your repository. It is often referred to -as your working directory. +This is basically the directories and files in your repository. It is often +referred to as your working directory. ### Index (component of .git dir) The Index is the staging area in git. It's basically a layer that separates your working tree -from the Git repository. This gives developers more power over what gets sent to the Git -repository. +from the Git repository. This gives developers more power over what gets sent +to the Git repository. ### Commit -A git commit is a snapshot of a set of changes, or manipulations to your Working Tree. -For example, if you added 5 files, and removed 2 others, these changes will be contained -in a commit (or snapshot). This commit can then be pushed to other repositories, or not! +A git commit is a snapshot of a set of changes, or manipulations to your Working +Tree. For example, if you added 5 files, and removed 2 others, these changes +will be contained in a commit (or snapshot). This commit can then be pushed to +other repositories, or not! ### Branch -A branch is essentially a pointer that points to the last commit you made. As you commit, -this pointer will automatically update and point to the latest commit. +A branch is essentially a pointer to the last commit you made. As you go on +committing, this pointer will automatically update to point the latest commit. + +### Tag + +A tag is a mark on specific point in history. Typically people use this +functionality to mark release points (v1.0, and so on) ### HEAD and head (component of .git dir) HEAD is a pointer that points to the current branch. A repository only has 1 *active* HEAD. head is a pointer that points to any commit. A repository can have any number of heads. +### Stages of Git +* Modified - Changes have been made to a file but file has not been committed to Git Database yet +* Staged - Marks a modified file to go into your next commit snapshot +* Committed - Files have been committed to the Git Database + ### Conceptual Resources * [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) @@ -90,7 +104,7 @@ head is a pointer that points to any commit. A repository can have any number of ### init -Create an empty Git repository. The Git repository's settings, stored information, +Create an empty Git repository. The Git repository's settings, stored information, and more is stored in a directory (a folder) named ".git". ```bash @@ -99,15 +113,12 @@ $ git init ### config -To configure settings. Whether it be for the repository, the system itself, or global -configurations. +To configure settings. Whether it be for the repository, the system itself, +or global configurations ( global config file is `~/.gitconfig` ). ```bash # Print & Set Some Basic Config Variables (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" ``` @@ -131,12 +142,26 @@ $ git help -a $ git help add $ git help commit $ git help init +# or git <command_here> --help +$ git add --help +$ git commit --help +$ git init --help +``` + +### ignore files + +To intentionally untrack file(s) & folder(s) from git. Typically meant for +private & temp files which would otherwise be shared in the repository. +```bash +$ echo "temp/" >> .gitignore +$ echo "private_key" >> .gitignore ``` + ### status -To show differences between the index file (basically your working copy/repo) and the current -HEAD commit. +To show differences between the index file (basically your working copy/repo) +and the current HEAD commit. ```bash @@ -149,8 +174,8 @@ $ git help status ### add -To add files to the current working tree/directory/repo. If you do not `git add` new files to the -working tree/directory, they will not be included in commits! +To add files to the staging area/index. If you do not `git add` new files to the +staging area/index, they will not be included in commits! ```bash # add a file in your current working directory @@ -163,6 +188,9 @@ $ git add /path/to/file/HelloWorld.c $ git add ./*.java ``` +This only adds a file to the staging area/index, it doesn't commit it to the +working directory/repo. + ### branch Manage your branches. You can view, edit, create, delete branches using this command. @@ -185,6 +213,28 @@ $ git branch -m myBranchName myNewBranchName $ git branch myBranchName --edit-description ``` +### tag + +Manage your tags + +```bash +# List tags +$ git tag +# Create a annotated tag +# The -m specifies a tagging message,which is stored with the tag. +# If you don’t specify a message for an annotated tag, +# Git launches your editor so you can type it in. +$ git tag -a v2.0 -m 'my version 2.0' +# Show info about tag +# That shows the tagger information, the date the commit was tagged, +# and the annotation message before showing the commit information. +$ git show v2.0 +# Push a single tag to remote +$ git push origin v2.0 +# Push a lot of tags to remote +$ git push origin --tags +``` + ### checkout Updates all files in the working tree to match the version in the index, or specified tree. @@ -194,7 +244,8 @@ Updates all files in the working tree to match the version in the index, or spec $ git checkout # Checkout a specified branch $ git checkout branchName -# Create a new branch & switch to it, like: "git branch <name>; git checkout <name>" +# Create a new branch & switch to it +# equivalent to "git branch <name>; git checkout <name>" $ git checkout -b newBranch ``` @@ -207,6 +258,10 @@ to a remote branch. ```bash # Clone learnxinyminutes-docs $ git clone https://github.com/adambard/learnxinyminutes-docs.git +# shallow clone - faster cloning that pulls only latest snapshot +$ git clone --depth 1 https://github.com/adambard/learnxinyminutes-docs.git +# clone only a specific branch +$ git clone -b master-cn https://github.com/adambard/learnxinyminutes-docs.git --single-branch ``` ### commit @@ -217,6 +272,12 @@ the changes made and a message created by the user. ```bash # commit with a message $ git commit -m "Added multiplyNumbers() function to HelloWorld.c" + +# automatically stage modified or deleted files, except new files, and then commit +$ git commit -a -m "Modified foo.php and removed bar.php" + +# change last commit (this deletes previous commit with a fresh commit) +$ git commit --amend -m "Correct message" ``` ### diff @@ -254,7 +315,7 @@ $ git config --global alias.g "grep --break --heading --line-number" $ git grep 'variableName' -- '*.java' # Search for a line that contains "arrayListName" and, "add" or "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) +$ git grep -e 'arrayListName' --and \( -e add -e remove \) ``` Google is your friend; for more examples @@ -268,11 +329,14 @@ Display commits to the repository. # Show all commits $ git log -# Show X number of commits -$ git log -n 10 +# Show only commit message & ref +$ git log --oneline # Show merge commits only $ git log --merges + +# Show all commits represented by an ASCII graph +$ git log --graph ``` ### merge @@ -289,7 +353,7 @@ $ git merge --no-ff branchName ### mv -Rename or move a file +Rename or move a file ```bash # Renaming a file @@ -311,9 +375,12 @@ Pulls from a repository and merges it with another branch. # Update your local repo, by merging in new changes # from the remote "origin" and "master" branch. # git pull <remote> <branch> -# git pull => implicitly defaults to => git pull origin master $ git pull origin master +# By default, git pull will update your current branch +# by merging in new changes from its remote-tracking branch +$ git pull + # Merge in changes from remote branch and rebase # branch commits onto your local repo, like: "git pull <remote> <branch>, git rebase <branch>" $ git pull origin master --rebase @@ -324,32 +391,37 @@ $ git pull origin master --rebase Push and merge changes from a branch to a remote & branch. ```bash -# Push and merge changes from a local repo to a +# Push and merge changes from a local repo to a # remote named "origin" and "master" branch. # git push <remote> <branch> -# git push => implicitly defaults to => git push origin master $ git push origin master +# By default, git push will push and merge changes from +# the current branch to its remote-tracking branch +$ git push + # To link up current local branch with a remote branch, add -u flag: $ git push -u origin master # Now, anytime you want to push from that same local branch, use shortcut: -$ git push +$ git push ``` ### stash -Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time. +Stashing takes the dirty state of your working directory and saves it on a stack +of unfinished changes that you can reapply at any time. -Let's say you've been doing some work in your git repo, but you want to pull from the remote. -Since you have dirty (uncommited) changes to some files, you are not able to run `git pull`. -Instead, you can run `git stash` to save your changes onto a stack! +Let's say you've been doing some work in your git repo, but you want to pull +from the remote. Since you have dirty (uncommited) changes to some files, you +are not able to run `git pull`. Instead, you can run `git stash` to save your +changes onto a stack! ```bash $ git stash Saved working directory and index state \ "WIP on master: 049d078 added the index file" HEAD is now at 049d078 added the index file - (To restore them type "git stash apply") + (To restore them type "git stash apply") ``` Now you can pull! @@ -396,7 +468,7 @@ Now you're ready to get back to work on your stuff! [Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing) -### rebase (caution) +### rebase (caution) Take all changes that were committed on one branch, and replay them onto another branch. *Do not rebase commits that you have pushed to a public repo*. @@ -431,6 +503,16 @@ $ git reset 31f2bb1 # after the specified commit). $ git reset --hard 31f2bb1 ``` +### revert + +Revert can be used to undo a commit. It should not be confused with reset which restores +the state of a project to a previous point. Revert will add a new commit which is the +inverse of the specified commit, thus reverting it. + +```bash +# Revert a specified commit +$ git revert <commit> +``` ### rm @@ -448,6 +530,10 @@ $ git rm /pather/to/the/file/HelloWorld.c * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + +* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/) + * [git-scm - Video Tutorials](http://git-scm.com/videos) * [git-scm - Documentation](http://git-scm.com/docs) @@ -459,3 +545,8 @@ $ git rm /pather/to/the/file/HelloWorld.c * [GitGuys](http://www.gitguys.com/) * [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + +* [Pro Git](http://www.git-scm.com/book/en/v2) + +* [An introduction to Git and GitHub for Beginners (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) + diff --git a/go.html.markdown b/go.html.markdown index 17f10bd9..dc684227 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Quint Guvernator", "https://github.com/qguv"] - ["Jose Donizetti", "https://github.com/josedonizetti"] - ["Alexej Friesen", "https://github.com/heyalexej"] + - ["Clayton Walker", "https://github.com/cwalk"] --- Go was created out of the need to get work done. It's not the latest trend @@ -64,7 +65,11 @@ func beyondHello() { learnTypes() // < y minutes, learn more! } -// Functions can have parameters and (multiple!) return values. +/* <- multiline comment +Functions can have parameters and (multiple!) return values. +Here `x`, `y` are the arguments and `sum`, `prod` is the signature (what's returned). +Note that `x` and `sum` receive the type `int`. +*/ func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Return two values. } @@ -83,7 +88,7 @@ can include line breaks.` // Same string type. 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 syntax with initializers. var u uint = 7 // Unsigned, but implementation dependent size as with int. var pi float32 = 22. / 7 @@ -103,15 +108,16 @@ can include line breaks.` // Same string type. bs := []byte("a slice") // Type conversion syntax. // Because they are dynamic, slices can be appended to on-demand. - // To append elements to a slice, built-in append() function is used. + // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, // the array variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a - // trailing elipsis, meaning take a slice and unpack its elements, + // trailing ellipsis, meaning take a slice and unpack its elements, // appending them to slice s. s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] @@ -125,7 +131,7 @@ can include line breaks.` // Same string type. m["one"] = 1 // Unused variables are an error in Go. - // The underbar lets you "use" a variable but discard its value. + // The underscore lets you "use" a variable but discard its value. _, _, _, _, _, _, _, _, _, _ = str, 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) @@ -160,7 +166,7 @@ func expensiveComputation() float64 { } func learnFlowControl() { - // If statements require brace brackets, and do not require parens. + // If statements require brace brackets, and do not require parentheses. if true { fmt.Println("told ya") } @@ -177,8 +183,14 @@ func learnFlowControl() { case 1: case 42: // Cases don't "fall through". + /* + There is a `fallthrough` keyword however, see: + https://github.com/golang/go/wiki/Switch#fall-through + */ case 43: // Unreached. + default: + // Default case is optional. } // Like if, for doesn't use parens either. // Variables declared in for and if are local to their scope. @@ -397,6 +409,8 @@ func requestServer() { The root of all things Go is the [official Go web site](http://golang.org/). There you can follow the tutorial, play interactively, and read lots. +Aside from a tour, [the docs](https://golang.org/doc/) contain information on +how to write clean and effective Go code, package and command docs, and release history. The language definition itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) @@ -410,3 +424,5 @@ idioms. Or you can click on a function name in [the documentation](http://golang.org/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). + +Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. diff --git a/groovy.html.markdown b/groovy.html.markdown index 8fb1b346..492c1ba2 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -6,7 +6,7 @@ contributors: filename: learngroovy.groovy --- -Groovy - A dynamic language for the Java platform [Read more here.](http://groovy.codehaus.org) +Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) ```groovy @@ -99,7 +99,7 @@ technologies.sort() // To sort without mutating original, you can do: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/ +/*** Manipulating Lists ***/e //Replace all elements in the list Collections.replaceAll(technologies, 'Gradle', 'gradle') @@ -200,6 +200,14 @@ def y = 10 def x = (y > 1) ? "worked" : "failed" assert x == "worked" +//Groovy supports 'The Elvis Operator' too! +//Instead of using the ternary operator: + +displayName = user.name ? user.name : 'Anonymous' + +//We can write it: +displayName = user.name ?: 'Anonymous' + //For loop //Iterate over a range def x = 0 @@ -231,7 +239,7 @@ for ( e in map ) { Operators Operator Overloading for a list of the common operators that Groovy supports: - http://groovy.codehaus.org/Operator+Overloading + http://www.groovy-lang.org/operators.html#Operator-Overloading Helpful groovy operators */ @@ -249,7 +257,7 @@ def username = user?.username A Groovy Closure is like a "code block" or a method pointer. It is a piece of code that is defined and then executed at a later point. - More info at: http://groovy.codehaus.org/Closures+-+Formal+Definition + More info at: http://www.groovy-lang.org/closures.html */ //Example: def clos = { println "Hello World!" } @@ -405,11 +413,11 @@ assert sum(2,5) == 7 ## Further resources -[Groovy documentation](http://groovy.codehaus.org/Documentation) +[Groovy documentation](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -Join a [Groovy user group](http://groovy.codehaus.org/User+Groups) +Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) ## Books @@ -422,6 +430,3 @@ Join a [Groovy user group](http://groovy.codehaus.org/User+Groups) [1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ [2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize [3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html - - - diff --git a/hack.html.markdown b/hack.html.markdown new file mode 100644 index 00000000..b3d19f8e --- /dev/null +++ b/hack.html.markdown @@ -0,0 +1,308 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +filename: learnhack.hh +--- + +Hack is a superset of PHP that runs under a virtual machine called HHVM. Hack +is almost completely interoperable with existing PHP code and adds a bunch of +useful features from statically typed languages. + + +Only Hack-specific features are covered here. Details about PHP's syntax are +available in the [PHP article](http://learnxinyminutes.com/docs/php/) on this site. + +```php +<?hh + +// Hack syntax is only enabled for files starting with an <?hh marker +// <?hh markers cannot be interspersed with HTML the way <?php can be. +// Using the marker "<?hh //strict" puts the type checker in strict mode. + + +// Scalar parameter type hints +function repeat(string $word, int $count) +{ + $word = trim($word); + return str_repeat($word . ' ', $count); +} + +// Type hints for return values +function add(...$numbers) : int +{ + return array_sum($numbers); +} + +// Functions that return nothing are hinted as "void" +function truncate(resource $handle) : void +{ + // ... +} + +// Type hints must explicitly allow being nullable +function identity(?string $stringOrNull) : ?string +{ + return $stringOrNull; +} + +// Type hints can be specified on class properties +class TypeHintedProperties +{ + public ?string $name; + + protected int $id; + + private float $score = 100.0; + + // Hack's type checker enforces that typed properties either have a + // default value or are set in the constructor. + public function __construct(int $id) + { + $this->id = $id; + } +} + + +// Concise anonymous functions (lambdas) +$multiplier = 5; +array_map($y ==> $y * $multiplier, [1, 2, 3]); + + +// Generics +class Box<T> +{ + protected T $data; + + public function __construct(T $data) { + $this->data = $data; + } + + public function getData(): T { + return $this->data; + } +} + +function openBox(Box<int> $box) : int +{ + return $box->getData(); +} + + +// Shapes +// +// Hack adds the concept of shapes for defining struct-like arrays with a +// guaranteed, type-checked set of keys +type Point2D = shape('x' => int, 'y' => int); + +function distance(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distance( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Type aliasing +// +// Hack adds a bunch of type aliasing features for making complex types readable +newtype VectorArray = array<int, Vector<int>>; + +// A tuple containing two integers +newtype Point = (int, int); + +function addPoints(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +addPoints( + tuple(1, 2), + tuple(5, 6) +); + + +// First-class enums +enum RoadType : int +{ + Road = 0; + Street = 1; + Avenue = 2; + Boulevard = 3; +} + +function getRoadType() : RoadType +{ + return RoadType::Avenue; +} + + +// Constructor argument promotion +// +// To avoid boilerplate property and constructor definitions that only set +// properties, Hack adds a concise syntax for defining properties and a +// constructor at the same time. +class ArgumentPromotion +{ + public function __construct(public string $name, + protected int $age, + private bool $isAwesome) {} +} + +class WithoutArgumentPromotion +{ + public string $name; + + protected int $age; + + private bool $isAwesome; + + public function __construct(string $name, int $age, bool $isAwesome) + { + $this->name = $name; + $this->age = $age; + $this->isAwesome = $isAwesome; + } +} + + +// Co-operative multi-tasking +// +// Two new keywords "async" and "await" can be used to perform multi-tasking +// Note that this does not involve threads - it just allows transfer of control +async function cooperativePrint(int $start, int $end) : Awaitable<void> +{ + for ($i = $start; $i <= $end; $i++) { + echo "$i "; + + // Give other tasks a chance to do something + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// This prints "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + cooperativePrint(1, 3), + cooperativePrint(4, 6), + cooperativePrint(7, 9) +])->getWaitHandle()->join(); + + +// Attributes +// +// Attributes are a form of metadata for functions. Hack provides some +// special built-in attributes that introduce useful behaviour. + +// The __Memoize special attribute causes the result of a function to be cached +<<__Memoize>> +function doExpensiveTask() : ?string +{ + return file_get_contents('http://example.com'); +} + +// The function's body is only executed once here: +doExpensiveTask(); +doExpensiveTask(); + + +// The __ConsistentConstruct special attribute signals the Hack type checker to +// ensure that the signature of __construct is the same for all subclasses. +<<__ConsistentConstruct>> +class ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function someMethod() + { + // ... + } +} + +class ConsistentBar extends ConsistentFoo +{ + public function __construct(int $x, float $y) + { + // Hack's type checker enforces that parent constructors are called + parent::__construct($x, $y); + + // ... + } + + // The __Override annotation is an optional signal for the Hack type + // checker to enforce that this method is overriding a method in a parent + // or trait. If not, this will error. + <<__Override>> + public function someMethod() + { + // ... + } +} + +class InvalidFooSubclass extends ConsistentFoo +{ + // Not matching the parent constructor will cause a type checker error: + // + // "This object is of type ConsistentBaz. It is incompatible with this object + // of type ConsistentFoo because some of their methods are incompatible" + // + public function __construct(float $x) + { + // ... + } + + // Using the __Override annotation on a non-overriden method will cause a + // type checker error: + // + // "InvalidFooSubclass::otherMethod() is marked as override; no non-private + // parent definition found or overridden parent is defined in non-<?hh code" + // + <<__Override>> + public function otherMethod() + { + // ... + } +} + + +// Traits can implement interfaces (standard PHP does not support this) +interface KittenInterface +{ + public function play() : void; +} + +trait CatTrait implements KittenInterface +{ + public function play() : void + { + // ... + } +} + +class Samuel +{ + use CatTrait; +} + + +$cat = new Samuel(); +$cat instanceof KittenInterface === true; // True + +``` + +## More Information + +Visit the [Hack language reference](http://docs.hhvm.com/manual/en/hacklangref.php) +for detailed explainations of the features Hack adds to PHP, or the [official Hack website](http://hacklang.org/) +for more general information. + +Visit the [official HHVM website](http://hhvm.com/) for HHVM installation instructions. + +Visit [Hack's unsupported PHP features article](http://docs.hhvm.com/manual/en/hack.unsupported.php) +for details on the backwards incompatibility between Hack and PHP. diff --git a/haml.html.markdown b/haml.html.markdown index aed3dcae..0948e9ef 100644 --- a/haml.html.markdown +++ b/haml.html.markdown @@ -62,11 +62,11 @@ $ haml input_file.haml output_file.html %h1 Headline copy / To write multiline content, nest it instead -%p +%p This is a lot of content that we could probably split onto two separate lines. -/ +/ You can escape html by using the ampersand and equals sign ( &= ). This converts html-sensitive characters (&, /, :) into their html encoded equivalents. For example @@ -102,7 +102,7 @@ $ haml input_file.haml output_file.html / Inserting Ruby / ------------------------------------------- -/ +/ To output a Ruby value as the contents of a tag, use an equals sign followed by the Ruby code @@ -122,11 +122,36 @@ $ haml input_file.haml output_file.html if book do %p This is a book + +/ Adding ordered / unordered list +%ul + %li + =item1 + =item2 / Again, no need to add the closing tags to the block, even for the Ruby. Indentation will take care of that for you. +/ ------------------------------------------- +/ Inserting Table with bootstrap classes +/ ------------------------------------------- + +%table.table.table-hover + %thead + %tr + %th Header 1 + %th Header 2 + + %tr + %td Value1 + %td value2 + + %tfoot + %tr + %td + Foot value + / ------------------------------------------- / Inline Ruby / Ruby interpolation @@ -141,7 +166,7 @@ $ haml input_file.haml output_file.html / ------------------------------------------- / - Use the colon to define Haml filters, one example of a filter you can + Use the colon to define Haml filters, one example of a filter you can use is :javascript, which can be used for writing inline js :javascript diff --git a/haskell.html.markdown b/haskell.html.markdown index 748a29da..936744a0 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -59,6 +59,7 @@ not False -- True "Hello " ++ "world!" -- "Hello world!" -- A string is a list of characters +['H', 'e', 'l', 'l', 'o'] -- "Hello" "This is a string" !! 0 -- 'T' @@ -67,10 +68,21 @@ not False -- True ---------------------------------------------------- -- Every element in a list must have the same type. --- Two lists that are the same +-- These two lists are the same: [1, 2, 3, 4, 5] [1..5] +-- Ranges are versatile. +['A'..'F'] -- "ABCDEF" + +-- You can create a step in a range. +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- This doesn't work because Haskell defaults to incrementing. +[5,4..1] -- [5, 4, 3, 2, 1] + +-- indexing into a list +[1..10] !! 3 -- 4 + -- You can also have infinite lists in Haskell! [1..] -- a list of all the natural numbers @@ -90,9 +102,6 @@ not False -- True -- adding to the head of a list 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- indexing into a list -[0..] !! 5 -- 5 - -- more list operations head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] @@ -139,12 +148,12 @@ add 1 2 -- 3 -- Guards: an easy way to do branching in functions fib x - | x < 2 = x + | x < 2 = 1 | otherwise = fib (x - 1) + fib (x - 2) -- Pattern matching is similar. Here we have given three different -- definitions for fib. Haskell will automatically call the first --- function that matches the pattern of the value. +-- function that matches the pattern of the value. fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) @@ -172,7 +181,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- -- partial application: if you don't pass in all the arguments to a function, --- it gets "partially applied". That means it returns a function that takes the +-- it gets "partially applied". That means it returns a function that takes the -- rest of the arguments. add a b = a + b @@ -186,26 +195,28 @@ foo 5 -- 15 -- function composition -- the (.) function chains functions together. -- For example, here foo is a function that takes a value. It adds 10 to it, --- multiplies the result of that by 5, and then returns the final value. -foo = (*5) . (+10) +-- multiplies the result of that by 4, and then returns the final value. +foo = (*4) . (+10) --- (5 + 10) * 5 = 75 -foo 5 -- 75 +-- (5 + 10) * 4 = 60 +foo 5 -- 60 -- fixing precedence --- Haskell has another function called `$`. This changes the precedence --- so that everything to the left of it gets computed first and then applied --- to everything on the right. You can use `$` (often in combination with `.`) --- to get rid of a lot of parentheses: +-- Haskell has another operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator +-- has priority of 0 and is right-associative. Such a low priority means that +-- the expression on its right is applied as the parameter to the function on its left. -- before -(even (fib 7)) -- true - --- after -even . fib $ 7 -- true +even (fib 7) -- false -- equivalently -even $ fib 7 -- true +even $ fib 7 -- false + +-- composing functions +even . fib $ 7 -- false + ---------------------------------------------------- -- 5. Type signatures @@ -272,7 +283,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 -- This is now the same as -(2 * 3 + (2 * 2 + (2 * 1 + 4))) +(2 * 1 + (2 * 2 + (2 * 3 + 4))) ---------------------------------------------------- -- 7. Data Types @@ -310,13 +321,13 @@ Nothing -- of type `Maybe a` for any `a` -- called. It must return a value of type `IO ()`. For example: main :: IO () -main = putStrLn $ "Hello, sky! " ++ (say Blue) +main = putStrLn $ "Hello, sky! " ++ (say Blue) -- putStrLn has type String -> IO () --- It is easiest to do IO if you can implement your program as --- a function from String to String. The function +-- It is easiest to do IO if you can implement your program as +-- a function from String to String. The function -- interact :: (String -> String) -> IO () --- inputs some text, runs a function on it, and prints out the +-- inputs some text, runs a function on it, and prints out the -- output. countLines :: String -> String @@ -330,43 +341,43 @@ main' = interact countLines -- the `do` notation to chain actions together. For example: sayHello :: IO () -sayHello = do +sayHello = do putStrLn "What is your name?" name <- getLine -- this gets a line and gives it the name "name" putStrLn $ "Hello, " ++ name - + -- Exercise: write your own version of `interact` that only reads -- one line of input. - + -- The code in `sayHello` will never be executed, however. The only --- action that ever gets executed is the value of `main`. --- To run `sayHello` comment out the above definition of `main` +-- action that ever gets executed is the value of `main`. +-- To run `sayHello` comment out the above definition of `main` -- and replace it with: -- main = sayHello --- Let's understand better how the function `getLine` we just +-- Let's understand better how the function `getLine` we just -- used works. Its type is: -- getLine :: IO String -- You can think of a value of type `IO a` as representing a --- computer program that will generate a value of type `a` +-- computer program that will generate a value of type `a` -- when executed (in addition to anything else it does). We can --- store and reuse this value using `<-`. We can also +-- store and reuse this value using `<-`. We can also -- make our own action of type `IO String`: action :: IO String action = do putStrLn "This is a line. Duh" - input1 <- getLine + input1 <- getLine input2 <- getLine -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `return` is not a keyword, but merely a function return (input1 ++ "\n" ++ input2) -- return :: String -> IO String -- We can use this just like we used `getLine`: main'' = do putStrLn "I will echo two lines!" - result <- action + result <- action putStrLn result putStrLn "This was all, folks!" diff --git a/haxe.html.markdown b/haxe.html.markdown index 6a868f09..ee214540 100644 --- a/haxe.html.markdown +++ b/haxe.html.markdown @@ -3,6 +3,7 @@ language: haxe filename: LearnHaxe3.hx contributors: - ["Justin Donaldson", "https://github.com/jdonaldson/"] + - ["Dan Korostelev", "https://github.com/nadako/"] --- Haxe is a web-oriented language that provides platform support for C++, C#, @@ -34,16 +35,20 @@ references. /* This is your first actual haxe code coming up, it's declaring an empty package. A package isn't necessary, but it's useful if you want to create a - namespace for your code (e.g. org.module.ClassName). + namespace for your code (e.g. org.yourapp.ClassName). + + Omitting package declaration is the same as declaring an empty package. */ package; // empty package, no namespace. /* - Packages define modules for your code. Each module (e.g. org.module) must - be lower case, and should exist as a folder structure containing the class. - Class (and type) names must be capitalized. E.g, the class "org.module.Foo" - should have the folder structure org/module/Foo.hx, as accessible from the - compiler's working directory or class path. + Packages are directories that contain modules. Each module is a .hx file + that contains types defined in a package. Package names (e.g. org.yourapp) + must be lower case while module names are capitalized. A module contain one + or more types whose names are also capitalized. + + E.g, the class "org.yourapp.Foo" should have the folder structure org/module/Foo.hx, + as accessible from the compiler's working directory or class path. If you import code from other files, it must be declared before the rest of the code. Haxe provides a lot of common default classes to get you started: @@ -53,6 +58,12 @@ import haxe.ds.ArraySort; // you can import many classes/modules at once with "*" import haxe.ds.*; +// you can import static fields +import Lambda.array; + +// you can also use "*" to import all static fields +import Math.*; + /* You can also import classes in a special way, enabling them to extend the functionality of other classes like a "mixin". More on 'using' later. @@ -172,7 +183,8 @@ class LearnHaxe3{ Regexes are also supported, but there's not enough space to go into much detail. */ - trace((~/foobar/.match('foo')) + " is the value for (~/foobar/.match('foo')))"); + var re = ~/foobar/; + trace(re.match('foo') + " is the value for (~/foobar/.match('foo')))"); /* Arrays are zero-indexed, dynamic, and mutable. Missing values are @@ -311,7 +323,7 @@ class LearnHaxe3{ var l = 0; do{ trace("do statement always runs at least once"); - } while (i > 0); + } while (l > 0); // for loop /* @@ -328,7 +340,7 @@ class LearnHaxe3{ // (more on ranges later as well) var n = ['foo', 'bar', 'baz']; for (val in 0...n.length){ - trace(val + " is the value for val (an index for m)"); + trace(val + " is the value for val (an index for n)"); } @@ -363,7 +375,7 @@ class LearnHaxe3{ case "rex" : favorite_thing = "shoe"; case "spot" : favorite_thing = "tennis ball"; default : favorite_thing = "some unknown treat"; - // case _ : "some unknown treat"; // same as default + // case _ : favorite_thing = "some unknown treat"; // same as default } // The "_" case above is a "wildcard" value // that will match anything. @@ -383,13 +395,9 @@ class LearnHaxe3{ */ // if statements - var k = if (true){ - 10; - } else { - 20; - } + var k = if (true) 10 else 20; - trace("K equals ", k); // outputs 10 + trace("k equals ", k); // outputs 10 var other_favorite_thing = switch(my_dog_name) { case "fido" : "teddy"; @@ -484,11 +492,13 @@ class LearnHaxe3{ // we can read this variable trace(foo_instance.public_read + " is the value for foo_instance.public_read"); // but not write it - // foo_instance.public_write = 4; // this will throw an error if uncommented: + // foo_instance.public_read = 4; // this will throw an error if uncommented: // trace(foo_instance.public_write); // as will this. - trace(foo_instance + " is the value for foo_instance"); // calls the toString method - trace(foo_instance.toString() + " is the value for foo_instance.toString()"); // same thing + // calls the toString method: + trace(foo_instance + " is the value for foo_instance"); + // same thing: + trace(foo_instance.toString() + " is the value for foo_instance.toString()"); /* @@ -516,8 +526,8 @@ class LearnHaxe3{ */ class FooClass extends BarClass implements BarInterface{ public var public_any:Int; // public variables are accessible anywhere - public var public_read (default,null): Int; // use this style to only enable public read - public var public_write (null, default): Int; // or public write + public var public_read (default, null): Int; // enable only public read + public var public_write (null, default): Int; // or only public write public var property (get, set): Int; // use this style to enable getters/setters // private variables are not available outside the class. @@ -526,9 +536,10 @@ class FooClass extends BarClass implements BarInterface{ // a public constructor public function new(arg:Int){ - super(); // call the constructor of the parent object, since we extended BarClass + // call the constructor of the parent object, since we extended BarClass: + super(); - this.public_any= 0; + this.public_any = 0; this._private = arg; } @@ -628,6 +639,7 @@ enum ComplexEnum{ ComplexEnumEnum(c:ComplexEnum); } // Note: The enum above can include *other* enums as well, including itself! +// Note: This is what's called *Algebraic data type* in some other languages. class ComplexEnumTest{ public static function example(){ diff --git a/hu-hu/coffeescript-hu.html.markdown b/hu-hu/coffeescript-hu.html.markdown new file mode 100644 index 00000000..267db4d0 --- /dev/null +++ b/hu-hu/coffeescript-hu.html.markdown @@ -0,0 +1,106 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tamás Diószegi", "http://github.com/ditam"] +filename: coffeescript-hu.coffee +--- + +A CoffeeScript egy apró nyelv ami egy-az-egyben egyenértékű Javascript kódra fordul, és így futásidőben már nem szükséges interpretálni. +Mint a JavaScript egyik követője, a CoffeeScript mindent megtesz azért, hogy olvasható, jól formázott és jól futó JavaScript kódot állítson elő, ami minden JavaScript futtatókörnyezetben jól működik. + +Rézletekért lásd még a [CoffeeScript weboldalát](http://coffeescript.org/), ahol egy teljes CoffeScript tutorial is található. + +```coffeescript +# A CoffeeScript egy hipszter nyelv. +# Követi több modern nyelv trendjeit. +# Így a kommentek, mint Ruby-ban és Python-ban, a szám szimbólummal kezdődnek. + +### +A komment blokkok ilyenek, és közvetlenül '/ *' és '* /' jelekre fordítódnak +az eredményül kapott JavaScript kódban. + +Mielőtt tovább olvasol, jobb, ha a JavaScript alapvető szemantikájával +tisztában vagy. + +(A kód példák alatt kommentként látható a fordítás után kapott JavaScript kód.) +### + +# Értékadás: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Feltételes utasítások: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Függvények: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# Szám tartományok: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objektumok: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; + +# "Splat" jellegű függvény-paraméterek: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; + +# Létezés-vizsgálat: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Tömb értelmezések: (array comprehensions) +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## További források + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
\ No newline at end of file diff --git a/hu-hu/go.html.markdown b/hu-hu/go-hu.html.markdown index 638c9489..638c9489 100644 --- a/hu-hu/go.html.markdown +++ b/hu-hu/go-hu.html.markdown diff --git a/hu-hu/ruby-hu.html.markdown b/hu-hu/ruby-hu.html.markdown new file mode 100644 index 00000000..169f2b8e --- /dev/null +++ b/hu-hu/ruby-hu.html.markdown @@ -0,0 +1,555 @@ +--- +language: ruby +lang: hu-hu +filenev: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + translators: + - ["Zsolt Prontvai", "https://github.com/prozsolt"] +--- + +```ruby +# Ez egy komment + +=begin +Ez egy többsoros komment +Senki sem használja +Neked sem kellene +=end + +# Először is: Minden objektum + +# A számok objektumok + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Néhány alapvető számtani művelet +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# A számtani művelet csak szintaktikus cukor +# az objektumon történő függvény hívásra +1.+(3) #=> 4 +10.* 5 #=> 50 + +# A speciális értékek objektumok +nil # Nincs itt semmi látnivaló +true # igaz +false # hamis + +nil.class #=> NilClass +true.class #=> TrueClass +false.class #=> FalseClass + +# Egyenlőség +1 == 1 #=> true +2 == 1 #=> false + +# Egyenlőtlenség +1 != 1 #=> false +2 != 1 #=> true + +# A false-on kívül, nil az egyetlen hamis érték + +!nil #=> true +!false #=> true +!0 #=> false + +# Még több összehasonlítás +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Logikai operátorok +true && false #=> false +true || false #=> true +!true #=> false + +# A logikai operátoroknak alternatív verziójuk is van sokkal kisebb +# precedenciával. Ezeket arra szánták, hogy több állítást összeláncoljanak +# amíg egyikük igaz vagy hamis értékkel nem tér vissza. + +# `csinalj_valami_mast` csak akkor fut le, ha `csinalj_valamit` igaz értékkel +# tért vissza. +csinalj_valamit() and csinalj_valami_mast() +# `log_error` csak akkor fut le, ha `csinalj_valamit` hamis értékkel +# tért vissza. +csinalj_valamit() or log_error() + + +# A sztringek objektumok + +'Én egy sztring vagyok'.class #=> String +"Én is egy sztring vagyok".class #=> String + +helykitolto = 'interpolációt használhatok' +"Sztring #{helykitolto}, ha dupla időzőjelben van a sztringem" +#=> "Sztring interpolációt használhatok, ha dupla időzőjelben van a sztringem" + +# A szimpla idézőjelet preferáljuk, ahol csak lehet, +# mert a dupla idézőjel extra számításokat végez. + +# Kombinálhatunk sztringeket, de nem számokkal +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# kiírás a kimenetre +puts "Írok" + +# Változók +x = 25 #=> 25 +x #=> 25 + +# Értékadás az adott értékkel tér vissza +# Ez azt jelenti, hogy használhatunk többszörös értékadást: + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Konvencióból, snake_case változó neveket használj +snake_case = true + +# Leíró változó neveket használj +ut_a_projekt_gyokerehez = '/jo/nev/' +ut = '/rossz/nev/' + +# A szimbólumok (objektumok) +# A szimbólumok megváltoztathatatlan, újra felhasználható konstans, +# mely belsőleg egész számként reprezentált. Sokszor sztring helyett használják, +# hogy effektíven közvetítsünk konkrét, értelmes értékeket + +:fuggoben.class #=> Symbol + +statusz = :fuggoben + +statusz == :fuggoben #=> true + +statusz == 'fuggoben' #=> false + +statusz == :jovahagyott #=> false + +# Tömbök + +# Ez egy tömb +tomb = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# A tömmbök különböző tipusú dolgokat tartalmazhat + +[1, 'hello', false] #=> [1, "hello", false] + +# Tömbök indexelhetőek +# Az elejéről +tomb[0] #=> 1 +tomb[12] #=> nil + +# Akárcsak a számtani műveletek [var] hozzáférés +# is csak szintaktikus cukor +# a [] függvény hívására az objektumon +tomb.[] 0 #=> 1 +tomb.[] 12 #=> nil + +# A végéről +tomb[-1] #=> 5 + +# Kezdőértékkel és hosszal +tomb[2, 3] #=> [3, 4, 5] + +# Tömb megfordítása +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Vagy tartománnyal +tomb[1..3] #=> [2, 3, 4] + +# Így adhatunk a tömbhöz +tomb << 6 #=> [1, 2, 3, 4, 5, 6] +# Vagy így +tomb.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Ellenőrízük, hogy a tömb tartalmaz egy elemet +tomb.include?(1) #=> true + +# Hash-ek a ruby elsődleges szótárjai kulcs/érték párokkal +# Hash-eket kapcsos zárójellel jelöljük +hash = { 'szin' => 'zold', 'szam' => 5 } + +hash.keys #=> ['szin', 'szam'] + +# Hash-ekben könnyen kreshetünk a kulcs segítségével: +hash['szin'] #=> 'zold' +hash['szam'] #=> 5 + +# Nem létező kulcsra keresve nil-t kapunk: +hash['nincs itt semmi'] #=> nil + +# Ruby 1.9-től, egy külnleges szintaxist is használhatunk a szimbólumot +# használunk kulcsnak + +uj_hash = { defcon: 3, action: true } + +uj_hash.keys #=> [:defcon, :action] + +# Ellenőrizzük, hogy az adott kulcs és érték bene-e van a hash-ben +uj_hash.has_key?(:defcon) #=> true +uj_hash.has_value?(3) #=> true + +# Tip: A tömbök és hash-ek is felsorolhatóak +# Sok közös függvényük van, akár az each, map, count, és több + +# Kontroll Struktúrák + +if true + 'ha állítás' +elsif false + 'különben ha, opcionális' +else + 'különben, szintén opcionális' +end + +for szamlalo in 1..5 + puts "iteracio #{szamlalo}" +end +#=> iteracio 1 +#=> iteracio 2 +#=> iteracio 3 +#=> iteracio 4 +#=> iteracio 5 + +# HOWEVER, No-one uses for loops. +# Instead you should use the "each" method and pass it a block. +# A block is a bunch of code that you can pass to a method like "each". +# It is analogous to lambdas, anonymous functions or closures in other +# programming languages. +# +# The "each" method of a range runs the block once for each element of the range. +# The block is passed a counter as a parameter. +# Calling the "each" method with a block looks like this: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# You can also surround blocks in curly brackets: +(1..5).each { |counter| puts "iteration #{counter}" } + +# The contents of data structures can also be iterated using each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +jegy = '4' + +case jegy +when '5' + puts 'Kitünő' +when '4' + puts 'Jó' +when '3' + puts 'Közepes' +when '2' + puts 'Elégsége' +when '1' + puts 'Elégtelen' +else + puts 'Alternatív értékelés, hm?' +end +#=> "Jó" + +# case-ek tartományokat is használhatnak +jegy = 82 +case jegy +when 90..100 + puts 'Hurrá!' +when 80...90 + puts 'Jó munka' +else + puts 'Megbuktál!' +end +#=> "Jó munka" + +# kivétel kezelés: +begin + # kód ami kivételt dobhat + raise NoMemoryError, 'Megtelt a memória' +rescue NoMemoryError => kivetel_valtozo + puts 'NoMemoryError-t dobott', kivetel_valtozo +rescue RuntimeError => mas_kivetel_valtozo + puts 'RuntimeError dobott most' +else + puts 'Ez akkor fut ha nem dob kivételt' +ensure + puts 'Ez a kód mindenképpen lefut' +end + +# Függvények + +def ketszeres(x) + x * 2 +end + +# Függvények (és egyébb blokkok) implicit viszatértnek az utolsó értékkel +ketszeres(2) #=> 4 + +# Zárójelezés opcionális, ha az eredmény félreérthetetlen +ketszeres 3 #=> 6 + +ketszeres ketszeres 3 #=> 12 + +def osszeg(x, y) + x + y +end + +# Függvény argumentumait vesszővel választjuk el. +osszeg 3, 4 #=> 7 + +osszeg osszeg(3, 4), 5 #=> 12 + +# yield +# Minden függvénynek van egy implicit, opcionális block paramétere +# 'yield' kulcsszóval hívhatjuk + +def korulvesz + puts '{' + yield + puts '}' +end + +korulvesz { puts 'hello world' } + +# { +# hello world +# } + + +# Fuggvénynek átadhatunk blokkot +# "&" jelöli az átadott blokk referenciáját +def vendegek(&block) + block.call 'valami_argumentum' +end + +# Argumentum lisát is átadhatunk, ami tömbé lesz konvertálva +# Erre való a splat operátor ("*") +def vendegek(*array) + array.each { |vendeg| puts vendeg } +end + +# Osztályt a class kulcsszóval definiálhatunk +class Ember + + # Az osztály változó. Az osztály minden példánnyával megvan osztva + @@faj = 'H. sapiens' + + # Alap inicializáló + def initialize(nev, kor = 0) + # Hozzárendeli az argumentumot a "nev" példány változóhoz + @nev = nev + # Ha nem adtunk meg kort akkor az alapértemezet értéket fogja használni + @kor = kor + end + + # Alap setter függvény + def nev=(nev) + @nev = nev + end + + # Alap getter függvény + def nev + @nev + end + + # A fönti funkcionalítást az attr_accessor függvénnyel is elérhetjük + attr_accessor :nev + + # Getter/setter függvények egyenként is kreálhatóak + attr_reader :nev + attr_writer :nev + + # Az osztály függvények "self"-et hasznalnak, hogy megkülönböztessék magukat a + # példány függvényektől + # Az osztályn hívhatóak, nem a példányon + def self.mond(uzenet) + puts uzenet + end + + def faj + @@faj + end +end + + +# Példányosítsuk az osztályt +jim = Ember.new('Jim Halpert') + +dwight = Ember.new('Dwight K. Schrute') + +# Hívjunk meg pár függvényt +jim.faj #=> "H. sapiens" +jim.nev #=> "Jim Halpert" +jim.nev = "Jim Halpert II" #=> "Jim Halpert II" +jim.nev #=> "Jim Halpert II" +dwight.faj #=> "H. sapiens" +dwight.nev #=> "Dwight K. Schrute" + +# Hívjuk meg az osztály függvényt +Ember.mond('Hi') #=> "Hi" + +# Változók szókjait az elnevezésük definiálja +# $ kezdetű változók globálisak +$var = "Én egy globális változó vagyok" +defined? $var #=> "global-variable" + +# Változók amik @-al kezdődnek példány szkópjuk van +@var = "Én egy példány változó vagyok" +defined? @var #=> "instance-variable" + +# Változók amik @@-al kezdődnek példány szkópjuk van +@@var = "Én egy osztály változó vagyok" +defined? @@var #=> "class variable" + +# Változók amik nagy betűvel kezdődnek a konstansok +Var = "Konstans vagyok" +defined? Var #=> "constant" + +# Az osztály is objetum. Tehát az osztálynak lehet példány változója +# Az osztályváltozón osztozik minden pédány és leszármazott + +# Ős osztály +class Ember + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(ertek) + @@foo = ertek + end +end + +# Leszarmazott osztály +class Dolgozo < Ember +end + +Ember.foo # 0 +Dolgozo.foo # 0 + +Ember.foo = 2 # 2 +Dolgozo.foo # 2 + +# Az osztálynak példány változóját nem látja az osztály leszármazottja. + +class Ember + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(ertek) + @bar = ertek + end +end + +class Doctor < Ember +end + +Ember.bar # 0 +Doctor.bar # nil + +module ModulePelda + def foo + 'foo' + end +end + +# Modulok include-olása a fügvényeiket az osztály példányaihoz köti. +# Modulok extend-elésa a fügvényeiket magához az osztályhoz köti. + +class Szemely + include ModulePelda +end + +class Konyv + extend ModulePelda +end + +Szemely.foo # => NoMethodError: undefined method `foo' for Szemely:Class +Szemely.new.foo # => 'foo' +Konyv.foo # => 'foo' +Konyv.new.foo # => NoMethodError: undefined method `foo' + +# Callback-ek végrehajtódnak amikor include-olunk és extend-elünk egy modult + +module ConcernPelda + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Valami + include ConcernPelda +end + +Valami.bar # => 'bar' +Valami.qux # => NoMethodError: undefined method `qux' +Valami.new.bar # => NoMethodError: undefined method `bar' +Valami.new.qux # => 'qux' +``` + +## Egyéb források + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - A régebbi [ingyenes változat](http://ruby-doc.com/docs/ProgrammingRuby/) elérhető online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) diff --git a/hy.html.markdown b/hy.html.markdown index 04bd05c9..9beaff0c 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -83,7 +83,7 @@ True ; => True (greet "bilbo") ;=> "hello bilbo" ; functions can take optional arguments as well as keyword arguments -(defn foolist [arg1 &optional [arg2 2]] +(defn foolists [arg1 &optional [arg2 2]] [arg1 arg2]) (foolists 3) ;=> [3 2] diff --git a/id-id/json-id.html.markdown b/id-id/json-id.html.markdown new file mode 100644 index 00000000..52e61449 --- /dev/null +++ b/id-id/json-id.html.markdown @@ -0,0 +1,60 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators + - ["Rizky Luthfianto", "https://github.com/rilut"] +--- + +JSON adalah format pertukaran data yang sangat simpel, kemungkinan besar, +ini adalah "Learn X in Y Minutes" yang paling singkat. + +Murninya, JSON tidak mempunyai fitur komentar, tapi kebanyakan parser akan +menerima komentar bergaya bahasa C (`//`, `/* */`). Namun, pada halaman ini, +hanya dicontohkan JSON yang 100% valid. + +```json +{ + "kunci": "nilai", + + "kunci": "harus selalu diapit tanda kutip", + "angka": 0, + "strings": "Halø, dunia. Semua karaktor unicode diperbolehkan, terumasuk \"escaping\".", + "punya tipe data boolean?": true, + "nilai kosong": null, + + "angka besar": 1.2e+100, + + "obyek": { + "komentar": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Array bisa berisi apapun.", 5], + + "obyek lainnya": { + "komentar": "Obyek-obyek JSON dapat dibuat bersarang, sangat berguna." + } + }, + + "iseng-iseng": [ + { + "sumber potassium": ["pisang"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "gaya alternatif": { + "komentar": "lihat ini!" + , "posisi tanda koma": "tak masalah. selama sebelum nilai berikutnya, valid-valid saja" + , "komentar lainnya": "betapa asyiknya" + }, + + "singkat": "Dan Anda selesai! Sekarang Anda tahu apa saja yang disediakan oleh JSON." +} +``` diff --git a/id-id/xml-id.html.markdown b/id-id/xml-id.html.markdown new file mode 100644 index 00000000..8b8d72ae --- /dev/null +++ b/id-id/xml-id.html.markdown @@ -0,0 +1,130 @@ +--- +language: xml +filename: learnxml-id.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Rizky Luthfianto", "https://github.com/rilut"] +lang: id-id +--- + +XML adalah bahasa markup yang dirancang untuk menyimpan dan mengirim data. + +Tidak seperti HTML, XML tidak menentukan bagaimana menampilkan atau format data, hanya membawanya. + +* Sintaks XML + +```xml +<!-- Komentar di XML seperti ini --> + +<?xml version="1.0" encoding="UTF-8"?> +<tokobuku> + <buku category="MEMASAK"> + <judul lang="en">Everyday Italian</judul> + <pengarang>Giada De Laurentiis</pengarang> + <tahun>2005</tahun> + <harga>30.00</harga> + </buku> + <buku category="ANAK"> + <judul lang="en">Harry Potter</judul> + <pengarang>J K. Rowling</pengarang> + <tahun>2005</tahun> + <harga>29.99</harga> + </buku> + <buku category="WEB"> + <judul lang="en">Learning XML</judul> + <pengarang>Erik T. Ray</pengarang> + <tahun>2003</tahun> + <harga>39.95</harga> + </buku> +</tokobuku> + +<!-- Di atas adalah contoh file XML biasa. + Dimulai dengan deklarasi, menginformasikan beberapa metadata (opsional). + + XML menggunakan struktur pohon. Di atas, simpul akar adalah 'tokobuku', + yang memiliki tiga node anak, para 'buku'. Node-node tersebut dapat memiliki + node-node anak, dan seterusnya ... + + Node dibuat menggunakan tag buka/tutup, dan node-node anak hanya + berada di antara tag buka dan tutup .--> + + +<!-- XML membawa dua jenis data: + 1 - Atribut -> Itu metadata tentang sebuah node. + Biasanya, parser XML menggunakan informasi ini untuk menyimpan data dengan + benar. Hal ini ditandai dengan muncul dengan format nama = "nilai" dalam pembukaan tag. + 2 - Elemen -> Itu data yang murni. + Itulah yang parser akan mengambil dari file XML. + Elemen muncul antara tag membuka dan menutup.--> + + +<!-- Di bawah ini, unsur dengan dua atribut--> +<file type="gif" id="4293">komputer.gif</file> + + +``` + +* Dokumen yang well-formated & Validasi + +Sebuah dokumen XML disebut well-formated jika sintaksisnya benar. +Namun, juga mungkin untuk mendefinisikan lebih banyak batasan dalam dokumen, +menggunakan definisi dokumen, seperti DTD dan XML Schema. + +Sebuah dokumen XML yang mengikuti definisi dokumen disebut valid, +jika sesuai dokumen itu. + +Dengan alat ini, Anda dapat memeriksa data XML di luar logika aplikasi. + +```xml + +<!-- Di bawah, Anda dapat melihat versi sederhana dari dokumen tokobuku, + dengan penambahan definisi DTD .--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE catatan SYSTEM "tokobuku.dtd"> +<tokobuku> + <buku category="MEMASAK"> + <judul >Everyday Italian</judul> + <harga>30.00</harga> + </buku> +</tokobuku> + +<!-- This DTD could be something like:--> + +<!DOCTYPE catatan +[ +<!ELEMENT tokobuku (buku+)> +<!ELEMENT buku (judul,harga)> +<!ATTLIST buku category CDATA "Sastra"> +<!ELEMENT judul (#PCDATA)> +<!ELEMENT harga (#PCDATA)> +]> + + +<!-- DTD dimulai dengan deklarasi. + Berikut, node akar dinyatakan, membutuhkan 1 atau lebih anak node 'buku'. + Setiap 'buku' harus berisi tepat satu 'judul' dan 'harga' dan atribut + disebut 'kategori', dengan "Sastra" sebagai nilai default. + Node yang 'judul' dan 'harga' mengandung karakter data diurai .--> + +<!-- DTD dapat dideklarasikan di dalam file XML itu sendiri .--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE catatan +[ +<!ELEMENT tokobuku (buku+)> +<!ELEMENT buku (judul,harga)> +<!ATTLIST buku category CDATA "Sastra"> +<!ELEMENT judul (#PCDATA)> +<!ELEMENT harga (#PCDATA)> +]> + +<tokobuku> + <buku category="MEMASAK"> + <judul >Everyday Italian</judul> + <harga>30.00</harga> + </buku> +</tokobuku> +``` diff --git a/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown new file mode 100644 index 00000000..af8823c4 --- /dev/null +++ b/it-it/bash-it.html.markdown @@ -0,0 +1,287 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] +filename: LearnBash.sh +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Tommaso Pifferi", "http://github.com/neslinesli93/"] +lang: it-it +--- + +Bash è il nome della shell di unix, la quale è stata distribuita anche come shell del sistema oprativo GNU e la shell di default su Linux e Mac OS X. +Quasi tutti gli esempi sottostanti possono fare parte di uno shell script o eseguiti direttamente nella shell. + +[Per saperne di più.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# La prima riga dello script è lo shebang il quale dice al sistema come eseguire +# lo script: http://it.wikipedia.org/wiki/Shabang +# Come avrai già immaginato, i commenti iniziano con #. Lo shebang stesso è un commento. + +# Semplice esempio ciao mondo: +echo Ciao mondo! + +# Ogni comando inizia su una nuova riga, o dopo un punto e virgola: +echo 'Questa è la prima riga'; echo 'Questa è la seconda riga' + +# Per dichiarare una variabile: +Variabile="Una stringa" + +# Ma non così: +Variabile = "Una stringa" +# Bash stabilirà che Variabile è un comando da eseguire e darà un errore +# perchè non esiste. + +# Usare la variabile: +echo $Variabile +echo "$Variabile" +echo '$Variabile' +# Quando usi la variabile stessa - assegnala, esportala, oppure — scrivi +# il suo nome senza $. Se vuoi usare il valore della variabile, devi usare $. +# Nota che ' (singolo apice) non espande le variabili! + +# Sostituzione di stringhe nelle variabili +echo ${Variabile/Una/A} +# Questo sostituirà la prima occorrenza di "Una" con "La" + +# Sottostringa di una variabile +Lunghezza=7 +echo ${Variabile:0:Lunghezza} +# Questo ritornerà solamente i primi 7 caratteri + +# Valore di default per la variabile +echo ${Foo:-"ValoreDiDefaultSeFooMancaOppureÈVuoto"} +# Questo funziona per null (Foo=), stringa vuota (Foo=""), zero (Foo=0) ritorna 0 +# Nota: viene ritornato il valore di default, il contenuto della variabile pero' non cambia. + +# Variabili builtin: +# Ci sono delle variabili builtin molto utili, come +echo "Valore di ritorno dell'ultimo programma eseguito: $?" +echo "PID dello script: $$" +echo "Numero di argomenti: $#" +echo "Argomenti dello script: $@" +echo "Argomenti dello script separati in variabili distinte: $1 $2..." + +# Leggere un valore di input: +echo "Come ti chiami?" +read Nome # Nota che non abbiamo dovuto dichiarare una nuova variabile +echo Ciao, $Nome! + +# Classica struttura if: +# usa 'man test' per maggiori informazioni sulle condizionali +if [ $Nome -ne $USER ] +then + echo "Il tuo nome non è lo username" +else + echo "Il tuo nome è lo username" +fi + +# Nota: se $Name è vuoto, la condizione precedente viene interpretata come: +if [ -ne $USER ] +# che genera un errore di sintassi. Quindi il metodo sicuro per usare +# variabili che possono contenere stringhe vuote è il seguente: +if [ "$Name" -ne $USER ] ... +# che viene interpretato come: +if [ "" -ne $USER ] ... +# e dunque funziona correttamente. + +# C'è anche l'esecuzione condizionale +echo "Sempre eseguito" || echo "Eseguito solo se la prima condizione fallisce" +echo "Sempre eseguito" && echo "Eseguito solo se la prima condizione NON fallisce" + +# Per usare && e || con l'if, c'è bisogno di piu' paia di parentesi quadre: +if [ "$Nome" == "Steve" ] && [ "$Eta" -eq 15 ] +then + echo "Questo verrà eseguito se $Nome è Steve E $Eta è 15." +fi + +if [ "$Nome" == "Daniya" ] || [ "$Nome" == "Zach" ] +then + echo "Questo verrà eseguito se $Nome è Daniya O Zach." +fi + +# Le espressioni sono nel seguente formato: +echo $(( 10 + 5 )) + +# A differenza di altri linguaggi di programmazione, bash è una shell - quindi lavora nel contesto +# della cartella corrente. Puoi elencare i file e le cartelle nella cartella +# corrente con il comando ls: +ls + +# Questi comandi hanno opzioni che controllano la loro esecuzione: +ls -l # Elenca tutti i file e le cartelle su una riga separata + +# I risultati del comando precedente possono essere passati al comando successivo come input. +# Il comando grep filtra l'input con il pattern passato. Ecco come possiamo elencare i +# file .txt nella cartella corrente: +ls -l | grep "\.txt" + +# Puoi redirezionare l'input e l'output del comando (stdin, stdout, e stderr). +# Leggi da stdin finchè ^EOF$ e sovrascrivi hello.py con le righe +# comprese tra "EOF": +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Esegui hello.py con diverse redirezioni stdin, stdout, e stderr: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Lo output error sovrascriverà il file se esiste, +# se invece vuoi appendere usa ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Sovrascrivi output.out, appendi a error.err, e conta le righe: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Esegui un comando e stampa il suo file descriptor (esempio: /dev/fd/123) +# vedi: man fd +echo <(echo "#ciaomondo") + +# Sovrascrivi output.out con "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Pulisci i file temporanei verbosamente (aggiungi '-i' per la modalità interattiva) +rm -v output.out error.err output-and-error.log + +# I comandi possono essere sostituiti con altri comandi usando $( ): +# Il comando seguente mostra il numero di file e cartelle nella +# cartella corrente. +echo "Ci sono $(ls | wc -l) oggetti qui." + +# Lo stesso puo' essere usato usando backticks `` ma non possono essere innestati - il modo migliore +# è usando $( ). +echo "Ci sono `ls | wc -l` oggetti qui." + +# Bash utilizza uno statemente case che funziona in maniera simile allo switch in Java e C++: +case "$Variabile" in + #Lista di pattern per le condizioni che vuoi soddisfare + 0) echo "C'è uno zero.";; + 1) echo "C'è un uno.";; + *) echo "Non è null.";; +esac + +# I cicli for iterano per ogni argomento fornito: +# I contenuti di $Variabile sono stampati tre volte. +for Variabile in {1..3} +do + echo "$Variabile" +done + +# O scrivilo con il "ciclo for tradizionale": +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Possono essere usati anche per agire su file.. +# Questo eseguirà il comando 'cat' su file1 e file2 +for Variabile in file1 file2 +do + cat "$Variabile" +done + +# ..o dall'output di un comando +# Questo eseguirà cat sull'output di ls. +for Output in $(ls) +do + cat "$Output" +done + +# while loop: +while [ true ] +do + echo "corpo del loop..." + break +done + +# Puoi anche definire funzioni +# Definizione: +function foo () +{ + echo "Gli argomenti funzionano come gli argomenti dello script: $@" + echo "E: $1 $2..." + echo "Questa è una funzione" + return 0 +} + +# o semplicemente +bar () +{ + echo "Un altro modo per dichiarare funzioni!" + return 0 +} + +# Per chiamare la funzione +foo "Il mio nome è" $Nome + +# Ci sono un sacco di comandi utili che dovresti imparare: +# stampa le ultime 10 righe di file.txt +tail -n 10 file.txt +# stampa le prime 10 righe di file.txt +head -n 10 file.txt +# ordina le righe di file.txt +sort file.txt +# riporta o ometti le righe ripetute, con -d le riporta +uniq -d file.txt +# stampa solamente la prima colonna prima del carattere ',' +cut -d ',' -f 1 file.txt +# sostituisce ogni occorrenza di 'okay' con 'great' in file.txt (compatible con le regex) +sed -i 's/okay/great/g' file.txt +# stampa su stdout tutte le righe di file.txt che soddisfano una certa regex +# L'esempio stampa le righe che iniziano con "foo" e che finiscono con "bar" +grep "^foo.*bar$" file.txt +# passa l'opzione "-c" per stampare invece il numero delle righe che soddisfano la regex +grep -c "^foo.*bar$" file.txt +# se vuoi letteralmente cercare la stringa, +# e non la regex, usa fgrep (o grep -F) +fgrep "^foo.*bar$" file.txt + + +# Leggi la documentazione dei builtin di bash con il builtin 'help' di bash: +help +help help +help for +help return +help source +help . + +# Leggi la manpage di bash con man +apropos bash +man 1 bash +man bash + +# Leggi la documentazione con info (? per help) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Leggi la documentazione di bash: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/it-it/brainfuck-it.html.markdown b/it-it/brainfuck-it.html.markdown index 4999d7e6..08d2ede9 100644 --- a/it-it/brainfuck-it.html.markdown +++ b/it-it/brainfuck-it.html.markdown @@ -1,75 +1,72 @@ --- - language: brainfuck contributors: - ["Prajit Ramachandran", "http://prajitr.github.io/"] - ["Mathias Bynens", "http://mathiasbynens.be/"] translators: - ["Ivan Sala", "http://slavni96.github.io/"] + - ["Christian Grasso", "http://chris54721.net"] lang: it-it - --- -Brainfuck è un linguaggio di programmazione estremamente minimale, -ma è ingrado di rappresentare completamente una macchina di turnig, -e sfrutta solo 8 caratteri. -[Per saperne di più](http://it.wikipedia.org/wiki/Brainfuck) +Brainfuck è un linguaggio di programmazione +[Turing equivalente](https://it.wikipedia.org/wiki/Turing_equivalenza) +estremamente minimale, composto da solo 8 comandi. + +Puoi provarlo nel tuo browser utilizzando +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). ``` -Qualsiasi carattere che non sia "><+-.,[]" (escludendo gli apici) +Qualsiasi carattere diverso da "><+-.,[]" (escludendo gli apici) viene ignorato. -Branfuck è caratterizzato da un array (vettore) di 30,000 celle -inizializzare a zero, e un puntatore che punta alla cella corrente. +Branfuck è caratterizzato da un array di 30,000 celle inizializzate a zero +e da un puntatore che punta alla cella corrente. -Vi sono solo otto comando: +Vi sono otto comandi: + : Incrementa il valore della cella attuale di uno. - : Decrementa il valore della cella attuale di uno. -> : Sposta il puntatore sulla cella seguente (prossima a destra). -< : Sposta il puntatore sulla cella precendete (precedente a sinistra). -. : Stampa il valore in ASCII della cella corrente. (es: 65 = 'A') -, : Legge un singolo carattere come input per la cella corrente. -[ : Se il valore della cella corrente è zero, conclude il ciclo - andando alla sua corrispondente ]. +> : Sposta il puntatore sulla cella seguente (sulla destra). +< : Sposta il puntatore sulla cella precendete (sulla sinistra). +. : Stampa il valore ASCII della cella corrente. (es. 65 = 'A') +, : Legge un singolo carattere come input e lo salva nella cella corrente. +[ : Se il valore della cella corrente è zero, prosegue fino alla ] corrispondente. Altrimenti, passa alla prossima istruzione. ] : Se il valore della cella corrente è zero, passa alla prossima istruzione. - Altrimenti torna indetro fino alla [ corrispondente. + Altrimenti, torna indietro fino alla [ corrispondente. -[ e ] creano un loop (while). Ovviamente dovranno essere bilanciati. -Per ogni [ dovrà corrispondere una ] +[ e ] formano un ciclo while. Ovviamente dovranno essere bilanciati. +(Ad ogni [ dovrà corrispondere una ]) -Alcuni semplici esempi di programmi scritti in Brainfuck: +Ecco alcuni semplici esempi di programmi scritti in Brainfuck: ++++++ [ > ++++++++++ < - ] > +++++ . -Questo programma stampa in output la lettera 'A'. Priam incrementa -la cella #1 fino a 6, Quindi la cella #1 viene usata per crare un ciclo. -Poi, entra in un loop ([) e si sposta alla cella #2. -Incrementa la cella #2 10 volte, e torna alla cella #1, e la decrementa. -Questo avviene 6 volte (servono che la cella #1 venga decrementata 6 volte -per raggiungere lo 0. Quindi passa alla corrispondente ] e prosegue). +Questo programma stampa in output la lettera 'A'. Prima di tutto, incrementa +la cella #1 fino al valore 6. La cella #1 verrà utilizzata per il ciclo. +Poi, entra nel ciclo ([) e si sposta alla cella #2. Incrementa la cella #2 10 +volte, torna alla cella #1, e decrementa quest'ultima. +Il ciclo si ripete 6 volte (la cella #1 viene decrementata 6 volte prima di +raggiungere lo 0, quindi prosegue oltre la corrispondente ]). -A questo punto, siamo sulla cella #1, che ha valore 0, -la cella #2 ha valore 60 (6*10). Ci spostiamo sulla cella #2, incrementiamo -per 5 volte, e otteniamo il valore 65, quindi stampaimo il valore della cella -#2 (.). -65 è 'A' in ASCII, quindi alla fine viene stampata 'A'. +A questo punto, siamo sulla cella #1, che ha valore 0, mentre la cella #2 ha +valore 60. Ci spostiamo sulla cella #2, la incrementiamo per 5 volte, ottenendo +il valore 65, quindi stampiamo il valore della cella #2. +Il valore 65 equivale ad 'A' in ASCII, per cui viene stampato 'A' nel terminale. , [ > + < - ] > . -Questo programma legge un carattere come input dall'utente, -quindi salva il carattere dentro la cella #1. -In seguito, incominca a ciclare. -Si sposta alla cella #², e increementa il valore della cella (#2). -Quindi torna alla cella #1, e decrementa il valore della cella (#1). -Questo continua fino a quando la cella #²1 diventa 0, e quindi la cella #2 -avrà il valore iniziale della cella #1. -Infine, visto che ci troviamo sulla cella #1 alla fine del ciclo, si sposta -sulla cella #2 e stampa il valore in ASCII. +Questo programma legge un carattere come input dall'utente, quindi salva il +carattere nella cella #1. Dopodichè entra in un ciclo. Si sposta alla cella #2, +incrementa quest'ultima, torna alla cella #1, e decrementa quest'ultima. +Il ciclo continua fino a quando la cella #1 diventa 0, e quindi la cella #2 +avrà il valore iniziale della cella #1. Infine, visto che ci troviamo sulla +cella #1 alla fine del ciclo, si sposta sulla cella #2 e stampa il valore in +ASCII. -Gli spazi nel codice sovrastante, sono presenti solo a scopo di ottenere -una maggiore leggibilità, si poteva anche scrivere senza: +Gli spazi nel codice sovrastante sono presenti solo a scopo di ottenere +una maggiore leggibilità. Lo stesso programma poteva essere scritto senza spazi: ,[>+<-]>. @@ -77,25 +74,19 @@ Proviamo, adesso, a capire cosa fa invece questo programma: ,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> -Prende due numeri in input e quindi li moltiplica. +Il programma legge 2 numeri come input dall'utente, e li moltiplica. -Prima prende in input i due numeri (,>,<), quindi inizia un cilclo -basandosi sulla cella #1. -Quindi si sposta sulla cella #2, e inizia un altro ciclo condizionato -dal valore della cella #2, incrementando la cella #3. +Innanzitutto, legge in input i due numeri. Poi entra nel ciclo più esterno +basandosi sulla cella #1. Quindi si sposta sulla cella #2, e inizia il ciclo +più interno basandosi sul valore della cella #2, incrementando la cella #3. Arrivati a questo punto abbiamo un problema: alla fine del ciclo interno -la cella #2 ha valore 0. In questo caso, quando il ciclo esterno rifarà -partire il ciclo interno, non funzionerà più perchè la cella #2 ha valore 0. -Per ovviare a questo problema, oltre alla cella 3, incrementiamo anche la cella -#4, e alla fine di ogni ciclo interno copiala il valore della cella #4 -nella cella #2, in modo che il ciclo interno -possa essere eseguito una altra volta. -Alla fine la cella #3 contiene il risultato. +la cella #2 avrà valore 0. Ciò impedirà di eseguire nuovamente il ciclo interno. +Per ovviare a questo problema, incrementiamo anche la cella #4, e copiamo il +valore di quest'ultima nella cella #2. +Il risultato sarà infine contenuto nella cella #3. ``` -E questo è brainfuck...Non è difficele, vero? -Per divertimento adesso puoi scrivere i tuoi programmi in brainfuck, -oppure puoi scrivere un interprete brainfuck in un altro linguaggio. -L'interprete è abbastanza semplice da implementare, ma se sei veramente -masochista prova ad implementare un interprete brainfuck in... -brainfuck. +E questo è brainfuck. Non è così difficile, eh? Se vuoi, ora puoi scrivere per +divertimento altri programmi in brainfuck, oppure scrivere un interprete +brainfuck in un altro linguaggio. L'interprete è abbastanza semplice da +implementare, ma se sei veramente masochista, prova ad implementare un interprete brainfuck... in brainfuck. diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown new file mode 100644 index 00000000..92ebc165 --- /dev/null +++ b/it-it/c++-it.html.markdown @@ -0,0 +1,879 @@ +--- +language: c++ +filename: learncpp-it.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "http://github.com/connorwaters"] +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] +lang: it-it +--- + +Il C++ è un linguaggio di programmazione il quale, +[secondo il suo inventore Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +è stato progettato per + +- essere un "miglior C" +- supportare l'astrazione dei dati +- supportare la programmazione orientata agli oggetti +- supportare la programmazione generica + +Nonostante la sintassi possa risultare più difficile o complessa di linguaggi più recenti, +è usato in maniera vasta poichè viene compilato in istruzioni macchina che possono +essere eseguite direttamente dal processore ed offre un controllo stretto sull'hardware (come il linguaggio C) +ed allo stesso tempo offre caratteristiche ad alto livello come i generici, le eccezioni, e le classi. +Questa combinazione di velocità e funzionalità rende il C++ +uno dei più utilizzati linguaggi di programmazione. + +```c++ +////////////////// +// Confronto con il C +////////////////// + +// Il C++ è _quasi_ un superset del C e con esso condivide la sintassi di base per +// la dichiarazione di variabili, tipi primitivi, e funzioni. + +// Proprio come nel C, l'inizio del programma è una funzione chiamata +// main con un intero come tipo di ritorno, +// Questo valore serve come stato d'uscita del programma. +// Vedi http://it.wikipedia.org/wiki/Valore_di_uscita per maggiori informazioni. +int main(int argc, char** argv) +{ + // Gli argomenti a linea di comando sono passati tramite argc e argv così come + // avviene in C. + // argc indica il numero di argomenti, + // e argv è un array di stringhe in stile-C (char*) + // che rappresenta gli argomenti. + // Il primo argomento è il nome che è stato assegnato al programma. + // argc e argv possono essere omessi se non hai bisogno di argomenti, + // in questa maniera la funzione avrà int main() come firma. + + // Lo stato di uscita 0 indica successo. + return 0; +} + +// Tuttavia, il C++ varia nei seguenti modi: + +// In C++, i caratteri come letterali sono dei char. +sizeof('c') == sizeof(char) == 1 + +// In C, i caratteri come letterali sono degli interi. +sizeof('c') == sizeof(int) + + +// C++ ha prototipizzazione rigida +void func(); // funziona che non accetta argomenti + +// In C +void func(); // funzione che può accettare un qualsiasi numero di argomenti + +// Usa nullptr invece di NULL in C++ +int* ip = nullptr; + +// Gli header C standard sono disponibili in C++, +// ma sono prefissati con "c" e non hanno il suffisso ".h". +#include <cstdio> + +int main() +{ + printf("Ciao, mondo!\n"); + return 0; +} + +/////////////////////////////// +// Overloading per le funzioni +////////////////////////////// + +// Il C++ supporta l'overloading per le funzioni +// sia dato che ogni funzione accetta parametri diversi. + +void print(char const* myString) +{ + printf("Stringa %s\n", myString); +} + +void print(int myInt) +{ + printf("Il mio int è %d", myInt); +} + +int main() +{ + print("Ciao"); // Viene chiamata void print(const char*) + print(15); // Viene chiamata void print(int) +} + +//////////////////////// +// Argomenti di default +/////////////////////// + +// Puoi fornire argomenti di default per una funzione +// se non sono forniti dal chiamante. + +void faiQualcosaConInteri(int a = 1, int b = 4) +{ + // fai qualcosa con gli interi qui +} + +int main() +{ + faiQualcosaConInteri(); // a = 1, b = 4 + faiQualcosaConInteri(20); // a = 20, b = 4 + faiQualcosaConInteri(20, 5); // a = 20, b = 5 +} + +// Gli argomenti di default devono essere alla fine della lista degli argomenti. + +void dichiarazioneInvalida(int a = 1, int b) // Errore! +{ +} + + +///////////// +// Namespaces +///////////// + +// I namespaces forniscono visibilità separata per dichiarazioni di variabili, funzioni, +// ed altro. +// I namespaces possono essere annidati. + +namespace Primo { + namespace Annidato { + void foo() + { + printf("Questa è Primo::Annidato::foo\n"); + } + } // fine di namespace Annidato +} // fine di namespace Primo + +namespace Secondo { + void foo() + { + printf("Questa è Secondo::foo\n") + } +} + +void foo() +{ + printf("Questa è foo globale\n"); +} + +int main() +{ + // Include tutti i simboli del namespace Secondo nello scope attuale. + // Osserva che chiamare semplicemente foo() non va più bene perché è ambiguo: + // bisogna specificare se vogliamo chiamare foo definita nel namespace Secondo + // o foo definita nel livello principale del programma. + + using namespace Secondo; + + Secondo::foo(); // stampa "Questa è Secondo::foo" + Primo::Annidato::foo(); // stampa "Questa è Primo::Annidato::foo" + ::foo(); // stampa "Questa è foo globale" +} + +/////////////// +// Input/Output +/////////////// + +// L'input e l'output in C++ utilizza gli streams +// cin, cout, e cerr i quali rappresentano stdin, stdout, e stderr. +// << è l'operatore di inserzione >> è l'operatore di estrazione. + +#include <iostream> // Include gli streams di I/O + +using namespace std; // Gli streams sono nel namespace std (libreria standard) + +int main() +{ + int myInt; + + // Stampa su stdout (o terminalee/schermo) + cout << "Inserisci il tuo numero preferito:\n"; + // Prende l'input + cin >> myInt; + + // cout può anche essere formattato + cout << "Il tuo numero preferito è " << myInt << "\n"; + // stampa "Il tuo numero preferito è <myInt>" + + cerr << "Usato per messaggi di errore"; +} + +//////////// +// Stringhe +/////////// + +// Le stringhe in C++ sono oggetti ed hanno molte funzioni membro +#include <string> + +using namespace std; // Anche le stringhe sono contenute nel namespace std (libreria standard) + +string myString = "Ciao"; +string myOtherString = " Mondo"; + +// + è usato per la concatenazione. +cout << myString + myOtherString; // "Ciao Mondo" + +cout << myString + " Bella"; // "Ciao Bella" + +// le stringhe in C++ possono essere modificate. +myString.append(" Mario"); +cout << myString; // "Ciao Mario" + + +/////////////// +// Riferimenti +////////////// + +// Oltre ai puntatori come quelli in C, +// il C++ ha i _riferimenti_. +// Questi non sono tipi puntatori che non possono essere riassegnati una volta settati +// e non possono essere null. +// Inoltre, essi hanno la stessa sintassi della variabile stessa: +// * non è necessario per la dereferenziazione e +// & ("indirizzo di") non è usato per l'assegnamento. + +using namespace std; + +string foo = "Io sono foo"; +string bar = "Io sono bar"; + + +string& fooRef = foo; // Questo crea un riferimento a foo. +fooRef += ". Ciao!"; // Modifica foo attraverso il riferimento +cout << fooRef; // Stampa "Io sono foo. Ciao!" + +// Non riassegna "fooRef". Questo è come scrivere "foo = bar", e +// foo == "Io sono bar" +// dopo questa riga. +cout << &fooRef << endl; // Stampa l'indirizzo di foo +fooRef = bar; +cout << &fooRef << endl; // Stampa lo stesso l'indirizzo di foo +cout << fooRef; // Stampa "Io sono bar" + +// L'indirizzo di fooRef rimane lo stesso, ovvero si riferisce ancora a foo. + + +const string& barRef = bar; // Crea un riferimento const a bar. +// Come in C, i valori const (i puntatori e i riferimenti) non possono essere modificati. +barRef += ". Ciao!"; // Errore, i riferimenti const non possono essere modificati. + +// Facciamo un piccolo excursus: prima di approfondire ancora i riferimenti, è necessario +// introdurre il concetto di oggetto temporaneo. Supponiamo di avere il seguente codice: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// Nella seconda riga si ha che: +// - un oggetto di tipo stringa viene ritornato da tempObjectFun +// - viene costruita una nuova stringa, utilizzando l'oggetto ritornato come +// argomento per il costruttore +// - l'oggetto ritornato da tempObjectFun viene distrutto +// L'oggetto ritornato da tempObjectFun viene detto oggetto temporaneo. +// Un oggetto temporaneo viene creato quando una funzione ritorna un oggetto, e viene +// distrutto quando l'espressione che lo racchiude termina la sua esecuzione - questo +// comportamento viene definito dallo standard, ma i compilatori possono modificarlo +// a piacere. Cerca su google "return value optimization" se vuoi approfondire. +// Dunque nel seguente codice: +foo(bar(tempObjectFun())) + +// dando per scontato che foo e bar esistano, l'oggetto ritornato da tempObjectFun +// è passato a bar ed è distrutto prima dell'invocazione di foo. + +// Tornando ai riferimenti, c'è un'eccezione a quanto appena detto. +// Infatti un oggetto temporaneo "viene distrutto quando l'espressione +// che lo racchiude termina la sua esecuzione", tranne quando è legato ad un +// riferimento di tipo const. In tal caso la sua vita viene estesa per tutto +// lo scope attuale: + +void constReferenceTempObjectFun() { + // constRef riceve l'oggetto temporaneo, che non viene distrutto fino + // alla fine di questa funzione. + const string& constRef = tempObjectFun(); + ... +} + +// Un altro tipo di riferimento introdotto nel C++11 è specifico per gli +// oggetti temporanei. Non puoi dichiarare una variabile di quel tipo, ma +// ha la precedenza nella risoluzione degli overload: + +void someFun(string& s) { ... } // Riferimento normale +void someFun(string&& s) { ... } // Riferimento ad un oggetto temporaneo + +string foo; +someFun(foo); // Chiama la versione con il riferimento normale +someFun(tempObjectFun()); // Chiama la versione con il riferimento temporaneo + +// Ad esempio potrai vedere questi due costruttori per std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// L'idea è che se noi costruiamo una nuova stringa a partire da un oggetto temporaneo +// (che in ogni caso verrà distrutto), possiamo avere un costruttore più efficiente +// che in un certo senso "recupera" parti di quella stringa temporanea. +// Ci si riferisce a questo concetto come "move semantics". + +///////////////////// +// Enum +///////////////////// + +// Gli enum sono un modo per assegnare un valore ad una costante, e sono +// principalmente usati per rendere il codice più leggibile. +enum ETipiMacchine +{ + AlfaRomeo, + Ferrari, + SUV, + Panda +}; + +ETipiMacchine GetPreferredCarType() +{ + return ETipiMacchine::Ferrari; +} + +// Dal C++11 in poi c'è un modo molto semplice per assegnare un tipo ad un enum, +// che può essere utile per la serializzazione dei dati o per convertire gli enum +// tra il tipo desiderato e le rispettive costanti. +enum ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // L'enum viene implicitamente convertito ad un uint8_t poiché + // è stato dichiarato come tale + WriteByteToFile(InputCarType); +} + +// D'altro canto potresti voler evitare che un enum venga accidentalmente convertito +// in un intero o in un altro tipo, quindi è possibile create una classe enum che +// impedisce la conversione implicita. +enum class ETipiMacchine : uint8_t +{ + AlfaRomeo, // 0 + Ferrari, // 1 + SUV = 254, // 254 + Ibrida // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // Serializza InputValue in un file +} + +void WritePreferredCarTypeToFile(ETipiMacchine InputCarType) +{ + // Il compilatore darà errore anche se ETipiMacchine è un uint8_t: questo + // perchè abbiamo dichiarato l'enum come "enum class"! + WriteByteToFile(InputCarType); +} + +////////////////////////////////////////////////// +// Classi e programmazione orientata agli oggetti +///////////////////////////////////////////////// + +// Primo esempio delle classi +#include <iostream> + +// Dichiara una classe. +// Le classi sono in genere dichiara in un header file (.h o .hpp). +class Cane { + // Variabili e funzioni membro sono private di default. + std::string nome; + int peso; + +// Tutti i membri dopo questo sono pubblici (public) +// finchè "private:" o "protected:" non compaiono. +public: + + // Costruttore di default + Cane(); + + // Dichiarazioni di funzioni membro (le implentazioni sono a seguito) + // Nota che stiamo usando std::string invece di porre + // using namespace std; + // sopra. + // Mai usare uno statement "using namespace" in uno header. + void impostaNome(const std::string& nomeCane); + + void impostaPeso(int pesoCane); + + // Le funzioni che non modificano lo stato dell'oggetto + // dovrebbero essere marcate come const. + // Questo permette di chiamarle con un riferimento const all'oggetto. + // Inoltre, nota che le funzioni devono essere dichiarate espliciamente come _virtual_ + // per essere sovrascritte in classi derivate. + // Le funzioni non sono virtual di default per motivi di performance. + virtual void print() const; + + // Le funzioni possono essere definite anche all'interno del corpo della classe. + // Le funzioni definite in questo modo sono automaticamente inline. + void abbaia() const { std::cout << nome << " abbaia!\n"; } + + // Assieme con i costruttori, il C++ fornisce i distruttori. + // Questi sono chiamati quando un oggetto è rimosso o esce dalla visibilità. + // Questo permette paradigmi potenti come il RAII + // (vedi sotto) + // I distruttori devono essere virtual per permettere a classi di essere + // derivate da questa; altrimenti, il distruttore della classe derivata + // non viene chiamato se l'oggetto viene distrutto tramite un riferimento alla + // classe da cui ha ereditato o tramite un puntatore. + virtual ~Dog(); + +}; // Un punto e virgola deve seguire la definizione della funzione + +// Le funzioni membro di una classe sono generalmente implementate in files .cpp . +Cane::Cane() +{ + std::cout << "Un cane è stato costruito\n"; +} + +// Gli oggetti (ad esempio le stringhe) devono essere passati per riferimento +// se li stai modificando o come riferimento const altrimenti. +void Cane::impostaNome(const std::string& nomeCane) +{ + nome = nomeCane; +} + +void Cane::impostaPeso(int pesoCane) +{ + peso = pesoCane; +} + +// Notare che "virtual" è solamente necessario nelle dichiarazioni, non nelle definizioni. +void Cane::print() const +{ + std::cout << "Il cane è " << nome << " e pesa " << peso << "kg\n"; +} + +Cane::~Cane() +{ + cout << "Ciao ciao " << nome << "\n"; +} + +int main() { + Cane myDog; // stampa "Un cane è stato costruito" + myDog.impostaNome("Barkley"); + myDog.impostaPeso(10); + myDog.print(); // stampa "Il cane è Barkley e pesa 10 kg" + return 0; +} // stampa "Ciao ciao Barkley" + +// Ereditarietà: + +// Questa classe eredita tutto ciò che è public e protected dalla classe Cane, +// ma anche ciò che privato: tuttavia non potrà accedere direttamente a membri/metodi +// privati se non c'è un metodo pubblico o privato che permetta di farlo. +class MioCane : public Cane { + + void impostaProprietario(const std::string& proprietarioCane); + + // Sovrascrivi il comportamento della funzione print per tutti i MioCane. Vedi + // http://it.wikipedia.org/wiki/Polimorfismo_%28informatica%29 + // per una introduzione più generale se non sei familiare con + // il polimorfismo. + // La parola chiave override è opzionale ma fa sì che tu stia effettivamente + // sovrascrivendo il metodo nella classe base. + void print() const override; + +private: + std::string proprietario; +}; + +// Nel frattempo, nel file .cpp corrispondente: + +void MioCane::impostaProprietario(const std::string& proprietarioCane) +{ + proprietario = proprietarioCane; +} + +void MioCane::print() const +{ + Cane::print(); // Chiama la funzione print nella classe base Cane + std::cout << "Il cane è di " << proprietario << "\n"; + // stampa "Il cane è <nome> e pesa <peso>" + // "Il cane è di <proprietario>" +} + +/////////////////////////////////////////////////// +// Inizializzazione ed Overloading degli Operatori +////////////////////////////////////////////////// + +// In C++ puoi sovrascrivere il comportamento di operatori come +, -, *, /, ecc... +// Questo è possibile definendo una funzione che viene chiamata +// ogniqualvolta l'operatore è usato. + +#include <iostream> +using namespace std; + +class Punto { +public: + // Così si assegna alle variabili membro un valore di default. + double x = 0; + double y = 0; + + // Definisce un costruttore di default che non fa nulla + // ma inizializza il Punto ai valori di default (0, 0) + Punto() { }; + + // La sintassi seguente è nota come lista di inizializzazione + // ed è il modo appropriato di inizializzare i valori membro della classe + Punto (double a, double b) : + x(a), + y(b) + { /* Non fa nulla eccetto inizializzare i valori */ } + + // Sovrascrivi l'operatore +. + Punto operator+(const Punto& rhs) const; + + // Sovrascrivi l'operatore += + Punto& operator+=(const Punto& rhs); + + // Avrebbe senso aggiungere gli operatori - e -=, + // ma li saltiamo per rendere la guida più breve. +}; + +Punto Punto::operator+(const Punto& rhs) const +{ + // Crea un nuovo punto come somma di questo e di rhs. + return Punto(x + rhs.x, y + rhs.y); +} + +Punto& Punto::operator+=(const Punto& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Punto su (0,1); + Punto destro (1,0); + // Questo chiama l'operatore + di Punto + // Il Punto su chiama la funzione + con destro come argomento + Punto risultato = su + destro; + // Stampa "Risultato è spostato in (1,1)" + cout << "Risultato è spostato (" << risultato.x << ',' << risultato.y << ")\n"; + return 0; +} + +///////////////// +// Templates +//////////////// + +// Generalmente i templates in C++ sono utilizzati per programmazione generica, anche se +// sono molto più potenti dei costrutti generici in altri linguaggi. Inoltre, +// supportano specializzazione esplicita e parziale, classi in stile funzionale, +// e sono anche complete per Turing. + +// Iniziamo con il tipo di programmazione generica con cui forse sei familiare. Per +// definire una classe o una funzione che prende un parametro di un dato tipo: +template<class T> +class Box { +public: + // In questa classe, T può essere usato come qualsiasi tipo. + void inserisci(const T&) { ... } +}; + +// Durante la compilazione, il compilatore in effetti genera copie di ogni template +// con i parametri sostituiti, e così la definizione completa della classe deve essere +// presente ad ogni invocazione. Questo è il motivo per cui vedrai le classi template definite +// interamente in header files. + +// Per instanziare una classe template sullo stack: +Box<int> intBox; + +// e puoi usarla come aspettato: +intBox.inserisci(123); + +//Puoi, ovviamente, innestare i templates: +Box<Box<int> > boxOfBox; +boxOfBox.inserisci(intBox); + +// Fino al C++11, devi porre uno spazio tra le due '>', altrimenti '>>' +// viene visto come l'operatore di shift destro. + +// Qualche volta vedrai +// template<typename T> +// invece. La parole chiavi 'class' e 'typename' sono _generalmente_ +// intercambiabili in questo caso. Per una spiegazione completa, vedi +// http://en.wikipedia.org/wiki/Typename +// (si, quella parola chiave ha una sua pagina di Wikipedia propria). + +// Similmente, una funzione template: +template<class T> +void abbaiaTreVolte(const T& input) +{ + input.abbaia(); + input.abbaia(); + input.abbaia(); +} + +// Nota che niente è specificato relativamente al tipo di parametri. Il compilatore +// genererà e poi verificherà il tipo di ogni invocazione del template, così che +// la funzione di cui sopra funzione con ogni tipo 'T' che ha const 'abbaia' come metodo! + +Cane fluffy; +fluffy.impostaNome("Fluffy") +abbaiaTreVolte(fluffy); // Stampa "Fluffy abbaia" tre volte. + +// I parametri template non devono essere classi: +template<int Y> +void stampaMessaggio() { + cout << "Impara il C++ in " << Y << " minuti!" << endl; +} + +// E poi esplicitamente specializzare i template per avere codice più efficiente. Ovviamente, +// la maggior parte delle casistiche reali non sono così triviali. +// Notare che avrai comunque bisogna di dichiarare la funzione (o classe) come un template +// anche se hai esplicitamente specificato tutti i parametri. +template<> +void stampaMessaggio<10>() { + cout << "Impara il C++ più velocemente in soli 10 minuti!" << endl; +} + +printMessage<20>(); // Stampa "impara il C++ in 20 minuti!" +printMessage<10>(); // Stampa "Impara il C++ più velocemente in soli 10 minuti!" + +//////////////////////////// +// Gestione delle eccezioni +/////////////////////////// + +// La libreria standard fornisce un paio di tipi d'eccezioni +// (vedi http://en.cppreference.com/w/cpp/error/exception) +// ma ogni tipo può essere lanciato come eccezione +#include <exception> +#include <stdexcept> + +// Tutte le eccezioni lanciate all'interno del blocco _try_ possono essere catturate dai successivi +// handlers _catch_. +try { + // Non allocare eccezioni nello heap usando _new_. + throw std::runtime_error("C'è stato un problema."); +} + +// Cattura le eccezioni come riferimenti const se sono oggetti +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} + +// Cattura ogni eccezioni non catturata dal blocco _catch_ precedente +catch (...) +{ + std::cout << "Catturata un'eccezione sconosciuta"; + throw; // Rilancia l'eccezione +} + +/////// +// RAII +/////// + +// RAII sta per "Resource Allocation Is Initialization". +// Spesso viene considerato come il più potente paradigma in C++. +// È un concetto semplice: un costruttore di un oggetto +// acquisisce le risorse di tale oggetto ed il distruttore le rilascia. + +// Per comprendere come questo sia vantaggioso, +// consideriamo una funzione che usa un gestore di file in C: +void faiQualcosaConUnFile(const char* nomefile) +{ + // Per cominciare, assumiamo che niente possa fallire. + + FILE* fh = fopen(nomefile, "r"); // Apri il file in modalità lettura. + + faiQualcosaConIlFile(fh); + faiQualcosAltroConEsso(fh); + + fclose(fh); // Chiudi il gestore di file. +} + +// Sfortunatamente, le cose vengono complicate dalla gestione degli errori. +// Supponiamo che fopen fallisca, e che faiQualcosaConUnFile e +// faiQualcosAltroConEsso ritornano codici d'errore se falliscono. +// (Le eccezioni sono la maniera preferita per gestire i fallimenti, +// ma alcuni programmatori, specialmente quelli con un passato in C, +// non sono d'accordo con l'utilità delle eccezioni). +// Adesso dobbiamo verificare che ogni chiamata per eventuali fallimenti e chiudere il gestore di file +// se un problema è avvenuto. +bool faiQualcosaConUnFile(const char* nomefile) +{ + FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura + if (fh == nullptr) // Il puntatore restituito è null in caso di fallimento. + return false; // Riporta il fallimento al chiamante. + + // Assumiamo che ogni funzione ritorni false se ha fallito + if (!faiQualcosaConIlFile(fh)) { + fclose(fh); // Chiude il gestore di file così che non sprechi memoria. + return false; // Propaga l'errore. + } + if (!faiQualcosAltroConEsso(fh)) { + fclose(fh); // Chiude il gestore di file così che non sprechi memoria. + return false; // Propaga l'errore. + } + + fclose(fh); // Chiudi il gestore di file così che non sprechi memoria. + return true; // Indica successo +} + +// I programmatori C in genere puliscono questa procedura usando goto: +bool faiQualcosaConUnFile(const char* nomefile) +{ + FILE* fh = fopen(nomefile, "r"); + if (fh == nullptr) + return false; + + if (!faiQualcosaConIlFile(fh)) + goto fallimento; + + if (!faiQualcosAltroConEsso(fh)) + goto fallimento; + + fclose(fh); // Chiude il file + return true; // Indica successo + +fallimento: + fclose(fh); + return false; // Propaga l'errore +} + +// Se le funzioni indicano errori usando le eccezioni, +// le cose sono un pò più pulite, ma sono sempre sub-ottimali. +void faiQualcosaConUnFile(const char* nomefile) +{ + FILE* fh = fopen(nomefile, "r"); // Apre il file in modalità lettura + if (fh == nullptr) + throw std::runtime_error("Errore nell'apertura del file."); + + try { + faiQualcosaConIlFile(fh); + faiQualcosAltroConEsso(fh); + } + catch (...) { + fclose(fh); // Fai sì che il file venga chiuso se si ha un errore. + throw; // Poi rilancia l'eccezione. + } + + fclose(fh); // Chiudi il file + // Tutto è andato bene +} + +// Confronta questo con l'utilizzo della classe C++ file stream (fstream) +// fstream usa i distruttori per chiudere il file. +// Come detto sopra, i distruttori sono automaticamente chiamati +// ogniqualvolta un oggetto esce dalla visibilità. +void faiQualcosaConUnFile(const std::string& nomefile) +{ + // ifstream è l'abbreviazione di input file stream + std::ifstream fh(nomefile); // Apre il file + + // Fai qualcosa con il file + faiQualcosaConIlFile(fh); + faiQualcosAltroConEsso(fh); + +} // Il file viene chiuso automaticamente chiuso qui dal distruttore + +// Questo ha vantaggi _enormi_: +// 1. Può succedere di tutto ma +// la risorsa (in questo caso il file handler) verrà ripulito. +// Una volta che scrivi il distruttore correttamente, +// È _impossibile_ scordarsi di chiudere l'handler e sprecare memoria. +// 2. Nota che il codice è molto più pulito. +// Il distruttore gestisce la chiusura del file dietro le scene +// senza che tu debba preoccupartene. +// 3. Il codice è sicuro da eccezioni. +// Una eccezione può essere lanciata in qualunque punto nella funzione e la ripulitura +// avverrà lo stesso. + +// Tutto il codice C++ idiomatico usa RAII in maniera vasta su tutte le risorse. +// Esempi aggiuntivi includono +// - Utilizzo della memoria con unique_ptr e shared_ptr +// - I contenitori - la lista della libreria standard, +// vettori (i.e. array auto-aggiustati), mappe hash, e così via +// sono tutti automaticamente distrutti con i loro contenuti quando escono dalla visibilità. +// - I mutex usano lock_guard e unique_lock + +/////////////////////// +// Roba divertente +////////////////////// + +// Aspetti del C++ che potrebbero sbalordire i nuovi arrivati (e anche qualche veterano). +// Questa sezione è, sfortunatamente, selvaggiamente incompleta; il C++ è uno dei linguaggi +// più facili con cui puoi spararti da solo nel piede. + +// Puoi sovrascrivere metodi privati! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Sovrascrive Foo::bar! +}; + + +// 0 == false == NULL (la maggior parte delle volte)! +bool* pt = new bool; +*pt = 0; // Setta il valore puntato da 'pt' come falso. +pt = 0; // Setta 'pt' al puntatore null. Entrambe le righe vengono compilate senza warnings. + +// nullptr dovrebbe risolvere alcune di quei problemi: +int* pt2 = new int; +*pt2 = nullptr; // Non compila +pt2 = nullptr; // Setta pt2 a null. + +// C'è un'eccezione per i bool. +// Questo permette di testare un puntatore a null con if(!ptr), ma +// come conseguenza non puoi assegnare nullptr a un bool direttamente! +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! + + +// '=' != '=' != '='! +// Chiama Foo::Foo(const Foo&) o qualche variante (vedi "move semantics") +// del costruttore di copia. +Foo f2; +Foo f1 = f2; + +// Chiama Foo::Foo(const Foo&) o qualche variante, ma solo copie di 'Foo' che fanno parte di +// 'fooSub'. Ogni altro membro di 'fooSub' viene scartato. Questo comportamento +// orribile viene chiamato "object slicing." +FooSub fooSub; +Foo f1 = fooSub; + +// Chiama Foo::operator=(Foo&) o una sua variante. +Foo f1; +f1 = f2; + + +// Come deallocare realmente le risorse all'interno di un vettore: +class Foo { ... }; +vector<Foo> v; +for (int i = 0; i < 10; ++i) + v.push_back(Foo()); + +// La riga seguente riduce la dimensione di v a 0, ma il distruttore non +// viene chiamato e dunque le risorse non sono deallocate! +v.empty(); +v.push_back(Foo()); // Il nuovo valore viene copiato nel primo Foo che abbiamo inserito + +// Distrugge realmente tutti i valori dentro v. Vedi la sezione riguardante gli +// oggetti temporanei per capire come mai funziona così. +v.swap(vector<Foo>()); + +``` +Letture consigliate: + +Un riferimento aggiornato del linguaggio può essere trovato qui +<http://cppreference.com/w/cpp> + +Risorse addizionali possono essere trovate qui <http://cplusplus.com> diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown new file mode 100644 index 00000000..31973369 --- /dev/null +++ b/it-it/coffeescript-it.html.markdown @@ -0,0 +1,109 @@ +--- +language: coffeescript +contributors: + - ["Luca 'Kino' Maroni", "http://github.com/kino90"] + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] +filename: coffeescript-it.coffee +lang: it-it +--- + +CoffeeScript è un piccolo linguaggio che compila direttamente nell'equivalente +JavaScript, non c'è nessuna interpretazione a runtime. Come possibile +successore di Javascript, CoffeeScript fa il suo meglio per restituire +un codice leggibile, ben stampato e performante in ogni ambiente JavaScript. + +Guarda anche [il sito di CoffeeScript](http://coffeescript.org/), che ha una +guida completa a CoffeeScript. + +```coffeescript +# CoffeeScript è un linguaggio hipster. +# Segue le mode di alcuni linguaggi moderni. +# Quindi i commenti sono come quelli di Ruby e Python, usano il cancelletto. + +### +I blocchi di commenti sono definiti con tre cancelletti, che vengono tradotti +direttamente in `/*` e `*/` nel codice JavaScript risultante. + +Prima di continuare devi conoscere la maggior parte +delle semantiche JavaScript. +### + +# Assegnamento: +numero = 42 #=> var numero = 42; +contrario = true #=> var contrario = true; + +# Condizioni: +numero = -42 if contrario #=> if(contrario) { numero = -42; } + +# Funzioni: +quadrato = (x) -> x * x #=> var quadrato = function(x) { return x * x; } + +riempi = (contenitore, liquido = "caffè") -> + "Sto riempiendo #{contenitore} con #{liquido}..." +#=>var riempi; +# +#riempi = function(contenitore, liquido) { +# if (liquido == null) { +# liquido = "caffè"; +# } +# return "Sto riempiendo " + contenitore + " con " + liquido + "..."; +#}; + +# Intervalli: +lista = [1..5] #=> var lista = [1, 2, 3, 4, 5]; + +# Oggetti: +matematica = + radice: Math.sqrt + quadrato: quadrato + cubo: (x) -> x * quadrato x +#=> var matematica = { +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +# } + +# Splats: +gara = (vincitore, partecipanti...) -> + print vincitore, partecipanti +#=>gara = function() { +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +# }; + +# Esistenza: +alert "Lo sapevo!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } + +# Comprensione degli Array: +cubi = (matematica.cubo num for num in lista) +#=>cubi = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; +# })(); + +cibi = ['broccoli', 'spinaci', 'cioccolato'] +mangia cibo for cibo in cibi when cibo isnt 'cioccolato' +#=>cibi = ['broccoli', 'spinaci', 'cioccolato']; +# +#for (_k = 0, _len2 = cibi.length; _k < _len2; _k++) { +# cibo = cibi[_k]; +# if (cibo !== 'cioccolato') { +# mangia(cibo); +# } +#} +``` + +## Altre risorse + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown new file mode 100644 index 00000000..60301b1a --- /dev/null +++ b/it-it/elixir-it.html.markdown @@ -0,0 +1,428 @@ +--- +language: elixir +contributors: + - ["Luca 'Kino' Maroni", "https://github.com/kino90"] + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +translators: + - ["Tommaso Pifferi","http://github.com/neslinesli93"] +filename: learnelixir-it.ex +lang: it-it +--- + +Elixir è un linguaggio funzionale moderno, costruito sulla VM Erlang. +È totalmente compatibile con Erlang, ma con una sintassi più standard +e molte altre funzionalità. + +```elixir + +# I commenti su una riga iniziano con un cancelletto. + +# Non esistono commenti multilinea, +# ma puoi concatenare più commenti. + +# Per usare la shell di elixir usa il comando `iex`. +# Compila i tuoi moduli con il comando `elixirc`. + +# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato +# elixir correttamente. + +## --------------------------- +## -- Tipi di base +## --------------------------- + +# Numeri +3 # intero (Integer) +0x1F # intero +3.0 # decimale (Float) + +# Atomi, che sono literals, una costante con un nome. Iniziano con `:`. +:ciao # atomo (Atom) + +# Tuple che sono salvate in celle di memoria contigue. +{1,2,3} # tupla (Tuple) + +# Possiamo accedere ad un elemento di una tupla con la funzione `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Liste, che sono implementate come liste concatenate (o linked list). +[1,2,3] # lista (List) + +# Possiamo accedere alla testa (head) e alla coda (tail) delle liste così: +[testa | coda] = [1,2,3] +testa #=> 1 +coda #=> [2,3] + +# In Elixir, proprio come in Erlang, il simbolo `=` denota pattern matching e +# non un assegnamento. +# +# Questo significa che la parte sinistra (pattern) viene confrontata alla +# parte destra. +# +# Questo spiega il funzionamento dell'esempio dell'accesso alla lista di prima. + +# Un pattern match darà errore quando le parti non combaciano, ad esempio se +# le tuple hanno dimensione differente. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Ci sono anche i binari +<<1,2,3>> # binari (Binary) + +# Stringhe e liste di caratteri +"ciao" # stringa (String) +'ciao' # lista di caratteri (List) + +# Stringhe multilinea +""" +Sono una stringa +multi-linea. +""" +#=> "Sono una stringa\nmulti-linea.\n" + +# Le stringhe sono tutte codificate in UTF-8: +"cìaò" +#=> "cìaò" + +# le stringhe in realtà sono dei binari, e le liste di caratteri sono liste. +<<?a, ?b, ?c>> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` in elixir restituisce il valore ASCII della lettera `a` +?a #=> 97 + +# Per concatenare liste si usa `++`, per binari si usa `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'ciao ' ++ 'mondo' #=> 'ciao mondo' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"ciao " <> "mondo" #=> "ciao mondo" + +# Gli intervalli sono rappresentati come `inizio..fine` (estremi inclusi) +1..10 #=> 1..10 (Range) +minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli +[minore, maggiore] #=> [1, 10] + +## --------------------------- +## -- Operatori +## --------------------------- + +# Un po' di matematica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In elixir l'operatore `/` restituisce sempre un decimale. + +# Per fare una divisione intera si usa `div` +div(10, 2) #=> 5 + +# Per ottenere il resto di una divisione si usa `rem` +rem(10, 3) #=> 1 + +# Ci sono anche gli operatori booleani: `or`, `and` e `not`. +# Questi operatori si aspettano un booleano come primo argomento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir fornisce anche `||`, `&&` e `!` che accettano argomenti +# di qualsiasi tipo. +# Tutti i valori tranne `false` e `nil` saranno valutati come true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Per i confronti abbiamo: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` sono più rigidi quando si confrontano interi e decimali: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Possiamo anche confrontare tipi di dato diversi: +1 < :ciao #=> true + +# L'ordine generale è definito sotto: +# numeri < atomi < riferimenti < funzioni < porte < pid < tuple < liste +# < stringhe di bit + +# Per citare Joe Armstrong su questo: "L'ordine non è importante, +# ma è importante che sia definito un ordine." + +## --------------------------- +## -- Controllo di flusso +## --------------------------- + +# espressione `se` (`if`) +if false do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# c'è anche un `se non` (`unless`) +unless true do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# Ti ricordi il pattern matching? +# Moltre strutture di controllo di flusso in elixir si basano su di esso. + +# `case` ci permette di confrontare un valore a diversi pattern: +case {:uno, :due} do + {:quattro, :cinque} -> + "Questo non farà match" + {:uno, x} -> + "Questo farà match e binderà `x` a `:due`" + _ -> + "Questo farà match con qualsiasi valore" +end + +# Solitamente si usa `_` se non si ha bisogno di utilizzare un valore. +# Ad esempio, se ci serve solo la testa di una lista: +[testa | _] = [1,2,3] +testa #=> 1 + +# Per aumentare la leggibilità possiamo usarlo in questo modo: +[testa | _coda] = [:a, :b, :c] +testa #=> :a + +# `cond` ci permette di verificare più condizioni allo stesso momento. +# Usa `cond` invece di innestare più espressioni `if`. +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + 1 + 2 == 3 -> + "Questa sì!" +end + +# È pratica comune mettere l'ultima condizione a `true`, che farà sempre match +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + true -> + "Questa sì! (essenzialmente funziona come un else)" +end + +# `try/catch` si usa per gestire i valori lanciati (throw), +# Supporta anche una clausola `after` che è invocata in ogni caso. +try do + throw(:ciao) +catch + message -> "Ho ricevuto #{message}." +after + IO.puts("Io sono la clausola 'after'.") +end +#=> Io sono la clausola 'after' +# "Ho ricevuto :ciao" + +## --------------------------- +## -- Moduli e Funzioni +## --------------------------- + +# Funzioni anonime (notare il punto) +quadrato = fn(x) -> x * x end +quadrato.(5) #=> 25 + +# Accettano anche guardie e condizioni multiple. +# le guardie ti permettono di perfezionare il tuo pattern matching, +# sono indicate dalla parola chiave `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir fornisce anche molte funzioni, disponibili nello scope corrente. +is_number(10) #=> true +is_list("ciao") #=> false +elem({1,2,3}, 0) #=> 1 + +# Puoi raggruppare delle funzioni all'interno di un modulo. +# All'interno di un modulo usa `def` per definire le tue funzioni. +defmodule Matematica do + def somma(a, b) do + a + b + end + + def quadrato(x) do + x * x + end +end + +Matematica.somma(1, 2) #=> 3 +Matematica.quadrato(3) #=> 9 + +# Per compilare il modulo 'Matematica' salvalo come `matematica.ex` e usa +# `elixirc`. +# nel tuo terminale: elixirc matematica.ex + +# All'interno di un modulo possiamo definire le funzioni con `def` e funzioni +# private con `defp`. +# Una funzione definita con `def` è disponibile per essere invocata anche da +# altri moduli, una funziona privata può essere invocata solo localmente. +defmodule MatematicaPrivata do + def somma(a, b) do + esegui_somma(a, b) + end + + defp esegui_somma(a, b) do + a + b + end +end + +MatematicaPrivata.somma(1, 2) #=> 3 +# MatematicaPrivata.esegui_somma(1, 2) #=> ** (UndefinedFunctionError) + +# Anche le dichiarazioni di funzione supportano guardie e condizioni multiple: +defmodule Geometria do + def area({:rettangolo, w, h}) do + w * h + end + + def area({:cerchio, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometria.area({:rettangolo, 2, 3}) #=> 6 +Geometria.area({:cerchio, 3}) #=> 28.25999999999999801048 +# Geometria.area({:cerchio, "non_un_numero"}) +#=> ** (FunctionClauseError) no function clause matching in Geometria.area/1 + +# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir +defmodule Ricorsione do + def somma_lista([testa | coda], accumulatore) do + somma_lista(coda, accumulatore + testa) + end + + def somma_lista([], accumulatore) do + accumulatore + end +end + +Ricorsione.somma_lista([1,2,3], 0) #=> 6 + +# I moduli di Elixir supportano attributi. Ci sono degli attributi incorporati +# e puoi anche aggiungerne di personalizzati. +defmodule Modulo do + @moduledoc """ + Questo è un attributo incorporato in un modulo di esempio. + """ + + @miei_dati 100 # Questo è un attributo personalizzato . + IO.inspect(@miei_dati) #=> 100 +end + +## --------------------------- +## -- Strutture ed Eccezioni +## --------------------------- + + +# Le Strutture (Structs) sono estensioni alle mappe che portano +# valori di default, garanzia alla compilazione e polimorfismo in Elixir. +defmodule Persona do + defstruct nome: nil, eta: 0, altezza: 0 +end + +luca = %Persona{ nome: "Luca", eta: 24, altezza: 185 } +#=> %Persona{eta: 24, altezza: 185, nome: "Luca"} + +# Legge al valore di 'nome' +luca.nome #=> "Luca" + +# Modifica il valore di eta +luca_invecchiato = %{ luca | eta: 25 } +#=> %Persona{eta: 25, altezza: 185, nome: "Luca"} + +# Il blocco `try` con la parola chiave `rescue` è usato per gestire le eccezioni +try do + raise "un errore" +rescue + RuntimeError -> "Salvato un errore di Runtime" + _error -> "Questo salverà da qualsiasi errore" +end + +# Tutte le eccezioni hanno un messaggio +try do + raise "un errore" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrenza +## --------------------------- + +# Elixir si basa sul modello degli attori per la concorrenza. +# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir +# sono tre primitive: creare processi, inviare messaggi e ricevere messaggi. + +# Per creare un nuovo processo si usa la funzione `spawn`, che riceve una +# funzione come argomento. +f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> +spawn(f) #=> #PID<0.40.0> + +# `spawn` restituisce un pid (identificatore di processo). Puoi usare questo +# pid per inviare messaggi al processo. +# Per passare messaggi si usa l'operatore `send`. +# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, +# oltre ad inviarli. Questo è realizzabile con `receive`: + +# Il blocco `receive do` viene usato per mettersi in ascolto di messaggi +# ed elaborarli quando vengono ricevuti. Un blocco `receive do` elabora +# un solo messaggio ricevuto: per fare elaborazione multipla di messaggi, +# una funzione con un blocco `receive do` al suo intero dovrà chiamare +# ricorsivamente sé stessa per entrare di nuovo nel blocco `receive do`. +defmodule Geometria do + def calcolo_area do + receive do + {:rettangolo, w, h} -> + IO.puts("Area = #{w * h}") + calcolo_area() + {:cerchio, r} -> + IO.puts("Area = #{3.14 * r * r}") + calcolo_area() + end + end +end + +# Compila il modulo e crea un processo che esegue `calcolo_area` nella shell +pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> +# Alternativamente +pid = spawn(Geometria, :calcolo_area, []) + +# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive +send pid, {:rettangolo, 2, 3} +#=> Area = 6 +# {:rettangolo,2,3} + +send pid, {:cerchio, 2} +#=> Area = 12.56000000000000049738 +# {:cerchio,2} + +# Anche la shell è un processo. Puoi usare `self` per ottenere il pid corrente +self() #=> #PID<0.27.0> +``` + +## Referenze + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org) +* [Documentazione Elixir](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) di Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) di Joe Armstrong diff --git a/it-it/java-it.html.markdown b/it-it/java-it.html.markdown index 6eabd61f..54602cff 100644 --- a/it-it/java-it.html.markdown +++ b/it-it/java-it.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Madison Dickson", "http://github.com/mix3d"] translators: - ["Ivan Sala","http://github.com/slavni96"] + - ["Tommaso Pifferi","http://github.com/neslinesli93"] lang: it-it --- @@ -31,9 +32,9 @@ import java.security.*; // Ogni file .java contiene una classe pubblica, con lo stesso nome del file public class LearnJava { - // Un programma deve avere un metodo main come punto di partenza - // Ma si possono creare anche file senza main, che però per essere usati - // devono essere richiamati da altri file. + // Un programma deve avere un metodo main come punto di partenza. + // Tuttavia si possono creare anche file senza main, che però + // per essere usati devono essere richiamati da altri file. public static void main (String[] args) { // Per stampare a schermo si usa System.out.println @@ -47,88 +48,157 @@ public class LearnJava { System.out.print("Ciao "); System.out.print("Mondo "); + // Per stampare del testo formattato, si puo' usare System.out.printf + System.out.printf("pi greco = %.5f", Math.PI); // => pi greco = 3.14159 /////////////////////////////////////// - // Tipi e Variabili + // Variabili /////////////////////////////////////// - // Si dichiara una variabile usando <tipo> <nome> - // Byte - variabile intera da 8 bit con segno + + /* + * Dichiarazione delle Variabili + */ + // Per dichiarare una variabile basta fare <tipoDato> <nomeVariabile> + int fooInt; + // Per dichiarare piu' di una variabile dello lo stesso tipo si usa: + // <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> + int fooInt1, fooInt2, fooInt3; + + /* + * Inizializzazione delle Variabili + */ + + // Per inizializzare una variabile si usa + // <tipoDato> <nomeVariabile> = <valore> + int fooInt = 1; + // Per inizializzare piu' di una variabile dello lo stesso tipo + // si usa <tipoDato> <nomeVariabile1>, <nomeVariabile2>, <nomeVariabile3> = <valore> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Tipi di Variabili + */ + // Byte - intero con segno a 8 bit (in complemento a 2) // (-128 <= byte <= 127) byte fooByte = 100; - // Short - variabile intera da 18 bit con segno + // Short - intero con segno a 16 bit (in complemento a 2) // (-32,768 <= short <= 32,767) short fooShort = 10000; - // Integer - variabile intera da 32 bit con segno + // Integer - intero con segno a 32 bit (in complemento a 2) // (-2,147,483,648 <= int <= 2,147,483,647) int fooInt = 1; - // Long - variabile da 64 bit intera con segno + // Long - intero con segno a 64 bit (in complemento a 2) // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) long fooLong = 100000L; - // L viene usato per specificare che il valore dalla variabile - // e' di tipo "Long", qualsiasi variabile che non viene contrassegnata - // e' trattata di base come un intero. + // L viene usato per indicare che il valore e' di tipo Long; + // altrimenti il valore viene considerato come intero. - // Nota: Java non dispone di variabili senza segno + // Nota: Java non dispone di interi senza segno. - // Float - variabile piu' precisa, con virgola [numeri reali] - // di grandezza 32 bit + // Float - Numero in virgola mobile a 32 bit con precisione singola (IEEE 754) + // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f e' usato per specificare che la variabile e'' di tipo "float" - // altrimenti di default viene trattata come un "dobule" + // f o F indicano the la variabile e' di tipo float; + // altrimenti il valore viene considerato come double. - // Double - ancora piu' precisione la si puo' ottenere con una variabile - // Double, con granzezza di 64 bit. + // Double - Numero in virgola mobile a 64 bit con precisione doppia (IEEE 754) + // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; - // Boolean - vero & falso + // Boolean - Puo' assumere il valore vero (true) o falso (false) boolean fooBoolean = true; boolean barBoolean = false; - // Char - un singolo carattere con grandezza 16 bit + // Char - Un singolo carattere Unicode a 16-bit char fooChar = 'A'; - // final - Costanti, non possono essere riassegnate ad un altro oggetto - final int ORE_LAVORATIVE_DI_UNA_SETTIMANA = 9001; - - // String - Stringhe, array di caratteri - String fooString = "Ecco una stringa!"; - - // \n e' un carattere speciale che permette di andare a capo. - String barString = "Andare a capo?\nNessun problema!"; - // \t e' un carattere speciale che permette di aggiungere un 'Tab' - String bazString = "Vuoi inserire tab?\tNessun problema"; + // Le variabili precedute da final possono essere inizializzate una volta sola, + final int HOURS_I_WORK_PER_WEEK = 9001; + // pero' e' possibile dichiararle e poi inizializzarle in un secondo momento. + final double E; + E = 2.71828; + + + // BigInteger - Interi a precisione arbitraria + // + // BigInteger e' un tipo di dato che permette ai programmatori di + // gestire interi piu' grandi di 64 bit. Internamente, le variabili + // di tipo BigInteger vengono memorizzate come un vettore di byte e + // vengono manipolate usando funzioni dentro la classe BigInteger. + // + // Una variabile di tipo BigInteger puo' essere inizializzata usando + // un array di byte oppure una stringa. + + BigInteger fooBigInteger = new BigDecimal(fooByteArray); + + // BigDecimal - Numero con segno, immutabile, a precisione arbitraria + // + // Una variabile di tipo BigDecimal e' composta da due parti: un intero + // a precisione arbitraria detto 'non scalato', e un intero a 32 bit + // che rappresenta la 'scala', ovvero la potenza di 10 con cui + // moltiplicare l'intero non scalato. + // + // I BigDecimal permettono un controllo completo sull'arrotondamento + // dei numeri. Essi sono molto usati in ambito finanziario, nella + // gestione delle valute, e in ogni altro posto in cui serve + // precisione esatta. + // + // Le variabili di tipo BigDecimal possono essere inizializzate con un + // int, long, double o String, oppure con un intero non scalato + // (di tipo BigInteger) e una scala (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + + + // Stringhe + String fooString = "Questa e' la mia stringa!"; + + // \n e' un carattere di escape che rappresenta l'andare a capo + String barString = "Stampare su una nuova riga?\nNessun problema!"; + // \t e' un carattere di escape che aggiunge un tab + String bazString = "Vuoi aggiungere un tab?\tNessun problema!"; System.out.println(fooString); System.out.println(barString); System.out.println(bazString); - // Vettori [array] - //La lunghezza del vettore deve essere decisa quando viene istanziato - //Si puo' dichiarare come segue: - //<tipodato> [] <nomevariabile> = new <tipodato>[<grandezza vettore>]; - //<tipodato> <nomevariabile>[] = new <tipodato>[<grandezza vettore>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; - - // Un altro modo per dichiarare & inizializzare un vettore - int [] y = {9000, 1000, 1337}; - String nomi [] = {"Andrea", "Bob", "Pippo", "Susan"}; + // Vettori + // La dimensione di un array deve essere decisa in fase di + // istanziazione. Per dichiarare un array si puo' fare in due modi: + // <tipoDato>[] <nomeVariabile> = new <tipoDato>[<dimensioneArray>]; + // <tipoDato> <nomeVariabile>[] = new <tipoDato>[<dimensioneArray>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; + + // Un altro modo per dichiarare ed insieme inizializzare un vettore. + int[] y = {9000, 1000, 1337}; + String names[] = {"Gianni", "Anna", "Luca", "Cristina"}; boolean bools[] = new boolean[] {true, false, false}; - - // I vettori vengono indicizzati a parire dallo 0 + + // Per accedere ad un elemento di un vettore System.out.println("intArray @ 0: " + intArray[0]); - // e' possibile un accesso diretto ad un elemento + // I vettori non sono immutabili (ma la loro dimensione si!) + // e gli indici partono da 0. intArray[1] = 1; System.out.println("intArray @ 1: " + intArray[1]); // => 1 - // Altro da vedere: - // Liste di array - come i vettori ma piu' funzionali - // e la loro grandezza puo' variare in corso di esecuzione - // Liste concatenate di memoria + // Ci sono altri tipo di dato interessanti. + // ArrayList - Simili ai vettori, pero' offrono altre funzionalita', + // e la loro dimensione puo' essere modificata. + // LinkedList - Si tratta di una lista linkata doppia, e come tale + // implementa tutte le operazioni del caso. + // Map - Un insieme di oggetti che fa corrispondere delle chiavi + // a dei valori. Non permette l'inserimento di chiavi uguali. + // HashMap - Questa classe usa una tabella di hash per implementare + // l'interfaccia di tipo Map. Questo permette di effettuare + // operazioni basilari, come inserimento e cancellazione, + // in tempo costante anche su insiemi molto grandi. /////////////////////////////////////// // Operatori diff --git a/it-it/json-it.html.markdown b/it-it/json-it.html.markdown new file mode 100644 index 00000000..379bad73 --- /dev/null +++ b/it-it/json-it.html.markdown @@ -0,0 +1,69 @@ +--- +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] + - ["Christian Grasso", "http://chris54721.net"] +lang: it-it +--- + +JSON è un formato per l'interscambio di dati estremamente semplice, per cui questo sarà +con molta probabilità il più semplice Learn X in Y Minutes. + +Nella sua forma più pura JSON non ha commenti, ma molti parser accettano +commenti in stile C (//, /\* \*/). Per lo scopo prefissato, tuttavia, tutto sarà +100% JSON valido. Fortunatamente, si spiega da sè. + +I tipi supportati da JSON comprendono: numeri, stringhe, boolean, array, oggetti e null. +I browser supportati sono: Firefox (Mozilla) 3.5+, Internet Explorer 8+, Google Chrome, +Opera 10+, Safari 4+. +I file JSON sono salvati nel formato ".json". Il MIME type per documenti JSON è +"application/json". Gli svantaggi del JSON includono l'assenza di una definizione dei tipi +e di una sorta di [DTD](https://it.wikipedia.org/wiki/Document_Type_Definition). + +```json +{ + "chiave": "valore", + + "chiavi": "devono sempre essere racchiuse tra doppi apici", + "numeri": 0, + "stringhe": "Ciaø, møndø. Tutti i caratteri Unicode sono permessi, insieme all'\"escaping\".", + "ha booleani?": true, + "il nulla": null, + + "numero grande": 1.2e+100, + + "oggetti": { + "commento": "La maggior parte della tua struttura viene dagli oggetti.", + + "array": [0, 1, 2, 3, "Gli array possono contenere qualsiasi cosa.", 5], + + "un altro oggetto": { + "commento": "Queste cose possono essere annidate, molto utile." + } + }, + + "sciocchezze": [ + { + "sorgenti di potassio": ["banane"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "stile alternativo": { + "commento": "Guarda qua!" + , "posizione della virgola": "non conta - se è prima della chiave successiva, allora è valida" + , "un altro commento": "che bello" + }, + + "è stato molto breve": "Ed hai finito. Adesso sai tutto cio che JSON ha da offrire." +} +``` diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown new file mode 100644 index 00000000..0c3160a2 --- /dev/null +++ b/ja-jp/julia-jp.html.markdown @@ -0,0 +1,762 @@ +--- +language: Julia +contributors: + - ["Leah Hanson", "http://leahhanson.us"] +translators: + - ["Yuichi Motoyama", "https://github.com/yomichi"] +filename: learnjulia-jp.jl +lang: ja-jp +--- + +Julia は科学技術計算向けに作られた、同図像性を持った(homoiconic) プログラミング言語です。 +マクロによる同図像性や第一級関数などの抽象化機能の恩恵を受けつつ、低階層をも扱えますが、 +それでいてPython 並に学習しやすく、使いやすい言語となっています。 + +この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 + +```ruby + +# ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 +#= 複数行コメントは、 + '#=' と '=#' とで囲むことで行えます。 + #= + 入れ子構造にすることもできます。 + =# +=# + +#################################################### +## 1. 基本的な型と演算子 +#################################################### + +# Julia ではすべて式となります。 + +# 基本となる数値型がいくつかあります。 +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# 一般的な中置演算子が使用可能です。 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # 整数型同士の割り算の結果は、浮動小数点数型になります +div(5, 2) # => 2 # 整数のまま割り算するには、 div を使います +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # べき乗です。排他的論理和ではありません +12 % 10 # => 2 + +# 丸括弧で演算の優先順位をコントロールできます +(1 + 3) * 2 # => 8 + +# ビット演算 +~2 # => -3 # ビット反転 +3 & 5 # => 1 # ビット積 +2 | 4 # => 6 # ビット和 +2 $ 4 # => 6 # ビット排他的論理和 +2 >>> 1 # => 1 # 右論理シフト +2 >> 1 # => 1 # 右算術シフト +2 << 1 # => 4 # 左シフト + +# bits 関数を使うことで、数の二進表現を得られます。 +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# ブール値が用意されています +true +false + +# ブール代数 +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true +# 比較演算子をつなげることもできます +1 < 2 < 3 # => true +2 < 3 < 2 # => false + +# 文字列は " で作れます +"This is a string." + +# 文字リテラルは ' で作れます +'a' + +# 文字列は文字の配列のように添字アクセスできます +"This is a string"[1] # => 'T' # Julia では添字は 1 から始まります +# ただし、UTF8 文字列の場合は添字アクセスではうまくいかないので、 +# イテレーションを行ってください(map 関数や for ループなど) + +# $ を使うことで、文字列に変数や、任意の式を埋め込めます。 +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" + +# 他にも、printf マクロを使うことでも変数を埋め込めます。 +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# 出力も簡単です +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. 変数と配列、タプル、集合、辞書 +#################################################### + +# 変数の宣言は不要で、いきなり変数に値を代入・束縛できます。 +some_var = 5 # => 5 +some_var # => 5 + +# 値に束縛されていない変数を使おうとするとエラーになります。 +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# 変数名は数字や記号以外の文字から始めます。 +# その後は、数字やアンダースコア(_), 感嘆符(!)も使えます。 +SomeOtherVar123! = 6 # => 6 + +# Unicode 文字も使えます。 +☃ = 8 # => 8 +# ギリシャ文字などを使うことで数学的な記法が簡単にかけます。 +2 * π # => 6.283185307179586 + +# Julia における命名習慣について: +# +# * 変数名における単語の区切りにはアンダースコアを使っても良いですが、 +# 使わないと読みにくくなる、というわけではない限り、 +# 推奨はされません。 +# +# * 型名は大文字で始め、単語の区切りにはキャメルケースを使います。 +# +# * 関数やマクロの名前は小文字で書きます。 +# 単語の分かち書きにはアンダースコアをつかわず、直接つなげます。 +# +# * 内部で引数を変更する関数は、名前の最後に ! をつけます。 +# この手の関数は、しばしば「破壊的な関数」とか「in-place な関数」とか呼ばれます。 + + +# 配列は、1 から始まる整数によって添字付けられる、値の列です。 +a = Int64[] # => 0-element Int64 Array + +# 一次元配列(列ベクトル)は、角括弧 [] のなかにカンマ , 区切りで値を並べることで作ります。 +b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 + +# 二次元配列は、空白区切りで作った行を、セミコロンで区切ることで作ります。 +matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] + +# 配列の末尾に値を追加するには push! を、 +# 他の配列を結合するには append! を使います。 +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# 配列の末尾から値を削除するには pop! を使います。 +pop!(b) # => 6 and b is now [4,5] + +# 一旦元に戻しておきましょう。 +push!(b,6) # b is now [4,5,6] again. + +a[1] # => 1 # Julia では添字は0 ではなく1 から始まること、お忘れなく! + +# end は最後の添字を表す速記法です。 +# 添字を書く場所ならどこにでも使えます。 +a[end] # => 6 + +# 先頭に対する削除・追加は shift!, unshift! です。 +shift!(a) # => 1 and a is now [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# ! で終わる関数名は、その引数を変更するということを示します。 +arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] +sort(arr) # => [4,5,6]; arr is still [5,4,6] +sort!(arr) # => [4,5,6]; arr is now [4,5,6] + +# 配列の範囲外アクセスをすると BoundsError が発生します。 +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# エラーが発生すると、どのファイルのどの行で発生したかが表示されます。 +# 標準ライブラリで発生したものでもファイル名と行数が出ます。 +# ソースからビルドした場合など、標準ライブラリのソースが手元にある場合は +# base/ ディレクトリから探し出して見てください。 + +# 配列は範囲オブジェクトから作ることもできます。 +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# 添字として範囲オブジェクトを渡すことで、 +# 配列の部分列を得ることもできます。 +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] + +# 添字を用いて配列から値の削除をしたい場合は、splice! を使います。 +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr is now [3,5] + +# 配列の結合は append! です。 +b = [1,2,3] +append!(a,b) # Now a is [1, 2, 3, 4, 5, 1, 2, 3] + +# 配列内に指定した値があるかどうかを調べるのには in を使います。 +in(1, a) # => true + +# length で配列の長さを取得できます。 +length(a) # => 8 + +# 変更不可能 (immutable) な値の組として、タプルが使えます。 +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# 配列に関する関数の多くが、タプルでも使えます。 +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# タプルから値をばらして(unpack して) 複数の変数に代入できます。 +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# 丸括弧なしでもタプルになります。 +d, e, f = 4, 5, 6 # => (4,5,6) + +# ひとつの値だけからなるタプルは、その値自体とは区別されます。 +(1,) == 1 # => false +(1) == 1 # => true + +# 値の交換もタプルを使えば簡単です。 +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# 辞書 (Dict) は、値から値への変換の集合です。 +empty_dict = Dict() # => Dict{Any,Any}() + +# 辞書型リテラルは次のとおりです。 +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# [] を使ったアクセスができます。 +filled_dict["one"] # => 1 + +# すべての鍵(添字)は keys で得られます。 +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 必ずしも辞書に追加した順番には並んでいないことに注意してください。 + +# 同様に、values はすべての値を返します。 +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 鍵と同様に、必ずしも辞書に追加した順番には並んでいないことに注意してください。 + +# in や haskey を使うことで、要素や鍵が辞書の中にあるかを調べられます。 +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# 存在しない鍵を問い合わせると、エラーが発生します。 +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# get 関数を使い、鍵がなかった場合のデフォルト値を与えておくことで、 +# このエラーを回避できます。 +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# 集合 (Set) は一意な値の、順序付けられていない集まりです。 +empty_set = Set() # => Set{Any}() +# 集合の初期化 +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# 集合への追加 +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# in で、値が既に存在するかを調べられます。 +in(2, filled_set) # => true +in(10, filled_set) # => false + +# 積集合や和集合、差集合を得る関数も用意されています。 +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) + + +#################################################### +## 3. 制御構文 +#################################################### + +# まずは変数を作ります。 +some_var = 5 + +# if 構文です。Julia ではインデントに意味はありません。 +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # elseif 節は省略可能です。 + println("some_var is smaller than 10.") +else # else 節も省略可能です。 + println("some_var is indeed 10.") +end +# => "some var is smaller than 10" と出力されます。 + +# for ループによって、反復可能なオブジェクトを走査できます。 +# 反復可能なオブジェクトの型として、 +# Range, Array, Set, Dict, String などがあります。 +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # $ を使うことで文字列に変数の値を埋め込めます。 + # You can use $ to interpolate variables or expression into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# for = の代わりに for in を使うこともできます +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# 辞書ではタプルが返ってきます。 +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# タプルのアンパック代入もできます。 +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# while ループは、条件式がtrue となる限り実行され続けます。 +x = 0 +while x < 4 + println(x) + x += 1 # Shorthand for x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# 例外は try/catch で捕捉できます。 +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. 関数 +#################################################### + +# function キーワードを次のように使うことで、新しい関数を定義できます。 +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # 最後に評価された式の値が、関数全体の返り値となります。 + x + y +end + +add(5, 6) # => 11 after printing out "x is 5 and y is 6" + +# 可変長引数関数も定義できます。 +function varargs(args...) + return args + # return キーワードを使うことで、好きな位置で関数から抜けられます。 +end +# => varargs (generic function with 1 method) + +varargs(1,2,3) # => (1,2,3) + +# ... はsplat と呼ばれます +# (訳注:「ピシャッという音(名詞)」「衝撃で平らにする(動詞)」) +# 今回は関数定義で使いましたが、関数呼び出しに使うこともできます。 +# その場合、配列やタプルの要素を開いて、複数の引数へと割り当てることとなります。 +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 「整数の配列」の集合 +Set([1,2,3]...) # => Set{Int64}(1,2,3) # 整数の集合 + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # タプルの集合 +Set(x...) # => Set{Int64}(2,3,1) + + +# 引数に初期値を与えることで、オプション引数をもった関数を定義できます。 +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# キーワード引数を持った関数も作れます。 +function keyword_args(;k1=4,name2="hello") # ; が必要なことに注意 + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# もちろん、これらを組み合わせることもできます。 +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia では関数は第一級関数として、値として扱われます。 +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# ラムダ式によって無名関数をつくれます。 +(x -> x > 2)(3) # => true + +# 先ほどの create_adder と同じもの +function create_adder(x) + y -> x + y +end + +# 中の関数に名前をつけても構いません。 +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# いくつかの高階関数が定義されています。 +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# map の代わりとしてリスト内包表記も使えます。 +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. 型 +#################################################### + +# Julia ではすべての値にひとつの型がついています。 +# 変数に、ではなくて値に、です。 +# typeof 関数を使うことで、値が持つ型を取得できます。 +typeof(5) # => Int64 + +# 型自身もまた、第一級の値であり、型を持っています。 +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType は型を表現する型であり、DataType 自身もDataType 型の値です。 + +# 型はドキュメント化や最適化、関数ディスパッチのために使われます。 +# 静的な型チェックは行われません。 + +# 自分で新しい型を定義することもできます。 +# 他の言語で言う、構造体やレコードに近いものになっています。 +# 型定義には type キーワードを使います。 +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # 型注釈を省略した場合、自動的に :: Any として扱われます。 +end + +# 型を定義すると、その型のプロパティすべてを、定義した順番に +# 引数として持つデフォルトコンストラクタが自動的に作られます。 +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# 型名がそのままコンストラクタ名(関数名)となります。 +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# このような、構造体スタイルの型は、具体型(concrete type)と呼ばれます。 +# 具体型はインスタンス化可能ですが、派生型(subtype)を持つことができません。 +# 具体型の他には抽象型(abstract type)があります。 + +# abstract Name +abstract Cat # 型の階層図の途中の一点を指し示す名前となります。 + +# 抽象型はインスタンス化できませんが、派生型を持つことができます。 +# 例えば、 Number は以下の派生型を持つ抽象型です。 +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# すべての型は、直接的にはただひとつの基本型(supertype) を持ちます。 +# super 関数でこれを取得可能です。 +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# Int64 を除き、これらはすべて抽象型です。 + +# <: は派生形を表す演算子です。 +# これを使うことで派生型を定義できます。 +type Lion <: Cat # Lion は 抽象型 Cat の派生型 + mane_color + roar::String +end + +# 型名と同じ名前の関数を定義し、既に存在するコンストラクタを呼び出して、 +# 必要とする型の値を返すことによって、 +# デフォルトコンストラクタ以外のコンストラクタを作ることができます。 + +Lion(roar::String) = Lion("green",roar) +# 型定義の外側で定義されたコンストラクタなので、外部コンストラクタと呼ばれます。 + +type Panther <: Cat # Panther も Cat の派生型 + eye_color + Panther() = new("green") + # Panther は内部コンストラクタとしてこれのみを持ち、 + # デフォルトコンストラクタを持たない +end +# 内部コンストラクタを使うことで、どのような値が作られるのかをコントロールすることができます。 +# 出来る限り、外部コンストラクタを使うべきです。 + +#################################################### +## 6. 多重ディスパッチ +#################################################### + +# Julia では、すべての名前付きの関数は総称的関数(generic function) です。 +# これは、関数はいくつかの細かいメソッドの集合である、という意味です。 +# 例えば先の Lion 型のコンストラクタ Lion は、Lion という関数の1つのメソッドです。 + +# コンストラクタ以外の例をみるために、新たに meow 関数を作りましょう。 + +# Lion, Panther, Tiger 型それぞれに対する meow 関数のメソッド定義 +function meow(animal::Lion) + animal.roar # 型のプロパティには . でアクセスできます。 +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# meow 関数の実行 +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# 型の階層関係を見てみましょう +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# 抽象型 Cat の派生型を引数にとる関数 +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# オブジェクト指向言語では、一般的にシングルディスパッチが用いられます。 +# つまり、関数に複数あるメソッドのうちにどれが呼ばれるかは、 +# その第一引数(もしくは、 . や -> の前にある値の型)によってのみ決定されます。 +# 一方でJulia では、すべての引数の型が、このメソッド決定に寄与します。 + +# 多変数関数を定義して、この辺りを見て行きましょう。 +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# 第二引数の Cat が実際は Lion だった時に、挙動が変わるようにします。 +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# 別に Tiger だけが戦う必要もないですね。 +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# 第一引数にも Cat を許しましょう。 +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# 警告が出ましたが、これは次の対戦で何が起きるのかが不明瞭だからです。 +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# Julia のバージョンによっては、結果が違うかもしれません。 + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Julia が生成する LLVM 内部表現や、アセンブリを調べることもできます。 + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# square_area に整数を渡すと何が起きる? +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # l を取得 + # imul RAX, RAX # l*l を計算して RAX に入れる + # pop RBP # Base Pointer を元に戻す + # ret # 終了。RAX の中身が結果 + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # 単精度浮動小数点数演算 (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # 倍精度浮動小数点数演算 (AVX) + # pop RBP + # ret + # + +# Julia では、浮動小数点数と整数との演算では +# 自動的に浮動小数点数用の命令が生成されることに注意してください。 +# 円の面積を計算してみましょう。 +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` + +## より勉強するために + +[公式ドキュメント](http://docs.julialang.org/en/latest/manual/) (英語)にはより詳細な解説が記されています。 + +Julia に関して助けが必要ならば、[メーリングリスト](https://groups.google.com/forum/#!forum/julia-users) が役に立ちます。 +みんな非常に親密に教えてくれます。 + diff --git a/java.html.markdown b/java.html.markdown index f08c4679..84978ecc 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,15 +1,19 @@ --- - language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] + - ["Jakukyo Friel", "http://weakish.github.io"] - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Cameron Schermerhorn", "http://github.com/cschermerhorn"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] filename: LearnJava.java - --- -Java is a general-purpose, concurrent, class-based, object-oriented computer programming language. -[Read more here.](http://docs.oracle.com/javase/tutorial/java/index.html) +Java is a general-purpose, concurrent, class-based, object-oriented computer +programming language. +[Read more here.](http://docs.oracle.com/javase/tutorial/java/) ```java // Single-line comments start with // @@ -30,26 +34,48 @@ import java.security.*; // the file. public class LearnJava { - // A program must have a main method as an entry point + // In order to run a java program, it must have a main method as an entry point. public static void main (String[] args) { - // Use System.out.println to print lines + // Use System.out.println() to print lines. System.out.println("Hello World!"); System.out.println( "Integer: " + 10 + " Double: " + 3.14 + " Boolean: " + true); - // To print without a newline, use System.out.print + // To print without a newline, use System.out.print(). System.out.print("Hello "); System.out.print("World"); + // Use System.out.printf() for easy formatted printing. + System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 /////////////////////////////////////// - // Types & Variables + // Variables /////////////////////////////////////// - // Declare a variable using <type> <name> [ + /* + * Variable Declaration + */ + // Declare a variable using <type> <name> + int fooInt; + // Declare multiple variables of the same type <type> <name1>, <name2>, <name3> + int fooInt1, fooInt2, fooInt3; + + /* + * Variable Initialization + */ + + // Initialize a variable using <type> <name> = <val> + int fooInt = 1; + // Initialize multiple variables of same type with same value <type> <name1>, <name2>, <name3> = <val> + int fooInt1, fooInt2, fooInt3; + fooInt1 = fooInt2 = fooInt3 = 1; + + /* + * Variable types + */ // Byte - 8-bit signed two's complement integer // (-128 <= byte <= 127) byte fooByte = 100; @@ -68,14 +94,16 @@ public class LearnJava { // L is used to denote that this variable value is of type Long; // anything without is treated as integer by default. - // Note: Java has no unsigned types + // Note: Java has no unsigned types. // Float - Single-precision 32-bit IEEE 754 Floating Point + // 2^-149 <= float <= (2-2^-23) * 2^127 float fooFloat = 234.5f; - // f is used to denote that this variable value is of type float; + // f or F is used to denote that this variable value is of type float; // otherwise it is treated as double. // Double - Double-precision 64-bit IEEE 754 Floating Point + // 2^-1074 <= x <= (2-2^-52) * 2^1023 double fooDouble = 123.4; // Boolean - true & false @@ -85,8 +113,44 @@ public class LearnJava { // Char - A single 16-bit Unicode character char fooChar = 'A'; - // final variables can't be reassigned to another object + // final variables can't be reassigned to another object, final int HOURS_I_WORK_PER_WEEK = 9001; + // but they can be initialized later. + final double E; + E = 2.71828; + + + // BigInteger - Immutable arbitrary-precision integers + // + // BigInteger is a data type that allows programmers to manipulate + // integers longer than 64-bits. Integers are stored as an array of + // of bytes and are manipulated using functions built into BigInteger + // + // BigInteger can be initialized using an array of bytes or a string. + + BigInteger fooBigInteger = new BigInteger(fooByteArray); + + + // BigDecimal - Immutable, arbitrary-precision signed decimal number + // + // A BigDecimal takes two parts: an arbitrary precision integer + // unscaled value and a 32-bit integer scale + // + // BigDecimal allows the programmer complete control over decimal + // rounding. It is recommended to use BigDecimal with currency values + // and where exact decimal precision is required. + // + // BigDecimal can be initialized with an int, long, double or String + // or by initializing the unscaled value (BigInteger) and scale (int). + + BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); + + // Be wary of the constructor that takes a float or double as + // the inaccuracy of the float/double will be copied in BigDecimal. + // Prefer the String constructor when you need an exact value. + + BigDecimal tenCents = new BigDecimal("0.1"); + // Strings String fooString = "My String Is Here!"; @@ -100,17 +164,17 @@ public class LearnJava { System.out.println(bazString); // Arrays - //The array size must be decided upon instantiation - //The following formats work for declaring an array - //<datatype> [] <var name> = new <datatype>[<array size>]; - //<datatype> <var name>[] = new <datatype>[<array size>]; - int [] intArray = new int[10]; - String [] stringArray = new String[1]; - boolean boolArray [] = new boolean[100]; + // The array size must be decided upon instantiation + // The following formats work for declaring an array + // <datatype>[] <var name> = new <datatype>[<array size>]; + // <datatype> <var name>[] = new <datatype>[<array size>]; + int[] intArray = new int[10]; + String[] stringArray = new String[1]; + boolean boolArray[] = new boolean[100]; // Another way to declare & initialize an array - int [] y = {9000, 1000, 1337}; - String names [] = {"Bob", "John", "Fred", "Juan Pedro"}; + int[] y = {9000, 1000, 1337}; + String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; boolean bools[] = new boolean[] {true, false, false}; // Indexing an array - Accessing an element @@ -121,17 +185,21 @@ public class LearnJava { System.out.println("intArray @ 1: " + intArray[1]); // => 1 // Others to check out - // ArrayLists - Like arrays except more functionality is offered, - // and the size is mutable + // ArrayLists - Like arrays except more functionality is offered, and + // the size is mutable. // LinkedLists - Implementation of doubly-linked list. All of the - // operations perform as could be expected for - // a doubly-linked list. - // Maps - A set of objects that maps keys to values. A map cannot contain - // duplicate keys; each key can map to at most one value. - // HashMaps - This class uses a hashtable to implement the Map interface. - // This allows the execution time of basic operations, - // such as get and insert element, to remain constant even - // for large sets. + // operations perform as could be expected for a + // doubly-linked list. + // Maps - A set of objects that map keys to values. Map is + // an interface and therefore cannot be instantiated. + // The type of keys and values contained in a Map must + // be specified upon instantiation of the implementing + // class. Each key may map to only one corresponding value, + // and each key may appear only once (no duplicates). + // HashMaps - This class uses a hashtable to implement the Map + // interface. This allows the execution time of basic + // operations, such as get and insert element, to remain + // constant even for large sets. /////////////////////////////////////// // Operators @@ -144,7 +212,8 @@ public class LearnJava { System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 truncated down) + System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns an int) + System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 // Modulo System.out.println("11%3 = "+(11 % 3)); // => 2 @@ -157,15 +226,20 @@ public class LearnJava { System.out.println("2 <= 2? " + (2 <= 2)); // => true System.out.println("2 >= 2? " + (2 >= 2)); // => true + // Boolean operators + System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false + System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true + System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true + // Bitwise operators! /* - ~ Unary bitwise complement - << Signed left shift - >> Signed right shift - >>> Unsigned right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR + ~ Unary bitwise complement + << Signed left shift + >> Signed/Arithmetic right shift + >>> Unsigned/Logical right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR */ // Incrementations @@ -174,10 +248,10 @@ public class LearnJava { // The ++ and -- operators increment and decrement by 1 respectively. // If they are placed before the variable, they increment then return; // after the variable they return then increment. - System.out.println(i++); //i = 1, prints 0 (post-increment) - System.out.println(++i); //i = 2, prints 2 (pre-increment) - System.out.println(i--); //i = 1, prints 2 (post-decrement) - System.out.println(--i); //i = 0, prints 0 (pre-decrement) + System.out.println(i++); // i = 1, prints 0 (post-increment) + System.out.println(++i); // i = 2, prints 2 (pre-increment) + System.out.println(i--); // i = 1, prints 2 (post-decrement) + System.out.println(--i); // i = 0, prints 0 (pre-decrement) /////////////////////////////////////// // Control Structures @@ -186,7 +260,7 @@ public class LearnJava { // If statements are c-like int j = 10; - if (j == 10){ + if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); @@ -196,81 +270,104 @@ public class LearnJava { // While loop int fooWhile = 0; - while(fooWhile < 100) - { - //System.out.println(fooWhile); - //Increment the counter - //Iterated 100 times, fooWhile 0,1,2...99 + while(fooWhile < 100) { + System.out.println(fooWhile); + // Increment the counter + // Iterated 100 times, fooWhile 0,1,2...99 fooWhile++; } System.out.println("fooWhile Value: " + fooWhile); // Do While Loop int fooDoWhile = 0; - do - { - //System.out.println(fooDoWhile); - //Increment the counter - //Iterated 99 times, fooDoWhile 0->99 + do { + System.out.println(fooDoWhile); + // Increment the counter + // Iterated 99 times, fooDoWhile 0->99 fooDoWhile++; - }while(fooDoWhile < 100); + } while(fooDoWhile < 100); System.out.println("fooDoWhile Value: " + fooDoWhile); // For Loop - int fooFor; - //for loop structure => for(<start_statement>; <conditional>; <step>) - for(fooFor=0; fooFor<10; fooFor++){ - //System.out.println(fooFor); - //Iterated 10 times, fooFor 0->9 + // for loop structure => for(<start_statement>; <conditional>; <step>) + for (int fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); - + + // Nested For Loop Exit with Label + outer: + for (int i = 0; i < 10; i++) { + for (int j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // breaks out of outer loop instead of only the inner one + } + } + } + // For Each Loop - // An automatic iteration through an array or list of objects. - int[] fooList = {1,2,3,4,5,6,7,8,9}; - //for each loop structure => for(<object> : <array_object>) - //reads as: for each object in the array - //note: the object type must match the array. - - for( int bar : fooList ){ - //System.out.println(bar); + // The for loop is also able to iterate over arrays as well as objects + // that implement the Iterable interface. + int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; + // for each loop structure => for (<object> : <iterable>) + // reads as: for each element in the iterable + // note: the object type must match the element type of the iterable. + + for (int bar : fooList) { + System.out.println(bar); //Iterates 9 times and prints 1-9 on new lines } // Switch Case // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), - // the String class, and a few special classes that wrap - // primitive types: Character, Byte, Short, and Integer. + // It also works with enumerated types (discussed in Enum Types), the + // String class, and a few special classes that wrap primitive types: + // Character, Byte, Short, and Integer. int month = 3; String monthString; - switch (month){ - case 1: - monthString = "January"; + switch (month) { + case 1: monthString = "January"; break; - case 2: - monthString = "February"; + case 2: monthString = "February"; break; - case 3: - monthString = "March"; - break; - default: - monthString = "Some other month"; + case 3: monthString = "March"; break; + default: monthString = "Some other month"; + break; } System.out.println("Switch Case Result: " + monthString); + + // Starting in Java 7 and above, switching Strings works like this: + String myAnswer = "maybe"; + switch(myAnswer) { + case "yes": + System.out.println("You answered yes."); + break; + case "no": + System.out.println("You answered no."); + break; + case "maybe": + System.out.println("You answered maybe."); + break; + default: + System.out.println("You answered " + myAnswer); + break; + } // Conditional Shorthand // You can use the '?' operator for quick assignments or logic forks. - // Reads as "If (statement) is true, use <first value>, otherwise, use <second value>" + // Reads as "If (statement) is true, use <first value>, otherwise, use + // <second value>" int foo = 5; String bar = (foo < 10) ? "A" : "B"; System.out.println(bar); // Prints A, because the statement is true - /////////////////////////////////////// - // Converting Data Types And Typcasting - /////////////////////////////////////// + //////////////////////////////////////// + // Converting Data Types And Typecasting + //////////////////////////////////////// // Converting data @@ -286,9 +383,8 @@ public class LearnJava { // String // Typecasting - // You can also cast java objects, there's a lot of details and - // deals with some more intermediate concepts. - // Feel free to check it out here: + // You can also cast Java objects, there's a lot of details and deals + // with some more intermediate concepts. Feel free to check it out here: // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html @@ -310,17 +406,45 @@ public class LearnJava { // toString returns this Object's string representation. System.out.println("trek info: " + trek.toString()); + // Double Brace Initialization + // The Java Language has no syntax for how to create static Collections + // in an easy way. Usually you end up in the following way: + + private static final Set<String> COUNTRIES = new HashSet<String>(); + static { + validCodes.add("DENMARK"); + validCodes.add("SWEDEN"); + validCodes.add("FINLAND"); + } + + // But there's a nifty way to achieve the same thing in an + // easier way, by using something that is called Double Brace + // Initialization. + + private static final Set<String> COUNTRIES = new HashSet<String>() {{ + add("DENMARK"); + add("SWEDEN"); + add("FINLAND"); + }} + + // The first brace is creating a new AnonymousInnerClass and the + // second one declares an instance initializer block. This block + // is called when the anonymous inner class is created. + // This does not only work for Collections, it works for all + // non-final classes. + } // End main method } // End LearnJava class -// You can include other, non-public outer-level classes in a .java file +// You can include other, non-public outer-level classes in a .java file, +// but it is good practice. Instead split classes into separate files. // Class Declaration Syntax: -// <public/private/protected> class <class name>{ -// //data fields, constructors, functions all inside. -// //functions are called as methods in Java. +// <public/private/protected> class <class name> { +// // data fields, constructors, functions all inside. +// // functions are called as methods in Java. // } class Bicycle { @@ -331,9 +455,22 @@ class Bicycle { protected int gear; // Protected: Accessible from the class and subclasses String name; // default: Only accessible from within this package + static String className; // Static class variable + + // Static block + // Java has no implementation of static constructors, but + // has a static block that can be used to initialize class variables + // (static variables). + // This block will be called when the class is loaded. + static { + className = "Bicycle"; + } + // Constructors are a way of creating classes // This is a constructor public Bicycle() { + // You can also call another constructor: + // this(1, 50, 5, "Bontrager"); gear = 1; cadence = 50; speed = 5; @@ -341,20 +478,21 @@ class Bicycle { } // This is a constructor that takes arguments - public Bicycle(int startCadence, int startSpeed, int startGear, String name) { + public Bicycle(int startCadence, int startSpeed, int startGear, + String name) { this.gear = startGear; this.cadence = startCadence; this.speed = startSpeed; this.name = name; } - // Function Syntax: + // Method Syntax: // <public/private/protected> <return type> <function name>(<args>) // Java classes often implement getters and setters for their fields // Method declaration syntax: - // <scope> <return type> <method name>(<args>) + // <access modifier> <return type> <method name>(<args>) public int getCadence() { return cadence; } @@ -385,12 +523,10 @@ class Bicycle { } //Method to display the attribute values of this Object. - @Override + @Override // Inherited from the Object class. public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; } } // end class Bicycle @@ -404,56 +540,228 @@ class PennyFarthing extends Bicycle { super(startCadence, startSpeed, 0, "PennyFarthing"); } - // You should mark a method you're overriding with an @annotation - // To learn more about what annotations are and their purpose - // check this out: http://docs.oracle.com/javase/tutorial/java/annotations/ + // You should mark a method you're overriding with an @annotation. + // To learn more about what annotations are and their purpose check this + // out: http://docs.oracle.com/javase/tutorial/java/annotations/ @Override public void setGear(int gear) { gear = 0; } - } -//Interfaces -//Interface declaration syntax -//<access-level> interface <interface-name> extends <super-interfaces> { -// //Constants -// //Method declarations -//} +// Interfaces +// Interface declaration syntax +// <access-level> interface <interface-name> extends <super-interfaces> { +// // Constants +// // Method declarations +// } -//Example - Food: +// Example - Food: public interface Edible { - public void eat(); //Any class that implements this interface, must implement this method + public void eat(); // Any class that implements this interface, must + // implement this method. } public interface Digestible { - public void digest(); + public void digest(); } -//We can now create a class that implements both of these interfaces +// We can now create a class that implements both of these interfaces. public class Fruit implements Edible, Digestible { - public void eat() { - //... - } + + @Override + public void eat() { + // ... + } - public void digest() { - //... - } + @Override + public void digest() { + // ... + } } -//In java, you can extend only one class, but you can implement many interfaces. -//For example: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { - public void InterfaceOneMethod() { +// In Java, you can extend only one class, but you can implement many +// interfaces. For example: +public class ExampleClass extends ExampleClassParent implements InterfaceOne, + InterfaceTwo { - } + @Override + public void InterfaceOneMethod() { + } - public void InterfaceTwoMethod() { + @Override + public void InterfaceTwoMethod() { + } - } } +// Abstract Classes + +// Abstract Class declaration syntax +// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> { +// // Constants and variables +// // Method declarations +// } + +// Marking a class as abstract means that it contains abstract methods that must +// be defined in a child class. Similar to interfaces, abstract classes cannot +// be instantiated, but instead must be extended and the abstract methods +// defined. Different from interfaces, abstract classes can contain a mixture of +// concrete and abstract methods. Methods in an interface cannot have a body, +// unless the method is static, and variables are final by default, unlike an +// abstract class. Also abstract classes CAN have the "main" method. + +public abstract class Animal +{ + public abstract void makeSound(); + + // Method can have a body + public void eat() + { + System.out.println("I am an animal and I am Eating."); + // Note: We can access private variable here. + age = 30; + } + + // No need to initialize, however in an interface + // a variable is implicitly final and hence has + // to be initialized. + protected int age; + + public void printAge() + { + System.out.println(age); + } + + // Abstract classes can have main function. + public static void main(String[] args) + { + System.out.println("I am abstract"); + } +} + +class Dog extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Bark"); + // age = 30; ==> ERROR! age is private to Animal + } + + // NOTE: You will get an error if you used the + // @Override annotation here, since java doesn't allow + // overriding of static methods. + // What is happening here is called METHOD HIDING. + // Check out this awesome SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Dog pluto = new Dog(); + pluto.makeSound(); + pluto.eat(); + pluto.printAge(); + } +} + +// Final Classes + +// Final Class declaration syntax +// <access-level> final <final-class-name> { +// // Constants and variables +// // Method declarations +// } + +// Final classes are classes that cannot be inherited from and are therefore a +// final child. In a way, final classes are the opposite of abstract classes +// because abstract classes must be extended, but final classes cannot be +// extended. +public final class SaberToothedCat extends Animal +{ + // Note still have to override the abstract methods in the + // abstract class. + @Override + public void makeSound() + { + System.out.println("Roar"); + } +} + +// Final Methods +public abstract class Mammal() +{ + // Final Method Syntax: + // <access modifier> final <return type> <function name>(<args>) + + // Final methods, like, final classes cannot be overridden by a child class, + // and are therefore the final implementation of the method. + public final boolean isWarmBlooded() + { + return true; + } +} + + +// Enum Type +// +// An enum type is a special data type that enables for a variable to be a set +// of predefined constants. The variable must be equal to one of the values that +// have been predefined for it. Because they are constants, the names of an enum +// type's fields are in uppercase letters. In the Java programming language, you +// define an enum type by using the enum keyword. For example, you would specify +// a days-of-the-week enum type as: + +public enum Day { + SUNDAY, MONDAY, TUESDAY, WEDNESDAY, + THURSDAY, FRIDAY, SATURDAY +} + +// We can use our enum Day like that: + +public class EnumTest { + + // Variable Enum + Day day; + + public EnumTest(Day day) { + this.day = day; + } + + public void tellItLikeItIs() { + switch (day) { + case MONDAY: + System.out.println("Mondays are bad."); + break; + + case FRIDAY: + System.out.println("Fridays are better."); + break; + + case SATURDAY: + case SUNDAY: + System.out.println("Weekends are best."); + break; + + default: + System.out.println("Midweek days are so-so."); + break; + } + } + + public static void main(String[] args) { + EnumTest firstDay = new EnumTest(Day.MONDAY); + firstDay.tellItLikeItIs(); // => Mondays are bad. + EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); + thirdDay.tellItLikeItIs(); // => Midweek days are so-so. + } +} + +// Enum types are much more powerful than we show above. +// The enum body can include methods and other fields. +// You can se more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + ``` ## Further Reading @@ -477,7 +785,7 @@ The links provided here below are just to get an understanding of the topic, fee * [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) **Online Practice and Tutorials** @@ -490,8 +798,8 @@ The links provided here below are just to get an understanding of the topic, fee * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) +* [Thinking in Java](http://www.mindview.net/Books/TIJ/) + * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) * [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300) - - diff --git a/javascript.html.markdown b/javascript.html.markdown index aabd5e43..98261334 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -16,13 +16,14 @@ JavaScript isn't just limited to web browsers, though: Node.js, a project that provides a standalone runtime for Google Chrome's V8 JavaScript engine, is becoming more and more popular. -Feedback would be highly appreciated! You can reach me at -[@adambrenecki](https://twitter.com/adambrenecki), or -[adam@brenecki.id.au](mailto:adam@brenecki.id.au). +JavaScript has a C-like syntax, so if you've used languages like C or Java, +a lot of the basic syntax will already be familiar. Despite this, and despite +the similarity in name, JavaScript's object model is significantly different to +Java's. ```js -// Comments are like C. Single-line comments start with two slashes, -/* and multiline comments start with slash-star +// Single-line comments start with two slashes. +/* Multiline comments start with slash-star, and end with star-slash */ // Statements can be terminated by ; @@ -40,7 +41,7 @@ doStuff() // JavaScript has one number type (which is a 64-bit IEEE 754 double). // Doubles have a 52-bit mantissa, which is enough to store integers -// up to about 9✕10¹⁵ precisely. +// up to about 9✕10¹⁵ precisely. 3; // = 3 1.5; // = 1.5 @@ -54,6 +55,11 @@ doStuff() // Including uneven division. 5 / 2; // = 2.5 +// And modulo division. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + // Bitwise operations also work; when you perform a bitwise operation your float // is converted to a signed int *up to* 32 bits. 1 << 2; // = 4 @@ -64,7 +70,7 @@ doStuff() // There are three special not-a-real-number values: Infinity; // result of e.g. 1/0 -Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0 +NaN; // result of e.g. 0/0, stands for 'Not a Number' // There's also a boolean type. true; @@ -95,6 +101,10 @@ false; // Strings are concatenated with + "Hello " + "world!"; // = "Hello world!" +// ... which works with more than just strings +"1, 2, " + 3; // = "1, 2, 3" +"Hello " + ["world", "!"] // = "Hello world,!" + // and are compared with < and > "a" < "b"; // = true @@ -104,25 +114,25 @@ null == undefined; // = true // ...unless you use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...which can result in some weird behaviour... 13 + !0; // 14 "13" + !0; // '13true' -// You can access characters in a string with charAt +// You can access characters in a string with `charAt` "This is a string".charAt(0); // = 'T' -// ...or use substring to get larger pieces +// ...or use `substring` to get larger pieces. "Hello world".substring(0, 5); // = "Hello" -// length is a property, so don't use () +// `length` is a property, so don't use (). "Hello".length; // = 5 -// There's also null and undefined -null; // used to indicate a deliberate non-value +// There's also `null` and `undefined`. +null; // used to indicate a deliberate non-value undefined; // used to indicate a value is not currently present (although - // undefined is actually a value itself) + // `undefined` is actually a value itself) // false, null, undefined, NaN, 0 and "" are falsy; everything else is truthy. // Note that 0 is falsy and "0" is truthy, even though 0 == "0". @@ -130,11 +140,12 @@ undefined; // used to indicate a value is not currently present (although /////////////////////////////////// // 2. Variables, Arrays and Objects -// Variables are declared with the var keyword. JavaScript is dynamically typed, -// so you don't need to specify type. Assignment uses a single = character. +// Variables are declared with the `var` keyword. JavaScript is dynamically +// typed, so you don't need to specify type. Assignment uses a single `=` +// character. var someVar = 5; -// if you leave the var keyword off, you won't get an error... +// If you leave the var keyword off, you won't get an error... someOtherVar = 10; // ...but your variable will be created in the global scope, not in the scope @@ -143,6 +154,10 @@ someOtherVar = 10; // Variables declared without being assigned to are set to undefined. var someThirdVar; // = undefined +// If you want to declare a couple of variables, then you could use a comma +// separator +var someFourthVar = 2, someFifthVar = 4; + // There's shorthand for performing math operations on variables: someVar += 5; // equivalent to someVar = someVar + 5; someVar is 10 now someVar *= 10; // now someVar is 100 @@ -165,7 +180,7 @@ myArray.length; // = 4 // Add/Modify at specific index myArray[3] = "Hello"; -// JavaScript's objects are equivalent to 'dictionaries' or 'maps' in other +// JavaScript's objects are equivalent to "dictionaries" or "maps" in other // languages: an unordered collection of key-value pairs. var myObj = {key1: "Hello", key2: "World"}; @@ -188,9 +203,7 @@ myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. Logic and Control Structures -// The syntax for this section is almost identical to Java's. - -// The if structure works as you'd expect. +// The `if` structure works as you'd expect. var count = 1; if (count == 3){ // evaluated if count is 3 @@ -200,23 +213,44 @@ if (count == 3){ // evaluated if it's not either 3 or 4 } -// As does while. +// As does `while`. while (true){ // An infinite loop! } // Do-while loops are like while loops, except they always run at least once. -var input +var input; do { input = getInput(); } while (!isValid(input)) -// the for loop is the same as C and Java: +// The `for` loop is the same as C and Java: // initialisation; continue condition; iteration. for (var i = 0; i < 5; i++){ // will run 5 times } +// The for/in statement iterates over every property across the entire prototype chain. +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +// To only consider properties attached to the object itself +// and not its prototypes, use the `hasOwnProperty()` check. +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +// For/in should not be used to iterate over an Array where the index order +// is important, as there is no guarantee that for/in will return the indexes +// in any particular order. + // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ house.contains = "bear"; @@ -229,9 +263,9 @@ if (colour == "red" || colour == "blue"){ var name = otherName || "default"; -// switch statement checks for equality with === -// use 'break' after each case -// or the cases after the correct one will be executed too. +// The `switch` statement checks for equality with `===`. +// Use 'break' after each case +// or the cases after the correct one will be executed too. grade = 'B'; switch (grade) { case 'A': @@ -252,21 +286,18 @@ switch (grade) { /////////////////////////////////// // 4. Functions, Scope and Closures -// JavaScript functions are declared with the function keyword. +// JavaScript functions are declared with the `function` keyword. function myFunction(thing){ return thing.toUpperCase(); } myFunction("foo"); // = "FOO" // Note that the value to be returned must start on the same line as the -// 'return' keyword, otherwise you'll always return 'undefined' due to +// `return` keyword, otherwise you'll always return `undefined` due to // automatic semicolon insertion. Watch out for this when using Allman style. -function myFunction() -{ +function myFunction(){ return // <- semicolon automatically inserted here - { - thisIsAn: 'object literal' - } + {thisIsAn: 'object literal'} } myFunction(); // = undefined @@ -280,6 +311,12 @@ setTimeout(myFunction, 5000); // Note: setTimeout isn't part of the JS language, but is provided by browsers // and Node.js. +// Another function provided by browsers is setInterval +function myFunction(){ + // this code will be called every 5 seconds +} +setInterval(myFunction, 5000); + // Function objects don't even have to be declared with a name - you can write // an anonymous function definition directly into the arguments of another. setTimeout(function(){ @@ -298,8 +335,8 @@ i; // = 5 - not undefined as you'd expect in a block-scoped language // scope. (function(){ var temporary = 5; - // We can access the global scope by assiging to the 'global object', which - // in a web browser is always 'window'. The global object may have a + // We can access the global scope by assigning to the "global object", which + // in a web browser is always `window`. The global object may have a // different name in non-browser environments such as Node.js. window.permanent = 10; })(); @@ -312,7 +349,7 @@ permanent; // = 10 function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; // Inner functions are put in the local scope by default, as if they were - // declared with 'var'. + // declared with `var`. function inner(){ alert(prompt); } @@ -320,7 +357,7 @@ function sayHelloInFiveSeconds(name){ // setTimeout is asynchronous, so the sayHelloInFiveSeconds function will // exit immediately, and setTimeout will call inner afterwards. However, // because inner is "closed over" sayHelloInFiveSeconds, inner still has - // access to the 'prompt' variable when it is finally called. + // access to the `prompt` variable when it is finally called. } sayHelloInFiveSeconds("Adam"); // will open a popup with "Hello, Adam!" in 5s @@ -336,7 +373,7 @@ var myObj = { myObj.myFunc(); // = "Hello world!" // When functions attached to an object are called, they can access the object -// they're attached to using the this keyword. +// they're attached to using the `this` keyword. myObj = { myString: "Hello world!", myFunc: function(){ @@ -352,7 +389,7 @@ var myFunc = myObj.myFunc; myFunc(); // = undefined // Inversely, a function can be assigned to the object and gain access to it -// through this, even if it wasn't attached when it was defined. +// through `this`, even if it wasn't attached when it was defined. var myOtherFunc = function(){ return this.myString.toUpperCase(); } @@ -360,38 +397,39 @@ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" // We can also specify a context for a function to execute in when we invoke it -// using 'call' or 'apply'. +// using `call` or `apply`. var anotherFunc = function(s){ return this.myString + s; } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// The 'apply' function is nearly identical, but takes an array for an argument list. +// The `apply` function is nearly identical, but takes an array for an argument +// list. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -// This is useful when working with a function that accepts a sequence of arguments -// and you want to pass an array. +// This is useful when working with a function that accepts a sequence of +// arguments and you want to pass an array. Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// But, 'call' and 'apply' are only temporary. When we want it to stick, we can use -// bind. +// But, `call` and `apply` are only temporary. When we want it to stick, we can +// use `bind`. var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -// Bind can also be used to partially apply (curry) a function. +// `bind` can also be used to partially apply (curry) a function. var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// When you call a function with the new keyword, a new object is created, and -// made available to the function via the this keyword. Functions designed to be +// When you call a function with the `new` keyword, a new object is created, and +// made available to the function via the `this` keyword. Functions designed to be // called like that are called constructors. var MyConstructor = function(){ @@ -405,7 +443,7 @@ myNewObj.myNumber; // = 5 // look at its prototype. // Some JS implementations let you access an object's prototype on the magic -// property __proto__. While this is useful for explaining prototypes it's not +// property `__proto__`. While this is useful for explaining prototypes it's not // part of the standard; we'll get to standard ways of using prototypes later. var myObj = { myString: "Hello world!" @@ -436,7 +474,7 @@ myObj.myBoolean; // = true myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// We mentioned that __proto__ was non-standard, and there's no standard way to +// We mentioned that `__proto__` was non-standard, and there's no standard way to // change the prototype of an existing object. However, there are two ways to // create a new object with a given prototype. @@ -473,8 +511,9 @@ myNumber === myNumberObj; // = false if (0){ // This code won't execute, because 0 is falsy. } -if (Number(0)){ - // This code *will* execute, because Number(0) is truthy. +if (new Number(0)){ + // This code will execute, because wrapped numbers are objects, and objects + // are always truthy. } // However, the wrapper objects and the regular builtins share a prototype, so @@ -503,28 +542,42 @@ if (Object.create === undefined){ // don't overwrite it if it exists ## Further Reading -The [Mozilla Developer -Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides -excellent documentation for JavaScript as it's used in browsers. Plus, it's a -wiki, so as you learn more you can help others out by sharing your own -knowledge. +The [Mozilla Developer Network][1] provides excellent documentation for +JavaScript as it's used in browsers. Plus, it's a wiki, so as you learn more you +can help others out by sharing your own knowledge. + +MDN's [A re-introduction to JavaScript][2] covers much of the concepts covered +here in more detail. This guide has quite deliberately only covered the +JavaScript language itself; if you want to learn more about how to use +JavaScript in web pages, start by learning about the [Document Object Model][3]. + +[Learn Javascript by Example and with Challenges][4] is a variant of this +reference with built-in challenges. + +[JavaScript Garden][5] is an in-depth guide of all the counter-intuitive parts +of the language. + +[JavaScript: The Definitive Guide][6] is a classic guide and reference book. + +[Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal + +[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great derivative of Eloquent Javascript with extra explanations and clarifications for some of the more complicated examples. -MDN's [A re-introduction to -JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -covers much of the concepts covered here in more detail. This guide has quite -deliberately only covered the JavaScript language itself; if you want to learn -more about how to use JavaScript in web pages, start by learning about the -[Document Object -Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. -[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth -guide of all the counter-intuitive parts of the language. +In addition to direct contributors to this article, some content is adapted from +Louie Dinh's Python tutorial on this site, and the [JS Tutorial][7] on the +Mozilla Developer Network. -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. -In addition to direct contributors to this article, some content is adapted -from Louie Dinh's Python tutorial on this site, and the [JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -on the Mozilla Developer Network. +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version +[10]: http://jstherightway.org/ diff --git a/json.html.markdown b/json.html.markdown index f5287138..cde7bc40 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -4,19 +4,36 @@ filename: learnjson.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] --- -As JSON is an extremely simple data-interchange format, this is most likely going -to be the simplest Learn X in Y Minutes ever. +As JSON is an extremely simple data-interchange format, this is most likely going to be the simplest Learn X in Y Minutes ever. -JSON in its purest form has no actual comments, but most parsers will accept -C-style (//, /\* \*/) comments. For the purposes of this, however, everything is -going to be 100% valid JSON. Luckily, it kind of speaks for itself. +JSON in its purest form has no actual comments, but most parsers will accept C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma (i.e. a comma after the last element of an array or the after the last property of an object), but they should be avoided for better compatibility. + +For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself. + +A JSON value must be a number, a string, an array, an object, or one of the following 3 literal names: true, false, null. + +Supporting browsers are: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, and Safari 4.0+. + +File extension for JSON files is ".json" and the MIME type for JSON text is "application/json". + +Many programming languages have support for serializing (encoding) and unserializing (decoding) JSON data into native data structures. Javascript has implicit support for manipulating JSON text as data. + +More information can be found at http://www.json.org/ + +JSON is built on two structures: +* A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. +* An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence. + +An object with various name/value pairs. ```json { "key": "value", - + "keys": "must always be enclosed in double quotes", "numbers": 0, "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", @@ -46,13 +63,23 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself. [0, 0, 0, 1] ] ], - + "alternative style": { "comment": "check this out!" - , "comma position": "doesn't matter - as long as its before the value, then its valid" + , "comma position": "doesn't matter - as long as it's before the next key, then it's valid" , "another comment": "how nice" - }, - - "that was short": "And, you're done. You now know everything JSON has to offer." + } } ``` + +A single array of values by itself is also valid JSON. + +```json +[1, 2, 3, "text", true] +``` + +Objects can be a part of the array as well. + +```json +[{"name": "Bob", "age": 25}, {"name": "Jane", "age": 29}, {"name": "Jack", "age": 31}] +``` diff --git a/julia.html.markdown b/julia.html.markdown index 3a52018c..ef3ea244 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -2,19 +2,20 @@ language: Julia contributors: - ["Leah Hanson", "http://leahhanson.us"] + - ["Pranit Bauva", "http://github.com/pranitbauva1997"] filename: learnjulia.jl --- Julia is a new homoiconic functional language focused on technical computing. While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python. -This is based on the current development version of Julia, as of October 18th, 2013. +This is based on Julia 0.3. ```ruby # Single line comments start with a hash (pound) symbol. #= Multiline comments can be written - by putting '#=' before the text and '=#' + by putting '#=' before the text and '=#' after the text. They can also be nested. =# @@ -81,17 +82,20 @@ false # Strings are created with " "This is a string." +# Julia has several types of strings, including ASCIIString and UTF8String. +# More on this in the Types section. + # Character literals are written with ' 'a' -# A string can be indexed like an array of characters +# Some strings can be indexed like an array of characters "This is a string"[1] # => 'T' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). # $ can be used for string interpolation: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# You can put any Julia expression inside the parenthesis. +# You can put any Julia expression inside the parentheses. # Another way to format strings is the printf macro. @printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 @@ -99,6 +103,11 @@ false # Printing is easy println("I'm Julia. Nice to meet you!") +# String can be compared lexicographically +"good" > "bye" # => true +"good" == "good" # => true +"1 + 2 = 3" == "1 + 2 = $(1+2)" # => true + #################################################### ## 2. Variables and Collections #################################################### @@ -114,11 +123,11 @@ catch e println(e) end -# Variable names start with a letter. +# Variable names start with a letter or underscore. # After that, you can use letters, digits, underscores, and exclamation points. SomeOtherVar123! = 6 # => 6 -# You can also use unicode characters +# You can also use certain unicode characters ☃ = 8 # => 8 # These are especially handy for mathematical notation 2 * π # => 6.283185307179586 @@ -190,7 +199,7 @@ end # inside the julia folder to find these files. # You can initialize arrays from ranges -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5] # You can look at ranges with slice syntax. a[1:3] # => [1, 2, 3] @@ -264,7 +273,7 @@ in(("two", 3), filled_dict) # => false haskey(filled_dict, "one") # => true haskey(filled_dict, 1) # => false -# Trying to look up a non-existant key will raise an error +# Trying to look up a non-existent key will raise an error try filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 catch e @@ -314,7 +323,7 @@ end # For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. +# Iterable types include Range, Array, Set, Dict, and AbstractString. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings @@ -387,6 +396,14 @@ end add(5, 6) # => 11 after printing out "x is 5 and y is 6" +# Compact assignment of functions +f_add(x, y) = x + y # => "f (generic function with 1 method)" +f_add(3, 4) # => 7 + +# Function can also return multiple values as tuple +f(x, y) = x + y, x - y +f(3, 4) # => (7, -1) + # You can define functions that take a variable number of # positional arguments function varargs(args...) @@ -537,6 +554,17 @@ subtypes(Number) # => 6-element Array{Any,1}: # Real subtypes(Cat) # => 0-element Array{Any,1} +# AbstractString, as the name implies, is also an abstract type +subtypes(AbstractString) # 8-element Array{Any,1}: + # Base.SubstitutionString{T<:AbstractString} + # DirectIndexString + # RepString + # RevString{T<:AbstractString} + # RopeString + # SubString{T<:AbstractString} + # UTF16String + # UTF8String + # Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed @@ -546,17 +574,21 @@ super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any # All of these type, except for Int64, are abstract. +typeof("fire") # => ASCIIString +super(ASCIIString) # => DirectIndexString +super(DirectIndexString) # => AbstractString +# Likewise here with ASCIIString # <: is the subtyping operator type Lion <: Cat # Lion is a subtype of Cat mane_color - roar::String + roar::AbstractString end # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type -Lion(roar::String) = Lion("green",roar) +Lion(roar::AbstractString) = Lion("green",roar) # This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther is also a subtype of Cat @@ -670,7 +702,7 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 # What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) +code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 # Prologue @@ -703,10 +735,10 @@ code_native(square_area, (Float64,)) # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) # pop RBP # ret - # + # # Note that julia will use floating point instructions if any of the -# arguements are floats. -# Let's calculate the area of a circle +# arguments are floats. +# Let's calculate the area of a circle circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 @@ -737,7 +769,7 @@ code_native(circle_area, (Float64,)) # vmulsd XMM0, XMM1, XMM0 # pop RBP # ret - # + # ``` ## Further Reading diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 4ca3bb5c..9561e80c 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -387,9 +387,6 @@ myNumber === myNumberObj // = false if (0){ // 0은 거짓이라서 이 코드는 실행되지 않습니다. } -if (Number(0)){ - // Number(0)은 참이라서 이 코드는 *실행됩니다*. -} // 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에 // 가령 문자열에 실제로 기능을 추가할 수 있습니다. diff --git a/latex.html.markdown b/latex.html.markdown new file mode 100644 index 00000000..31231a70 --- /dev/null +++ b/latex.html.markdown @@ -0,0 +1,237 @@ +--- +language: latex +contributors: + - ["Chaitanya Krishna Ande", "http://icymist.github.io"] + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Sricharan Chiruvolu", "http://sricharan.xyz"] +filename: learn-latex.tex +--- + +```tex +% All comment lines start with % +% There are no multi-line comments + +% LaTeX is NOT a "What You See Is What You Get" word processing software like +% MS Word, or OpenOffice Writer + +% Every LaTeX command starts with a backslash (\) + +% LaTeX documents start with a defining the type of document it's compiling +% Other document types include book, report, presentations, etc. +% The options for the document appear in the [] brackets. In this case +% it specifies we want to use 12pt font. +\documentclass[12pt]{article} + +% Next we define the packages the document uses. +% If you want to include graphics, colored text, or +% source code from another language file into your document, +% you need to enhance the capabilities of LaTeX. This is done by adding packages. +% I'm going to include the float and caption packages for figures. +\usepackage{caption} +\usepackage{float} + +% We can define some other document properties too! +\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} +\date{\today} +\title{Learn LaTeX in Y Minutes!} + +% Now we're ready to begin the document +% Everything before this line is called "The Preamble" +\begin{document} +% if we set the author, date, title fields, we can have LaTeX +% create a title page for us. +\maketitle + +% Most research papers have abstract, you can use the predefined commands for this. +% This should appear in its logical order, therefore, after the top matter, +% but before the main sections of the body. +% This command is available in the document classes article and report. +\begin{abstract} + LaTeX documentation written as LaTeX! How novel and totally not my idea! +\end{abstract} + +% Section commands are intuitive. +% All the titles of the sections are added automatically to the table of contents. +\section{Introduction} +Hello, my name is Colton and together we're going to explore LaTeX! + +\section{Another section} +This is the text for another section. I think it needs a subsection. + +\subsection{This is a subsection} % Subsections are also intuitive. +I think we need another one + +\subsubsection{Pythagoras} +Much better now. +\label{subsec:pythagoras} + +% By using the asterisk we can suppress LaTeX's inbuilt numbering. +% This works for other LaTeX commands as well. +\section*{This is an unnumbered section} +However not all sections have to be numbered! + +\section{Some Text notes} +LaTeX is generally pretty good about placing text where it should go. If +a line \\ needs \\ to \\ break \\ you add \textbackslash\textbackslash to +the source code. \\ + +\section{Lists} +Lists are one of the easiest things to create in LaTeX! I need to go shopping +tomorrow, so let's make a grocery list. +\begin{enumerate} % This creates an "enumerate" environment. + % \item tells the enumerate to increment + \item Salad. + \item 27 watermelon. + \item A single jackrabbit. + % we can even override the item number by using [] + \item[how many?] Medium sized squirt guns. + + Not a list item, but still part of the enumerate. + +\end{enumerate} % All environments must have an end. + +\section{Math} + +One of the primary uses for LaTeX is to produce academic articles or +technical papers. Usually in the realm of math and science. As such, +we need to be able to add special symbols to our paper! \\ + +Math has many symbols, far beyond what you can find on a keyboard; +Set and relation symbols, arrows, operators, and Greek letters to name a few.\\ + +Sets and relations play a vital role in many mathematical research papers. +Here's how you state all y that belong to X, $\forall$ x $\in$ X. \\ +% Notice how I needed to add $ signs before and after the symbols. This is +% because when writing, we are in text-mode. +% However, the math symbols only exist in math-mode. +% We can enter math-mode from text mode with the $ signs. +% The opposite also holds true. Variable can also be rendered in math-mode. +% We can also enter math mode with \[\] + +\[a^2 + b^2 = c^2 \] + +My favorite Greek letter is $\xi$. I also like $\beta$, $\gamma$ and $\sigma$. +I haven't found a Greek letter that yet that LaTeX doesn't know about! + +Operators are essential parts of a mathematical document: +trigonometric functions ($\sin$, $\cos$, $\tan$), +logarithms and exponentials ($\log$, $\exp$), +limits ($\lim$), etc. +have per-defined LaTeX commands. +Let's write an equation to see how it's done: \\ + +$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ + +Fractions(Numerator-denominators) can be written in these forms: + +% 10 / 7 +$^{10}/_{7}$ + +% Relatively complex fractions can be written as +% \frac{numerator}{denominator} +$\frac{n!}{k!(n - k)!}$ \\ + +We can also insert equations in an "equation environment". + +% Display math with the equation 'environment' +\begin{equation} % enters math-mode + c^2 = a^2 + b^2. + \label{eq:pythagoras} % for referencing +\end{equation} % all \begin statements must have an end statement + +We can then reference our new equation! +Eqn.~\ref{eq:pythagoras} is also known as the Pythagoras Theorem which is also +the subject of Sec.~\ref{subsec:pythagoras}. A lot of things can be labeled: +figures, equations, sections, etc. + +Summations and Integrals are written with sum and int commands: + +% Some LaTeX compilers will complain if there are blank lines +% In an equation environment. +\begin{equation} + \sum_{i=0}^{5} f_{i} +\end{equation} +\begin{equation} + \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x +\end{equation} + +\section{Figures} + +Let's insert a Figure. Figure placement can get a little tricky. +I definitely have to lookup the placement options each time. + +\begin{figure}[H] % H here denoted the placement option. + \centering % centers the figure on the page + % Inserts a figure scaled to 0.8 the width of the page. + %\includegraphics[width=0.8\linewidth]{right-triangle.png} + % Commented out for compilation purposes. Please use your imagination. + \caption{Right triangle with sides $a$, $b$, $c$} + \label{fig:right-triangle} +\end{figure} + +\subsection{Table} +We can also insert Tables in the same way as figures. + +\begin{table}[H] + \caption{Caption for the Table.} + % the {} arguments below describe how each row of the table is drawn. + % Again, I have to look these up. Each. And. Every. Time. + \begin{tabular}{c|cc} + Number & Last Name & First Name \\ % Column rows are separated by $ + \hline % a horizontal line + 1 & Biggus & Dickus \\ + 2 & Monty & Python + \end{tabular} +\end{table} + +% \section{Hyperlinks} % Coming soon + +\section{Getting LaTeX to not compile something (i.e. Source Code)} +Let's say we want to include some code into our LaTeX document, +we would then need LaTeX to not try and interpret that text and +instead just print it to the document. We do this we a verbatim +environment. + +% There are other packages that exist (i.e. minty, lstlisting, etc.) +% but verbatim is the bare-bones basic one. +\begin{verbatim} + print("Hello World!") + a%b; % look! We can use % signs in verbatim. + random = 4; #decided by fair random dice roll +\end{verbatim} + +\section{Compiling} + +By now you're probably wondering how to compile this fabulous document +and look at the glorious glory that is a LaTeX pdf. +(yes, this document actually does compiles). \\ +Getting to the final document using LaTeX consists of the following steps: + \begin{enumerate} + \item Write the document in plain text (the "source code"). + \item Compile source code to produce a pdf. + The compilation step looks something like this (in Linux): \\ + \begin{verbatim} + $pdflatex learn-latex.tex learn-latex.pdf + \end{verbatim} + \end{enumerate} + +A number of LaTeX editors combine both Step 1 and Step 2 in the same piece of +software. So, you get to see Step 1, but not Step 2 completely. +Step 2 is still happening behind the scenes. + +You write all your formatting information in plain text in Step 1. +The compilation part in Step 2 takes care of producing the document in the +format you defined in Step 1. + +\section{End} + +That's all for now! + +% end the document +\end{document} +``` + +## More on LaTeX + +* The amazing LaTeX wikibook: [https://en.wikibooks.org/wiki/LaTeX](https://en.wikibooks.org/wiki/LaTeX) +* An actual tutorial: [http://www.latex-tutorial.com/](http://www.latex-tutorial.com/) diff --git a/livescript.html.markdown b/livescript.html.markdown index 429b91cb..9235f5ce 100644 --- a/livescript.html.markdown +++ b/livescript.html.markdown @@ -166,7 +166,7 @@ not false # => true ######################################################################## ## 3. Functions -######################################################################## +######################################################################## # Since LiveScript is functional, you'd expect functions to get a nice # treatment. In LiveScript it's even more apparent that functions are @@ -219,8 +219,8 @@ identity 1 # => 1 # Operators are not functions in LiveScript, but you can easily turn # them into one! Enter the operator sectioning: -divide-by-2 = (/ 2) -[2, 4, 8, 16].map(divide-by-2) .reduce (+) +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two) .reduce (+) # Not only of function application lives LiveScript, as in any good @@ -229,7 +229,7 @@ double-minus-one = (- 1) . (* 2) # Other than the usual `f . g` mathematical formulae, you get the `>>` # and `<<` operators, that describe how the flow of values through the -# functions. +# functions. double-minus-one = (* 2) >> (- 1) double-minus-one = (- 1) << (* 2) @@ -248,8 +248,8 @@ reduce = (f, xs, initial) --> xs.reduce f, initial # The underscore is also used in regular partial application, which you # can use for any function: div = (left, right) -> left / right -div-by-2 = div _, 2 -div-by-2 4 # => 2 +div-by-two = div _, 2 +div-by-two 4 # => 2 # Last, but not least, LiveScript has back-calls, which might help @@ -344,7 +344,7 @@ kitten.hug! # => "*Mei (a cat) is hugged*" ## Further reading There's just so much more to LiveScript, but this should be enough to -get you started writing little functional things in it. The +get you started writing little functional things in it. The [official website](http://livescript.net/) has a lot of information on the language, and a nice online compiler for you to try stuff out! diff --git a/lua.html.markdown b/lua.html.markdown index 0809215f..3d95c146 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -190,7 +190,7 @@ end -------------------------------------------------------------------------------- -- A table can have a metatable that gives the table operator-overloadish --- behavior. Later we'll see how metatables support js-prototypey behavior. +-- behavior. Later we'll see how metatables support js-prototypey behaviour. f1 = {a = 1, b = 2} -- Represents the fraction a/b. f2 = {a = 2, b = 3} diff --git a/make.html.markdown b/make.html.markdown new file mode 100644 index 00000000..e8cfd2b5 --- /dev/null +++ b/make.html.markdown @@ -0,0 +1,241 @@ +---
+language: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+filename: Makefile
+---
+
+A Makefile defines a graph of rules for creating a target (or targets).
+Its purpose is to do the minimum amount of work needed to update a
+target to the most recent version of the source. Famously written over a
+weekend by Stuart Feldman in 1976, it is still widely used (particularly
+on Unix) despite many competitors and criticisms.
+
+There are many varieties of make in existance, this article assumes that
+we are using GNU make which is the standard on Linux.
+
+```make
+
+# Comments can be written like this.
+
+# Files should be named Makefile and then be can run as `make <target>`.
+# Otherwise we use `make -f "filename" <target>`.
+
+# Warning - only use TABS to indent in Makefiles, never spaces!
+
+#-----------------------------------------------------------------------
+# Basics
+#-----------------------------------------------------------------------
+
+# A rule - this rule will only run if file0.txt doesn't exist.
+file0.txt:
+ echo "foo" > file0.txt
+ # Even comments in these 'recipe' sections get passed to the shell.
+ # Try `make file0.txt` or simply `make` - first rule is the default.
+
+
+# This rule will only run if file0.txt is newer than file1.txt.
+file1.txt: file0.txt
+ cat file0.txt > file1.txt
+ # use the same quoting rules as in the shell.
+ @cat file0.txt >> file1.txt
+ # @ stops the command from being echoed to stdout.
+ -@echo 'hello'
+ # - means that make will keep going in the case of an error.
+ # Try `make file1.txt` on the commandline.
+
+# A rule can have multiple targets and multiple prerequisites
+file2.txt file3.txt: file0.txt file1.txt
+ touch file2.txt
+ touch file3.txt
+
+# Make will complain about multiple recipes for the same rule. Empty
+# recipes don't count though and can be used to add new dependencies.
+
+#-----------------------------------------------------------------------
+# Phony Targets
+#-----------------------------------------------------------------------
+
+# A phony target. Any target that isn't a file.
+# It will never be up to date so make will always try to run it.
+all: maker process
+
+# We can declare things out of order.
+maker:
+ touch ex0.txt ex1.txt
+
+# Can avoid phony rules breaking when a real file has the same name by
+.PHONY: all maker process
+# This is a special target. There are several others.
+
+# A rule with a dependency on a phony target will always run
+ex0.txt ex1.txt: maker
+
+# Common phony targets are: all make clean install ...
+
+#-----------------------------------------------------------------------
+# Automatic Variables & Wildcards
+#-----------------------------------------------------------------------
+
+process: file*.txt #using a wildcard to match filenames
+ @echo $^ # $^ is a variable containing the list of prerequisites
+ @echo $@ # prints the target name
+ #(for multiple target rules, $@ is whichever caused the rule to run)
+ @echo $< # the first prerequisite listed
+ @echo $? # only the dependencies that are out of date
+ @echo $+ # all dependencies including duplicates (unlike normal)
+ #@echo $| # all of the 'order only' prerequisites
+
+# Even if we split up the rule dependency definitions, $^ will find them
+process: ex1.txt file0.txt
+# ex1.txt will be found but file0.txt will be deduplicated.
+
+#-----------------------------------------------------------------------
+# Patterns
+#-----------------------------------------------------------------------
+
+# Can teach make how to convert certain files into other files.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# Pattern rules will only do anything if make decides to create the \
+target.
+
+# Directory paths are normally ignored when matching pattern rules. But
+# make will try to use the most appropriate rule available.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# make will use the last version for a pattern rule that it finds.
+%.png: %.svg
+ @echo this rule is chosen
+
+# However make will use the first pattern rule that can make the target
+%.png: %.ps
+ @echo this rule is not chosen if *.svg and *.ps are both present
+
+# make already has some pattern rules built-in. For instance, it knows
+# how to turn *.c files into *.o files.
+
+# Older makefiles might use suffix rules instead of pattern rules
+.png.ps:
+ @echo this rule is similar to a pattern rule.
+
+# Tell make about the suffix rule
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variables
+#-----------------------------------------------------------------------
+# aka. macros
+
+# Variables are basically all string types
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # This won't work, treated as $(n)ame.
+ @echo $(name3) # Unknown variables are treated as empty strings.
+
+# There are 4 places to set variables.
+# In order of priority from highest to lowest:
+# 1: commandline arguments
+# 2: Makefile
+# 3: shell enviroment variables - make imports these automatically.
+# 4: make has some predefined variables
+
+name4 ?= Jean
+# Only set the variable if enviroment variable is not already defined.
+
+override name5 = David
+# Stops commandline arguments from changing this variable.
+
+name4 +=grey
+# Append values to variable (includes a space).
+
+# Pattern-specific variable values (GNU extension).
+echo: name2 = Sara # True within the matching rule
+ # and also within its remade recursive dependencies
+ # (except it can break when your graph gets too complicated!)
+
+# Some variables defined automatically by make.
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX)}
+ echo $(FC)
+ echo ${CFLAGS)}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variables 2
+#-----------------------------------------------------------------------
+
+# The first type of variables are evaluated each time they are used.
+# This can be expensive, so a second type of variable exists which is
+# only evaluated once. (This is a GNU make extension)
+
+var := hello
+var2 ::= $(var) hello
+#:= and ::= are equivalent.
+
+# These variables are evaluated procedurely (in the order that they
+# appear), thus breaking with the rest of the language !
+
+# This doesn't work
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Functions
+#-----------------------------------------------------------------------
+
+# make has lots of functions available.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# Format is $(func arg0,arg1,arg2...)
+
+# Some examples
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Directives
+#-----------------------------------------------------------------------
+
+# Include other makefiles, useful for platform specific code
+include foo.mk
+
+sport = tennis
+# Conditional compilation
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# There are also ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+### More Resources
+
++ [gnu make documentation](https://www.gnu.org/software/make/manual/)
++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
diff --git a/markdown.html.markdown b/markdown.html.markdown index 7541f904..8961c995 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -2,45 +2,63 @@ language: markdown contributors: - ["Dan Turkel", "http://danturkel.com/"] + - ["Jacob Ward", "http://github.com/JacobCWard/"] filename: markdown.md --- -Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). - -Give me as much feedback as you want! / Feel free to fork and pull request! +Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well). +Markdown also varies in implementation from one parser to a next. This +guide will attempt to clarify when features are universal or when they are +specific to a certain parser. + +- [HTML Elements](#html-elements) +- [Headings](#headings) +- [Simple Text Styles](#simple-text-styles) +- [Paragraphs](#paragraphs) +- [Lists](#lists) +- [Code blocks](#code-blocks) +- [Horizontal rule](#horizontal-rule) +- [Links](#links) +- [Images](#images) +- [Miscellany](#miscellany) + +## HTML Elements +Markdown is a superset of HTML, so any HTML file is valid Markdown. ```markdown -<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that -means we can use HTML elements in Markdown, such as the comment element, and -they won't be affected by a markdown parser. However, if you create an HTML -element in your markdown file, you cannot use markdown syntax within that -element's contents. --> +<!--This means we can use HTML elements in Markdown, such as the comment element, +and they won't be affected by a markdown parser. However, if you create an HTML element +in your markdown file, you cannot use markdown syntax within that element's contents.--> +``` -<!-- Markdown also varies in implementation from one parser to a next. This -guide will attempt to clarify when features are universal or when they are -specific to a certain parser. --> +## Headings -<!-- Headers --> -<!-- You can create HTML elements <h1> through <h6> easily by prepending the -text you want to be in that element by a number of hashes (#) --> +You can create HTML elements `<h1>` through `<h6>` easily by prepending the +text you want to be in that element by a number of hashes (#). + +```markdown # This is an <h1> ## This is an <h2> ### This is an <h3> #### This is an <h4> ##### This is an <h5> ###### This is an <h6> +``` +Markdown also provides us with two alternative ways of indicating h1 and h2. -<!-- Markdown also provides us with two alternative ways of indicating h1 and h2 --> +```markdown This is an h1 ============= This is an h2 ------------- +``` +## Simple text styles -<!-- Simple text styles --> -<!-- Text can be easily styled as italic or bold using markdown --> +Text can be easily styled as italic or bold using markdown. +```markdown *This text is in italics.* _And so is this text._ @@ -50,15 +68,20 @@ __And so is this text.__ ***This text is in both.*** **_As is this!_** *__And this!__* +``` -<!-- In Github Flavored Markdown, which is used to render markdown files on -Github, we also have strikethrough: --> +In Github Flavored Markdown, which is used to render markdown files on +Github, we also have strikethrough: +```markdown ~~This text is rendered with strikethrough.~~ +``` +## Paragraphs -<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or -multiple blank lines. --> +Paragraphs are a one or multiple adjacent lines of text separated by one or +multiple blank lines. +```markdown This is a paragraph. I'm typing in a paragraph isn't this fun? Now I'm in paragraph 2. @@ -66,16 +89,20 @@ I'm still in paragraph 2 too! I'm in paragraph three! +``` -<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph -with two or more spaces and then begin a new paragraph. --> +Should you ever want to insert an HTML <br /> tag, you can end a paragraph +with two or more spaces and then begin a new paragraph. -I end with two spaces (highlight me to see them). +```markdown +I end with two spaces (highlight me to see them). There's a <br /> above me! +``` -<!-- Block quotes are easy and done with the > character. --> +Block quotes are easy and done with the > character. +```markdown > This is a block quote. You can either > manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own. > It doesn't make a difference so long as they start with a `>`. @@ -84,9 +111,12 @@ There's a <br /> above me! >> of indentation? > How neat is that? -<!-- Lists --> -<!-- Unordered lists can be made using asterisks, pluses, or hyphens --> +``` + +## Lists +Unordered lists can be made using asterisks, pluses, or hyphens. +```markdown * Item * Item * Another item @@ -97,158 +127,187 @@ or + Item + One more item -or +or - Item - Item - One last item +``` +Ordered lists are done with a number followed by a period. -<!-- Ordered lists are done with a number followed by a period --> - +```markdown 1. Item one 2. Item two 3. Item three +``` -<!-- You don't even have to label the items correctly and markdown will still -render the numbers in order, but this may not be a good idea --> +You don't even have to label the items correctly and markdown will still +render the numbers in order, but this may not be a good idea. +```markdown 1. Item one 1. Item two 1. Item three -<!-- (This renders the same as the above example) --> - -<!-- You can also use sublists --> +``` +(This renders the same as the above example) +You can also use sublists +```markdown 1. Item one 2. Item two 3. Item three * Sub-item * Sub-item 4. Item four +``` -<!-- There are even task lists. This creates HTML checkboxes. --> +There are even task lists. This creates HTML checkboxes. +```markdown Boxes below without the 'x' are unchecked HTML checkboxes. -- [ ] First task to complete. +- [ ] First task to complete. - [ ] Second task that needs done This checkbox below will be a checked HTML checkbox. - [x] This task has been completed +``` + +## Code blocks -<!-- Code blocks --> -<!-- You can indicate a code block (which uses the <code> element) by indenting -a line with four spaces or a tab --> +You can indicate a code block (which uses the `<code>` element) by indenting +a line with four spaces or a tab. +```markdown This is code So is this +``` -<!-- You can also re-tab (or add an additional four spaces) for indentation -inside your code --> +You can also re-tab (or add an additional four spaces) for indentation +inside your code +```markdown my_array.each do |item| puts item end +``` -<!-- Inline code can be created using the backtick character ` --> +Inline code can be created using the backtick character ` +```markdown John didn't even know what the `go_to()` function did! +``` -<!-- In Github Flavored Markdown, you can use a special syntax for code --> - +In Github Flavored Markdown, you can use a special syntax for code +```markdown \`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! --> def foobar puts "Hello world!" end \`\`\` <!-- here too, no backslashes, just ``` --> +``` -<-- The above text doesn't require indenting, plus Github will use syntax -highlighting of the language you specify after the ``` --> +The above text doesn't require indenting, plus Github will use syntax +highlighting of the language you specify after the \`\`\` -<!-- Horizontal rule (<hr />) --> -<!-- Horizontal rules are easily added with three or more asterisks or hyphens, -with or without spaces. --> +## Horizontal rule +Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens, +with or without spaces. +```markdown *** --- -- - - +- - - **************** +``` -<!-- Links --> -<!-- One of the best things about markdown is how easy it is to make links. Put -the text to display in hard brackets [] followed by the url in parentheses () --> - -[Click me!](http://test.com/) +## Links -<!-- You can also add a link title using quotes inside the parentheses --> +One of the best things about markdown is how easy it is to make links. Put +the text to display in hard brackets [] followed by the url in parentheses () +```markdown +[Click me!](http://test.com/) +``` +You can also add a link title using quotes inside the parentheses. +```markdown [Click me!](http://test.com/ "Link to Test.com") - -<!-- Relative paths work too. --> - +``` +Relative paths work too. +```markdown [Go to music](/music/). - -<!-- Markdown also supports reference style links --> - +``` +Markdown also supports reference style links. +```markdown [Click this link][link1] for more info about it! [Also check out this link][foobar] if you want to. [link1]: http://test.com/ "Cool!" [foobar]: http://foobar.biz/ "Alright!" - -<!-- The title can also be in single quotes or in parentheses, or omitted +``` +The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs -can be anything so long as they are unique. --> - -<!-- There is also "implicit naming" which lets you use the link text as the id --> +can be anything so long as they are unique. +There is also "implicit naming" which lets you use the link text as the id. +```markdown [This][] is a link. [this]: http://thisisalink.com/ +``` +But it's not that commonly used. -<!-- But it's not that commonly used. --> - -<!-- Images --> -<!-- Images are done the same way as links but with an exclamation point in front! --> - +## Images +Images are done the same way as links but with an exclamation point in front! +```markdown ![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title") - -<!-- And reference style works as expected --> - +``` +And reference style works as expected. +```markdown ![This is the alt-attribute.][myimage] [myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +``` -<!-- Miscellany --> -<!-- Auto-links --> - +## Miscellany +### Auto-links +```markdown <http://testwebsite.com/> is equivalent to [http://testwebsite.com/](http://testwebsite.com/) +``` -<!-- Auto-links for emails --> - +### Auto-links for emails +```markdown <foo@bar.com> +``` -<!-- Escaping characters --> - +### Escaping characters +```markdown I want to type *this text surrounded by asterisks* but I don't want it to be in italics, so I do this: \*this text surrounded by asterisks\*. +``` -<!-- Tables --> -<!-- Tables are only available in Github Flavored Markdown and are slightly -cumbersome, but if you really want it: --> +### Keyboard keys +In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys. +```markdown +Your computer crashed? Try sending a +<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd> +``` +### Tables + +Tables are only available in Github Flavored Markdown and are slightly +cumbersome, but if you really want it: +```markdown | Col1 | Col2 | Col3 | | :----------- | :------: | ------------: | | Left-aligned | Centered | Right-aligned | | blah | blah | blah | +``` +or, for the same results -<!-- or, for the same results --> - +```markdown Col 1 | Col2 | Col3 :-- | :-: | --: Ugh this is so ugly | make it | stop - -<!-- The end! --> - ``` - +--- For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet). diff --git a/matlab.html.markdown b/matlab.html.markdown index 9de41275..25f762bb 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -1,22 +1,25 @@ --- language: Matlab +filename: learnmatlab.mat contributors: - ["mendozao", "http://github.com/mendozao"] - ["jamesscottbrown", "http://jamesscottbrown.com"] - + - ["Colton Kohnke", "http://github.com/voltnor"] + - ["Claudson Martins", "http://github.com/claudsonm"] --- -MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. +MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. If you have any feedback please feel free to reach me at [@the_ozzinator](https://twitter.com/the_ozzinator), or [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). ```matlab +%% Code sections start with two percent signs. Section titles go on the same line. % Comments start with a percent sign. %{ -Multi line comments look +Multi line comments look something like this @@ -43,7 +46,7 @@ edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window profile on % turns on the code profiler -profile of % turns off the code profiler +profile off % turns off the code profiler profile viewer % Open profiler help command % Displays documentation for command in Command Window @@ -62,10 +65,10 @@ disp('text') % print "text" to the screen % Variables & Expressions myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 -a = 2; b = 3; +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 % Calling functions can be done in either of two ways: @@ -73,7 +76,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 load('myFile.mat', 'y') % arguments within parantheses, spererated by commas % Command syntax: load myFile.mat y % no parentheses, and spaces instead of commas -% Note the lack of quote marks in command form: inputs are always passed as +% Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A); % this has no equivalent in command form [~,D] = eig(A); % if you only want D and not V @@ -103,7 +106,7 @@ a(2) % ans = y % Cells -a = {'one', 'two', 'three'} +a = {'one', 'two', 'three'} a(1) % ans = 'one' - returns a cell char(a(1)) % ans = one - returns a string @@ -113,7 +116,7 @@ A.c = [1 2]; A.d.e = false; % Vectors -x = [4 32 53 7 1] +x = [4 32 53 7 1] x(2) % ans = 32, indices in Matlab start 1, not 0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -121,9 +124,10 @@ x(2:end) % ans = 32 53 7 1 x = [4; 32; 53; 7; 1] % Column vector x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 +x = [1:2:10] % Increment by 2, i.e. x = 1 3 5 7 9 % Matrices -A = [1 2 3; 4 5 6; 7 8 9] +A = [1 2 3; 4 5 6; 7 8 9] % Rows are separated by a semicolon; elements are separated with space or comma % A = @@ -132,7 +136,7 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6, A(row, column) -A(6) % ans = 8 +A(6) % ans = 8 % (implicitly concatenates columns into vector, then indexes into that) @@ -171,7 +175,7 @@ A(1,:) % All columns in row 1 % 4 5 42 % 7 8 9 -% this is the same as +% this is the same as vertcat(A,A); @@ -183,7 +187,7 @@ vertcat(A,A); % 4 5 42 4 5 42 % 7 8 9 7 8 9 -% this is the same as +% this is the same as horzcat(A,A); @@ -201,21 +205,23 @@ A(:, 1) =[] % Delete the first column of the matrix transpose(A) % Transpose the matrix, which is the same as: A one -ctranspose(A) % Hermitian transpose the matrix +ctranspose(A) % Hermitian transpose the matrix % (the transpose, followed by taking complex conjugate of each element) +A' % Concise version of complex transpose +A.' % Concise version of transpose (without taking complex conjugate) -% Element by Element Arithmetic vs. Matrix Arithmetic +% Element by Element Arithmetic vs. Matrix Arithmetic % On their own, the arithmetic operators act on whole matrices. When preceded % by a period, they act on each element instead. For example: A * B % Matrix multiplication A .* B % Multiple each element in A by its corresponding element in B -% There are several pairs of functions, where one acts on each element, and +% There are several pairs of functions, where one acts on each element, and % the other (whose name ends in m) acts on the whole matrix. -exp(A) % exponentiate each element +exp(A) % exponentiate each element expm(A) % calculate the matrix exponential sqrt(A) % take the square root of each element sqrtm(A) % find the matrix whose square is A @@ -233,7 +239,7 @@ axis([0 2*pi -1 1]) % x range from 0 to 2*pi, y range from -1 to 1 plot(x,y1,'-',x,y2,'--',x,y3,':') % For multiple functions on one plot legend('Line 1 label', 'Line 2 label') % Label curves with a legend -% Alternative method to plot multiple functions in one plot. +% Alternative method to plot multiple functions in one plot. % while 'hold' is on, commands add to existing graph rather than replacing it plot(x, y) hold on @@ -252,6 +258,8 @@ axis equal % Set aspect ratio so data units are the same in every direction scatter(x, y); % Scatter-plot hist(x); % Histogram +stem(x); % Plot values as stems, useful for displaying discrete data +bar(x); % Plot bar graph z = sin(x); plot3(x,y,z); % 3D line plot @@ -260,7 +268,7 @@ pcolor(A) % Heat-map of matrix: plot as grid of rectangles, coloured by value contour(A) % Contour plot of matrix mesh(A) % Plot as a mesh surface -h = figure % Create new figure object, with handle f +h = figure % Create new figure object, with handle h figure(h) % Makes the figure corresponding to handle h the current figure close(h) % close figure with handle h close all % close all open figure windows @@ -271,9 +279,9 @@ clf clear % clear current figure window, and reset most figure properties % Properties can be set and changed through a figure handle. % You can save a handle to a figure when you create it. -% The function gcf returns a handle to the current figure +% The function gcf returns a handle to the current figure h = plot(x, y); % you can save a handle to a figure when you create it -set(h, 'Color', 'r') +set(h, 'Color', 'r') % 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black set(h, 'LineStyle', '--') % '--' is solid line, '---' dashed, ':' dotted, '-.' dash-dot, 'none' is no line @@ -298,8 +306,8 @@ cd /path/to/move/into % change directory % Variables can be saved to .mat files -save('myFileName.mat') % Save the variables in your Workspace -load('myFileName.mat') % Load saved variables into Workspace +save('myFileName.mat') % Save the variables in your Workspace +load('myFileName.mat') % Load saved variables into Workspace % M-file Scripts % A script file is an external file that contains a sequence of statements. @@ -312,11 +320,11 @@ load('myFileName.mat') % Load saved variables into Workspace % Also, they have their own workspace (ie. different variable scope). % Function name should match file name (so save this example as double_input.m). % 'help double_input.m' returns the comments under line beginning function -function output = double_input(x) +function output = double_input(x) %double_input(x) returns twice the value of x output = 2*x; end -double_input(6) % ans = 12 +double_input(6) % ans = 12 % You can also have subfunctions and nested functions. @@ -325,10 +333,10 @@ double_input(6) % ans = 12 % functions, and have access to both its workspace and their own workspace. % If you want to create a function without creating a new file you can use an -% anonymous function. Useful when quickly defining a function to pass to -% another function (eg. plot with fplot, evaluate an indefinite integral +% anonymous function. Useful when quickly defining a function to pass to +% another function (eg. plot with fplot, evaluate an indefinite integral % with quad, find roots with fzero, or find minimum with fminsearch). -% Example that returns the square of it's input, assigned to to the handle sqr: +% Example that returns the square of it's input, assigned to the handle sqr: sqr = @(x) x.^2; sqr(10) % ans = 100 doc function_handle % find out more @@ -336,12 +344,12 @@ doc function_handle % find out more % User input a = input('Enter the value: ') -% Stops execution of file and gives control to the keyboard: user can examine +% Stops execution of file and gives control to the keyboard: user can examine % or change variables. Type 'return' to continue execution, or 'dbquit' to exit keyboard % Reading in data (also xlsread/importdata/imread for excel/CSV/image files) -fopen(filename) +fopen(filename) % Output disp(a) % Print out the value of variable a @@ -363,8 +371,8 @@ end for k = 1:5 disp(k) end - -k = 0; + +k = 0; while (k < 5) k = k + 1; end @@ -382,7 +390,7 @@ password = 'root'; driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); %xx depends on version, download available at http://dev.mysql.com/downloads/connector/j/ -conn = database(dbname, username, password, driver, dburl); +conn = database(dbname, username, password, driver, dburl); sql = ['SELECT * from table_name where id = 22'] % Example sql statement a = fetch(conn, sql) %a will contain your data @@ -394,11 +402,11 @@ tan(x) asin(x) acos(x) atan(x) -exp(x) +exp(x) sqrt(x) log(x) log10(x) -abs(x) +abs(x) %If x is complex, returns magnitude min(x) max(x) ceil(x) @@ -409,6 +417,14 @@ rand % Uniformly distributed pseudorandom numbers randi % Uniformly distributed pseudorandom integers randn % Normally distributed pseudorandom numbers +%Complex math operations +abs(x) % Magnitude of complex variable x +phase(x) % Phase (or angle) of complex variable x +real(x) % Returns the real part of x (i.e returns a if x = a +jb) +imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb) +conj(x) % Returns the complex conjugate + + % Common constants pi NaN @@ -426,7 +442,7 @@ pinv(A) % calculate the pseudo-inverse zeros(m,n) % m x n matrix of 0's ones(m,n) % m x n matrix of 1's diag(A) % Extracts the diagonal elements of a matrix A -diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere +diag(x) % Construct a matrix with diagonal elements listed in x, and zeroes elsewhere eye(m,n) % Identity matrix linspace(x1, x2, n) % Return n equally spaced points, with min x1 and max x2 inv(A) % Inverse of matrix A @@ -452,17 +468,73 @@ flipud(A) % Flip matrix up to down [U,S,V] = svd(X) % SVD: XV = US, U and V are unitary matrices, S has non-negative diagonal elements in decreasing order % Common vector functions -max % largest component -min % smallest component +max % largest component +min % smallest component length % length of a vector -sort % sort in ascending order -sum % sum of elements +sort % sort in ascending order +sum % sum of elements prod % product of elements -mode % modal value -median % median value -mean % mean value +mode % modal value +median % median value +mean % mean value std % standard deviation perms(x) % list all permutations of elements of x +find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, + % i.e. find( x == 3 ) returns indexes of elements that are equal to 3 + % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3 + + +% Classes +% Matlab can support object-oriented programming. +% Classes must be put in a file of the class name with a .m extension. +% To begin, we create a simple class to store GPS waypoints. +% Begin WaypointClass.m +classdef WaypointClass % The class name. + properties % The properties of the class behave like Structures + latitude + longitude + end + methods + % This method that has the same name of the class is the constructor. + function obj = WaypointClass(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Other functions that use the Waypoint object + function r = multiplyLatBy(obj, n) + r = n*[obj.latitude]; + end + + % If we want to add two Waypoint objects together without calling + % a special function we can overload Matlab's arithmetic like so: + function r = plus(o1,o2) + r = WaypointClass([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End WaypointClass.m + +% We can create an object of the class using the constructor +a = WaypointClass(45.0, 45.0) + +% Class properties behave exactly like Matlab Structures. +a.latitude = 70.0 +a.longitude = 25.0 + +% Methods can be called in the same way as functions +ans = multiplyLatBy(a,3) + +% The method can also be called using dot notation. In this case, the object +% does not need to be passed to the method. +ans = a.multiplyLatBy(a,1/3) + +% Matlab functions can be overloaded to handle objects. +% In the method above, we have overloaded how Matlab handles +% the addition of two Waypoint objects. +b = WaypointClass(15.0, 32.0) +c = a + b ``` diff --git a/ms-my/coffeescript-my.html.markdown b/ms-my/coffeescript-my.html.markdown new file mode 100644 index 00000000..9820a561 --- /dev/null +++ b/ms-my/coffeescript-my.html.markdown @@ -0,0 +1,105 @@ +--- +language: coffeescript +contributors: + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: coffeescript-ms.coffee +translators: + - ["hack1m", "https://github.com/hack1m"] +lang: ms-my +--- + +CoffeeScript adalah bahasa kecil yang menyusun/kompil satu-per-satu menjadi setara JavaScript, dan tidak ada interpretasi di runtime. +Sebagai salah satu pengganti kepada JavaScript, CoffeeScript mencuba yang terbaik untuk output kod JavaScript yang mudah dibaca, cantik-dicetak dan berfungsi lancar, yang mana berfungsi baik pada setiap runtime JavaScript. + +Lihat juga [Laman sesawang CoffeeScript](http://coffeescript.org/), yang mana ada tutorial lengkap untuk CoffeeScript. + +```coffeescript +# CoffeeScript adalah bahasa hipster. +# Ia beredar mengikut trend kebanyakkan bahasa moden. +# Jadi komen sama seperti Ruby dan Python, ia menggunakan simbol nombor. + +### +Blok komen seperti ini, dan ia terjemah terus ke '/ *'s dan '* /'s +untuk keputusan kod JavaScript. + +Sebelum meneruskan anda perlu faham kebanyakkan daripada +JavaScript adalah semantik. +### + +# Menetapkan: +number = 42 #=> var number = 42; +opposite = true #=> var opposite = true; + +# Bersyarat: +number = -42 if opposite #=> if(opposite) { number = -42; } + +# Fungsi: +square = (x) -> x * x #=> var square = function(x) { return x * x; } + +fill = (container, liquid = "coffee") -> + "Filling the #{container} with #{liquid}..." +#=>var fill; +# +#fill = function(container, liquid) { +# if (liquid == null) { +# liquid = "coffee"; +# } +# return "Filling the " + container + " with " + liquid + "..."; +#}; + +# Julat: +list = [1..5] #=> var list = [1, 2, 3, 4, 5]; + +# Objek: +math = + root: Math.sqrt + square: square + cube: (x) -> x * square x +#=> var math = { +# "root": Math.sqrt, +# "square": square, +# "cube": function(x) { return x * square(x); } +# }; + +# Splats: +race = (winner, runners...) -> + print winner, runners +#=>race = function() { +# var runners, winner; +# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(winner, runners); +# }; + +# Kewujudan: +alert "I knew it!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } + +# Pemahaman array: +cubes = (math.cube num for num in list) +#=>cubes = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = list.length; _i < _len; _i++) { +# num = list[_i]; +# _results.push(math.cube(num)); +# } +# return _results; +# })(); + +foods = ['broccoli', 'spinach', 'chocolate'] +eat food for food in foods when food isnt 'chocolate' +#=>foods = ['broccoli', 'spinach', 'chocolate']; +# +#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) { +# food = foods[_k]; +# if (food !== 'chocolate') { +# eat(food); +# } +#} +``` + +## Sumber tambahan + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown new file mode 100644 index 00000000..90e37133 --- /dev/null +++ b/ms-my/javascript-my.html.markdown @@ -0,0 +1,588 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ms.js +translators: + - ["abdalim", "https://github.com/abdalim"] +lang: ms-my +--- + +Javascript dicipta oleh Brendan Eich dari Netscape pada 1995. Pada awalnya, ia +dicipta sebagai bahasa skrip yang ringkas untuk laman web, melengkapi penggunaan +Java untuk aplikasi web yang lebih rumit, namun begitu, integrasi rapat pada +halaman web dan sokongan tersedia dalam pelayar web telah menyebabkan ia menjadi +lebih kerap digunakan berbanding Java pada bahagian hadapan laman web. + +Namun begitu, Javascript tidak terhad pada pelayar web; Node.js, sebuah projek +yang menyediakan 'runtime' berdiri sendiri untuk enjin V8 Google Chrome sedang +kian mendapat sambutan yang hangat. + +```js +// Komentar adalah seperti dalam C. Komentar sebaris bermula dengan dua sengkang +/* dan komentar banyak baris bermula dengan sengkang-bintang + dan berakhir dengan bintang-sengkang */ + +// Pernyataan boleh ditamatkan dengan ';' +doStuff(); + +// ... tetapi ia tidak wajib, kerana koma bertitik secara automatik akan +// dimasukkan dimana tempat yang ada baris baru, kecuali dalam kes - kes +// tertentu. +doStuff() + +// Disebabkan kes - kes itu boleh menyebabkan hasil yang tidak diduga, kami +// akan sentiasa menggunakan koma bertitik dalam panduan ini. + +/////////////////////////////////// +// 1. Nombor, String dan Operator + +// Javascript mempunyai satu jenis nombor (iaitu 64-bit IEEE 754 double). +// Double mempunyai 52-bit mantissa, iaitu ia cukup untuk menyimpan integer +// sehingga 9✕10¹⁵ secara tepatnya. +3; // = 3 +1.5; // = 1.5 + +// Sebahagian aritmetic asas berfungsi seperti yang anda jangkakan. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Termasuk pembahagian tidak rata. +5 / 2; // = 2.5 + +// Dan pembahagian modulo. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + +// Operasi bitwise juga boleh digunakan; bila anda melakukan operasi bitwise, +// float anda akan ditukarkan kepada int bertanda *sehingga* 32 bit. +1 << 2; // = 4 + +// Keutamaan ditekankan menggunakan kurungan. +(1 + 3) * 2; // = 8 + +// Terdapat tiga nilai nombor-tidak-nyata istimewa +Infinity; // hasil operasi seperti 1/0 +-Infinity; // hasil operasi seperti -1/0 +NaN; // hasil operasi seperti 0/0, bermaksud 'Bukan Sebuah Nombor' + +// Terdapat juga jenis boolean +true; +false; + +// Talian dicipta dengan ' atau ''. +'abc'; +"Hello, world"; + +// Penafian menggunakan simbol ! +!true; // = tidak benar +!false; // = benar + +// Sama ialah === +1 === 1; // = benar +2 === 1; // = tidak benar + +// Tidak sama ialah !== +1 !== 1; // = tidak benar +2 !== 1; // = benar + +// Lagi perbandingan +1 < 10; // = benar +1 > 10; // = tidak benar +2 <= 2; // = benar +2 >= 2; // = benar + +// Talian disambungkan dengan + +"Hello " + "world!"; // = "Hello world!" + +// dan dibandingkan dengan < dan > +"a" < "b"; // = benar + +// Paksaan jenis dilakukan untuk perbandingan menggunakan dua sama dengan... +"5" == 5; // = benar +null == undefined; // = benar + +// ...melainkan anda menggunakan === +"5" === 5; // = tidak benar +null === undefined; // = tidak benar + +// ...yang boleh menghasilkan keputusan yang pelik... +13 + !0; // 14 +"13" + !0; // '13true' + +// Anda boleh akses huruf dalam perkataan dengan `charAt` +"This is a string".charAt(0); // = 'T' + +// ...atau menggunakan `substring` untuk mendapatkan bahagian yang lebih besar. +"Hello world".substring(0, 5); // = "Hello" + +// `length` adalah ciri, maka jangan gunakan (). +"Hello".length; // = 5 + +// Selain itu, terdapat juga `null` dan `undefined`. +null; // digunakan untuk menandakan bukan-nilai yang disengajakan +undefined; // digunakan untuk menandakan nilai yang tidak wujud pada waktu ini (walaupun `undefined` adalah nilai juga) + +// false, null, undefined, NaN, 0 dan "" adalah tidak benar; semua selain itu adalah benar. +// Peringatan, 0 adalah tidak benar dan "0" adalah benar, walaupun 0 == "0". + +/////////////////////////////////// +// 2. Pembolehubah, Array dan Objek + +// Pembolehubah digunakan dengan kata kunci 'var'. Javascript ialah sebuah +// bahasa aturcara yang jenisnya dinamik, maka anda tidak perlu spesifikasikan +// jenis pembolehubah. Penetapan menggunakan satu '=' karakter. +var someVar = 5; + +// jika anda tinggalkan kata kunci var, anda tidak akan dapat ralat... +someOtherVar = 10; + +// ...tetapi pembolehubah anda akan dicipta di dalam skop global, bukan di +// dalam skop anda menciptanya. + +// Pembolehubah yang dideklarasikan tanpa ditetapkan sebarang nilai akan +// ditetapkan kepada undefined. +var someThirdVar; // = undefined + +// jika anda ingin mendeklarasikan beberapa pembolehubah, maka anda boleh +// menggunakan koma sebagai pembahagi +var someFourthVar = 2, someFifthVar = 4; + +// Terdapat cara mudah untuk melakukan operasi - operasi matematik pada +// pembolehubah: +someVar += 5; // bersamaan dengan someVar = someVar +5; someVar sama dengan 10 sekarang +someVar *= 10; // sekarang someVar bernilai 100 + +// dan cara lebih mudah untuk penambahan atau penolakan 1 +someVar++; // sekarang someVar ialah 101 +someVar--; // kembali kepada 100 + +// Array adalah senarai nilai yang tersusun, yang boleh terdiri daripada +// pembolehubah pelbagai jenis. +var myArray = ["Hello", 45, true]; + +// Setiap ahli array boleh diakses menggunakan syntax kurungan-petak. +// Indeks array bermula pada sifar. +myArray[1]; // = 45 + +// Array boleh diubah dan mempunyai panjang yang tidak tetap dan boleh ubah. +myArray.push("World"); +myArray.length; // = 4 + +// Tambah/Ubah di index yang spesifik +myArray[3] = "Hello"; + +// Objek javascript adalah sama dengan "dictionaries" atau "maps" dalam bahasa +// aturcara yang lain: koleksi pasangan kunci-nilai yang tidak mempunyai +// sebarang susunan. +var myObj = {key1: "Hello", key2: "World"}; + +// Kunci adalah string, tetapi 'quote' tidak diperlukan jika ia adalah pengecam +// javascript yang sah. Nilai boleh mempunyai sebarang jenis. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Ciri - ciri objek boleh juga diakses menggunakan syntax subskrip (kurungan- +// petak), +myObj["my other key"]; // = 4 + +// ... atau menggunakan syntax titik, selagi kuncinya adalah pengecam yang sah. +myObj.myKey; // = "myValue" + +// Objek adalah boleh diubah; nilai boleh diubah dan kunci baru boleh ditambah. +myObj.myThirdKey = true; + +// Jika anda cuba untuk akses nilai yang belum ditetapkan, anda akan mendapat +// undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logik dan Struktur Kawalan + +// Syntax untuk bahagian ini adalah hampir sama dengan Java. + +// Struktur `if` berfungsi seperti yang anda jangkakan. +var count = 1; +if (count == 3){ + // dinilai jika count ialah 3 +} else if (count == 4){ + // dinilai jika count ialah 4 +} else { + // dinilai jika count bukan 3 atau 4 +} + +// Sama juga dengan `while`. +while (true){ + // Sebuah ulangan yang tidak terhingga! + // An infinite loop! +} + +// Ulangan do-while adalah sama dengan ulangan while, kecuali ia akan diulang +// sekurang-kurangnya sekali. +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// Ulangan `for` adalah sama dengan C dan Java: +// Persiapan; kondisi untuk bersambung; pengulangan. +for (var i = 0; i < 5; i++){ + // akan berulang selama 5 kali +} + +// Pernyataan ulangan For/In akan mengulang setiap ciri seluruh jaringan +// 'prototype' +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +// Jika anda cuma mahu mengambil kira ciri - ciri yang ditambah pada objek it +// sendiri dan bukan 'prototype'nya, sila gunakan semakan hasOwnProperty() +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +// for/in tidak sepatutnya digunakan untuk mengulang sebuah Array di mana +// indeks susunan adalah penting. +// Tiada sebarang jaminan bahawa for/in akan mengembalikan indeks dalam +// mana - mana susunan + +// && adalah logikal dan, || adalah logikal atau +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // warna adalah sama ada 'red' atau 'blue' +} + +// && dan || adalah "lintar pintas", di mana ia berguna untuk menetapkan +// nilai asal. +var name = otherName || "default"; + + +// Pernyataan `switch` menyemak persamaan menggunakan `===`. +// gunakan pernyataan `break` selepas setiap kes +// atau tidak, kes - kes selepas kes yang betul akan dijalankan juga. +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Skop dan Closures + +// Function javascript dideklarasikan dengan kata kunci `function`. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Perhatikan yang nilai yang dikembalikan mesti bermula pada baris yang sama +// dengan kata kunci `return`, jika tidak, anda akan sentiasa mengembalikan +// `undefined` disebabkan kemasukan 'semicolon' secara automatik. Sila berjaga - +// jaga dengan hal ini apabila menggunakan Allman style. +function myFunction(){ + return // <- semicolon dimasukkan secara automatik di sini + {thisIsAn: 'object literal'} +} +myFunction(); // = undefined + +// Function javascript adalah objek kelas pertama, maka ia boleh diberikan +// nama pembolehubah yang lain dan diberikan kepada function yang lain sebagai +// input - sebagai contoh, apabila membekalkan pengendali event: +function myFunction(){ + // kod ini akan dijalankan selepas 5 saat +} +setTimeout(myFunction, 5000); +// Nota: setTimeout bukan sebahagian daripada bahasa JS, tetapi ia disediakan +// oleh pelayar web dan Node.js. + +// Satu lagi function yang disediakan oleh pelayar web adalah setInterval +function myFunction(){ + // kod ini akan dijalankan setiap 5 saat +} +setInterval(myFunction, 5000); + +// Objek function tidak perlu dideklarasikan dengan nama - anda boleh menulis +// function yang tidak bernama didalam input sebuah function lain. +setTimeout(function(){ + // kod ini akan dijalankan dalam 5 saat +}, 5000); + +// Javascript mempunyai skop function; function mempunyai skop mereka +// tersendiri tetapi blok tidak. +if (true){ + var i = 5; +} +i; // = 5 - bukan undefined seperti yang anda jangkakan di dalam bahasa blok-skop + +// Ini telah menyebabkan corak biasa iaitu "immediately-executing anonymous +// functions", yang mengelakkan pembolehubah sementara daripada bocor ke +// skop global. +(function(){ + var temporary = 5; + // Kita boleh akses skop global dengan menetapkan nilai ke "objek global", + // iaitu dalam pelayar web selalunya adalah `window`. Objek global mungkin + // mempunyai nama yang berlainan dalam alam bukan pelayar web seperti Node.js. + window.permanent = 10; +})(); +temporary; // akan menghasilkan ralat ReferenceError +permanent; // = 10 + +// Salah satu ciri terhebat Javascript ialah closure. Jika sebuah function +// didefinisikan di dalam sebuah function lain, function yang di dalam akan +// mempunyai akses kepada semua pembolehubah function yang di luar, mahupun +// selepas function yang di luar tersebut selesai. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Function dalam diletakkan di dalam skop lokal secara asal, seperti + // ia dideklarasikan dengan `var`. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout adalah tak segerak atau asinkroni, maka function sayHelloInFiveSeconds akan selesai serta merta, dan setTimeout akan memanggil + // inner selepas itu. Walaubagaimanapun, disebabkan inner terletak didalam + // sayHelloInFiveSeconds, inner tetap mempunyai akses kepada pembolehubah + // `prompt` apabila ia dipanggil. +} +sayHelloInFiveSeconds("Adam"); // akan membuka sebuah popup dengan "Hello, Adam!" selepas 5s + +/////////////////////////////////// +// 5. Lagi tentang Objek, Constructor dan Prototype + +// Objek boleh mengandungi function. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Apabila function sesebuah object dipanggil, ia boleh mengakses objek asalnya +// dengan menggunakan kata kunci `this`. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Nilai sebenar yang ditetapkan kepada this akan ditentukan oleh bagaimana +// sesebuah function itu dipanggil, bukan dimana ia didefinisikan. Oleh it, +// sesebuah function tidak akan berfungsi jika ia dipanggil bukan pada konteks +// objeknya. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Sebaliknya, sebuah function boleh ditetapkan kepada objek dan mendapat akses +// kepada objek itu melalui `this`, walaupun ia tidak ditetapkan semasa ia +// didefinisikan. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// Kita juga boleh menentukan konteks untuk sebuah function dijalankan apabila +// ia dipanggil menggunakan `call` atau `apply`. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// Function `apply` adalah hampir sama, tetapi ia mengambil sebuah array +// sebagai senarai input. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// Ini sangat berguna apabila menggunakan sebuah function yang menerima senarai +// input dan anda mahu menggunakan sebuah array sebagai input. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Tetapi, `call` dan `apply` adalah hanya sementara, sebagaimana hidup ini. +// Apabila kita mahu ia kekal, kita boleh menggunakan `bind`. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` boleh juga digunakan untuk menggunakan sebuah function tidak +// sepenuhnya (curry). + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Apabila anda memanggil sebuah function dengan kata kunci `new`, sebuah +// objek baru akan dicipta dan dijadikan tersedia kepada function itu melalui +// kata kunci `this`. Function yang direka bentuk untuk dipanggil sebegitu rupa +// dikenali sebagai constructors. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Setiap objek JavaScript mempunyai `prototype`. Apabila anda akses sesuatu +// ciri sebuah objek yang tidak wujud dalam objek sebenar itu, interpreter akan +// mencari ciri itu didalam `prototype`nya. + +// Sebahagian implementasi JS membenarkan anda untuk akses prototype sebuah +// objek pada ciri istimewa `__proto__`. Walaupun ini membantu dalam menerangkan +// mengenai prototypes, ia bukan sebahagian dari piawai; kita akan melihat +// cara - cara piawai untuk menggunakan prototypes nanti. +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Ini berfungsi untuk function juga. +myObj.myFunc(); // = "hello world!" + +// Sudah pasti, jika ciri anda bukan pada prototype anda, prototype kepada +// prototype anda akan disemak, dan seterusnya. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Tiada penyalinan terlibat disini; setiap objek menyimpan rujukan kepada +// prototypenya sendiri. Ini bermaksud, kita boleh mengubah prototypenya dan +// pengubahsuaian itu akan dilihat dan berkesan dimana sahaja. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Kami menyatakan yang `__proto__` adalah bukan piawai, dan tiada cara rasmi +// untuk mengubah prototype sesebuah objek. Walaubagaimanapun, terdapat dua +// cara untuk mencipta objek baru dengan sesebuah prototype. + +// Yang pertama ialah Object.create, yang merupakan tambahan terbaru pada JS, +// dan oleh itu tiada dalam semua implementasi buat masa ini. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Cara kedua, yang boleh digunakan dimana sahaja, adalah berkaitan dengan +// constructor. Constructors mempunyai sebuah ciri yang dipanggil prototype. +// Ini *bukan* prototype constructor terbabit; tetapi, ia adalah prototype yang +// diberikan kepada objek baru apabila ia dicipta menggunakan constructor dan +// kata kunci new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Jenis yang terbina sedia seperti string dan nombor juga mempunyai constructor +// yang mencipta objek pembalut yang serupa. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Kecuali, mereka sebenarnya tak sama sepenuhnya. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Kod ini tidak akan dilaksanakan, kerana 0 adalah tidak benar. +} + +// Walaubagaimanapun, pembalut objek dan jenis terbina yang biasa berkongsi +// prototype, maka sebagai contoh, anda sebenarnya boleh menambah fungsi +// kepada string. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Fakta ini selalu digunakan dalam "polyfilling", iaitu melaksanakan fungsi +// baru JavaScript didalam subset JavaScript yang lama, supaya ia boleh +// digunakan di dalam persekitaran yang lama seperti pelayar web yang lama. + +// Sebagai contoh, kami menyatakan yang Object.create belum lagi tersedia +// di semua implementasi, tetapi kita masih boleh menggunakannya dengan polyfill: +if (Object.create === undefined){ // jangan ganti jika ia sudah wujud + Object.create = function(proto){ + // buat satu constructor sementara dengan prototype yang betul + var Constructor = function(){}; + Constructor.prototype = proto; + // kemudian gunakannya untuk mencipta objek baru yang diberikan + // prototype yang betul + return new Constructor(); + } +} +``` +## Bacaan Lanjut + +[Mozilla Developer Network][1] menyediakan dokumentasi yang sangat baik untuk +JavaScript kerana ia digunakan di dalam pelayar - pelayar web. Tambahan pula, +ia adalah sebuah wiki, maka, sambil anda belajar lebih banyak lagi, anda boleh +membantu orang lain dengan berkongsi pengetahuan anda. + +[A re-introduction to JavaScript][2] oleh MDN meliputi semua konsep yang +diterangkan di sini dengan lebih terperinci. Panduan ini menerangkan bahasa +aturcara JavaScript dengan agak mudah; jika anda mahu belajar lebih lanjut +tentang menggunakan JavaScript didalam laman web, mulakan dengan mempelajari +tentang [Document Object Model][3]. + +[Learn Javascript by Example and with Challenges][4] adalah variasi panduan ini +dengan cabaran yang tersedia pakai. + +[JavaScript Garden][5] pula adalah panduan yang lebih terperinci mengenai +semua bahagian bahasa aturcara ini yang bertentangan dengan naluri atau +kebiasaan. + +[JavaScript: The Definitive Guide][6] adalah panduan klasik dan buku rujukan. + +Selain daripada penyumbang terus kepada artikel ini, sebahagian kandungannya +adalah adaptasi daripada tutorial Python Louie Dinh di dalam laman web ini, +dan [JS Tutorial][7] di Mozilla Developer Network. + + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript diff --git a/neat.html.markdown b/neat.html.markdown index e99d1e0e..f02461ee 100644 --- a/neat.html.markdown +++ b/neat.html.markdown @@ -47,18 +47,18 @@ void main(string[] args) { // There are no one-value tuples though. // So you can always use () in the mathematical sense. // (string) arg; <- is an error - + /* byte: 8 bit signed integer char: 8 bit UTF-8 byte component. short: 16 bit signed integer int: 32 bit signed integer long: 64 bit signed integer - + float: 32 bit floating point double: 64 bit floating point real: biggest native size floating point (80 bit on x86). - + bool: true or false */ int a = 5; @@ -139,14 +139,14 @@ void main(string[] args) { assert !(hewo is s); // same as assert (hewo !is s); - + // Allocate arrays using "new array length" int[] integers = new int[] 10; assert(integers.length == 10); assert(integers[0] == 0); // zero is default initializer integers = integers ~ 5; // This allocates a new array! assert(integers.length == 11); - + // This is an appender array. // Instead of (length, pointer), it tracks (capacity, length, pointer). // When you append to it, it will use the free capacity if it can. @@ -156,13 +156,13 @@ void main(string[] args) { appender ~= 2; appender ~= 3; appender.free(); // same as {mem.free(appender.ptr); appender = null;} - + // Scope variables are automatically freed at the end of the current scope. scope int[auto~] someOtherAppender; // This is the same as: int[auto~] someOtherAppender2; onExit { someOtherAppender2.free; } - + // You can do a C for loop too // - but why would you want to? for (int i = 0; i < 5; ++i) { } @@ -178,23 +178,23 @@ void main(string[] args) { assert(i == 5); break; // otherwise we'd go back up to do { } - + // This is a nested function. // Nested functions can access the surrounding function. string returnS() { return s; } writeln returnS(); - + // Take the address of a function using & // The type of a global function is ReturnType function(ParameterTypeTuple). void function() foop = &foo; - + // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple). string delegate() returnSp = &returnS; writeln returnSp(); // Class member functions and struct member functions also fit into delegate variables. // In general, delegates are functions that carry an additional context pointer. // ("fat pointers" in C) - + // Allocate a "snapshot" with "new delegate". // Snapshots are not closures! I used to call them closures too, // but then my Haskell-using friends yelled at me so I had to stop. @@ -232,8 +232,8 @@ void main(string[] args) { auto nestfun = λ() { } // There is NO semicolon needed here! // "}" can always substitute for "};". // This provides syntactic consistency with built-in statements. - - + + // This is a class. // Note: almost all elements of Neat can be used on the module level // or just as well inside a function. @@ -268,7 +268,7 @@ void main(string[] args) { E e = E:cd; // dynamic class cast! e.doE(); writeln "$e"; // all interfaces convert to Object implicitly. - + // Templates! // Templates are parameterized namespaces, taking a type as a parameter. template Templ(T) { diff --git a/nim.html.markdown b/nim.html.markdown index c74fece7..79271732 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -3,14 +3,15 @@ language: Nim filename: learnNim.nim contributors: - ["Jason J. Ayala P.", "http://JasonAyala.com"] + - ["Dennis Felsing", "http://felsin9.de/nnis/"] --- -Nim (formally Nimrod) is a statically typed, imperative programming language +Nim (formerly Nimrod) is a statically typed, imperative programming language that gives the programmer power without compromises on runtime efficiency. Nim is efficient, expressive, and elegant. -```ruby +```nimrod var # Declare (and assign) variables, letter: char = 'n' # with or without type annotations lang = "N" & "im" @@ -60,6 +61,13 @@ var drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal +drinks.add("Milk") + +if "Milk" in drinks: + echo "We have Milk and ", drinks.len - 1, " other drinks" + +let myDrink = drinks[2] + # # Defining Types # @@ -147,7 +155,7 @@ var anotherArray = ["Default index", "starts at", "0"] # More data structures are available, including tables, sets, lists, queues, # and crit bit trees. -# http://nimrod-lang.org/lib.html#collections-and-algorithms +# http://nim-lang.org/docs/lib.html#collections-and-algorithms # # IO and Control Flow @@ -166,7 +174,7 @@ else: # `while`, `if`, `continue`, `break` -import strutils as str # http://nimrod-lang.org/strutils.html +import strutils as str # http://nim-lang.org/docs/strutils.html echo "I'm thinking of a number between 41 and 43. Guess which!" let number: int = 42 var @@ -227,7 +235,7 @@ proc ask(question: string): Answer = else: echo("Please be clear: yes or no") proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing - assert(amount > 0 or amount < 9000, "Crazy Sugar") + assert(amount > 0 and amount < 9000, "Crazy Sugar") for a in 1..amount: echo(a, " sugar...") @@ -255,11 +263,11 @@ performance, and compile-time features. ## Further Reading -* [Home Page](http://nimrod-lang.org) -* [Download](http://nimrod-lang.org/download.html) -* [Community](http://nimrod-lang.org/community.html) -* [FAQ](http://nimrod-lang.org/question.html) -* [Documentation](http://nimrod-lang.org/documentation.html) -* [Manual](http://nimrod-lang.org/manual.html) -* [Standard Libray](http://nimrod-lang.org/lib.html) -* [Rosetta Code](http://rosettacode.org/wiki/Category:Nimrod) +* [Home Page](http://nim-lang.org) +* [Download](http://nim-lang.org/download.html) +* [Community](http://nim-lang.org/community.html) +* [FAQ](http://nim-lang.org/question.html) +* [Documentation](http://nim-lang.org/documentation.html) +* [Manual](http://nim-lang.org/docs/manual.html) +* [Standard Library](http://nim-lang.org/docs/lib.html) +* [Rosetta Code](http://rosettacode.org/wiki/Category:Nim) diff --git a/nl-nl/amd-nl.html.markdown b/nl-nl/amd-nl.html.markdown new file mode 100644 index 00000000..d5e0022a --- /dev/null +++ b/nl-nl/amd-nl.html.markdown @@ -0,0 +1,235 @@ +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +translators: + - ["Reinoud Kruithof", "https://github.com/reinoudk"] +filename: learnamd-nl.js +lang: nl-nl +--- + +## Aan de slag met AMD + +De **Asynchronous Module Definition** API specificeert een mechanisme om JavaScript + modules the definiren zodat de module en dependencies (afhankelijkheden) asynchroon + geladen kunnen worden. Dit is vooral erg geschikt voor de browseromgeving, waar het + synchroon laden van modules zorgt voor problemen qua prestatie, gebruiksvriendelijkheid, + debugging en cross-domain toegangsproblemen. + +### Basis concept +```javascript +// De basis AMD API bestaat uit niks meer dan twee methodes: `define` en `require` +// and gaat vooral over de definitie en gebruik van modules: +// `define(id?, dependencies?, factory)` definieert een module +// `require(dependencies, callback)` importeert een set van dependencies en +// gebruikt ze in de gegeven callback + +// Laten we starten met het gebruiken van define om een nieuwe module (met naam) +// te creeren, welke geen dependencies heeft. Dit doen we door een naam +// en een zogeheten factory functie door te geven aan define: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // De return waarde van een module's factory functie is + // wat andere modules of require calls ontvangen wanneer + // ze onze `awesomeAMD` module requiren. + // De gexporteerde waarde kan van alles zijn: (constructor) functies, + // objecten, primitives, zelfs undefined (hoewel dat niet veel nut heeft). + return isAMDAwesome; +}); + + +// We gaan nu een andere module defineren die afhankelijk is van onze +// `awesomeAMD` module. Merk hierbij op dat er nu een extra functieargument +// is die de dependencies van onze module defineert: +define('schreewlelijk', ['awesomeAMD'], function(awesomeAMD){ + // dependencies worden naar de factory's functieargumenten + // gestuurd in de volgorde waarin ze gespecificeert zijn + var vertelIedereen = function(){ + if (awesomeAMD()){ + alert('Dit is zOoOo cool!'); + } else { + alert('Vrij saai, niet?'); + } + }; + return vertelIedereen; +}); + +// Nu we weten hoe we define moeten gebruiken, kunnen we require gebruiken +// om ons programma mee te starten. De vorm van `require` is +// `(arrayVanDependencies, callback)`. +require(['schreeuwlelijk'], function(schreewlelijk){ + schreeuwlelijk(); +}); + +// Om deze tutorial code uit te laten voeren, gaan we hier een vrij basic +// (niet-asynchrone) versie van AMD implementeren: +function define(naam, deps, factory){ + // merk op hoe modules zonder dependencies worden afgehandeld + define[naam] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // we halen eerst alle dependecies op die nodig zijn + // om require aan te roepen + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // voldoe aan alle dependencies van de callback + return callback.apply(null, args); +} +// je kan deze code hier in actie zien (Engels): http://jsfiddle.net/qap949pd/ +``` + +### require.js in de echte wereld + +In contrast met het voorbeeld uit de introductie, implementeert `require.js` + (de meest populaire AMD library) de **A** in **AMD**. Dit maakt het mogelijk + om je modules en hun dependencies asynchroon in the laden via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // de callback word uitgesteld tot de dependency geladen is + var things = new SomeClass(); +}); +console.log('Dus, hier wachten we!'); // dit wordt als eerste uitgevoerd +``` + +De afspraak is dat je over het algemeen n module in n bestand opslaat. +`require.js` kan module-namen achterhalen gebaseerd op de bestandslocatie, +dus je hoeft je module geen naam te geven. Je kan simpelweg aan ze referen + door hun locatie te gebruiken. +In het voorbeeld nemen we aan dat `someClass` aanwezig is in de `modules` map, + relatief ten opzichte van de `baseUrl` uit je configuratie. + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +Dit betekent dat we `someClass` kunnen defineren zonder een module-id te specificeren: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // definitie van de module gebeurt, natuurlijk, ook asynchroon + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` +Gebruik `requirejs.config(configObj)` om het gedrag van de standaard mapping + aan te passen in je `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // je kan ook modules uit andere locatie inladen + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibUitBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // een `main` bestand moet require minstens eenmaal aanroepen, + // anders zal er geen code uitgevoerd worden + coolLib.doFancyDingenMet(helpers.transform($('#foo'))); +}); +``` +Op `require.js` gebaseerde apps hebben vaak een enkel beginpunt (`main.js`) + welke toegevoegd wordt aan de `require.js` script tag als een data-attribuut. +Deze zal automisch geladen en uitgevoerd worden als de pagina laadt: + +```html +<!DOCTYPE html> +<html> +<head> + <title>Honder script tags? Nooi meer!</title> +</head> +<body> + <script src="require.js" data-main="app/main"></script> +</body> +</html> +``` + +### Een heel project optimaliseren met r.js + +Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de + ontwikkelfase om code op een gezonde manier te organiseren maar + willen nog steeds een enkel scriptbestand gebruiken in productie in + plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. + +`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk +uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de +dependency book van je project analyseert en een enkel bestand bouwt met daarin +al je module (juist genaamd), geminificeerd en klaar voor productie. + +Instaleren met `npm`: +```shell +$ npm install requirejs -g +``` + +Nu kun je het een configuratiebestand voeden: +```shell +$ r.js -o app.build.js +``` + +Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: +```javascript +/* file : app.build.js */ +({ + name : 'main', // naam van het beginpunt + out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt + baseUrl : 'app', + paths : { + // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, + // gebruik makend van de locatie gespecificeert in `main.js` + jquery : 'empty:', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}) +``` +Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: +```html +<script src="require.js" data-main="app/main-built"></script> +``` + +Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is +beschikbar in de GitHub repo (Engels). + +Hieronder vind je nog meer informatie over AMD (Engels). + +### Onderwerpen die niet aan bod zijn gekomen +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Verder lezen: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementaties: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown index cd12b1d0..6062b24c 100644 --- a/nl-nl/brainfuck-nl.html.markdown +++ b/nl-nl/brainfuck-nl.html.markdown @@ -15,7 +15,7 @@ minimalistische Turing-complete programmeertaal met maar acht commando's. ``` Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd. -Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel +Brainfuck wordt gerepresenteerd door een array met 30.000 cellen die initieel gevuld is met nullen en een pointer die wijst naar de huidige cel. Dit zijn de acht commando's: diff --git a/nl-nl/yaml-nl.html.markdown b/nl-nl/yaml-nl.html.markdown new file mode 100644 index 00000000..a4a9d5fc --- /dev/null +++ b/nl-nl/yaml-nl.html.markdown @@ -0,0 +1,139 @@ +--- +language: yaml +filename: learnyaml-nl.yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Niels van Velzen", "https://nielsvanvelzen.me"] +lang: nl-nl +--- + +YAML is een data serialisatie taal ontworpen om snel te kunnen worden begrepen door mensen. + +Het is een strikte superset van JSON en bevat nieuwe regels en een stricte manier van inspringen, zoals bij Python. In tegenstelling tot Python kan je alleen geen tab tekens gebruiken. + +```yaml +# Commentaar in YAML ziet er zo uit + +################ +# SCALAR TYPES # +################ + +# Ons hoofd object (Wat in het hele document gebruikt wordt) is een map, +# dit staat gelijk aan een dictionary, hash of object in andere talen. +sleutel: waarde +nog_een_sleutel: Een andere waarde +nummer_waarde: 100 +wetenschappelijke_waarde: 1e+12 +boolean_waarde: true +null_waarde: null +sleutel met spaties: waarde +# Merk op dat strings niet verplicht in quotes moeten, maar dit kan wel. +quote_waarde: "Een string in quotes" +"Ook sleutels kunnen in quotes": "Dit is bijvoorbeeld handig als je een dubbelepunt wilt gebruiken in je key" + +# Tekst over meerdere lijnen kan je schrijven als een 'letterlijk blok' (met |) +# Of een 'gevouwen blok' (met >) +letterlijk_blok: | + Dit hele blok met tekst is de waarde van de 'letterlijk_blok' sleutel, + met nieuwe lijnen behouden. + + Het blok blijft door gaan tot het geeindigd wordt door korter te inspringen. + + Lijnen die groter zijn ingesprongen behouden dit. +gevouwen_stijl: > + Dit blok met tekst zal de waarde zijn van 'gevouwen_stijl', + maar deze keer zullen alle nieuwe lijnen worden vervangen met een spatie. + + Lege lijnen, zoals hierboven, zullen worden vertaald naar een nieuwe lijn. + + Meer ingesprongen lijnen zullen hun nieuwe lijnen ook behouden, + deze tekst zal over 2 lijnen te zien zijn. + +#################### +# COLLECTION TYPES # +#################### + +# Nesten wordt bereikt met inspringen. +geneste_map: + sleutel: waarde + andere_sleutel: andere waarde + andere_geneste_map: + hallo: wereld + +# In een map is een sleutel niet verplicht om een string te gebruiken +0.25: een float als sleutel + +# Sleutels kunnen ook meerdere lijnen gebruiken met behulp van het vraagteken +? | + Dit is een sleutel + met meerdere lijnen +: en dit is de waarde + +# YAML staat ook collection types toe in sleutels, maar veel programmeertalen +# zullen hierover klagen. + +# Sequences (gelijk aan lijsten of arrays) zien er zo uit: +een_sequence: + - Item 1 + - Item 2 + - 0.5 # sequences kunnen meerdere type waardes bevatten. + - Item 4 + - sleutel: waarde + andere_sleutel: andere waarde + - + - Dit is een sequence + - in een andere sequence + +# Doordat YAML een superset van JSON is kan je ook JSON-stijl mappen en +# sequences maken: +json_map: {"sleutel": "waarde"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# EXTRA YAML FUNCTIES # +####################### + +# YAML heeft ook een handige functie genaamd 'anchors' (ankers), deze laten je +# makkelijk de waarde van ergens anders in je document kopieëren. Beide sleutels +# krijgen dezelfde waarde: +geankert_content: &anker_naam Deze string zal verschijnen als waarde voor de twee sleutels +andere_anker: *anker_naam + +# YAML heeft ook tags, deze gebruik je om een expliciet type te verklaren +expliciete_string: !!str 0.5 +# Sommige parsers gebruiken taal specifieke tags, zoals deze voor Python's +# complexe nummer type: +python_complex_nummer: !!python/complex 1+2j + +#################### +# EXTRA YAML TYPES # +#################### + +# Strings en nummer zijn niet de enige types die YAML begrijpt. +# ISO opgemaakte datum en datumtijd notaties werken ook: +datumtijd: 2001-12-15T02:59:43.1Z +datumtijd_met_spaties: 2001-12-14 21:59:43.10 -5 +datum: 2002-12-14 + +# De !!binary tag geeft aan dat de string een base64-gecodeerde +# binary blob is. +gif_bestand: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML heeft ook een set type, dat ziet er zo uit: +set: + ? item1 + ? item2 + ? item3 + +# Zoals in Python zijn sets gewoon mappen met null waardes; +# bovenstaand is gelijk aan: +set2: + item1: null + item2: null + item3: null +``` diff --git a/no-nb/bash-no.html.markdown b/no-nb/bash-no.html.markdown new file mode 100644 index 00000000..ab0c064f --- /dev/null +++ b/no-nb/bash-no.html.markdown @@ -0,0 +1,270 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] +filename: LearnBash-no.sh +translators: + - ["Andreas Lindahl Flåten", "https://github.com/anlif"] +lang: no-nb +--- +Bash er navnet på unix skallet, som også var distribuert som skallet for GNU +operativsystemet og som standard skall på de fleste Linux distribusjoner og +Mac OS X. + +[Les mer her.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Den første linjen i et bash skript starter med '#!' (shebang) +# etterfulgt av stien til bash http://en.wikipedia.org/wiki/Shebang_(Unix) +# Kommentarer starter med #. + +# Enkelt hello world eksempel: +echo Hello world! + +# Hver kommando starter på en ny linje, eller etter et semikolon: +echo 'Dette er den første linjen'; echo 'Dette er en andre linjen' + +# Deklarering av en variabel ser slik ut: +VARIABLE="En tekststreng" + +# Men ikke slik: +VARIABLE = "En tekststreng" +# Bash vil tolke dette som at VARIABLE er en kommando den skal kjøre +# og gi en feilmelding dersom kommandoen ikke finnes + +# Bruk av den nydeklarerte variabelen: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Når du bruker variabelen, for eksempel setter verdien eller eksporterer den, +# skriver du navnet dens uten $. Hvis du vil bruke variabelens verdi, +# skriver du $ før variabelnavnet. + +# Strenginnhold i en variabel kan erstattes på følgende måte: +echo ${VARIABLE/tull/ball} +# Dette vil erstatte første forekomst av 'tull' med 'ball' + +# Substreng av en variabel: +echo ${VARIABLE:0:7} +# Dette vil returnere de første 7 tegnene i en strengvariabel + +# Å angi en standardverdi dersom en variabel er udeklarert gjøres slik: +echo ${FOO:-"StandardVerdiDersomFOOErTom"} +# Dette fungerer for null (FOO=), tom streng (FOO="") og tallet null (FOO=0) + +# Det finnes en rekke hendige innebygde variable, eksempel: +echo "Siste programs returnerte verdi: $?" +echo "Skript's PID: $$" +echo "Antall argumenter: $#" +echo "Alle argumenter til skriptet: $@" +echo "Argumenter til skriptet i egne variable: $1 $2..." + +# Lesing av input: +echo "Hva heter du?" +read NAME # variabelen NAME blir automatisk deklarert av 'read' kommandoen +echo Hei, $NAME! + +# if setninger ser slik ut: +# se 'man test' for mer informasjon om betingelser +if [ $NAME -ne $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# Det finnes også betinget eksekvering +echo "Kjøres alltid" || echo "Kjøres kun dersom første kommando feilet" +echo "Kjøres alltid" && echo "Kjøres kun dersom første kommando IKKE feilet" + +# For å bruke && (logisk OG) og || (logisk ELLER) sammen med if setninger, +# trenger man par av firkantklammer [] på hver side av et logisk uttrykk: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "Dette kjører dersom $NAME er Steve OG $AGE er lik 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "Dette kjører dersom $NAME er Daniya ELLER Zach." +fi + +# Matematiske uttrykk skrives slik: +echo $(( 10 + 5 )) + +# Ulikt de fleste programmeringsspråk, så er bash et skall - det medfører at en +# kommando i et skript kjører i en bestemt mappe i filsystemet. Du kan skrive +# ut innholdet i nåværende mappe med ls kommandoen: +ls + +# Kommandoen har parametre som kontrollerer hvordan kommandoen utføres: +ls -l # Skriv hver fil og mappe på sin egen linje + +# Resultatet av forrige kommando kan bli sendt til neste kommando som input. +# grep kommandoen filtrerer input ved hjelp av et regulært uttrykk. +# Ved å bruke grep kan vi skrive ut kun .txt filer på følgende måte: +ls -l | grep "\.txt" # lær mer om grep ved å skrive 'man grep' + +# Input og output fra filer kan dirigeres (stdin, stdout og stderr). +# 'cat' kommandoen uten argumenter skriver fra stdin til stdout. +# I det følgende eksempelet overskrives filen hello.py med linjene mellom EOF. +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Kjør hello.py (et python skript) +# med ulike stdin, stdout, and stderr omdirigeringer: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# '>' operatoren overskriver filen dersom den finnes. +# Hvis du heller vil legge til på slutten av en eksisterende fil, bruk '>>' +python hello.py >> "output.out" 2>> "error.err" + +# Overskriv output.txt, legg til error.err, og tell antall linjer med 'wc': +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Run a command and print its file descriptor (e.g. /dev/fd/123) +# Kjør en kommando og print tilhørende 'file descriptor' +# se 'man fd' +echo <(echo "#helloworld") + +# Ulike måter å overskrive output.out med '#helloworld': +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Slett noen filer med økt verbositet '-v', legg til '-i' for interaktiv modus +rm -v output.out error.err output-and-error.log + +# Kommandoer kan kjøres i deklarasjonen av andre kommandoer ved å bruke $( ): +# Følgende kommando skriver antall filer og mapper i nåværende mappe +echo "There are $(ls | wc -l) items here." + +# Det samme kan gjøres med backticks `` men de kan ikke være nøstede, +# det anbefales å bruke $( ) slik som i forrige eksempel. +echo "There are `ls | wc -l` items here." + +# Bash har en 'case' setning som fungerer omtrent som en 'switch' i Java/C: +case "$VARIABLE" in + # Skriv ønskede match med tilhørende kommandoer + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# for løkker kan iterere over en mengde argumenter: +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Eller vi kan skrive en for løkke omtrent slik det kan gjøres i Java/C: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Man kan også iterere over resultatet av en annen kommando. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# while løkke, se if setninger: +while [ true ] +do + echo "loop body here..." + break +done + +# Man kan også definere funksjoner. +# Definisjon: +function foo () +{ + echo "Argumenter fungerer akkurat som skript argumenter: $@" + echo "Og: $1 $2..." + echo "Dette er en funksjon" + return 0 +} + +# eller bare: +bar () +{ + echo "En annen måte å deklarere en funksjon." + return 0 +} + +# Å kalle en funksjon: +foo "Mitt navn er" $NAME + +# There are a lot of useful commands you should learn: +# prints last 10 lines of file.txt +# Det er mange nyttige kommandoer du bør lære deg: +# "tail" skriver ut slutten av en fil, i dette tilfellet de siste 10 linjene +tail -n 10 file.txt +# skriv ut de første 10 linjene av file.txt +head -n 10 file.txt +# sorter linjene i file.txt ("man sort") +sort file.txt +# skriv ut eller fjern repeterte linjer, med -d skrives de ut +uniq -d file.txt +# skriver kun den første kolonnen før ',' tegnet +cut -d ',' -f 1 file.txt +# erstatter hvert tilfelle av 'bjarne' med 'alfa' i file.txt, +# sed støtter regulære uttrykk ("man sed"). +sed -i 's/bjarne/alfa/g' file.txt +# skriv til stdout alle linjer i file.txt som matches av et regulært uttrykk +# eksempelet skriver ut alle linjer som begynner med "foo" og slutter med "bar" +grep "^foo.*bar$" file.txt +# skriv "-c" hvis du heller vil vite antall linjer som matcher +grep -c "^foo.*bar$" file.txt +# hvis du vil matche en bestemt streng, og ikke et regulært uttrykk +# bruker du enten "fgrep" eller ekvivalenten "grep -f" +fgrep "^foo.*bar$" file.txt + + +# Les Bash sin egen dokumentasjon om innebygde konstruksjoner: +help +help help +help for +help return +help source +help . + +# Les Bash sin "manpage": +apropos bash +man 1 bash +man bash + +# Les "info" dokumentasjon: +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Les bash sin info dokumentasjon: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/objective-c.html.markdown b/objective-c.html.markdown index caad49a5..097cb846 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -1,24 +1,28 @@ --- - language: Objective-C contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] - ["Levi Bostian", "https://github.com/levibostian"] + - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: LearnObjectiveC.m - --- Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch. -It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. +It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. -```objective_c +```objective-c // Single-line comments start with // /* Multi-line comments look like this */ +// XCode supports pragma mark directive that improve jump bar readability +#pragma mark Navigation Functions // New tag on jump bar named 'Navigation Functions' +#pragma mark - Navigation Functions // Same tag, now with a separator + // Imports the Foundation headers with #import // Use <> to import global files (in general frameworks) // Use "" to import local files (from project) @@ -40,31 +44,31 @@ int main (int argc, const char * argv[]) // Use NSLog to print lines to the console NSLog(@"Hello World!"); // Print the string "Hello World!" - + /////////////////////////////////////// // Types & Variables /////////////////////////////////////// - + // Primitive declarations int myPrimitive1 = 1; long myPrimitive2 = 234554664565; - + // Object declarations // Put the * in front of the variable names for strongly-typed object declarations MyClass *myObject1 = nil; // Strong typing id myObject2 = nil; // Weak typing // %@ is an object // 'description' is a convention to display the value of the Objects - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // Print "(null) and (null)" - + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // prints => "(null) and (null)" + // String NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // prints => "Hello World!" + NSLog(@"Hello %@!", worldString); // prints => "Hello World!" // NSMutableString is a mutable version of the NSString object NSMutableString *mutableString = [NSMutableString stringWithString:@"Hello"]; [mutableString appendString:@" World!"]; NSLog(@"%@", mutableString); // prints => "Hello World!" - + // Character literals NSNumber *theLetterZNumber = @'Z'; char theLetterZ = [theLetterZNumber charValue]; // or 'Z' @@ -74,11 +78,11 @@ int main (int argc, const char * argv[]) NSNumber *fortyTwoNumber = @42; int fortyTwo = [fortyTwoNumber intValue]; // or 42 NSLog(@"%i", fortyTwo); - + NSNumber *fortyTwoUnsignedNumber = @42U; unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // or 42 NSLog(@"%u", fortyTwoUnsigned); - + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; short fortyTwoShort = [fortyTwoShortNumber shortValue]; // or 42 NSLog(@"%hi", fortyTwoShort); @@ -86,7 +90,7 @@ int main (int argc, const char * argv[]) NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // or 41 NSLog(@"%u", fortyOneUnsigned); - + NSNumber *fortyTwoLongNumber = @42L; long fortyTwoLong = [fortyTwoLongNumber longValue]; // or 42 NSLog(@"%li", fortyTwoLong); @@ -100,7 +104,7 @@ int main (int argc, const char * argv[]) float piFloat = [piFloatNumber floatValue]; // or 3.141592654f NSLog(@"%f", piFloat); // prints => 3.141592654 NSLog(@"%5.2f", piFloat); // prints => " 3.14" - + NSNumber *piDoubleNumber = @3.1415926535; double piDouble = [piDoubleNumber doubleValue]; // or 3.1415926535 NSLog(@"%f", piDouble); @@ -110,7 +114,7 @@ int main (int argc, const char * argv[]) NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; // NSDecimalNumber isn't able to use standard +, -, *, / operators so it provides its own: - [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberByAdding:twoDecNum]; [oneDecNum decimalNumberBySubtracting:twoDecNum]; [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; [oneDecNum decimalNumberByDividingBy:twoDecNum]; @@ -128,9 +132,10 @@ int main (int argc, const char * argv[]) // May contain different data types, but must be an Objective-C object NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" - // NSMutableArray is mutable version of NSArray allowing to change items in array - // and extend or shrink array object. Convenient, but not as efficient as NSArray + NSLog(@"Third number = %@", thirdNumber); // prints => "Third number = 3" + // NSMutableArray is a mutable version of NSArray, allowing you to change + // the items in the array and to extend or shrink the array object. + // Convenient, but not as efficient as NSArray. NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; [mutableArray addObject:@"Hello"]; [mutableArray addObject:@"World"]; @@ -140,13 +145,19 @@ int main (int argc, const char * argv[]) // Dictionary object NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Print "Object = (null)" + NSLog(@"Object = %@", valueObject); // prints => "Object = (null)" // NSMutableDictionary also available as a mutable dictionary object NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; [mutableDictionary setObject:@"value1" forKey:@"key1"]; [mutableDictionary setObject:@"value2" forKey:@"key2"]; [mutableDictionary removeObjectForKey:@"key1"]; + // Change types from Mutable To Immutable + //In general [object mutableCopy] will make the object mutable whereas [object copy] will make the object immutable + NSMutableDictionary *aMutableDictionary = [aDictionary mutableCopy]; + NSDictionary *mutableDictionaryChanged = [mutableDictionary copy]; + + // Set object NSSet *set = [NSSet setWithObjects:@"Hello", @"Hello", @"World", nil]; NSLog(@"%@", set); // prints => {(Hello, World)} (may be in different order) @@ -159,7 +170,7 @@ int main (int argc, const char * argv[]) /////////////////////////////////////// // Operators /////////////////////////////////////// - + // The operators works like in the C language // For example: 2 + 5; // => 7 @@ -204,13 +215,13 @@ int main (int argc, const char * argv[]) NSLog(@"I print"); } break; } - + // While loops statements int ii = 0; while (ii < 4) { NSLog(@"%d,", ii++); // ii++ increments ii in-place, after using its value - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," @@ -220,25 +231,25 @@ int main (int argc, const char * argv[]) for (jj=0; jj < 4; jj++) { NSLog(@"%d,", jj); - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," - - // Foreach statements + + // Foreach statements NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { NSLog(@"%@,", value); - } // => prints "0," + } // prints => "0," // "1," // "2," // "3," // Object for loop statement. Can be used with any Objective-C object type - for (id item in values) { - NSLog(@"%@,", item); - } // => prints "0," + for (id item in values) { + NSLog(@"%@,", item); + } // prints => "0," // "1," // "2," // "3," @@ -249,26 +260,26 @@ int main (int argc, const char * argv[]) // Your statements here @throw [NSException exceptionWithName:@"FileNotFoundException" reason:@"File Not Found on System" userInfo:nil]; - } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. + } @catch (NSException * e) // use: @catch (id exceptionName) to catch all objects. { NSLog(@"Exception: %@", e); } @finally { NSLog(@"Finally. Time to clean up."); - } // => prints "Exception: File Not Found on System" + } // prints => "Exception: File Not Found on System" // "Finally. Time to clean up." - // NSError objects are useful for function arguments to populate on user mistakes. + // NSError objects are useful for function arguments to populate on user mistakes. NSError *error = [NSError errorWithDomain:@"Invalid email." code:4 userInfo:nil]; - + /////////////////////////////////////// // Objects /////////////////////////////////////// - + // Create an object instance by allocating memory and initializing it // An object is not fully functional until both steps have been completed MyClass *myObject = [[MyClass alloc] init]; - + // The Objective-C model of object-oriented programming is based on message // passing to object instances // In Objective-C one does not simply call a method; one sends a message @@ -279,7 +290,7 @@ int main (int argc, const char * argv[]) // End of @autoreleasepool } - + // End the program return 0; } @@ -300,9 +311,9 @@ int main (int argc, const char * argv[]) @interface MyClass : NSObject <MyProtocol> // NSObject is Objective-C's base object class. { // Instance variable declarations (can exist in either interface or implementation file) - int count; // Protected access by default. + int count; // Protected access by default. @private id data; // Private access (More convenient to declare in implementation file) - NSString *name; + NSString *name; } // Convenient notation for public access variables to auto generate a setter method // By default, setter method name is 'set' followed by @property variable name @@ -312,7 +323,7 @@ int main (int argc, const char * argv[]) @property (readonly) NSString *roString; // Use @synthesize in @implementation to create accessor // You can customize the getter and setter names instead of using default 'set' name: @property (getter=lengthGet, setter=lengthSet:) int length; - + // Methods +/- (return type)methodSignature:(Parameter Type *)parameterName; @@ -334,7 +345,7 @@ int main (int argc, const char * argv[]) // To access public variables from the implementation file, @property generates a setter method // automatically. Method name is 'set' followed by @property variable name: MyClass *myClass = [[MyClass alloc] init]; // create MyClass object instance -[myClass setCount:10]; +[myClass setCount:10]; NSLog(@"%d", [myClass count]); // prints => 10 // Or using the custom getter and setter method defined in @interface: [myClass lengthSet:32]; @@ -357,7 +368,7 @@ NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Hell // as a variable // SEL is the data type. @selector() returns a selector from method name provided // methodAParameterAsString:andAParameterAsNumber: is method name for method in MyClass -SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); if ([myClass respondsToSelector:selectorVar]) { // Checks if class contains method // Must put all method arguments into one object to send to performSelector function NSArray *arguments = [NSArray arrayWithObjects:@"Hello", @4, nil]; @@ -381,7 +392,7 @@ distance = 18; // References "long distance" from MyClass implementation @synthesize roString = _roString; // _roString available now in @implementation // Called before calling any class methods or instantiating any objects -+ (void)initialize ++ (void)initialize { if (self == [MyClass class]) { distance = 0; @@ -391,7 +402,7 @@ distance = 18; // References "long distance" from MyClass implementation // Counterpart to initialize method. Called when an object's reference count is zero - (void)dealloc { - [height release]; // If not using ARC, make sure to release class variable objects + [height release]; // If not using ARC, make sure to release class variable objects [super dealloc]; // and call parent class dealloc } @@ -406,7 +417,7 @@ distance = 18; // References "long distance" from MyClass implementation return self; } // Can create constructors that contain arguments: -- (id)initWithDistance:(int)defaultDistance +- (id)initWithDistance:(int)defaultDistance { distance = defaultDistance; return self; @@ -414,10 +425,10 @@ distance = 18; // References "long distance" from MyClass implementation + (NSString *)classMethod { - return [[self alloc] init]; + return @"Some string"; } -+ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight { height = defaultHeight; return [[self alloc] init]; @@ -433,7 +444,7 @@ distance = 18; // References "long distance" from MyClass implementation return @42; } -// Objective-C does not have private method declarations, but you can simulate them. +// Objective-C does not have private method declarations, but you can simulate them. // To simulate a private method, create the method in the @implementation but not in the @interface. - (NSNumber *)secretPrivateMethod { return @72; @@ -452,15 +463,15 @@ distance = 18; // References "long distance" from MyClass implementation // Categories /////////////////////////////////////// // A category is a group of methods designed to extend a class. They allow you to add new methods -// to an existing class for organizational purposes. This is not to be mistaken with subclasses. -// Subclasses are meant to CHANGE functionality of an object while categories instead ADD +// to an existing class for organizational purposes. This is not to be mistaken with subclasses. +// Subclasses are meant to CHANGE functionality of an object while categories instead ADD // functionality to an object. // Categories allow you to: // -- Add methods to an existing class for organizational purposes. // -- Allow you to extend Objective-C object classes (ex: NSString) to add your own methods. -// -- Add ability to create protected and private methods to classes. -// NOTE: Do not override methods of the base class in a category even though you have the ability -// to. Overriding methods may cause compiler errors later between different categories and it +// -- Add ability to create protected and private methods to classes. +// NOTE: Do not override methods of the base class in a category even though you have the ability +// to. Overriding methods may cause compiler errors later between different categories and it // ruins the purpose of categories to only ADD functionality. Subclass instead to override methods. // Here is a simple Car base class. @@ -492,8 +503,8 @@ distance = 18; // References "long distance" from MyClass implementation @end // Now, if we wanted to create a Truck object, we would instead create a subclass of Car as it would -// be changing the functionality of the Car to behave like a truck. But lets say we want to just add -// functionality to this existing Car. A good example would be to clean the car. So we would create +// be changing the functionality of the Car to behave like a truck. But lets say we want to just add +// functionality to this existing Car. A good example would be to clean the car. So we would create // a category to add these cleaning methods: // @interface filename: Car+Clean.h (BaseClassName+CategoryName.h) #import "Car.h" // Make sure to import base class to extend. @@ -517,7 +528,7 @@ distance = 18; // References "long distance" from MyClass implementation NSLog(@"Waxed."); } -@end +@end // Any Car object instance has the ability to use a category. All they need to do is import it: #import "Car+Clean.h" // Import as many different categories as you want to use. @@ -532,7 +543,7 @@ int main (int argc, const char * argv[]) { [mustang turnOn]; // Use methods from base Car class. [mustang washWindows]; // Use methods from Car's Clean category. } - return 0; + return 0; } // Objective-C does not have protected method declarations but you can simulate them. @@ -546,7 +557,7 @@ int main (int argc, const char * argv[]) { //To use protected methods, import the category, then implement the methods: #import "Car+Protected.h" // Remember, import in the @implementation file only. -@implementation Car +@implementation Car - (void)lockCar { NSLog(@"Car locked."); // Instances of Car can't use lockCar because it's not in the @interface. @@ -569,8 +580,8 @@ int main (int argc, const char * argv[]) { // You can override numOfSides variable or getNumOfSides method to edit them with an extension: // @implementation filename: Shape.m #import "Shape.h" -// Extensions live in the same file as the class @implementation. -@interface Shape () // () after base class name declares an extension. +// Extensions live in the same file as the class @implementation. +@interface Shape () // () after base class name declares an extension. @property (copy) NSNumber *numOfSides; // Make numOfSides copy instead of readonly. -(NSNumber)getNumOfSides; // Make getNumOfSides return a NSNumber instead of an int. @@ -578,7 +589,7 @@ int main (int argc, const char * argv[]) { @end // The main @implementation: -@implementation Shape +@implementation Shape @synthesize numOfSides = _numOfSides; @@ -591,6 +602,52 @@ int main (int argc, const char * argv[]) { @end +// Starting in Xcode 7.0, you can create Generic classes, +// allowing you to provide greater type safety and clarity +// without writing excessive boilerplate. +@interface Result<__covariant A> : NSObject + +- (void)handleSuccess:(void(^)(A))success + failure:(void(^)(NSError *))failure; + +@property (nonatomic) A object; + +@end + +// we can now declare instances of this class like +Result<NSNumber *> *result; +Result<NSArray *> *result; + +// Each of these cases would be equivalent to rewriting Result's interface +// and substituting the appropriate type for A +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSArray *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSArray * object; +@end + +@interface Result : NSObject +- (void)handleSuccess:(void(^)(NSNumber *))success + failure:(void(^)(NSError *))failure; +@property (nonatomic) NSNumber * object; +@end + +// It should be obvious, however, that writing one +// Class to solve a problem is always preferable to writing two + +// Note that Clang will not accept generic types in @implementations, +// so your @implemnation of Result would have to look like this: + +@implementation Result + +- (void)handleSuccess:(void (^)(id))success + failure:(void (^)(NSError *))failure { + // Do something +} + +@end + + /////////////////////////////////////// // Protocols /////////////////////////////////////// @@ -602,14 +659,14 @@ int main (int argc, const char * argv[]) { @property BOOL engineOn; // Adopting class must @synthesize all defined @properties and - (void)turnOnEngine; // all defined methods. @end -// Below is an example class implementing the protocol. +// Below is an example class implementing the protocol. #import "CarUtilities.h" // Import the @protocol file. @interface Car : NSObject <CarUtilities> // Name of protocol goes inside <> // You don't need the @property or method names here for CarUtilities. Only @implementation does. - (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // You can use protocols as data too. @end -// The @implementation needs to implement the @properties and methods for the protocol. +// The @implementation needs to implement the @properties and methods for the protocol. @implementation Car : NSObject <CarUtilities> @synthesize engineOn = _engineOn; // Create a @synthesize statement for the engineOn @property. @@ -618,16 +675,16 @@ int main (int argc, const char * argv[]) { _engineOn = YES; // how you implement a method, it just requires that you do implement it. } // You may use a protocol as data as you know what methods and variables it has implemented. -- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind { +- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind { [objectOfSomeKind engineOn]; // You have access to object variables - [objectOfSomeKind turnOnEngine]; // and the methods inside. + [objectOfSomeKind turnOnEngine]; // and the methods inside. [objectOfSomeKind engineOn]; // May or may not be YES. Class implements it however it wants. } @end -// Instances of Car now have access to the protocol. +// Instances of Car now have access to the protocol. Car *carInstance = [[Car alloc] init]; -[[carInstance setEngineOn:NO]; +[carInstance setEngineOn:NO]; [carInstance turnOnEngine]; if ([carInstance engineOn]) { NSLog(@"Car engine is on."); // prints => "Car engine is on." @@ -654,10 +711,10 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { // See the problem is that Sister relies on Brother, and Brother relies on Sister. #import "Sister.h" -@protocol Sister; // These lines stop the recursion, resolving the issue. +@protocol Sister; // These lines stop the recursion, resolving the issue. @protocol Brother <NSObject> - + - (void)beNiceToSister:(id <Sister>)sister; @end @@ -666,24 +723,24 @@ if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { /////////////////////////////////////// // Blocks /////////////////////////////////////// -// Blocks are statements of code, just like a function, that are able to be used as data. +// Blocks are statements of code, just like a function, that are able to be used as data. // Below is a simple block with an integer argument that returns the argument plus 4. -int (^addUp)(int n); // Declare a variable to store the block. -void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. +int (^addUp)(int n); // Declare a variable to store the block. +void (^noParameterBlockVar)(void); // Example variable declaration of block with no arguments. // Blocks have access to variables in the same scope. But the variables are readonly and the -// value passed to the block is the value of the variable when the block is created. +// value passed to the block is the value of the variable when the block is created. int outsideVar = 17; // If we edit outsideVar after declaring addUp, outsideVar is STILL 17. __block long mutableVar = 3; // __block makes variables writable to blocks, unlike outsideVar. -addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. +addUp = ^(int n) { // Remove (int n) to have a block that doesn't take in any parameters. NSLog(@"You may have as many lines in a block as you would like."); NSSet *blockSet; // Also, you can declare local variables. mutableVar = 32; // Assigning new value to __block variable. - return n + outsideVar; // Return statements are optional. + return n + outsideVar; // Return statements are optional. } -int addUp = add(10 + 16); // Calls block code with arguments. +int addUp = addUp(10 + 16); // Calls block code with arguments. // Blocks are often used as arguments to functions to be called later, or for callbacks. -@implementation BlockExample : NSObject - +@implementation BlockExample : NSObject + - (void)runBlock:(void (^)(NSString))block { NSLog(@"Block argument returns nothing and takes in a NSString object."); block(@"Argument given to block to execute."); // Calling block. @@ -695,19 +752,19 @@ int addUp = add(10 + 16); // Calls block code with arguments. /////////////////////////////////////// // Memory Management /////////////////////////////////////// -/* +/* For each object used in an application, memory must be allocated for that object. When the application -is done using that object, memory must be deallocated to ensure application efficiency. -Objective-C does not use garbage collection and instead uses reference counting. As long as +is done using that object, memory must be deallocated to ensure application efficiency. +Objective-C does not use garbage collection and instead uses reference counting. As long as there is at least one reference to an object (also called "owning" an object), then the object -will be available to use (known as "ownership"). +will be available to use (known as "ownership"). When an instance owns an object, its reference counter is increments by one. When the object is released, the reference counter decrements by one. When reference count is zero, -the object is removed from memory. +the object is removed from memory. -With all object interactions, follow the pattern of: -(1) create the object, (2) use the object, (3) then free the object from memory. +With all object interactions, follow the pattern of: +(1) create the object, (2) use the object, (3) then free the object from memory. */ MyClass *classVar = [MyClass alloc]; // 'alloc' sets classVar's reference count to one. Returns pointer to object @@ -722,11 +779,11 @@ MyClass *newVar = [classVar retain]; // If classVar is released, object is still // Automatic Reference Counting (ARC) // Because memory management can be a pain, Xcode 4.2 and iOS 4 introduced Automatic Reference Counting (ARC). -// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, +// ARC is a compiler feature that inserts retain, release, and autorelease automatically for you, so when using ARC, // you must not use retain, relase, or autorelease -MyClass *arcMyClass = [[MyClass alloc] init]; +MyClass *arcMyClass = [[MyClass alloc] init]; // ... code using arcMyClass -// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, +// Without ARC, you will need to call: [arcMyClass release] after you're done using arcMyClass. But with ARC, // there is no need. It will insert this release statement for you // As for the 'assign' and 'retain' @property attributes, with ARC you use 'weak' and 'strong' @@ -746,4 +803,8 @@ __unsafe_unretained NSArray *unsafeArray; // Like __weak, but unsafeArray not se [Programming with Objective-C. Apple PDF book](https://developer.apple.com/library/ios/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/ProgrammingWithObjectiveC.pdf) +[Programming with Objective-C for iOS](https://developer.apple.com/library/ios/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectiveC.html) + +[Programming with Objective-C for Mac OSX](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) + [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) diff --git a/ocaml.html.markdown b/ocaml.html.markdown index f9db7080..8faab297 100644 --- a/ocaml.html.markdown +++ b/ocaml.html.markdown @@ -34,13 +34,13 @@ For a source file you can use "ocamlc -i /path/to/file.ml" command to print all names and type signatures. ``` -$ cat sigtest.ml +$ cat sigtest.ml let inc x = x + 1 let add x y = x + y -let a = 1 +let a = 1 -$ ocamlc -i ./sigtest.ml +$ ocamlc -i ./sigtest.ml val inc : int -> int val add : int -> int -> int val a : int @@ -104,7 +104,7 @@ let fact_4 = factorial (5-1) ;; let sqr2 = sqr (-2) ;; (* Every function must have at least one argument. - Since some funcions naturally don't take any arguments, there's + Since some funcions naturally don't take any arguments, there's "unit" type for it that has the only one value written as "()" *) let print_hello () = print_endline "hello world" ;; @@ -144,11 +144,16 @@ x + y ;; (* Alternatively you can use "let ... and ... in" construct. This is especially useful for mutually recursive functions, with ordinary "let .. in" the compiler will complain about - unbound values. - It's hard to come up with a meaningful but self-contained - example of mutually recursive functions, but that syntax - works for non-recursive definitions too. *) -let a = 3 and b = 4 in a * b ;; + unbound values. *) +let rec + is_even = function + | 0 -> true + | n -> is_odd (n-1) +and + is_odd = function + | 0 -> false + | n -> is_even (n-1) +;; (* Anonymous functions use the following syntax: *) let my_lambda = fun x -> x * x ;; @@ -191,7 +196,7 @@ let (~/) x = 1.0 /. x ;; ~/4.0 (* = 0.25 *) -(*** Built-in datastructures ***) +(*** Built-in data structures ***) (* Lists are enclosed in square brackets, items are separated by semicolons. *) @@ -288,7 +293,7 @@ type int_list_list = int list_of_lists ;; (* Types can also be recursive. Like in this type analogous to built-in list of integers. *) type my_int_list = EmptyList | IntList of int * my_int_list ;; -let l = Cons (1, EmptyList) ;; +let l = IntList (1, EmptyList) ;; (*** Pattern matching ***) @@ -296,7 +301,7 @@ let l = Cons (1, EmptyList) ;; (* Pattern matching is somewhat similar to switch statement in imperative languages, but offers a lot more expressive power. - Even though it may look complicated, it really boils down to matching + Even though it may look complicated, it really boils down to matching an argument against an exact value, a predicate, or a type constructor. The type system is what makes it so powerful. *) @@ -315,7 +320,7 @@ let is_one = function ;; (* Matching predicates, aka "guarded pattern matching". *) -let abs x = +let abs x = match x with | x when x < 0 -> -x | _ -> x @@ -336,10 +341,10 @@ let say x = say (Cat "Fluffy") ;; (* "Fluffy says meow". *) -(** Traversing datastructures with pattern matching **) +(** Traversing data structures with pattern matching **) (* Recursive types can be traversed with pattern matching easily. - Let's see how we can traverse a datastructure of the built-in list type. + Let's see how we can traverse a data structure of the built-in list type. Even though the built-in cons ("::") looks like an infix operator, it's actually a type constructor and can be matched like any other. *) let rec sum_list l = diff --git a/perl.html.markdown b/perl.html.markdown index aac95939..1b86f410 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -12,16 +12,16 @@ Perl 5 is a highly capable, feature-rich programming language with over 25 years Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects. ```perl -# Single line comments start with a number symbol. +# Single line comments start with a number sign. #### Perl variable types -# Variables begin with the $ symbol. +# Variables begin with a sigil, which is a symbol showing the type. # A valid variable name starts with a letter or underscore, # followed by any number of letters, numbers, or underscores. -### Perl has three main variable types: scalars, arrays, and hashes. +### Perl has three main variable types: $scalar, @array, and %hash. ## Scalars # A scalar represents a single value: @@ -47,9 +47,9 @@ my %fruit_color = ("apple", "red", "banana", "yellow"); # You can use whitespace and the "=>" operator to lay them out more nicely: my %fruit_color = ( - apple => "red", - banana => "yellow", - ); + apple => "red", + banana => "yellow", +); # Scalars, arrays and hashes are documented more fully in perldata. # (perldoc perldata). @@ -60,17 +60,17 @@ my %fruit_color = ( # Perl has most of the usual conditional and looping constructs. -if ( $var ) { - ... -} elsif ( $var eq 'bar' ) { - ... +if ($var) { + ... +} elsif ($var eq 'bar') { + ... } else { - ... + ... } -unless ( condition ) { - ... - } +unless (condition) { + ... +} # This is provided as a more readable version of "if (!condition)" # the Perlish post-condition way @@ -78,20 +78,32 @@ print "Yow!" if $zippy; print "We have no bananas" unless $bananas; # while - while ( condition ) { - ... - } +while (condition) { + ... +} + +# for loops and iteration +for (my $i = 0; $i < $max; $i++) { + print "index is $i"; +} -# for and foreach -for ($i = 0; $i <= $max; $i++) { - ... - } +for (my $i = 0; $i < @elements; $i++) { + print "Current element is " . $elements[$i]; +} -foreach (@array) { - print "This element is $_\n"; - } +for my $element (@elements) { + print $element; +} +# implicitly + +for (@elements) { + print; +} + +# the Perlish post-condition way again +print for @elements; #### Regular expressions @@ -129,9 +141,11 @@ my @lines = <$in>; # Writing subroutines is easy: sub logger { - my $logmessage = shift; - open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; - print $logfile $logmessage; + my $logmessage = shift; + + open my $logfile, ">>", "my.log" or die "Could not open my.log: $!"; + + print $logfile $logmessage; } # Now we can use the subroutine just as any other built-in function: diff --git a/perl6.html.markdown b/perl6.html.markdown index b178de1e..3eec19f3 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1,17 +1,16 @@ --- -name: perl6 category: language language: perl6 filename: learnperl6.pl contributors: - - ["Nami-Doc", "http://github.com/Nami-Doc"] + - ["vendethiel", "http://github.com/vendethiel"] --- -Perl 6 is a highly capable, feature-rich programming language made for the -upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for at +least the next hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on +the JVM and [the MoarVM](http://moarvm.com). Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. @@ -35,7 +34,8 @@ my $variable; ## * Scalars. They represent a single value. They start with a `$` my $str = 'String'; -my $str2 = "String"; # double quotes allow for interpolation +# double quotes allow for interpolation (which we'll see later): +my $str2 = "String"; # variable names can contain but not end with simple quotes and dashes, # and can contain (and end with) underscores : @@ -66,23 +66,13 @@ my @keys = 0, 2; @array[@keys] = @letters; # Assign using an array say @array; #=> a 6 b -# There are two more kinds of lists: Parcel and Arrays. -# Parcels are immutable lists (you can't modify a list that's not assigned). -# This is a parcel: -(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error -# This is a list: -my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay! - -# Lists flatten (in list context). You'll see below how to apply item context -# or use arrays to have real nested lists. - - -## * Hashes. Key-Value Pairs. -# Hashes are actually arrays of Pairs (`Key => Value`), -# except they get "flattened", removing duplicated keys. +## * Hashes, or key-value Pairs. +# Hashes are actually arrays of Pairs +# (you can construct a Pair object using the syntax `Key => Value`), +# except they get "flattened" (hash context), removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys *can* get auto-quoted +my %hash = foo => "bar", # keys get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = <key1 value1 key2 value2>; # you can also create a hash @@ -103,7 +93,6 @@ say %hash<key2>; # If it's a string, you can actually use <> # (`{key1}` doesn't work, as Perl6 doesn't have barewords) ## * Subs (subroutines, or functions in most other languages). -# Stored in variable, they use `&`. sub say-hello { say "Hello, world" } sub say-hello-to(Str $name) { # You can provide the type of an argument @@ -112,34 +101,10 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument say "Hello, $name !"; } -# Since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello`. -my &s = &say-hello; -my &other-s = sub { say "Anonymous function !" } - -# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" -sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". - # Note: you can have parameters *before* (like here) - # a slurpy one, but not *after*. - say @rest.join(' / ') ~ " !"; -} -say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume - # the parameter before. - -## You can call a function with an array using the -# "argument list flattening" operator `|` -# (it's not actually the only role of this operator, but it's one of them) -sub concat3($a, $b, $c) { - say "$a, $b, $c"; -} -concat3(|@array); #=> a, b, c - # `@array` got "flattened" as a part of the argument list - ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` if I don't have an argument passed, - or I'll return my argument"; + say "I might return `(Any)` (Perl's "null"-like value) if I don't have + an argument passed, or I'll return my argument"; $arg; } with-optional; # returns Any @@ -154,30 +119,27 @@ hello-to; #=> Hello, World ! hello-to(); #=> Hello, World ! hello-to('You'); #=> Hello, You ! -## You can also, by using a syntax akin to the one of hashes (yay unification !), +## You can also, by using a syntax akin to the one of hashes (yay unified syntax !), ## pass *named* arguments to a `sub`. +# They're optional, and will default to "Any". sub with-named($normal-arg, :$named) { say $normal-arg + $named; } with-named(1, named => 6); #=> 7 # There's one gotcha to be aware of, here: # If you quote your key, Perl 6 won't be able to see it at compile time, -# and you'll have a single Pair object as a positional paramater. +# and you'll have a single Pair object as a positional parameter, +# which means this fails: +with-named(1, 'named' => 6); with-named(2, :named(5)); #=> 7 -with-named(3, :4named); #=> 7 - # (special colon pair syntax for numbers, - # to be used with s// and such, see later) - -with-named(3); # warns, because we tried to use the undefined $named in a `+`: - # by default, named arguments are *optional* # To make a named argument mandatory, you can use `?`'s inverse, `!` sub with-mandatory-named(:$str!) { say "$str !"; } with-mandatory-named(str => "My String"); #=> My String ! -with-mandatory-named; # run time error: "Required named parameter not passed" +with-mandatory-named; # run time error: "Required named parameter not passed" with-mandatory-named(3); # run time error: "Too many positional parameters passed" ## If a sub takes a named boolean argument ... @@ -187,22 +149,37 @@ sub takes-a-bool($name, :$bool) { # ... you can use the same "short boolean" hash syntax: takes-a-bool('config', :bool); # config takes True takes-a-bool('config', :!bool); # config takes False -# or you can use the "adverb" form: -takes-a-bool('config'):bool; #=> config takes True -takes-a-bool('config'):!bool; #=> config takes False -# You'll learn to love (or maybe hate, eh) that syntax later. - ## You can also provide your named arguments with defaults: sub named-def(:$def = 5) { say $def; } named-def; #=> 5 -named-def(:10def); #=> 10 named-def(def => 15); #=> 15 -# -- Note: we're going to learn *more* on subs really soon, -# but we need to grasp a few more things to understand their real power. Ready? +# Since you can omit parenthesis to call a function with no arguments, +# you need "&" in the name to store `say-hello` in a variable. +my &s = &say-hello; +my &other-s = sub { say "Anonymous function !" } + +# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many" +sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else". + # Note: you can have parameters *before* (like here) + # a slurpy one, but not *after*. + say @rest.join(' / ') ~ " !"; +} +say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! + # Note that the splat (the *) did not + # consume the parameter before. + +## You can call a function with an array using the +# "argument list flattening" operator `|` +# (it's not actually the only role of this operator, but it's one of them) +sub concat3($a, $b, $c) { + say "$a, $b, $c"; +} +concat3(|@array); #=> a, b, c + # `@array` got "flattened" as a part of the argument list ### Containers # In Perl 6, values are actually stored in "containers". @@ -216,27 +193,23 @@ sub mutate($n is rw) { say "\$n is now $n !"; } -# If what you want is a copy instead, use `is copy`. +# If what you want a copy instead, use `is copy`. # A sub itself returns a container, which means it can be marked as rw: my $x = 42; -sub mod() is rw { $x } -mod() = 52; # in this case, the parentheses are mandatory - # (else Perl 6 thinks `mod` is a "term") +sub x-store() is rw { $x } +x-store() = 52; # in this case, the parentheses are mandatory + # (else Perl 6 thinks `x-store` is an identifier) say $x; #=> 52 ### Control Flow Structures - -# You don't need to put parenthesis around the condition, -# but that also means you always have to use brackets (`{ }`) for their body: - ## Conditionals # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { @@ -247,30 +220,40 @@ unless False { say "It's not false !"; } +# As you can see, you don't need parentheses around conditions. +# However, you do need the brackets around the "body" block: +# if (true) say; # This doesn't work ! + # You can also use their postfix versions, with the keyword after: say "Quite truthy" if True; -# if (true) say; # This doesn't work ! - # - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages) my $a = $condition ?? $value-if-true !! $value-if-false; -# - `given`-`when` looks like other languages `switch`, but much more +# - `given`-`when` looks like other languages' `switch`, but much more # powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_. +# # This variable contains the default argument of a block, # a loop's current iteration (unless explicitly named), etc. +# # `given` simply puts its argument into `$_` (like a block would do), # and `when` compares it using the "smart matching" (`~~`) operator. +# # Since other Perl 6 constructs use this variable (as said before, like `for`, # blocks, etc), this means the powerful `when` is not only applicable along with # a `given`, but instead anywhere a `$_` exists. given "foo bar" { - when /foo/ { # Don't worry about smart matching -- just know `when` uses it. + say $_; #=> foo bar + when /foo/ { # Don't worry about smart matching yet – just know `when` uses it. # This is equivalent to `if $_ ~~ /foo/`. say "Yay !"; } when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True, # so you can also put "normal" conditionals. + # This when is equivalent to this `if`: + # if $_ ~~ ($_.chars > 50) {...} + # Which means: + # if $_.chars > 50 {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) @@ -281,7 +264,7 @@ given "foo bar" { ## Looping constructs # - `loop` is an infinite loop if you don't pass it arguments, -# but can also be a c-style `for`: +# but can also be a C-style `for` loop: loop { say "This is an infinite loop !"; last; # last breaks out of the loop, like the `break` keyword in other languages @@ -296,14 +279,14 @@ loop (my $i = 0; $i < 5; $i++) { # - `for` - Passes through an array for @array -> $variable { - say "I've found $variable !"; + say "I've got $variable !"; } # As we saw with given, for's default "current iteration" variable is `$_`. -# That means you can use `when` in a `for` just like you were in a when. +# That means you can use `when` in a `for` just like you were in a `given`. for @array { say "I've got $_"; - + .say; # This is also allowed. # A dot call with no "topic" (receiver) is sent to `$_` by default $_.say; # the above and this are equivalent. @@ -316,45 +299,15 @@ for @array { last if $_ == 5; # Or break out of a loop (like `break` in C-like languages). } -# Note - the "lambda" `->` syntax isn't reserved to `for`: +# The "pointy block" syntax isn't specific to for. +# It's just a way to express a block in Perl6. if long-computation() -> $result { say "The result is $result"; } -## Loops can also have a label, and be jumped to through these. -OUTER: while 1 { - say "hey"; - while 1 { - OUTER.last; # All the control keywords must be called on the label itself - } -} - -# Now that you've seen how to traverse a list, you need to be aware of something: -# List context (@) flattens. If you traverse nested lists, you'll actually be traversing a -# shallow list (except if some sub-list were put in item context ($)). -for 1, 2, (3, (4, ((5)))) { - say "Got $_."; -} #=> Got 1. Got 2. Got 3. Got 4. Got 5. - -# ... However: (forcing item context with `$`) -for 1, 2, $(3, 4) { - say "Got $_."; -} #=> Got 1. Got 2. Got 3 4. - -# Note that the last one actually joined 3 and 4. -# While `$(...)` will apply item to context to just about anything, you can also create -# an array using `[]`: -for [1, 2, 3, 4] { - say "Got $_."; -} #=> Got 1 2 3 4. - -# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array -# whereas `$()` will return a Parcel when given a Parcel. - - ### Operators -## Since Perl languages are very much operator-based languages +## Since Perl languages are very much operator-based languages, ## Perl 6 operators are actually just funny-looking subroutines, in syntactic ## categories, like infix:<+> (addition) or prefix:<!> (bool not). @@ -394,9 +347,6 @@ $arg ~~ &bool-returning-function; # `True` if the function, passed `$arg` 1 ~~ True; # smart-matching against a boolean always returns that boolean # (and will warn). -# - `===` is value identity and uses `.WHICH` on the objects to compare them -# - `=:=` is container identity and uses `VAR()` on the objects to compare them - # You also, of course, have `<`, `<=`, `>`, `>=`. # Their string equivalent are also avaiable : `lt`, `le`, `gt`, `ge`. 3 > 4; @@ -416,17 +366,25 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !) # Note : when reading an infinite list, Perl 6 will "reify" the elements # it needs, then keep them in memory. They won't be calculated more than once. - -# Warning, though: if you try this example in the REPL and just put `1..*`, -# Perl 6 will be forced to try and evaluate the whole array (to print it), -# so you'll end with an infinite loop. +# It also will never calculate more elements that are needed. + +# An array subscript can also be a closure. +# It'll be called with the length as the argument +say join(' ', @array[15..*]); #=> 15 16 17 18 19 +# which is equivalent to: +say join(' ', @array[-> $n { 15..$n }]); +# Note: if you try to do either of those with an infinite loop, +# you'll trigger an infinite loop (your program won't finish) # You can use that in most places you'd expect, even assigning to an array my @numbers = ^20; -@numbers[5..*] = 3, 9 ... * > 90; # The right hand side could be infinite as well. - # (but not both, as this would be an infinite loop) -say @numbers; #=> 3 9 15 21 27 [...] 81 87 +# Here numbers increase by "6"; more on `...` operator later. +my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99; +@numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, + # only the 15 needed values will be calculated. +say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87 + # (only 20 values) ## * And, Or 3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`. @@ -438,7 +396,7 @@ $a && $b && $c; # Returns the first argument that evaluates to False, $a || $b; # And because you're going to want them, -# you also have composed assignment operators: +# you also have compound assignment operators: $a *= 2; # multiply and assignment $b %%= 5; # divisible by and assignment @array .= sort; # calls the `sort` method and assigns the result back @@ -448,7 +406,7 @@ $b %%= 5; # divisible by and assignment # a few more key concepts that make them better than in any other language :-). ## Unpacking ! -# It's the ability to "extract" arrays and keys. +# It's the ability to "extract" arrays and keys (AKA "destructuring"). # It'll work in `my`s and in parameter lists. my ($a, $b) = 1, 2; say $a; #=> 1 @@ -559,6 +517,21 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` +## About types... +# Perl6 is gradually typed. This means you can specify the type +# of your variables/arguments/return types, or you can omit them +# and they'll default to "Any". +# You obviously get access to a few base types, like Int and Str. +# The constructs for declaring types are "class", "role", +# which you'll see later. + +# For now, let us examine "subset": +# a "subset" is a "sub-type" with additional checks. +# For example: "a very big integer is an Int that's greater than 500" +# You can specify the type you're subtyping (by default, Any), +# and add additional checks with the "where" keyword: +subset VeryBigInteger of Int where * > 500; + ## Multiple Dispatch # Perl 6 can decide which variant of a `sub` to call based on the type of the # arguments, or on arbitrary preconditions, like with a type or a `where`: @@ -567,20 +540,19 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # the `sub` is the default +multi sayit(Str $s) { # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" sayit(True); # fails at *compile time* with # "calling 'sayit' will never work with arguments of types ..." -# with arbitrary precondition: +# with arbitrary precondition (remember subsets?): multi is-big(Int $n where * > 50) { "Yes !" } # using a closure multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching # (could use a regexp, etc) multi is-big(Int $) { "No" } -# You can also name these checks, by creating "subsets": subset Even of Int where * %% 2; multi odd-or-even(Even) { "Even" } # The main case using the type. @@ -636,40 +608,39 @@ sub foo { bar(); # call `bar` in-place } sub bar { - say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, + say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s, # even though the blocks aren't nested (they're call-nested). #=> 1 } ### Object Model -## Perl 6 has a quite comprehensive object model # You declare a class with the keyword `class`, fields with `has`, -# methods with `method`. Every field to private, and is named `$!attr`, -# but you have `$.` to get a public (immutable) accessor along with it. -# (using `$.` is like using `$!` plus a `method` with the same name) +# methods with `method`. Every attribute that is private is named `$!attr`. +# Immutable public attributes are named `$.attr` +# (you can make them mutable with `is rw`) -# (Perl 6's object model ("SixModel") is very flexible, +# Perl 6's object model ("SixModel") is very flexible, # and allows you to dynamically add methods, change semantics, etc ... # (this will not be covered here, and you should refer to the Synopsis). class A { has $.field; # `$.field` is immutable. # From inside the class, use `$!field` to modify it. - has $.other-field is rw; # You can obviously mark a public field `rw`. + has $.other-field is rw; # You can mark a public attribute `rw`. has Int $!private-field = 10; method get-value { - $.field + $!private-field + $n; + $.field + $!private-field; } - + method set-value($n) { # $.field = $n; # As stated before, you can't use the `$.` immutable version. $!field = $n; # This works, because `$!` is always mutable. - + $.other-field = 5; # This works, because `$.other-field` is `rw`. } - + method !private-method { say "This method is private to the class !"; } @@ -678,29 +649,28 @@ class A { # Create a new instance of A with $.field set to 5 : # Note: you can't set private-field from here (more later on). my $a = A.new(field => 5); -$a.get-value; #=> 18 +$a.get-value; #=> 15 #$a.field = 5; # This fails, because the `has $.field` is immutable $a.other-field = 10; # This, however, works, because the public field # is mutable (`rw`). ## Perl 6 also has inheritance (along with multiple inheritance) -# (though considered a misfeature by many) class A { has $.val; - + submethod not-inherited { say "This method won't be available on B."; say "This is most useful for BUILD, which we'll see later"; } - + method bar { $.val * 5 } } class B is A { # inheritance uses `is` method foo { say $.val; } - + method bar { $.val * 10 } # this shadows A's `bar` } @@ -724,23 +694,23 @@ role PrintableVal { } } -# you "use" a mixin with "does" : +# you "import" a mixin (a "role") with "does": class Item does PrintableVal { has $.val; - + # When `does`-ed, a `role` literally "mixes in" the class: # the methods and fields are put together, which means a class can access # the private fields/methods of its roles (but not the inverse !): method access { say $!counter++; } - + # However, this: # method print {} # is ONLY valid when `print` isn't a `multi` with the same dispatch. # (this means a parent class can shadow a child class's `multi print() {}`, # but it's an error if a role does) - + # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods # will be shadowed, since the compiler will consider `ROLE` to be a class. } @@ -779,7 +749,7 @@ fail "foo"; # We're not trying to access the value, so no problem. try { fail "foo"; CATCH { - default { say "It threw because we try to get the fail's value!" } + default { say "It threw because we tried to get the fail's value!" } } } @@ -791,25 +761,21 @@ try { ### Packages # Packages are a way to reuse code. Packages are like "namespaces", and any # element of the six model (`module`, `role`, `class`, `grammar`, `subset` -# and `enum`) are actually packages. (Packages are the lowest common denomitor) +# and `enum`) are actually packages. (Packages are the lowest common denominator) # Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. -# You usually don't use packages directly: you use `class Package::Name::Here;`, -# or if you only want to export variables/subs, you can use `module`: +# You're not supposed to use the package keyword, usually: +# you use `class Package::Name::Here;` to declare a class, +# or if you only want to export variables/subs, you can use `module`: module Hello::World { # Bracketed form # If `Hello` doesn't exist yet, it'll just be a "stub", # that can be redeclared as something else later. # ... declarations here ... } -module Parse::Text; # file-scoped form +unit module Parse::Text; # file-scoped form grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } -# NOTE for Perl 5 users: even though the `package` keyword exists, -# the braceless form is invalid (to catch a "perl5ism"). This will error out: -# package Foo; # because Perl 6 will think the entire file is Perl 5 -# Just use `module` or the brace version of `package`. - # You can use a module (bring its declarations into scope) with `use` use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module say from-json('[1]').perl; #=> [1] @@ -825,10 +791,8 @@ my $actions = JSON::Tiny::Actions.new; # You've already seen `my` and `has`, we'll now explore the others. ## * `our` (happens at `INIT` time -- see "Phasers" below) -# Along with `my`, there are several others declarators you can use. -# The first one you'll want for the previous part is `our`. +# It's like `my`, but it also creates a package variable. # (All packagish things (`class`, `role`, etc) are `our` by default) -# it's like `my`, but it also creates a package variable: module Foo::Bar { our $n = 1; # note: you can't put a type constraint on an `our` variable our sub inc { @@ -840,7 +804,7 @@ module Foo::Bar { say "Can't access me from outside, I'm my !"; } } - + say ++$n; # lexically-scoped variables are still available } say $Foo::Bar::n; #=> 1 @@ -857,7 +821,7 @@ constant why-not = 5, 15 ... *; say why-not[^5]; #=> 5 15 25 35 45 ## * `state` (happens at run time, but only once) -# State variables are only executed one time +# State variables are only initialized one time # (they exist in other langages such as C as `static`) sub fixed-rand { state $val = rand; @@ -890,7 +854,7 @@ for ^5 -> $a { ## * Compile-time phasers BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } -CHECK { say "[*] Runs at compile time, instead as late as possible, only once" } +CHECK { say "[*] Runs at compile time, as late as possible, only once" } ## * Run-time phasers INIT { say "[*] Runs at run time, as soon as possible, only once" } @@ -898,10 +862,21 @@ END { say "Runs at run time, as late as possible, only once" } ## * Block phasers ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } -LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." } +LEAVE { say "Runs everytime you leave a block, even when an exception + happened. Repeats on loop blocks." } + +PRE { say "Asserts a precondition at every block entry, + before ENTER (especially useful for loops)" } +# exemple: +for 0..2 { + PRE { $_ > 1 } # This is going to blow up with "Precondition failed" +} -PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } -POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } +POST { say "Asserts a postcondition at every block exit, + after LEAVE (especially useful for loops)" } +for 0..2 { + POST { $_ < 2 } # This is going to blow up with "Postcondition failed" +} ## * Block/exceptions phasers sub { @@ -919,12 +894,12 @@ for ^5 { ## * Role/class phasers COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" } -# They allow for cute trick or clever code ...: -say "This code took " ~ (time - CHECK time) ~ "s to run"; +# They allow for cute tricks or clever code ...: +say "This code took " ~ (time - CHECK time) ~ "s to compile"; # ... or clever organization: sub do-db-stuff { - ENTER $db.start-transaction; # New transaction everytime we enter the sub + $db.start-transaction; # start a new transaction KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } @@ -971,7 +946,7 @@ say join ',', gather if False { # But consider: constant thrice = gather for ^3 { say take $_ }; # Doesn't print anything # versus: -constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 3 4 +constant thrice = eager gather for ^3 { say take $_ }; #=> 0 1 2 # - `lazy` - Defer actual evaluation until value is fetched (forces lazy context) # Not yet implemented !! @@ -1048,7 +1023,7 @@ sub circumfix:<[ ]>(Int $n) { $n ** $n } say [5]; #=> 3125 - # circumfix is around. Again, not whitespace. + # circumfix is around. Again, no whitespace. sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is @@ -1072,7 +1047,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # *everything* -- with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep +# Oh boy, get ready. Get ready, because we're delving deep # into the rabbit's hole, and you probably won't want to go # back to other languages after reading that. # (I'm guessing you don't want to already at that point). @@ -1080,12 +1055,10 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # Basically, they're operators that apply another operator. ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and +# It's a prefix meta-operator that takes a binary function and # one or many lists. If it doesn't get passed any argument, -# it either return a "default value" for this operator -# (a value that wouldn't change the result if passed as one -# of the element of the list to be passed to the operator), -# or `Any` if there's none (examples below). +# it either returns a "default value" for this operator +# (a meaningless value) or `Any` if there's none (examples below). # # Otherwise, it pops an element from the list(s) one at a time, and applies # the binary function to the last result (or the list's first element) @@ -1105,11 +1078,9 @@ say [//] Nil, Any, False, 1, 5; #=> False # Default value examples: -say [*] (); #=> 1 -say [+] (); #=> 0 - # In both cases, they're results that, were they in the lists, - # wouldn't have any impact on the final value - # (since N*1=N and N+0=N). +say [*] (); #=> 1 +say [+] (); #=> 0 + # meaningless values, since N*1=N and N+0=N. say [//]; #=> (Any) # There's no "default value" for `//`. @@ -1121,7 +1092,7 @@ say [[&add]] 1, 2, 3; #=> 6 # This one is an infix meta-operator than also can be used as a "normal" operator. # It takes an optional binary function (by default, it just creates a pair), # and will pop one value off of each array and call its binary function on these -# until it runs out of elements. It runs the an array with all these new elements. +# until it runs out of elements. It returns an array with all of these new elements. (1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array 1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function @@ -1141,8 +1112,7 @@ say [[&add]] 1, 2, 3; #=> 6 # (and might include a closure), and on the right, a value or the predicate # that says when to stop (or Whatever for a lazy infinite list). my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, - # because Perl 6 can't figure out the end +#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element # (the iteration when the predicate matches). my @list = 1, 3, 9 ... * > 30; # you can use a predicate @@ -1163,90 +1133,6 @@ say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # That's why `@primes[^100]` will take a long time the first time you print # it, then be instant. - -## * Sort comparison -# They return one value of the `Order` enum : `Less`, `Same` and `More` -# (which numerify to -1, 0 or +1). -1 <=> 4; # sort comparison for numerics -'a' leg 'b'; # sort comparison for string -$obj eqv $obj2; # sort comparison using eqv semantics - -## * Generic ordering -3 before 4; # True -'b' after 'a'; # True - -## * Short-circuit default operator -# Like `or` and `||`, but instead returns the first *defined* value : -say Any // Nil // 0 // 5; #=> 0 - -## * Short-circuit exclusive or (XOR) -# Returns `True` if one (and only one) of its arguments is true -say True ^^ False; #=> True - -## * Flip Flop -# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). -# are operators that take two predicates to test: -# They are `False` until their left side returns `True`, then are `True` until -# their right side returns `True`. -# Like for ranges, you can exclude the iteration when it became `True`/`False` -# by using `^` on either side. -# Let's start with an example : -for <well met young hero we shall meet later> { - # by default, `ff`/`fff` smart-match (`~~`) against `$_`: - if 'met' ^ff 'meet' { # Won't enter the if for "met" - # (explained in details below). - .say - } - - if rand == 0 ff rand == 1 { # compare variables other than `$_` - say "This ... probably will never run ..."; - } -} -# This will print "young hero we shall meet" (excluding "met"): -# the flip-flop will start returning `True` when it first encounters "met" -# (but will still return `False` for "met" itself, due to the leading `^` -# on `ff`), until it sees "meet", which is when it'll start returning `False`. - -# The difference between `ff` (awk-style) and `fff` (sed-style) is that -# `ff` will test its right side right when its left side changes to `True`, -# and can get back to `False` right away -# (*except* it'll be `True` for the iteration that matched) - -# While `fff` will wait for the next iteration to -# try its right side, once its left side changed: -.say if 'B' ff 'B' for <A B C B A>; #=> B B - # because the right-hand-side was tested - # directly (and returned `True`). - # "B"s are printed since it matched that time - # (it just went back to `False` right away). -.say if 'B' fff 'B' for <A B C B A>; #=> B C B - # The right-hand-side wasn't tested until - # `$_` became "C" - # (and thus did not match instantly). - -# A flip-flop can change state as many times as needed: -for <test start print it stop not printing start print again stop not anymore> { - .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", - #=> "print this printing again" -} - -# you might also use a Whatever Star, -# which is equivalent to `True` for the left side or `False` for the right: -for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here - # (sometimes called "superstitious parentheses") - .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, - # it'll never go back to `False` - #=> 60 3 40 60 -} - -# You can also use this property to create an `If` -# that'll not go through the first time : -for <a b c> { - .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, - # but the `^` makes it *not run* on the first iteration - #=> b c -} - - ### Regular Expressions # I'm sure a lot of you have been waiting for this one. # Well, now that you know a good deal of Perl 6 already, we can get started. @@ -1338,7 +1224,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) # they use a more perl6-ish syntax: say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa' # You can use ranges: -say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou' +say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae' # Just like in normal regexes, if you want to use a special character, escape it # (the last one is escaping a space) say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !' @@ -1358,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left # Group: you can group parts of your regexp with `[]`. # These groups are *not* captured (like PCRE's `(?:)`). so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing -so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; +so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /; # The previous line returns `True`. -# We match the "abc" 1 or more time (the `+` was applied to the group). +# We match the "012" 1 or more time (the `+` was applied to the group). # But this does not go far enough, because we can't actually get back what # we matched. # Capture: We can actually *capture* the results of the regexp, using parentheses. -so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below) +so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below) # So, starting with the grouping explanations. # As we said before, our `Match` object is available as `$/`: @@ -1403,10 +1289,12 @@ say $/[0][0].Str; #=> ~ # This stems from a very simple fact: `$/` does not contain strings, integers or arrays, # it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods. -# (but you can also just use `match<key>` for hash access and `match[idx]` for array access) +# (but you can also just use `match<key>` for hash access +# and `match[idx]` for array access) say $/[0].list.perl; #=> (Match.new(...),).list - # We can see it's a list of Match objects. Those contain a bunch of infos: - # where the match started/ended, the "ast" (see actions later), etc. + # We can see it's a list of Match objects. Those contain + # a bunch of infos: where the match started/ended, + # the "ast" (see actions later), etc. # You'll see named capture below with grammars. ## Alternatives - the `or` of regexps @@ -1444,14 +1332,14 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. -# It's very powerful, because Perl 6 actually parses the argument +# It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) # and will even go as far as to autogenerate a `--help` sub MAIN($name) { say "Hello, $name !" } # This produces: # $ perl6 cli.pl # Usage: -# t.pl <name> +# t.pl <name> # And since it's a regular Perl 6 sub, you can haz multi-dispatch: # (using a "Bool" for the named argument so that we can do `--replace` @@ -1462,14 +1350,113 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... } multi MAIN('remove', $key) { ... } multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # This produces: -# $ perl 6 cli.pl +# $ perl6 cli.pl # Usage: -# t.pl [--replace] add <key> <value> +# t.pl [--replace] add <key> <value> # t.pl remove <key> # t.pl [--as=<Str>] import (File) # As you can see, this is *very* powerful. # It even went as far as to show inline the constants. # (the type is only displayed if the argument is `$`/is named) + +### +### APPENDIX A: +### +### List of things +### + +# It's considered by now you know the Perl6 basics. +# This section is just here to list some common operations, +# but which are not in the "main part" of the tutorial to bloat it up + +## Operators + + +## * Sort comparison +# They return one value of the `Order` enum : `Less`, `Same` and `More` +# (which numerify to -1, 0 or +1). +1 <=> 4; # sort comparison for numerics +'a' leg 'b'; # sort comparison for string +$obj eqv $obj2; # sort comparison using eqv semantics + +## * Generic ordering +3 before 4; # True +'b' after 'a'; # True + +## * Short-circuit default operator +# Like `or` and `||`, but instead returns the first *defined* value : +say Any // Nil // 0 // 5; #=> 0 + +## * Short-circuit exclusive or (XOR) +# Returns `True` if one (and only one) of its arguments is true +say True ^^ False; #=> True +## * Flip Flop +# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`). +# are operators that take two predicates to test: +# They are `False` until their left side returns `True`, then are `True` until +# their right side returns `True`. +# Like for ranges, you can exclude the iteration when it became `True`/`False` +# by using `^` on either side. +# Let's start with an example : +for <well met young hero we shall meet later> { + # by default, `ff`/`fff` smart-match (`~~`) against `$_`: + if 'met' ^ff 'meet' { # Won't enter the if for "met" + # (explained in details below). + .say + } + + if rand == 0 ff rand == 1 { # compare variables other than `$_` + say "This ... probably will never run ..."; + } +} +# This will print "young hero we shall meet" (excluding "met"): +# the flip-flop will start returning `True` when it first encounters "met" +# (but will still return `False` for "met" itself, due to the leading `^` +# on `ff`), until it sees "meet", which is when it'll start returning `False`. + +# The difference between `ff` (awk-style) and `fff` (sed-style) is that +# `ff` will test its right side right when its left side changes to `True`, +# and can get back to `False` right away +# (*except* it'll be `True` for the iteration that matched) - +# While `fff` will wait for the next iteration to +# try its right side, once its left side changed: +.say if 'B' ff 'B' for <A B C B A>; #=> B B + # because the right-hand-side was tested + # directly (and returned `True`). + # "B"s are printed since it matched that time + # (it just went back to `False` right away). +.say if 'B' fff 'B' for <A B C B A>; #=> B C B + # The right-hand-side wasn't tested until + # `$_` became "C" + # (and thus did not match instantly). + +# A flip-flop can change state as many times as needed: +for <test start print it stop not printing start print again stop not anymore> { + .say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop", + #=> "print it print again" +} + +# you might also use a Whatever Star, +# which is equivalent to `True` for the left side or `False` for the right: +for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here + # (sometimes called "superstitious parentheses") + .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, + # it'll never go back to `False` + #=> 60 3 40 60 +} + +# You can also use this property to create an `If` +# that'll not go through the first time : +for <a b c> { + .say if * ^ff *; # the flip-flop is `True` and never goes back to `False`, + # but the `^` makes it *not run* on the first iteration + #=> b c +} + + +# - `===` is value identity and uses `.WHICH` on the objects to compare them +# - `=:=` is container identity and uses `VAR()` on the objects to compare them + ``` If you want to go further, you can: @@ -1477,5 +1464,4 @@ If you want to go further, you can: - Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such. - Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful. - Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize). - - Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting. - + - Read [the language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting. diff --git a/php.html.markdown b/php.html.markdown index 039288a0..0504ced2 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -12,7 +12,7 @@ This document describes PHP 5+. <?php // PHP code must be enclosed with <?php tags // If your php file only contains PHP code, it is best practice -// to omit the php closing tag. +// to omit the php closing tag to prevent accidental output. // Two forward slashes start a one-line comment. @@ -60,7 +60,7 @@ $float = 1.2e3; $float = 7E-10; // Delete variable -unset($int1) +unset($int1); // Arithmetic $sum = 1 + 1; // 2 @@ -103,6 +103,9 @@ END; // String concatenation is done with . echo 'This string ' . 'is concatenated'; +// Strings can be passed in as parameters to echo +echo 'Multiple', 'Parameters', 'Valid'; // Returns 'MultipleParametersValid' + /******************************** * Constants @@ -115,8 +118,10 @@ echo 'This string ' . 'is concatenated'; // followed by any number of letters, numbers, or underscores. define("FOO", "something"); -// access to a constant is possible by direct using the choosen name -echo 'This outputs '.FOO; +// access to a constant is possible by calling the choosen name without a $ +echo FOO; // Returns 'something' +echo 'This outputs '.FOO; // Returns 'This ouputs something' + /******************************** @@ -141,6 +146,8 @@ echo $array[0]; // => "One" // Add an element to the end of an array $array[] = 'Four'; +// or +array_push($array, 'Five'); // Remove element from array unset($array[3]); @@ -155,9 +162,9 @@ echo('Hello World!'); print('Hello World!'); // The same as echo -// echo is actually a language construct, so you can drop the parentheses. +// echo and print are language constructs too, so you can drop the parentheses echo 'Hello World!'; -print 'Hello World!'; // So is print +print 'Hello World!'; $paragraph = 'paragraph'; @@ -215,6 +222,18 @@ assert($a !== $d); assert(1 === '1'); assert(1 !== '1'); +// 'Spaceship' operator (since PHP 7) +// Returns 0 if values on either side are equal +// Returns 1 if value on the left is greater +// Returns -1 if the value on the right is greater + +$a = 100; +$b = 1000; + +echo $a <=> $a; // 0 since they are equal +echo $a <=> $b; // -1 since $a < $b +echo $b <=> $a; // 1 since $b > $a + // Variables can be converted between types, depending on their usage. $integer = 1; @@ -264,6 +283,18 @@ if (false) { // ternary operator print (false ? 'Does not get printed' : 'Does'); +// ternary shortcut operator since PHP 5.3 +// equivalent of "$x ? $x : 'Does'"" +$x = false; +print($x ?: 'Does'); + +// null coalesce operator since php 7 +$a = null; +$b = 'Does print'; +echo $a ?? 'a is not set'; // prints 'a is not set' +echo $b ?? 'b is not set'; // prints 'Does print' + + $x = 0; if ($x === '0') { print 'Does not print'; @@ -359,7 +390,7 @@ for ($i = 0; $i < 5; $i++) { // Define a function with "function": function my_function () { - return 'Hello'; + return 'Hello'; } echo my_function(); // => "Hello" @@ -368,8 +399,8 @@ echo my_function(); // => "Hello" // number of letters, numbers, or underscores. function add ($x, $y = 1) { // $y is optional and defaults to 1 - $result = $x + $y; - return $result; + $result = $x + $y; + return $result; } echo add(4); // => 5 @@ -380,21 +411,21 @@ echo add(4, 2); // => 6 // Since PHP 5.3 you can declare anonymous functions; $inc = function ($x) { - return $x + 1; + return $x + 1; }; echo $inc(2); // => 3 function foo ($x, $y, $z) { - echo "$x - $y - $z"; + echo "$x - $y - $z"; } // Functions can return functions function bar ($x, $y) { - // Use 'use' to bring in outside variables - return function ($z) use ($x, $y) { - foo($x, $y, $z); - }; + // Use 'use' to bring in outside variables + return function ($z) use ($x, $y) { + foo($x, $y, $z); + }; } $bar = bar('A', 'B'); @@ -406,6 +437,31 @@ echo $function_name(1, 2); // => 3 // Useful for programatically determining which function to run. // Or, use call_user_func(callable $callback [, $parameter [, ... ]]); + +// You can get the all the parameters passed to a function +function parameters() { + $numargs = func_num_args(); + if ($numargs > 0) { + echo func_get_arg(0) . ' | '; + } + $args_array = func_get_args(); + foreach ($args_array as $key => $arg) { + echo $key . ' - ' . $arg . ' | '; + } +} + +parameters('Hello', 'World'); // Hello | 0 - Hello | 1 - World | + +// Since PHP 5.6 you can get a variable number of arguments +function variable($word, ...$list) { + echo $word . " || "; + foreach ($list as $item) { + echo $item . ' | '; + } +} + +variable("Separate", "Hello", "World") // Separate || Hello | World | + /******************************** * Includes */ @@ -487,7 +543,7 @@ class MyClass * Declaring class properties or methods as static makes them accessible without * needing an instantiation of the class. A property declared as static can not * be accessed with an instantiated class object (though a static method can). -*/ + */ public static function myStaticMethod() { @@ -495,7 +551,9 @@ class MyClass } } +// Class constants can always be accessed statically echo MyClass::MY_CONST; // Outputs 'value'; + echo MyClass::$staticVar; // Outputs 'static'; MyClass::myStaticMethod(); // Outputs 'I am static'; @@ -671,8 +729,80 @@ use My\Namespace as SomeOtherNamespace; $cls = new SomeOtherNamespace\MyClass(); + +/********************** +* Late Static Binding +* */ +class ParentClass { + public static function who() { + echo "I'm a " . __CLASS__ . "\n"; + } + public static function test() { + // self references the class the method is defined within + self::who(); + // static references the class the method was invoked on + static::who(); + } +} + +ParentClass::test(); +/* +I'm a ParentClass +I'm a ParentClass +*/ + +class ChildClass extends ParentClass { + public static function who() { + echo "But I'm " . __CLASS__ . "\n"; + } +} + +ChildClass::test(); +/* +I'm a ParentClass +But I'm ChildClass +*/ + + +/********************** +* Error Handling +* +*/ + +// Simple error handling can be done with try catch block + +try { + // Do something +} catch (Exception $e) { + // Handle exception +} + +// When using try catch blocks in a namespaced enviroment use the following + +try { + // Do something +} catch (\Exception $e) { + // Handle exception +} + +// Custom exceptions + +class MyException extends Exception {} + +try { + + $condition = true; + + if ($condition) { + throw new MyException('Something just happend'); + } + +} catch (MyException $e) { + // Handle my exception +} + ``` ## More Information diff --git a/pl-pl/brainfuck-pl.html.markdown b/pl-pl/brainfuck-pl.html.markdown new file mode 100644 index 00000000..69d814c4 --- /dev/null +++ b/pl-pl/brainfuck-pl.html.markdown @@ -0,0 +1,93 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Jakub Młokosiewicz", "https://github.com/hckr"] +lang: pl-pl +--- + +Brainfuck (pisane małymi literami, za wyjątkiem początku zdania) jest bardzo +minimalistycznym, kompletnym w sensie Turinga, językiem programowania. +Zawiera zaledwie 8 poleceń. + +Możesz przetesotwać brainfucka w swojej przeglądarce, korzystając z narzędzia +[brainfuck-visualizer](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Wszystkie znaki oprócz "><+-.,[]" (wyłączając znaki zapytania) są ignorowane. + +Pamięć w brainfucku jest reprezentowana przez tablicę 30.000 komórek +zainicjalizowanych zerami, ze wskaźnikiem pokazującym na aktualną komórkę. + +Oto osiem poleceń brainfucka: ++ : inkrementuje (zwiększa o jeden) wartość aktualnie wskazywanej komórki +- : dekrementuje (zmniejsza o jeden) wartość aktualnie wskazywanej komórki +> : przesuwa wskaźnik na następną komórkę (w prawo) +< : przesuwa wskaźnik na poprzednią komórkę (w lewo) +. : wyświetla wartość bieżącej komórki (w formie znaku ASCII, np. 65 = 'A') +, : wczytuje (jeden) znak z wejścia do bieżącej komórki + (konkretnie jego numer z tabeli ASCII) +[ : jeśli wartość w bieżącej komórce jest rózna zero, przechodzi do + odpowiadającego ]; w przeciwnym wypdaku przechodzi do następnej instrukcji +] : Jeśli wartość w bieżącej komórce jest rózna od zera, przechodzi do + następnej instrukcji; w przeciwnym wypdaku przechodzi do odpowiadającego [ + +[ i ] oznaczają pętlę while. Oczywiście każda pętla rozpoczęta [ +musi być zakończona ]. + +Zobaczmy kilka prostych programów w brainfucku. + + +++++++ [ > ++++++++++ < - ] > +++++ . + +Ten program wypisuje literę 'A'. Najpierw zwiększa wartość komórki #1 do 6. +Komórka #1 będzie wykorzystana w pętli. Następnie program wchodzi w pętlę ([) +i przechodzi do komórki #2. Pętla wykonuje się sześć razy (komórka #1 jest +dekrementowana sześć razy, nim osiągnie wartość zero, kiedy to program +przechodzi do odpowiadającego ] i wykonuje kolejne instrukcje). + +W tym momencie wskaźnik pokazuje na komórkę #1, mającą wartość 0, podczas gdy +komórka #2 ma wartość 60. Przesuwamy wskaźnik na komórkę #2, inkrementujemy ją +pięć razy, uzyskując wartość 65. Następnie wyświetlamy wartość komórki #2. +65 to 'A' w tabeli ASCII, więc właśnie ten znak jest wypisany na konsolę. + + +, [ > + < - ] > . + +Ten program wczytuje znak z wejścia i umieszcza jego kod ASCII w komórce #1. +Następnie zaczyna się pętla, w której znajdują się następujące instrukcje: +przesunięcie wskaźnika na komórkę #2, inkrementacja wartości komóri #2, +powrót do komórki #1 i dekrementacja wartości komórki #1. Instrukcje pętli +wykonują się aż wartość komórki #1 osiągnie zero, a komórka #2 osiągnie +poprednią wartość komórki #1. Ponieważ na końcu pętli wskaźnik pokazuje na +komórkę #1, po pętli następuje instrukcja przejścia do komórki #2 i wysłanie +jej wartości (w formie znaku ASCII) na wyjście. + +Zauważ, że odstępy służą wyłącznie poprawie czytelności. +Równie dobrze można powyższy program zapisać tak: + +,[>+<-]>. + + +Spróbuj odgadnąć, co robi poniższy program: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Ten program pobiera z wejścia dwie liczby i je mnoży. + +Po wczytaniu dwóch wejść (do komórek #1 i #2) następuje pętla zewnętrzna, +warunkowana wartością komórki #1. Następnie program przechodzi do komórki #2 +i rozpoczyna pętlę wewnętrzną z warunkiem zakończenia w komórce #2, +inkrementującą komórkę #3. Tu jednak pojawia się problem: w chwili zakończenia +wewnętrznej pętli komórka #2 ma wartość zero. W takim razie wewętrzna pętla +nie wywoła się następny raz. Aby rozwiązać ten problem, inkrementujemy także +wartość komórki #4, a następnie kopiujemy jej wartość do komórki #2. +Ostatecznie wynik działania znajduje się w komórce #3. +``` + +I to właśnie jest brainfuck. Nie taki trudny, co? W ramach rozrywki możesz +napisać własne programy w brainfucku. Możesz też napisać interpreter brainfucka +w innym języku. Implementacja interpretera to dość proste zadanie. Jeśli +jesteś masochistą, spróbuj napisać interpreter brainfucka w... brainfucku. diff --git a/pl-pl/python-pl.html.markdown b/pl-pl/python-pl.html.markdown new file mode 100644 index 00000000..ade1d7ca --- /dev/null +++ b/pl-pl/python-pl.html.markdown @@ -0,0 +1,637 @@ +--- +name: python +category: language +language: python +filename: learnpython-pl.py +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Dominik Krzemiński", "https://github.com/dokato"] +lang: pl-pl +--- + +Python został opracowany przez Guido Van Rossuma na początku lat 90-tych. +Obecnie jest jednym z najbardziej popularnych języków programowania. +Zakochałem się w Pythonie dzięki porządkowi, jaki utrzymywany jest w kodzie. +To po prostu wykonywalny pseudokod. + +Zapraszam do kontaktu. Złapiecie nas na: +- kontakt polski: raymon92 [at] [google's email service] +- kontakt angielski: [@louiedinh](http://twitter.com/louiedinh) lub louiedinh [at] [google's email service] + +Uwaga: Ten artykuł odnosi się do wersji Pythona 2.7, ale powinien +działać w wersjach 2.x. Dla wersji 3.x znajdziesz odpowiedni artykuł na stronie głównej. + +```python +# -*- coding: utf-8 -*- + +# Pojedyncze komentarze oznaczamy takim symbolem. + +""" Wielolinijkowe napisy zapisywane są przy użyciu + trzech znaków cudzysłowiu i często + wykorzystywane są jako komentarze. +""" + +#################################################### +## 1. Podstawowe typy danych i operatory +#################################################### + +# Liczby to liczby +3 # => 3 + +# Matematyka jest intuicyjna +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# Dzielenie może być kłopotliwe. Poniższe to dzielenie +# całkowitoliczbowe(int) i wynik jest automatycznie zaokrąglany. +5 / 2 # => 2 + +# Aby to naprawić musimy powiedzieć nieco o liczbach zmiennoprzecinkowych. +2.0 # To liczba zmiennoprzecinkowa, tzw. float +11.0 / 4.0 # => 2.75 ahhh...znacznie lepiej + +# Wynik dzielenia całkowitoliczbowego jest obcinany dla liczb +# dodatnich i ujemnych. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # działa też na floatach +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Operator modulo - wyznaczanie reszty z dzielenia +7 % 3 # => 1 + +# Potęgowanie (x do potęgi ytej) +2**4 # => 16 + +# Wymuszanie pierwszeństwa w nawiasach +(1 + 3) * 2 # => 8 + +# Operacje logiczne +# Zauważ, że przy "and" i "or" trzeba zwracać uwagę na rozmiar liter +True and False #=> False # Fałsz +False or True #=> True # Prawda + +# Zauważ, że operatorów logicznych można używać z intami +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +k1 == True #=> True + +# aby zanegować użyj "not" +not True # => False +not False # => True + +# Równość == +1 == 1 # => True +2 == 1 # => False + +# Nierówność != +1 != 1 # => False +2 != 1 # => True + +# Więcej porównań +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Porównania można układać w łańcuch! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Napisy (typ string) tworzone są przy użyciu cudzysłowów " lub ' +"Jestem napisem." +'Ja też jestem napisem.' + +# Napisy można dodawać! +"Witaj " + "świecie!" # => "Witaj świecie!" + +# ... a nawet mnożone +"Hej" * 3 # => "HejHejHej" + +# Napis może być traktowany jako lista znaków +"To napis"[0] # => 'T' + +# % może być używane do formatowania napisów: +"%s są %s" % ("napisy", "fajne") + +# Jednak nowszym sposobem formatowania jest metoda "format". +# Ta metoda jest obecnie polecana: +"{0} są {1}".format("napisy", "fajne") +# Jeśli nie chce ci się liczyć użyj słów kluczowych. +"{imie} chce zjeść {jadlo}".format(imie="Bob", jadlo="makaron") + +# None jest obiektem +None # => None + +# Nie używaj "==" w celu porównania obiektów z None +# Zamiast tego użyj "is" +"etc" is None # => False +None is None # => True + +# Operator 'is' testuje identyczność obiektów. To nie jest zbyt +# pożyteczne, gdy działamy tylko na prostych wartościach, +# ale przydaje się, gdy mamy do czynienia z obiektami. + +# None, 0, i pusty napis "" są odpowiednikami logicznego False. +# Wszystkie inne wartości są True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Zmienne i zbiory danych +#################################################### + +# Python ma wyrażenie wypisujące "print" we wszystkich wersjach 2.x, ale +# zostało usunięte z wersji 3. +print "Jestem Python. Miło poznać!" +# Python ma też funkcję "print" dostępną w wersjach 2.7 and 3... +# ale w 2.7 musisz dodać import (odkomentuj): +# from __future__ import print_function +print("Ja też jestem Python! ") + +# Nie trzeba deklarować zmiennych przed przypisaniem. +jakas_zmienna = 5 # Konwencja mówi: używaj małych znaków i kładki _ +jakas_zmienna # => 5 + +# Próba dostępu do niezadeklarowanej zmiennej da błąd. +# Przejdź do sekcji Obsługa wyjątków po więcej... +inna_zmienna # Wyrzuca nazwę błędu + +# "if" może być użyte jako wyrażenie +"huraaa!" if 3 > 2 else 2 # => "huraaa!" + +# Listy: +li = [] +# Możesz zacząć od wypełnionej listy +inna_li = [4, 5, 6] + +# Dodaj na koniec używając "append" +li.append(1) # li to teraz [1] +li.append(2) # li to teraz [1, 2] +li.append(4) # li to teraz [1, 2, 4] +li.append(3) # li to teraz [1, 2, 4, 3] +# Usuwanie z konca da "pop" +li.pop() # => 3 a li stanie się [1, 2, 4] +# Dodajmy ponownie +li.append(3) # li to znowu [1, 2, 4, 3]. + +# Dostęp do list jak do każdej tablicy +li[0] # => 1 +# Użyj = aby nadpisać wcześniej wypełnione miejsca w liście +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Uwaga: ustawiamy starą wartość +# Tak podglądamy ostatni element +li[-1] # => 3 + +# Jeżeli wyjdziesz poza zakres... +li[4] # ... zobaczysz IndexError + +# Możesz tworzyć wyniki. +li[1:3] # => [2, 4] +# Bez początku +li[2:] # => [4, 3] +# Omijamy koniec +li[:3] # => [1, 2, 4] +# Wybierz co drugi +li[::2] # =>[1, 4] +# Odwróć listę +li[::-1] # => [3, 4, 2, 1] +# Użyj kombinacji powyższych aby tworzyć bardziej skomplikowane wycinki +# li[poczatek:koniec:krok] + +# Usuń element używając "del" +del li[2] # li to teraz [1, 2, 3] + +# Listy można dodawać +li + inna_li # => [1, 2, 3, 4, 5, 6] +# Uwaga: wartości poszczególnych list się nie zmieniają. + +# Do łączenia list użyj "extend()" +li.extend(other_li) # li to teraz [1, 2, 3, 4, 5, 6] + +# Sprawdź czy jest w liście używając "in" +1 in li # => True + +# "len()" pokazuje długość listy +len(li) # => 6 + + +# Krotki (tuple) są jak listy, ale nie można ich modyfikować. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # wyrzuci TypeError + +# Ale wielu akcji dla list możesz używać przy krotkach +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Można rozpakować krotki i listy do poszczególych zmiennych +a, b, c = (1, 2, 3) # a to teraz 1, b jest 2, a c to 3 +# Jeżeli zapomnisz nawiasów automatycznie tworzone są krotki +d, e, f = 4, 5, 6 +# Popatrz jak prosto zamienić wartości +e, d = d, e # d to teraz 5 a e to 4 + + +# Słowniki są również pożyteczne +pusty_slownik = {} +# Tu tworzymy wypełniony: +pelen_slownik = {"raz": 1, "dwa": 2, "trzy": 3} + +# Podglądany wartość +pelen_slownik["one"] # => 1 + +# Wypisz wszystkie klucze używając "keys()" +pelen_slownik.keys() # => ["trzy", "dwa", "raz"] +# Uwaga: słowniki nie gwarantują kolejności występowania kluczy. + +# A teraz wszystkie wartości "values()" +pelen_slownik.values() # => [3, 2, 1] +# Uwaga: to samo dotyczy wartości. + +# Sprawdzanie czy występuje to "in" +"raz" in pelen_slownik # => True +1 in pelen_slownik # => False + +# Próba dobrania się do nieistniejącego klucza da KeyError +pelen_slownik["cztery"] # KeyError + +# Użyj "get()" method aby uniknąć KeyError +pelen_slownik.get("raz") # => 1 +pelen_slownik.get("cztery") # => None +# Metoda get zwraca domyślną wartość gdy brakuje klucza +pelen_slownik.get("one", 4) # => 1 +pelen_slownik.get("cztery", 4) # => 4 +# zauważ, że pelen_slownik.get("cztery") jest wciąż => None +# (get nie ustawia wartości słownika) + +# przypisz wartość do klucza podobnie jak w listach +pelen_slownik["cztery"] = 4 # teraz: pelen_slownik["cztery"] => 4 + +# "setdefault()" wstawia do słownika tylko jeśli nie było klucza +pelen_slownik.setdefault("piec", 5) # pelen_slownik["piec"] daje 5 +pelen_slownik.setdefault("piec", 6) # pelen_slownik["piec"] to wciąż 5 + + +# Teraz zbiory (set) ... cóż zbiory (to po prostu listy ale bez potórzeń) +pusty_zbior = set() +# Inicjalizujemy "set()" pewnymi wartościami +jakis_zbior = set([1, 2, 2, 3, 4]) # jakis_zbior to teraz set([1, 2, 3, 4]) + +# kolejność nie jest gwarantowana, nawet gdy wydaje się posortowane +inny_zbior = set([4, 3, 2, 2, 1]) # inny_zbior to set([1, 2, 3, 4]) + +# Od Pythona 2.7 nawiasy klamrowe {} mogą być użyte do deklarowania zbioru +pelen_zbior = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Dodaj więcej elementów przez "add()" +pelen_zbior.add(5) # pelen_zbior is now {1, 2, 3, 4, 5} + +# Znajdź przecięcie zbiorów używając & +inny_zbior = {3, 4, 5, 6} +pelen_zbior & other_set # => {3, 4, 5} + +# Suma zbiorów | +pelen_zbior | other_set # => {1, 2, 3, 4, 5, 6} + +# Różnicę zbiorów da znak - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Sprawdzanie obecności w zbiorze: "in". +2 in pelen_zbior # => True +10 in pelen_zbior # => False + + +#################################################### +## 3. Kontrola przepływu +#################################################### + +# Tworzymy zmienną some_var +some_var = 5 + +# Tutaj widzisz wyrażenie warunkowe "if". Wcięcia są ważne Pythonie! +# wypisze "some_var jest mniejsza niż 10" +if some_var > 10: + print("some_var jest wieksza niż 10") +elif some_var < 10: # This elif clause is optional. + print("some_var jest mniejsza niż 10") +else: # This is optional too. + print("some_var jest równa 10") + + +""" +Pętla for iteruje po elementach listy wypisując: + pies to ssak + kot to ssak + mysz to ssak +""" +for zwierze in ["pies", "kot", "mysz"]: + # Możesz użyć % aby stworzyć sformatowane napisy + print("%s to ssak" % zwierze) + +""" +"range(liczba)" zwraca listę liczb +od zera do danej liczby: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +While to pętla która jest wykonywana dopóki spełniony jest warunek: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Skrót od x = x + 1 + +# Wyjątki wyłapujemy używając try, except + +# Działa w Pythonie 2.6 i wyższych: +try: + # Użyj "raise" aby wyrzucić wyjąte + raise IndexError("To błąd indeksu") +except IndexError as e: + pass # Pass to brak reakcji na błąd. Zazwyczaj nanosisz tu poprawki. +except (TypeError, NameError): + pass # kilka wyjątków może być przechwyce razem. +else: # Opcjonalna część bloku try/except. Musi wystąpić na końcu + print "Wszystko ok!" # Zadziała tylko, gdy program nie napotka wyjatku. + + +#################################################### +## 4. Funkcjie +#################################################### + +# Użyj "def" aby stworzyć nową funkcję +def dodaj(x, y): + print("x to %s a y to %s" % (x, y)) + return x + y # słówko kluczowe return zwraca wynik działania + +# Tak wywołuje się funkcję z parametrami (args): +dodaj(5, 6) # => wypisze "x to 5 a y to 6" i zwróci 11 + +# Innym sposobem jest wywołanie z parametrami nazwanymi. +dodaj(y=6, x=5) # tutaj kolejność podania nie ma znaczenia. + + +# Można też stworzyć funkcję, które przyjmują różną ilość parametrów +# nienazwanych args, co będzie interpretowane jako krotka jeśli nie użyjesz * +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + + +# Można też stworzyć funkcję, które przyjmują różną ilość parametrów +# nazwanych kwargs, które będa interpretowane jako słownik jeśli nie dasz ** +def keyword_args(**kwargs): + return kwargs + +# Wywołajmy to i sprawdźmy co się dzieje +keyword_args(wielka="stopa", loch="ness") # => {"wielka": "stopa", "loch": "ness"} + + +# Możesz też to pomieszać +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) wyrzuci: + (1, 2) + {"a": 3, "b": 4} +""" + +# Użyj * aby rozwinąć parametry z krotki args +# i użyj ** aby rozwinąć parametry nazwane ze słownika kwargs. +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # odpowiednik foo(1, 2, 3, 4) +all_the_args(**kwargs) # odpowiednik foo(a=3, b=4) +all_the_args(*args, **kwargs) # odpowiednik foo(1, 2, 3, 4, a=3, b=4) + +# Możesz podać parametry args i kwargs do funkcji równocześnie +# przez rozwinięcie odpowiednio * i ** +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Zakres widoczności +x = 5 + +def setX(num): + # Lokalna zmienna x nie jest tym samym co zmienna x + x = num # => 43 + print x # => 43 + +def setGlobalX(num): + global x + print x # => 5 + x = num # globalna zmienna to teraz 6 + print x # => 6 + +setX(43) +setGlobalX(6) + +# Można tworzyć funkcje wewnętrzne i zwrócić je jako wynik +def rob_dodawacz(x): + def dodawacz(y): + return x + y + return dodawacz + +dodaj_10 = rob_dodawacz(10) +dodaj_10(3) # => 13 + +# Są również funkcje nienazwane "lambda" +(lambda x: x > 2)(3) # => True + +# Są także wbudowane funkcje wysokiego poziomu +map(add_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Można używać wyrażeń listowych do mapowania (map) i filtrowania (filter) +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + + +#################################################### +## 5. Klasy +#################################################### + +# Wszystkie klasy są podklasą object +class Czlowiek(object): + + # Atrybut klasy. Występuje we wszystkich instancjach klasy. + gatunek = "H. sapiens" + + # Podstawowa inicjalizacja - wywoływana podczas tworzenia instacji. + # Zauważ, że podwójne podkreślenia przed i za nazwą oznaczają + # obietky lub atrybuty, który żyją tylko w kontrolowanej przez + # użytkownika przestrzeni nazw. Nie używaj ich we własnych metodach. + def __init__(self, nazwa): + # przypisz parametr "nazwa" do atrybutu instancji + self.nazwa = nazwa + + # Metoda instancji. Wszystkie metody biorą "self" jako pierwszy argument + def mow(self, wiadomosc): + return "%s: %s" % (self.nazwa, wiadomosc) + + # Metoda klasowa współdzielona przez instancje. + # Ma wywołującą klasę jako pierwszy argument. + @classmethod + def daj_gatunek(cls): + return cls.gatunek + + # Metoda statyczna jest wywoływana bez argumentów klasy czy instancji. + @staticmethod + def grunt(): + return "*grunt*" + + +# Instancja klasy +i = Czlowiek(name="Ian") +print(i.mow("cześć")) # wypisze "Ian: cześć" + +j = Czlowiek("Joel") +print(j.mow("cześć")) # wypisze "Joel: cześć" + +# Wywołujemy naszą metodę klasową +i.daj_gatunek() # => "H. sapiens" + +# Zmieniamy wspólny parametr +Czlowiek.gatunek = "H. neanderthalensis" +i.daj_gatunek() # => "H. neanderthalensis" +j.daj_gatunek() # => "H. neanderthalensis" + +# Wywołanie metody statycznej +Czlowiek.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduły +#################################################### + +# Tak importuje się moduły: +import math +print(math.sqrt(16)) # => 4 + +# Można podać konkretne funkcje, np. ceil, floor z modułu math +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Można zaimportować wszystkie funkcje z danego modułu. +# Ostrzeżenie: nie jest to polecane. +from math import * + +# Można skracać nazwy modułów. +import math as m +math.sqrt(16) == m.sqrt(16) # => True +# sprawdźmy czy funkcje są równoważne +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True + +# Moduły pythona to zwykłe skrypty napisane w tym języku. Możesz +# pisać własne i importować je. Nazwa modułu to nazwa pliku. + +# W ten sposób sprawdzisz jakie funkcje wchodzą w skład modułu. +import math +dir(math) + + +#################################################### +## 7. Zaawansowane +#################################################### + +# Generatory pomagają tworzyć tzw. "leniwy kod" +def podwojne_liczby(iterowalne): + for i in iterowalne: + yield i + i + +# Generatory tworzą wartości w locie. +# W przeciwienstwie do wygenerowania wartości raz i ich zachowania, +# powstają one na bieżąco, w wyniku iteracji. To oznacza, że wartości +# większe niż 15 nie będą przetworzone w funkcji "podwojne_liczby". +# Zauważ, że xrange to generator, który wykonuje tę samą operację co range. +# Stworzenie listy od 1 do 900000000 zajęłoby sporo czasu i pamięci, +# a xrange tworzy obiekt generatora zamiast tworzyć całą listę jak range. +# Użyto podkreślinika, aby odróżnić nazwę zmiennej od słówka kluczowego +# Pythona. +xrange_ = xrange(1, 900000000) + +# poniższa pętla będzie podwajać liczby aż do 30 +for i in podwojne_liczby(xrange_): + print(i) + if i >= 30: + break + + +# Dekoratory +# w tym przykładzie "beg" jest nakładką na "say" +# Beg wywołuje say. Jeśli say_please jest prawdziwe wtedy wzracana wartość +# zostanie zmieniona + +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Proszę! Jestem spłukany :(") + return msg + return wrapper + + +@beg +def say(say_please=False): + msg = "Kupisz mi piwo?" + return msg, say_please + + +print(say()) # Kupisz mi piwo? +print(say(say_please=True)) # Kupisz mi piwo? Proszę! Jestem spłukany :( +``` + +## Gotowy na więcej? +### Polskie + +* [Zanurkuj w Pythonie](http://pl.wikibooks.org/wiki/Zanurkuj_w_Pythonie) +* [LearnPythonPl](http://www.learnpython.org/pl/) + +### Angielskie: +#### Darmowe źródła online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [The Official Docs](http://docs.python.org/2.6/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) + +#### Inne + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/pogo.html.markdown b/pogo.html.markdown index 60a83edd..aa5d49f3 100644 --- a/pogo.html.markdown +++ b/pogo.html.markdown @@ -199,4 +199,4 @@ That's it. Download [Node.js](http://nodejs.org/) and `npm install pogo`. -There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), inlcuding a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! +There is plenty of documentation on [http://pogoscript.org/](http://pogoscript.org/), including a [cheat sheet](http://pogoscript.org/cheatsheet.html), a [guide](http://pogoscript.org/guide/), and how [Pogoscript translates to Javascript](http://featurist.github.io/pogo-examples/). Get in touch on the [google group](http://groups.google.com/group/pogoscript) if you have questions! diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown new file mode 100644 index 00000000..9e4b458d --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown @@ -0,0 +1,85 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] + - ["Rodrigo Muniz", "http://github.com/muniz95"] +lang: pt-br +--- + +Brainfuck (em letras minúsculas, exceto no início de frases) é uma linguagem de +programação Turing-completa extremamente simples com apenas 8 comandos. + +``` +Qualquer caractere exceto "><+-.,[]" (sem contar as aspas) é ignorado. + +Brainfuck é representado por um vetor com 30 000 células inicializadas em zero +e um ponteiro de dados que aponta para a célula atual. + +Existem 8 comandos: ++ : Incrementa o valor da célula atual em 1. +- : Decrementa o valor da célula atual em 1. +> : Move o ponteiro de dados para a célula seguinte (célula à direita). +< : Move o ponteiro de dados para a célula anterior (célula à esquerda). +. : Imprime o valor ASCII da célula atual. (ex. 65 = 'A'). +, : Lê um único caractere para a célula atual. +[ : Se o valor da célula atual for zero, salta para o ] correspondente. + Caso contrário, passa para a instrução seguinte. +] : Se o valor da célula atual for zero, passa para a instrução seguinte. + Caso contrário, volta para a instrução relativa ao [ correspondente. + +[ e ] formam um ciclo while. Obviamente, devem ser equilibrados. + +Vamos ver alguns exemplos básicos em brainfuck: + +++++++ [ > ++++++++++ < - ] > +++++ . + +Este programa imprime a letra 'A'. Primeiro incrementa a célula #1 para 6. +A célula #1 será usada num ciclo. Depois é iniciado o ciclo ([) e move-se +o ponteiro de dados para a célula #2. O valor da célula #2 é incrementado 10 +vezes, move-se o ponteiro de dados de volta para a célula #1, e decrementa-se +a célula #1. Este ciclo acontece 6 vezes (são necessários 6 decrementos para +a célula #1 chegar a 0, momento em que se salta para o ] correspondente, +continuando com a instrução seguinte). + +Nesta altura estamos na célula #1, cujo valor é 0, enquanto a célula #2 +tem o valor 60. Movemos o ponteiro de dados para a célula #2, incrementa-se 5 +vezes para um valor final de 65, e então é impresso o valor da célula #2. O valor +65 corresponde ao caractere 'A' em ASCII, então 'A' é impresso no terminal. + +, [ > + < - ] > . + +Este programa lê um caractere e copia o seu valor para a célula #1. Um ciclo é +iniciado. Movemos o ponteiro de dados para a célula #2, incrementamos o valor na +célula #2, movemos o ponteiro de dados de volta para a célula #1 e finalmente +decrementamos o valor na célula #1. Isto continua até o valor na célula #1 ser +igual a 0 e a célula #2 ter o antigo valor da célula #1. Como o ponteiro de +dados está apontando para a célula #1 no fim do ciclo, movemos o ponteiro para a +célula #2 e imprimimos o valor em ASCII. + +Os espaços servem apenas para tornar o programa mais legível. Podemos escrever +o mesmo programa da seguinte maneira: + +,[>+<-]>. + +Tente descobrir o que este programa faz: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Este programa lê dois números e os multiplica. + +Basicamente o programa pede dois caracteres ao usuário. Depois é iniciado um +ciclo exterior controlado pelo valor da célula #1. Movemos o ponteiro de dados +para a célula #2 e inicia-se o ciclo interior controlado pelo valor da célula +#2, incrementando o valor da célula #3. Porém existe um problema, no final do +ciclo interior: a célula #2 tem o valor 0. Para resolver este problema o valor da +célula #4 é também incrementado e copiado para a célula #2. +``` + +E isto é brainfuck. Simples, não? Por divertimento você pode escrever os +seus próprios programas em brainfuck, ou então escrever um interpretador de +brainfuck em outra linguagem. O interpretador é relativamente fácil de se +implementar, mas caso você seja masoquista, tente escrever um interpretador de +brainfuck… em brainfuck. diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown new file mode 100644 index 00000000..61e267f5 --- /dev/null +++ b/pt-br/c++-pt.html.markdown @@ -0,0 +1,590 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +C++ é uma linguagem de programação de sistemas que, +[de acordo com seu inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +foi concebida para + +- ser um "C melhor" +- suportar abstração de dados +- suportar programação orientada a objetos +- suportar programação genérica + +Embora sua sintaxe pode ser mais difícil ou complexa do que as linguagens mais +recentes, C++ é amplamente utilizado porque compila para instruções nativas que +podem ser executadas diretamente pelo processador e oferece um controlo rígido sobre hardware (como C), enquanto oferece recursos de alto nível, como os +genéricos, exceções e classes. Esta combinação de velocidade e funcionalidade +faz C++ uma das linguagens de programação mais utilizadas. + +```c++ +////////////////// +// Comparação com C +////////////////// + +// C ++ é quase um super conjunto de C e compartilha sua sintaxe básica para +// declarações de variáveis, tipos primitivos, e funções. No entanto, C++ varia +// em algumas das seguintes maneiras: + +// A função main() em C++ deve retornar um int, embora void main() é aceita +// pela maioria dos compiladores (gcc, bumbum, etc.) +// Este valor serve como o status de saída do programa. +// Veja http://en.wikipedia.org/wiki/Exit_status para mais informações. + +int main(int argc, char** argv) +{ + // Argumentos de linha de comando são passados em pelo argc e argv da mesma + // forma que eles estão em C. + // argc indica o número de argumentos, + // e argv é um array de strings, feito C (char*) representado os argumentos + // O primeiro argumento é o nome pelo qual o programa foi chamado. + // argc e argv pode ser omitido se você não se importa com argumentos, + // dando a assinatura da função de int main() + + // Uma saída de status de 0 indica sucesso. + return 0; +} + +// Em C++, caracteres literais são um byte. +sizeof('c') == 1 + +// Em C, caracteres literais são do mesmo tamanho que ints. +sizeof('c') == sizeof(10) + +// C++ tem prototipagem estrita +void func(); // função que não aceita argumentos + +// Em C +void func(); // função que pode aceitar qualquer número de argumentos + +// Use nullptr em vez de NULL em C++ +int* ip = nullptr; + +// Cabeçalhos padrão C estão disponíveis em C++, +// mas são prefixados com "c" e não têm sufixo .h + +#include <cstdio> + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// Sobrecarga de função +/////////////////////// + +// C++ suporta sobrecarga de função +// desde que cada função tenha parâmetros diferentes. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Funciona para void print(const char*) + print(15); // Funciona para void print(int) +} + +///////////////////////////// +// Parâmetros padrão de função +///////////////////////////// + +// Você pode fornecer argumentos padrões para uma função se eles não são +// fornecidos pelo chamador. + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // Faça alguma coisa com os ints aqui +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// Argumentos padrões devem estar no final da lista de argumentos. + +void invalidDeclaration(int a = 1, int b) // Erro! +{ +} + + +///////////// +// Namespaces (nome de espaços) +///////////// + +// Namespaces fornecem escopos distintos para variável, função e outras +// declarações. Namespaces podem estar aninhados. + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // Fim do namespace aninhado +} // Fim do namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // Assuma que tudo é do namespace "Second" a menos que especificado de + // outra forma. + using namespace Second; + + foo(); // imprime "This is Second::foo" + First::Nested::foo(); // imprime "This is First::Nested::foo" + ::foo(); // imprime "This is global foo" +} + +/////////////// +// Entrada/Saída +/////////////// + +// C ++ usa a entrada e saída de fluxos (streams) +// cin, cout, and cerr representa stdin, stdout, and stderr. +// << É o operador de inserção e >> é o operador de extração. + +#include <iostream> // Inclusão para o I/O streams + +using namespace std; // Streams estão no namespace std (biblioteca padrão) + +int main() +{ + int myInt; + + // Imprime na saída padrão (ou terminal/tela) + cout << "Enter your favorite number:\n"; + // Pega a entrada + cin >> myInt; + + // cout também pode ser formatado + cout << "Your favorite number is " << myInt << "\n"; + // imprime "Your favorite number is <myInt>" + + cerr << "Usado para mensagens de erro"; +} + +////////// +// Strings +////////// + +// Strings em C++ são objetos e têm muitas funções de membro +#include <string> + +using namespace std; // Strings também estão no namespace std (bib. padrão) + +string myString = "Hello"; +string myOtherString = " World"; + +// + é usado para concatenação. +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// Em C++, strings são mutáveis e têm valores semânticos. +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// Referência +///////////// + +// Além de indicadores como os de C, C++ têm _referências_. Esses são tipos de +// ponteiro que não pode ser reatribuída uma vez definidos e não pode ser nulo. +// Eles também têm a mesma sintaxe que a própria variável: Não * é necessário +// para _dereferencing_ e & (endereço de) não é usado para atribuição. + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // Isso cria uma referência para foo. +fooRef += ". Hi!"; // Modifica foo através da referência +cout << fooRef; // Imprime "I am foo. Hi!" + +// Não realocar "fooRef". Este é o mesmo que "foo = bar", e foo == "I am bar" +// depois desta linha. + +fooRef = bar; + +const string& barRef = bar; // Cria uma referência const para bar. +// Como C, valores const (e ponteiros e referências) não podem ser modificado. +barRef += ". Hi!"; // Erro, referência const não pode ser modificada. + +////////////////////////////////////////// +// Classes e programação orientada a objeto +////////////////////////////////////////// + +// Primeiro exemplo de classes +#include <iostream> + +// Declara a classe. +// As classes são geralmente declarado no cabeçalho arquivos (.h ou .hpp). +class Dog { + // Variáveis de membro e funções são privadas por padrão. + std::string name; + int weight; + +// Todos os membros a seguir este são públicos até que "private:" ou +// "protected:" é encontrado. +public: + + // Construtor padrão + Dog(); + + // Declarações de função Membro (implementações a seguir) + // Note que usamos std :: string aqui em vez de colocar + // using namespace std; + // acima. + // Nunca coloque uma declaração "using namespace" em um cabeçalho. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Funções que não modificam o estado do objecto devem ser marcadas como + // const. Isso permite que você chamá-los se for dada uma referência const + // para o objeto. Além disso, observe as funções devem ser explicitamente + // declarados como _virtual_, a fim de ser substituídas em classes + // derivadas. As funções não são virtuais por padrão por razões de + // performance. + + virtual void print() const; + + // As funções também podem ser definidas no interior do corpo da classe. + // Funções definidas como tal são automaticamente embutidas. + void bark() const { std::cout << name << " barks!\n" } + + // Junto com os construtores, C++ fornece destruidores. + // Estes são chamados quando um objeto é excluído ou fica fora do escopo. + // Isto permite paradigmas poderosos, como RAII + // (veja abaixo) + // Destruidores devem ser virtual para permitir que as classes de ser + // derivada desta. + virtual ~Dog(); + +}; // Um ponto e vírgula deve seguir a definição de classe. + +// Funções membro da classe geralmente são implementados em arquivos .cpp. +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// Objetos (como strings) devem ser passados por referência +// se você pretende modificá-los, ou com const caso contrário. +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Observe que "virtual" só é necessária na declaração, não a definição. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // imprime "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // imprime "Dog is Barkley and weighs 10 kg" + return 0; +} // imprime "Goodbye Barkley" + +// herança: + +// Essa classe herda tudo público e protegido da classe Dog +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // Substituir o comportamento da função de impressão de todas OwnedDogs. + // Ver http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // Para uma introdução mais geral, se você não estiver familiarizado com o + // polimorfismo subtipo. A palavra-chave override é opcional, mas torna-se + // na verdade você está substituindo o método em uma classe base. + void print() const override; + +private: + std::string owner; +}; + +// Enquanto isso, no arquivo .cpp correspondente: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // Chame a função de impressão na classe Dog base de + std::cout << "Dog is owned by " << owner << "\n"; + // Prints "Dog is <name> and weights <weight>" + // "Dog is owned by <owner>" +} + +////////////////////////////////////////// +// Inicialização e Sobrecarga de Operadores +////////////////////////////////////////// + +// Em C ++, você pode sobrecarregar o comportamento dos operadores, tais como +// +, -, *, /, etc. Isto é feito através da definição de uma função que é +// chamado sempre que o operador é usado. + +#include <iostream> +using namespace std; + +class Point { +public: + // Variáveis membro pode ser dado valores padrão desta maneira. + double x = 0; + double y = 0; + + // Define um construtor padrão que não faz nada + // mas inicializar o Point para o valor padrão (0, 0) + Point() { }; + + // A sintaxe a seguir é conhecido como uma lista de inicialização + // e é a maneira correta de inicializar os valores de membro de classe + Point (double a, double b) : + x(a), + y(b) + { /* Não fazer nada, exceto inicializar os valores */ } + + // Sobrecarrega o operador +. + Point operator+(const Point& rhs) const; + + // Sobrecarregar o operador +=. + Point& operator+=(const Point& rhs); + + // Ele também faria sentido para adicionar os operadores - e -=, + // mas vamos pular para sermos breves. +}; + +Point Point::operator+(const Point& rhs) const +{ + // Criar um novo ponto que é a soma de um e rhs. + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // Isto chama que o operador ponto + + // Ressalte-se a chamadas (função)+ com direito como seu parâmetro... + Point result = up + right; + // Imprime "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////////// +// Tratamento de Exceções +///////////////////////// + +// A biblioteca padrão fornece alguns tipos de exceção +// (see http://en.cppreference.com/w/cpp/error/exception) +// mas qualquer tipo pode ser jogado como uma exceção +#include <exception> + +// Todas as exceções lançadas dentro do bloco try pode ser capturado por +// manipuladores de captura subseqüentes +try { + // Não aloca exceções no heap usando _new_. + throw std::exception("A problem occurred"); +} +// Capturar exceções por referência const se eles são objetos +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Captura qualquer exceção não capturada pelos blocos _catch_ anteriores +} catch (...) +{ + std::cout << "Exceção desconhecida encontrada"; + throw; // Re-lança a exceção +} + +/////// +// RAII +/////// + +// RAII significa alocação de recursos é de inicialização. +// Muitas vezes, é considerado o paradigma mais poderoso em C++, e é o +// conceito simples que um construtor para um objeto adquire recursos daquele +// objeto e o destruidor liberá-los. + +// Para entender como isso é útil, +// Considere uma função que usa um identificador de arquivo C: +void doSomethingWithAFile(const char* filename) +{ + // Para começar, assuma que nada pode falhar. + + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Feche o arquivo. +} + +// Infelizmente, as coisas são levemente complicadas para tratamento de erros. +// Suponha que fopen pode falhar, e que doSomethingWithTheFile e +// doSomethingElseWithIt retornam códigos de erro se eles falharem. (As +// exceções são a forma preferida de lidar com o fracasso, mas alguns +// programadores, especialmente aqueles com um conhecimento em C, discordam +// sobre a utilidade de exceções). Agora temos que verificar cada chamada para +// o fracasso e fechar o identificador de arquivo se ocorreu um problema. + +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura + if (fh == nullptr) // O ponteiro retornado é nulo em caso de falha. + reuturn false; // Relate o fracasso para o chamador. + + // Suponha cada função retorne false, se falhar + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return false; // Propague o erro. + } + + fclose(fh); // Feche o identificador de arquivo para que ele não vaze. + return true; // Indica sucesso +} + +// Programadores C frequentemente limpam isso um pouco usando Goto: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + reuturn false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indica sucesso + +failure: + fclose(fh); + return false; // Propague o erro. +} + +// Se as funções indicam erros usando exceções, +// as coisas são um pouco mais limpo, mas ainda abaixo do ideal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Abra o arquivo em modo de leitura. + if (fh == nullptr) + throw std::exception("Não pode abrir o arquivo."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Certifique-se de fechar o arquivo se ocorrer um erro. + throw; // Em seguida, re-lance a exceção. + } + + fclose(fh); // Feche o arquivo + // Tudo ocorreu com sucesso! +} + +// Compare isso com o uso de C++ classe fluxo de arquivo (fstream) fstream usa +// seu destruidor para fechar o arquivo. Lembre-se de cima que destruidores são +// automaticamente chamado sempre que um objeto cai fora do âmbito. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream é curto para o fluxo de arquivo de entrada + std::ifstream fh(filename); // Abra o arquivo + + // faça alguma coisa com o arquivo + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // O arquivo é automaticamente fechado aqui pelo destructor + +// Isto tem _grandes_ vantagens: +// 1. Não importa o que aconteça, +// o recurso (neste caso, o identificador de ficheiro) irá ser limpo. +// Depois de escrever o destruidor corretamente, +// É _impossível_ esquecer de fechar e vazar o recurso +// 2. Nota-se que o código é muito mais limpo. +// As alças destructor fecham o arquivo por trás das cenas +// sem que você precise se preocupar com isso. +// 3. O código é seguro de exceção. +// Uma exceção pode ser jogado em qualquer lugar na função e a limpeza +// irá ainda ocorrer. + +// Todos códigos C++ usam RAII extensivamente para todos os recursos. +// Outros exemplos incluem +// - Memória usa unique_ptr e shared_ptr +// - Contentores - a lista da biblioteca ligada padrão, +// vetor (i.e. array de autodimensionamento), mapas hash, e assim por diante +// tudo é automaticamente destruído quando eles saem de escopo +// - Mutex usa lock_guard e unique_lock +``` +Leitura Adicional: + +Uma referência atualizada da linguagem pode ser encontrada em +<http://cppreference.com/w/cpp> + +Uma fonte adicional pode ser encontrada em <http://cplusplus.com> diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 451df4f3..2c274f12 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -6,29 +6,31 @@ contributors: - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] translators: - ["João Farias", "https://github.com/JoaoGFarias"] + - ["Elton Viana", "https://github.com/eltonvs"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] lang: pt-br filename: c-pt.el --- Ah, C. Ainda é **a** linguagem de computação de alta performance. -C é a liguangem de mais baixo nível que a maioria dos programadores -irão usar, e isso dá a ela uma grande velocidade bruta. Apenas fique -antento que este manual de gerenciamento de memória e C vai levanter-te -tão longe quanto você precisa. +C é a linguagem de mais baixo nível que a maioria dos programadores +utilizarão, e isso dá a ela uma grande velocidade bruta. Apenas fique +atento se este manual de gerenciamento de memória e C vai te levar +tão longe quanto precisa. ```c // Comentários de uma linha iniciam-se com // - apenas disponível a partir do C99 /* -Comentários de multiplas linhas se parecem com este. +Comentários de múltiplas linhas se parecem com este. Funcionam no C89 também. */ // Constantes: #define <palavra-chave> #definie DAY_IN_YEAR 365 -//enumarações também são modos de definir constantes. +//enumerações também são modos de definir constantes. enum day {DOM = 1, SEG, TER, QUA, QUI, SEX, SAB}; // SEG recebe 2 automaticamente, TER recebe 3, etc. @@ -53,13 +55,13 @@ int soma_dois_ints(int x1, int x2); // protótipo de função // O ponto de entrada do teu programa é uma função // chamada main, com tipo de retorno inteiro int main() { - // Usa-se printf para escrever na tela, + // Usa-se printf para escrever na tela, // para "saída formatada" // %d é um inteiro, \n é uma nova linha printf("%d\n", 0); // => Imprime 0 // Todos as declarações devem acabar com // ponto e vírgula - + /////////////////////////////////////// // Tipos /////////////////////////////////////// @@ -77,7 +79,7 @@ int main() { // longs tem entre 4 e 8 bytes; longs long tem garantia // de ter pelo menos 64 bits long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // floats são normalmente números de ponto flutuante // com 32 bits @@ -92,7 +94,7 @@ int main() { unsigned int ux_int; unsigned long long ux_long_long; - // caracteres dentro de aspas simples são inteiros + // caracteres dentro de aspas simples são inteiros // no conjunto de caracteres da máquina. '0' // => 48 na tabela ASCII. 'A' // => 65 na tabela ASCII. @@ -103,7 +105,7 @@ int main() { // Se o argumento do operador `sizeof` é uma expressão, então seus argumentos // não são avaliados (exceto em VLAs (veja abaixo)). - // O valor devolve, neste caso, é uma constante de tempo de compilação. + // O valor devolve, neste caso, é uma constante de tempo de compilação. int a = 1; // size_t é um inteiro sem sinal com pelo menos 2 bytes que representa // o tamanho de um objeto. @@ -119,7 +121,7 @@ int main() { // Você pode inicializar um array com 0 desta forma: char meu_array[20] = {0}; - // Indexar um array é semelhante a outras linguages + // Indexar um array é semelhante a outras linguagens // Melhor dizendo, outras linguagens são semelhantes a C meu_array[0]; // => 0 @@ -128,7 +130,7 @@ int main() { printf("%d\n", meu_array[1]); // => 2 // No C99 (e como uma features opcional em C11), arrays de tamanho variável - // VLA (do inglês), podem ser declarados também. O tamanho destes arrays + // VLA (do inglês), podem ser declarados também. O tamanho destes arrays // não precisam ser uma constante de tempo de compilação: printf("Entre o tamanho do array: "); // Pergunta ao usuário pelo tamanho char buf[0x100]; @@ -139,22 +141,22 @@ int main() { int var_length_array[size]; // declara o VLA printf("sizeof array = %zu\n", sizeof var_length_array); - //Uma possível saída para esse programa seria: - // > Entre o tamanho do array:: 10 + // Uma possível saída para esse programa seria: + // > Entre o tamanho do array: 10 // > sizeof array = 40 - // String são apenas arrays de caracteres terminados por um - // byte NUL (0x00), representado em string pelo caracter especial '\0'. - // (Não precisamos incluir o byte NUL em literais de string; o compilador + // String são apenas arrays de caracteres terminados por um + // byte nulo (0x00), representado em string pelo caracter especial '\0'. + // (Não precisamos incluir o byte nulo em literais de string; o compilador // o insere ao final do array para nós.) - char uma_string[20] = "Isto é uma string"; + char uma_string[20] = "Isto é uma string"; // Observe que 'é' não está na tabela ASCII // A string vai ser salva, mas a saída vai ser estranha - // Porém, comentários podem conter acentos + // Porém, comentários podem conter acentos printf("%s\n", uma_string); // %s formata a string - printf("%d\n", uma_string[16]); // => 0 - // i.e., byte #17 é 0 (assim como 18, 19, e 20) + printf("%d\n", uma_string[17]); // => 0 + // i.e., byte #18 é 0 (assim como o 19°, 20°, 21°...) // Se temos caracteres entre aspas simples, temos um caracter literal. // Seu tipo é `int`, *não* `char` (por razões históricas). @@ -174,7 +176,7 @@ int main() { /////////////////////////////////////// // Atalho para multiplas declarações: - int i1 = 1, i2 = 2; + int i1 = 1, i2 = 2; float f1 = 1.0, f2 = 2.0; int a, b, c; @@ -205,7 +207,7 @@ int main() { 2 <= 2; // => 1 2 >= 2; // => 1 - // C não é Python - comparações não se encadeam. + // C não é Python - comparações não se encadeiam. int a = 1; // Errado: int entre_0_e_2 = 0 < a < 2; @@ -220,17 +222,17 @@ int main() { 0 || 1; // => 1 (Ou lógico) 0 || 0; // => 0 - //Expressão condicional ( ? : ) + //Expressão condicional ternária ( ? : ) int a = 5; int b = 10; int z; - z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b." + z = (a > b) ? a : b; // => 10 "se a > b retorne a, senão retorne b." //Operadores de incremento e decremento: char *s = "iLoveC"; int j = 0; s[j++]; // => "i". Retorna o j-ésimo item de s E DEPOIS incrementa o valor de j. - j = 0; + j = 0; s[++j]; // => "L". Incrementa o valor de j. E DEPOIS retorna o j-ésimo item de s. // o mesmo com j-- e --j @@ -290,6 +292,8 @@ int main() { for (i = 0; i <= 5; i++) { ; // Use ponto e vírgula para agir como um corpo (declaração nula) } + // Ou + for (i = 0; i <= 5; i++); // Criando branchs com escolhas múltiplas: switch() switch (alguma_expressao_integral) { @@ -305,7 +309,7 @@ int main() { exit(-1); break; } - + /////////////////////////////////////// // Cast de tipos @@ -324,8 +328,8 @@ int main() { // Tipos irão ter overflow sem aviso printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 se char tem 8 bits) - // Para determinar o valor máximo de um `char`, de um `signed char` e de - // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX + // Para determinar o valor máximo de um `char`, de um `signed char` e de + // um `unisigned char`, respectivamente, use as macros CHAR_MAX, SCHAR_MAX // e UCHAR_MAX de <limits.h> // Tipos inteiros podem sofrer cast para pontos-flutuantes e vice-versa. @@ -338,7 +342,7 @@ int main() { /////////////////////////////////////// // Um ponteiro é uma variável declarada para armazenar um endereço de memória. - // Seu declaração irá também dizer o tipo de dados para o qual ela aponta. Você + // Sua declaração irá também dizer o tipo de dados para o qual ela aponta. Você // Pode usar o endereço de memória de suas variáveis, então, brincar com eles. int x = 0; @@ -360,13 +364,13 @@ int main() { printf("%d\n", *px); // => Imprime 0, o valor de x // Você também pode mudar o valor que o ponteiro está apontando. - // Teremo que cercar a de-referência entre parenteses, pois + // Temos que cercar a de-referência entre parênteses, pois // ++ tem uma precedência maior que *. (*px)++; // Incrementa o valor que px está apontando por 1 printf("%d\n", *px); // => Imprime 1 printf("%d\n", x); // => Imprime 1 - // Arrays são um boa maneira de alocar um bloco contínuo de memória + // Arrays são uma boa maneira de alocar um bloco contínuo de memória int x_array[20]; // Declara um array de tamanho 20 (não pode-se mudar o tamanho int xx; for (xx = 0; xx < 20; xx++) { @@ -376,7 +380,7 @@ int main() { // Declara um ponteiro do tipo int e inicialize ele para apontar para x_array int* x_ptr = x_array; // x_ptr agora aponta para o primeiro elemento do array (o inteiro 20). - // Isto funciona porque arrays são apenas ponteiros para seu primeiros elementos. + // Isto funciona porque arrays são apenas ponteiros para seus primeiros elementos. // Por exemplo, quando um array é passado para uma função ou é atribuído a um // ponteiro, ele transforma-se (convertido implicitamente) em um ponteiro. // Exceções: quando o array é o argumento de um operador `&` (endereço-de): @@ -392,7 +396,7 @@ int main() { printf("%zu, %zu\n", sizeof arr, sizeof ptr); // provavelmente imprime "40, 4" ou "40, 8" // Ponteiros podem ser incrementados ou decrementados baseado no seu tipo - // (isto é chamado aritimética de ponteiros + // (isto é chamado aritmética de ponteiros printf("%d\n", *(x_ptr + 1)); // => Imprime 19 printf("%d\n", x_array[1]); // => Imprime 19 @@ -410,9 +414,9 @@ int main() { // "resultados imprevisíveis" - o programa é dito ter um "comportamento indefinido" printf("%d\n", *(my_ptr + 21)); // => Imprime quem-sabe-o-que? Talvez até quebre o programa. - // Quando termina-se de usar um bloco de memória alocado, você pode liberá-lo, + // Quando se termina de usar um bloco de memória alocado, você pode liberá-lo, // ou ninguém mais será capaz de usá-lo até o fim da execução - // (Isto cham-se "memory leak"): + // (Isto chama-se "memory leak"): free(my_ptr); // Strings são arrays de char, mas elas geralmente são representadas @@ -534,7 +538,7 @@ int area(retan r) return r.largura * r.altura; } -// Se você tiver structus grande, você pode passá-las "por ponteiro" +// Se você tiver structus grande, você pode passá-las "por ponteiro" // para evitar cópia de toda a struct: int area(const retan *r) { @@ -551,8 +555,8 @@ conhecidos. Ponteiros para funções são como qualquer outro ponteiro diretamente e passá-las para por toda parte. Entretanto, a sintaxe de definição por ser um pouco confusa. -Exemplo: use str_reverso através de um ponteiro -*/ +Exemplo: use str_reverso através de um ponteiro +*/ void str_reverso_através_ponteiro(char *str_entrada) { // Define uma variável de ponteiro para função, nomeada f. void (*f)(char *); //Assinatura deve ser exatamente igual à função alvo. @@ -572,7 +576,7 @@ typedef void (*minha_função_type)(char *); // Declarando o ponteiro: // ... -// minha_função_type f; +// minha_função_type f; //Caracteres especiais: '\a' // Alerta (sino) @@ -583,7 +587,7 @@ typedef void (*minha_função_type)(char *); '\r' // Retorno de carroça '\b' // Backspace '\0' // Caracter nulo. Geralmente colocado ao final de string em C. - // oi\n\0. \0 é usado por convenção para marcar o fim da string. + // oi\n\0. \0 é usado por convenção para marcar o fim da string. '\\' // Barra invertida '\?' // Interrogação '\'' // Aspas simples @@ -603,7 +607,7 @@ typedef void (*minha_função_type)(char *); "%p" // ponteiro "%x" // hexadecimal "%o" // octal -"%%" // imprime % +"%%" // imprime % /////////////////////////////////////// // Ordem de avaliação diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown new file mode 100644 index 00000000..dbc0c25c --- /dev/null +++ b/pt-br/clojure-macros-pt.html.markdown @@ -0,0 +1,154 @@ +--- +language: clojure +filename: learnclojure-pt.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Raphael Bezerra do Nascimento"] +lang: pt-br +--- + +Como todas as Lisps, a inerente [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +do Clojure lhe dá acesso a toda a extensão da linguagem +para escrever rotinas de geração de código chamados "macros". Macros fornecem uma poderosa forma de adequar a linguagem +às suas necessidades. + +Pórem Tenha cuidado. É considerado má pratica escrever uma macro quando uma função vai fazer. Use uma macro apenas +quando você precisar do controle sobre quando ou se os argumentos para um formulário será avaliado. + +Você vai querer estar familiarizado com Clojure. Certifique-se de entender tudo em +[Clojure em Y Minutos](/docs/clojure/). + +```clojure +;; Defina uma macro utilizando defmacro. Sua macro deve ter como saida uma lista que possa +;; ser avaliada como codigo Clojure. +;; +;; Essa macro é a mesma coisa que se você escrever (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Inspecione o resultado de uma macro utilizando macroexpand or macroexpand-1. +;; +;; Note que a chamada deve utilizar aspas simples. +(macroexpand '(my-first-macro)) +;; -> (#<core$reverse clojure.core$reverse@xxxxxxxx> "Hello World") + +;; Você pode avaliar o resultad de macroexpand diretamente: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; mas você deve usar esse mais suscinto, sintax como de função: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Você pode tornar as coisas mais faceis pra você, utilizando a sintaxe de citação mais suscinta +;; para criar listas nas suas macros: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Note que reverse não é mais uma função objeto, mas um simbolo. + +;; Macros podem ter argumentos. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Mas se você tentar fazer isso com uma lista entre aspas simples, você vai receber um erro, por que o +;; argumento irá entra aspas simples também. Para contornar isso, Clojure prover uma maneira de utilizar aspas simples +;; em macros: `. Dentro `, você pode usar ~ para chegar ao escopo externo. +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Você pode usar os argumentos de destruturação habituais. Expandir lista de variaveis usando ~@ +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Lembrar o do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) avalia e retorna seu corpo, se o primeiro argumento é falso. +;; caso contrario, retorna nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Usado sem cuidados, macros podem fazer muito mal por sobreporem suas variaveis +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;;s Para evitar isso, use gensym para receber um identificador unico +(gensym 'x) ; -> x1281 (ou outra coisa) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Você pode usar # dentro de ` para produzir uma gensym para cada simbolo automaticamente +(defmacro define-x-hygenically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygenically) ; -> (2) +(list x) ; -> (4) + +;; É típico o uso de funções de auxilio com macros. Vamos criar um pouco +;; Vamos criar um pouco para nos ajudar a suportar uma sintaxe aritmética inline (estupida) +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Podemos testar isso imediatamente, sem criar uma macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Entretanto, temos que tornar isso uma macro caso quisermos que isso seja rodado em tempo de compilação +(defmacro inline-2 [form] + (inline-2-helper form))) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (Na verdade, 3N, desde que o numero ficou convertido em uma fração racional com / + +### Leitura adicional + +Escrevendo Macros de [Clojure para o Brave e True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Documentos oficiais +[http://clojure.org/macros](http://clojure.org/macros) + +Quando utilizar macros? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) diff --git a/pt-br/common-lisp-pt.html.markdown b/pt-br/common-lisp-pt.html.markdown new file mode 100644 index 00000000..03a7c15c --- /dev/null +++ b/pt-br/common-lisp-pt.html.markdown @@ -0,0 +1,622 @@ +--- +language: "Common Lisp" +filename: commonlisp-pt.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] +translators: + - ["Édipo Luis Féderle", "https://github.com/edipofederle"] +lang: pt-br +--- + +ANSI Common Lisp é uma linguagem de uso geral, multi-paradigma, designada +para uma variedade de aplicações na indústria. É frequentemente citada +como uma linguagem de programação programável. + + +O ponto inicial clássico é [Practical Common Lisp e livremente disponível](http://www.gigamonkeys.com/book/) + +Outro livro recente e popular é o +[Land of Lisp](http://landoflisp.com/). + + +```common_lisp + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 0. Sintaxe +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; "Form" Geral + + +;; Lisp tem dois pedaços fundamentais de sintaxe: o ATOM e S-expression. +;; Tipicamente, S-expressions agrupadas são chamadas de `forms`. + + +10 ; um atom; é avaliado para ele mesmo + +:THING ;Outro atom; avaliado para o símbolo :thing. + +t ; outro atom, denotado true. + +(+ 1 2 3 4) ; uma s-expression + +'(4 :foo t) ;outra s-expression + + +;;; Comentários + +;; Comentários de uma única linha começam com ponto e vírgula; usar dois para +;; comentários normais, três para comentários de seção, e quadro para comentários +;; em nível de arquivo. + +#| Bloco de comentário + pode abranger várias linhas e... + #| + eles podem ser aninhados + |# +|# + +;;; Ambiente + +;; Existe uma variedade de implementações; a maioria segue o padrão. +;; CLISP é um bom ponto de partida. + +;; Bibliotecas são gerenciadas através do Quicklisp.org's Quicklisp sistema. + +;; Common Lisp é normalmente desenvolvido com um editor de texto e um REPL +;; (Read Evaluate Print Loop) rodando ao mesmo tempo. O REPL permite exploração +;; interativa do programa como ele é "ao vivo" no sistema. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;;; 1. Tipos Primitivos e Operadores +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Símbolos + +'foo ; => FOO Perceba que um símbolo é automáticamente convertido para maiúscula. + +;; Intern manualmente cria um símbolo a partir de uma string. + +(intern "AAAA") ; => AAAA + +(intern "aaa") ; => |aaa| + +;;; Números +9999999999999999999999 ; inteiro +#b111 ; binário => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; ratios +#C(1 2) ; números complexos + + +;; Funções são escritas como (f x y z ...) +;; onde f é uma função e x, y, z, ... são operadores +;; Se você quiser criar uma lista literal de dados, use ' para evitar +;; que a lista seja avaliada - literalmente, "quote" os dados. +'(+ 1 2) ; => (+ 1 2) +;; Você também pode chamar uma função manualmente: +(funcall #'+ 1 2 3) ; => 6 +;; O mesmo para operações aritiméticas +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + + ;;; Booleans +t ; para true (qualquer valor não nil é true) +nil ; para false - e para lista vazia +(not nil) ; => t +(and 0 t) ; => t +(or 0 nil) ; => 0 + + ;;; Caracteres +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; String são arrays de caracteres com tamanho fixo. +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; barra é um escape de caracter + +;; String podem ser concatenadas também! +(concatenate 'string "Hello " "world!") ; => "Hello world!" + +;; Uma String pode ser tratada como uma sequência de caracteres +(elt "Apple" 0) ; => #\A + +;; format pode ser usado para formatar strings +(format nil "~a can be ~a" "strings" "formatted") + +;; Impimir é bastante fácil; ~% indica nova linha +(format t "Common Lisp is groovy. Dude.~%") + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Variáveis +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Você pode criar uma global (escopo dinâmico) usando defparameter +;; um nome de variável pode conter qualquer caracter, exceto: ()",'`;#|\ + +;; Variáveis de escopo dinâmico devem ter asteriscos em seus nomes! + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;; Você pode usar caracteres unicode também. +(defparameter *AΛB* nil) + + +;; Acessando uma variável anteriormente não ligada é um +;; comportamento não definido (mas possível). Não faça isso. + +;; Ligação local: `me` é vinculado com "dance with you" somente dentro +;; de (let ... ). Let permite retornar o valor do último `form` no form let. + +(let ((me "dance with you")) + me) +;; => "dance with you" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Estruturas e Coleções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Estruturas +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) + +(dog-p *rover*) ; => t ;; ewww) +(dog-name *rover*) ; => "rover" + +;; Dog-p, make-dog, e dog-name foram todas criadas por defstruct! + +;;; Pares +;; `cons' constroi pares, `car' and `cdr' extrai o primeiro +;; e o segundo elemento +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + +;;; Listas + +;; Listas são estruturas de dados do tipo listas encadeadas, criadas com `cons' +;; pares e terminam `nil' (ou '()) para marcar o final da lista +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) +;; `list' é um construtor conveniente para listas +(list 1 2 3) ; => '(1 2 3) +;; e a quote (') também pode ser usado para um valor de lista literal +'(1 2 3) ; => '(1 2 3) + +;; Ainda pode-se usar `cons' para adicionar um item no começo da lista. +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Use `append' para - surpreendentemente - juntar duas listas +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Ou use concatenate - + +(concatenate 'list '(1 2) '(3 4)) + +;; Listas são um tipo muito central, então existe uma grande variedade de +;; funcionalidades para eles, alguns exemplos: +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => nil +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vetores + +;; Vector's literais são arrays de tamanho fixo. +#(1 2 3) ; => #(1 2 3) + +;; Use concatenate para juntar dois vectors +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Arrays + +;; Ambos vetores e strings são um caso especial de arrays. + +;; 2D arrays + +(make-array (list 2 2)) + +;; (make-array '(2 2)) também funciona. + +; => #2A((0 0) (0 0)) + +(make-array (list 2 2 2)) + +; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;; Cuidado - os valores de inicialição padrões são +;; definidos pela implementção. Aqui vai como defini-lós. + +(make-array '(2) :initial-element 'unset) + +; => #(UNSET UNSET) + +;; E, para acessar o element em 1,1,1 - +(aref (make-array (list 2 2 2)) 1 1 1) + +; => 0 + +;;; Vetores Ajustáveis + +;; Vetores ajustáveis tem a mesma representação impressa que os vectores +;; de tamanho fixo +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) + +*adjvec* ; => #(1 2 3) + +;; Adicionando novo elemento +(vector-push-extend 4 *adjvec*) ; => 3 + +*adjvec* ; => #(1 2 3 4) + + + +;;; Ingenuamente, conjuntos são apenas listas: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;; Mas você irá querer usar uma estrutura de dados melhor que uma lista encadeada. +;; para performance. + +;;; Dicionários são implementados como hash tables + +;; Cria um hash table +(defparameter *m* (make-hash-table)) + +;; seta um valor +(setf (gethash 'a *m*) 1) + +;; Recupera um valor +(gethash 'a *m*) ; => 1, t + +;; Detalhe - Common Lisp tem multiplos valores de retorno possíveis. gethash +;; retorna t no segundo valor se alguma coisa foi encontrada, e nil se não. + +;; Recuperando um valor não presente retorna nil + (gethash 'd *m*) ;=> nil, nil + +;; Você pode fornecer um valor padrão para uma valores não encontrados +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;; Vamos tratas múltiplos valores de rotorno aqui. + +(multiple-value-bind + (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind + (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Funções +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `lambda' para criar funções anônimas +;; Uma função sempre retorna um valor da última expressão avaliada. +;; A representação exata impressão de uma função varia de acordo ... + +(lambda () "Hello World") ; => #<FUNCTION (LAMBDA ()) {1004E7818B}> + +;; Use funcall para chamar uma função lambda. +(funcall (lambda () "Hello World")) ; => "Hello World" + +;; Ou Apply +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;; "De-anonymize" a função +(defun hello-world () + "Hello World") +(hello-world) ; => "Hello World" + +;; O () acima é a lista de argumentos da função. +(defun hello (name) + (format nil "Hello, ~a " name)) + +(hello "Steve") ; => "Hello, Steve" + +;; Funções podem ter argumentos opcionais; eles são nil por padrão + +(defun hello (name &optional from) + (if from + (format t "Hello, ~a, from ~a" name from) + (format t "Hello, ~a" name))) + + (hello "Jim" "Alpacas") ;; => Hello, Jim, from Alpacas + +;; E os padrões podem ser configurados... +(defun hello (name &optional (from "The world")) + (format t "Hello, ~a, from ~a" name from)) + +(hello "Steve") +; => Hello, Steve, from The world + +(hello "Steve" "the alpacas") +; => Hello, Steve, from the alpacas + + +;; E é claro, palavras-chaves são permitidas também... frequentemente mais +;; flexivel que &optional. + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~a ~a, from ~a" honorific name from)) + +(generalized-greeter "Jim") ; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Igualdade +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Common Lisp tem um sistema sofisticado de igualdade. Alguns são cobertos aqui. + +;; Para número use `=' +(= 3 3.0) ; => t +(= 2 1) ; => nil + +;; para identidade de objeto (aproximadamente) use `eql` +(eql 3 3) ; => t +(eql 3 3.0) ; => nil +(eql (list 3) (list 3)) ; => nil + +;; para listas, strings, e para pedaços de vetores use `equal' +(equal (list 'a 'b) (list 'a 'b)) ; => t +(equal (list 'a 'b) (list 'b 'a)) ; => nil + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Fluxo de Controle +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Condicionais + +(if t ; testa a expressão + "this is true" ; então expressão + "this is false") ; senão expressão +; => "this is true" + +;; Em condicionais, todos valores não nulos são tratados como true +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;; `cond' encadeia uma série de testes para selecionar um resultado +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;; Typecase é um condicional que escolhe uma de seus cláusulas com base do tipo +;; do seu valor + +(typecase 1 + (string :string) + (integer :int)) + +; => :int + +;;; Interação + +;; Claro que recursão é suportada: + +(defun walker (n) + (if (zerop n) + :walked + (walker (1- n)))) + +(walker 5) ; => :walked + +;; Na maioria das vezes, nós usamos DOTLISO ou LOOP + +(dolist (i '(1 2 3 4)) + (format t "~a" i)) + +; => 1234 + +(loop for i from 0 below 10 + collect i) + +; => (0 1 2 3 4 5 6 7 8 9) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Mutação +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Use `setf' para atribuir um novo valor para uma variável existente. Isso foi +;; demonstrado anteriormente no exemplo da hash table. + +(let ((variable 10)) + (setf variable 2)) + ; => 2 + + +;; Um bom estilo Lisp é para minimizar funções destrutivas e para evitar +;; mutação quando razoável. + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Classes e Objetos +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Sem clases Animal, vamos usar os veículos de transporte de tração +;; humana mecânicos. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;; defcalss, seguido do nome, seguido por uma list de superclass, +;; seguido por um uma 'slot list', seguido por qualidades opcionais como +;; :documentation + +;; Quando nenhuma lista de superclasse é setada, uma lista padrão para +;; para o objeto padrão é usada. Isso *pode* ser mudado, mas não até você +;; saber o que está fazendo. Olhe em Art of the Metaobject Protocol +;; para maiores informações. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + + +;; Chamando DESCRIBE na classe human-powered-conveyance no REPL dá: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #<STANDARD-CLASS +; HUMAN-POWERED-CONVEYANCE>: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;; Note o comportamento reflexivo disponível para você! Common Lisp é +;; projetada para ser um sistema interativo. + +;; Para definir um métpdo, vamos encontrar o que nossa cirunferência da +;; roda da bicicleta usando a equação: C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;; pi já é definido para a gente em Lisp! + +;; Vamos supor que nós descobrimos que o valor da eficiência do número +;; de remadores em uma canoa é aproximadamente logarítmica. Isso provavelmente +;; deve ser definido no construtor / inicializador. + +;; Veja como initializar sua instância após Common Lisp ter construído isso: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;; Em seguida, para a construção de uma ocorrência e verificar a eficiência média ... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Macros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Macros permitem que você estenda a sintaxe da lingaugem + +;; Common Lisp não vem com um loop WHILE - vamos adicionar um. +;; Se obedecermos nossos instintos 'assembler', acabamos com: + +(defmacro while (condition &body body) + "Enquanto `condition` é verdadeiro, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + (let ((block-name (gensym))) + `(tagbody + (unless ,condition + (go ,block-name)) + (progn + ,@body) + ,block-name))) + +;; Vamos dar uma olhada em uma versão alto nível disto: + + +(defmacro while (condition &body body) + "Enquanto `condition` for verdadeira, `body` é executado. + +`condition` é testado antes de cada execução do `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;; Entretanto, com um compilador moderno, isso não é preciso; o LOOP +;; 'form' compila igual e é bem mais fácil de ler. + +;; Noteq ue ``` é usado , bem como `,` e `@`. ``` é um operador 'quote-type' +;; conhecido como 'quasiquote'; isso permite o uso de `,` . `,` permite "unquoting" +;; e variáveis. @ interpolará listas. + +;; Gensym cria um símbolo único garantido que não existe em outras posições +;; o sistema. Isto é porque macros são expandidas em tempo de compilação e +;; variáveis declaradas na macro podem colidir com as variáveis usadas na +;; código regular. + +;; Veja Practical Common Lisp para maiores informações sobre macros. +``` + + +## Leitura Adicional + +[Continua em frente com Practical Common Lisp book.](http://www.gigamonkeys.com/book/) + + +## Créditos + +Muitos agradecimentos ao pessoal de Schema por fornecer um grande ponto de partida +o que facilitou muito a migração para Common Lisp. + +- [Paul Khuong](https://github.com/pkhuong) pelas grandes revisões. diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown new file mode 100644 index 00000000..b1fbd961 --- /dev/null +++ b/pt-br/css-pt.html.markdown @@ -0,0 +1,257 @@ +--- +language: css +filename: learncss-pt.css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] +lang: pt-br +--- + +Nos primeiros dias da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornou comum. + +CSS ajuda a manter a separação entre o conteúdo (HTML) e o look-and-feel de uma página web. + +CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles. + +Este guia foi escrito para CSS2, embora CSS3 está rapidamente se tornando popular. + +**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa tentar de tudo em um playground CSS como [dabblet](http://dabblet.com/). +O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. + +```css +/* Comentários aparecem dentro do slash-asterisk, tal como esta linha! + não há "comentários de uma linha"; este é o único estilo de comentário * / + +/* #################### + ## SELETORES + #################### */ + +/* O seletor é usado para direcionar um elemento em uma página. + seletor { propriedade: valor; / * Mais propriedades ... * / } + +/* +Abaixo um elemento de exemplo: + +<div class='class1 class2' id='anID' attr='value' otherAttr='pt-br foo bar' /> +*/ + +/* Você pode direciona-lo usando uma das suas classes CSS */ +.class1 { } + +/* ou ambas as classes! */ +.class1.class2 { } + +/* ou o seu nome */ +div { } + +/* ou o seu id */ +#anID { } + +/* ou utilizando o fator de que tem um atributo!*/ +[attr] { font-size:smaller; } + +/* ou que o atributo tem um valor específico */ +[attr='value'] { font-size:smaller; } + +/* começa com um valor (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* ou terminando com um valor (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + + +/* Ou contém um valor em uma lista separada por espaços */ +[otherAttr ~ = 'foo'] {} +[otherAttr ~ = 'bar'] {} + +/* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */ +[otherAttr | = 'en'] {font-size: smaller; } + + +/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não + colocar espaços entre eles. */ +classe div.some [attr $ = 'ue'] {} + +/* Você pode selecionar um elemento que é filho de outro elemento */ +div.some-parent> .class-name {} + +/* Ou um descendente de um outro elemento. As crianças são os descendentes diretos de + seu elemento pai, apenas um nível abaixo da árvore. Pode ser qualquer descendentes + nivelar por baixo da árvore. */ +div.some-parent class-name {} + +/* Atenção: o mesmo seletor sem espaço tem um outro significado. + Você consegue adivinhar o que? */ +div.some-parent.class-name {} + +/* Você também pode selecionar um elemento com base em seu irmão adjacente */ +.i am just-antes + .Este elemento {} + +/* Ou qualquer irmão que o precede */ +.i am-qualquer-elemento antes ~ .Este elemento {} + +/* Existem alguns selectores chamado pseudo classes que podem ser usados para selecionar um + elemento quando ele está em um determinado estado */ + +/* Por exemplo, quando o cursor passa sobre um elemento */ +seletor:hover {} + +/* Ou um link foi visitado */ +seletor:visited {} + +/* Ou não tenha sido visitado */ +seletor:link {} + +/* Ou um elemento em foco */ +seletor:focus {} + +/* Qualquer elemento que é o primeiro filho de seu pai */ +seletor:first-child {} + +/* Qualquer elemento que é o último filho de seu pai */ +seletor:last-child {} + +/* Assim como pseudo classes, pseudo elementos permitem que você estilo certas partes de um documento */ + +/* Corresponde a um primeiro filho virtual do elemento selecionado */ +seletor::before {} + +/* Corresponde a um último filho virtual do elemento selecionado */ +seletor::after {} + +/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos + elemento */ +* {} /* */ Todos os elementos +.parent * {} /* */ todos os descendentes +.parent> * {} /* */ todas as crianças + +/* #################### + ## PROPRIEDADES + #################### */ + +seletor { + + /* Unidades de comprimento pode ser absoluta ou relativa. */ + + /* Unidades relativas */ + width: 50%; /* Percentagem de largura elemento pai */ + font-size: 2em; /* Múltiplos de font-size original de elemento */ + font-size: 2rem; /* Ou do elemento raiz font-size */ + font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */ + font-size: 2vh; /* Ou a sua altura */ + font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */ + font-size: 2vmax; /* Ou superior */ + + /* Unidades absolutas */ + width: 200px; /* píxeis */ + font-size: 20pt; /* Pontos */ + width: 5cm; /* Centímetros */ + min-width: 50mm; /* Milímetros */ + max-width: 5 polegadas; /* Polegadas */ + + /* Cores */ + color: # F6E; /* Formato hexadecimal curto */ + color: # FF66EE; /* Formato hexadecimal longo */ + color: tomato; /* Uma cor nomeada */ + color: rgb (255, 255, 255); /* Como valores rgb */ + color: RGB (10%, 20%, 50%); /* Como porcentagens rgb */ + color: rgba (255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 <a <1 */ + color: transparent; /* Equivale a definir o alfa a 0 */ + color: HSL (0, 100%, 50%); /* Como porcentagens HSL (CSS 3) */ + color: HSLA (0, 100%, 50%, 0,3); /* Como porcentagens HSLA com alfa */ + + /* Imagens como fundos de elementos */ + background-image: url (/img-path/img.jpg); /* Citações dentro url () opcional */ + + /* Fontes */ + font-family: Arial; + /* Se o nome da família de fonte tem um espaço, deve ser citado */ + font-family: "Courier New"; + /* Se o primeiro não for encontrada, o navegador usa o próximo, e assim por diante */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Uso + +Guardar uma folha de estilo CSS com a extensão `.css`. + +```xml +<!-- Você precisa incluir o arquivo css no da sua página <head>. Isto é o + método recomendado. Consulte http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Você também pode incluir alguns CSS inline na sua marcação. --> +<style> + a { color: purple; } +</style> + +<!-- Ou diretamente definir propriedades CSS no elemento. --> +<div style="border: 1px solid red;"> +</div> +``` + +## Precedência ou Cascata + +Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre os outros. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior. + +Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata. + +Dado o seguinte CSS: + +```css +/* UMA */ +p.class1[attr="value"] + +/* B */ +p.class1 {} + +/* C */ +p.class2 {} + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +e a seguinte marcação: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + +A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco. + +* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso. +* `F` é a próxima, porque é um estilo interno. +* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`. +* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`. +* `B` é o próximo. +* `D` é a última. + +## Compatibilidade + +A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática para verificar antes de usar um novo recurso. + +## Recursos + +* Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/) + +## Leitura adicional + +* [Entendendo Estilo Precedência em CSS: Especificidade, Herança, eo Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) e [menos](http://lesscss.org/) para CSS pré-processamento +* [CSS-Tricks](https://css-tricks.com) diff --git a/pt-br/git-pt.html.markdown b/pt-br/git-pt.html.markdown index 6d2a55cd..981da503 100644 --- a/pt-br/git-pt.html.markdown +++ b/pt-br/git-pt.html.markdown @@ -1,110 +1,119 @@ --- category: tool tool: git +lang: pt-br +filename: LearnGit.txt contributors: - ["Jake Prather", "http://github.com/JakeHP"] translators: - - ["Miguel Araújo", "https://github.com/miguelarauj1o"] -lang: pt-br -filename: learngit-pt.txt + - ["Suzane Sant Ana", "http://github.com/suuuzi"] --- -Git é um sistema de controle de versão distribuído e de gerenciamento de código-fonte. +Git é um sistema distribuido de gestão para código fonte e controle de versões. -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. +Funciona através de uma série de registos de estado do projeto e usa esse +registo para permitir funcionalidades de versionamento e gestão de código +fonte. -## Versionando Conceitos +## Conceitos de versionamento -### O que é controle de versão? +### 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. +Controle de versão (*source control*) é um processo de registo de alterações +a um arquivo ou conjunto de arquivos ao longo do tempo. -### Versionamento Centralizado VS Versionamento Distribuído +### Controle de versão: Centralizado VS 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. +* Controle de versão centralizado foca na sincronização, registo e *backup* +de arquivos. +* Controle de versão distribuído foca em compartilhar alterações. Cada +alteração é associada a um *id* único. +* Sistemas distribuídos não tem estrutura definida. É possivel ter um sistema +centralizado ao estilo SVN usando git. -[Informação Adicional](http://git-scm.com/book/en/Getting-Started-About-Version-Control) +[Informação adicional (EN)](http://git-scm.com/book/en/Getting-Started-About-Version-Control) -### Porque usar o Git? +### Por que usar git? -* Possibilidade de trabalhar offline -* Colaborar com os outros é fácil! -* Ramificação é fácil -* Mesclagem é fácil -* Git é rápido -* Git é flexível. +* Permite trabalhar offline. +* Colaborar com outros é fácil! +* Criar *branches* é fácil! +* Fazer *merge* é fácil! +* Git é rápido. +* Git é flexivel. + +## Git - Arquitetura -## 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 conjunto de arquivos, diretórios, registos históricos, *commits* e +referências. Pode ser descrito como uma estrutura de dados de código fonte +com a particularidade de cada elemento do código fonte permitir acesso ao +histórico das suas alterações, entre outras coisas. -Um repositório git é composto do diretório git. e árvore de trabalho. +Um repositório git é constituido pelo diretório .git e a *working tree* ### 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) +O repositório .git contém todas as configurações, *logs*, *branches*, +referências e outros. + +[Lista detalhada (EN)](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) -### Árvore de trabalho (componente do repositório) +### *Working Tree* (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. +A *Working Tree* é basicamente a listagem dos diretórios e arquivos do repositório. É chamada também de diretório do projeto. -### Índice (componente do diretório .git) +### *Index* (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. +O *Index* é a camada da interface no git. É o elemento que separa +o diretório do projeto do repositório git. Isto permite aos programadores um +maior controle sobre o que é registado no repositório git. -### Comete (commit) +### *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! +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos arquivos do projeto. +Por exemplo, ao adicionar cinco arquivos e remover outros 2, estas alterações +serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado +para outros repositórios ou não! -### Ramo (branch) +### *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. +Um *branch* é essencialmente uma referência que aponta para o último *commit* +efetuado. Na medida que são feitos novos commits, esta referência é atualizada +automaticamente e passa a apontar para o commit mais recente. -### Cabeça (HEAD) e cabeça (head) (componente do diretório .git) +### *HEAD* e *head* (componentes 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. +*HEAD* é a referência que aponta para o *branch* em uso. Um repositório só tem +uma *HEAD* activa. +*head* é uma referência que aponta para qualquer *commit*. Um repositório pode +ter um número indefinido de *heads* -### Recursos Conceituais +### Recursos conceituais (EN) -* [Git para Cientistas da Computação](http://eagain.net/articles/git-for-computer-scientists/) +* [Git para Cientistas de Computação](http://eagain.net/articles/git-for-computer-scientists/) * [Git para Designers](http://hoth.entp.com/output/git_for_designers.html) ## Comandos -### init +### *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". +Cria um repositório Git vazio. As definições, informação guardada e outros do +repositório git são guardados em uma pasta chamada ".git". ```bash $ git init ``` -### config +### *config* -Para configurar as definições. Quer seja para o repositório, o próprio sistema, ou -configurações globais. +Permite configurar as definições, sejam as definições do repositório, sistema +ou configurações globais. ```bash -# Impressão e definir algumas variáveis de configuração básica (global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -112,22 +121,21 @@ $ 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) +[Aprenda mais sobre git config. (EN)](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. +Para visualizar rapidamente o detalhamento de cada comando ou apenas lembrar da semântica. ```bash -# Rapidamente verificar os comandos disponíveis +# Ver rapidamente os comandos disponiveis $ git help -# Confira todos os comandos disponíveis +# Ver todos os comandos disponiveis $ git help -a -# Ajuda específica de comando - manual do usuário -# git help <command_here> +# Usar o *help* para um comando especifico +# git help <comando_aqui> $ git help add $ git help commit $ git help init @@ -135,85 +143,89 @@ $ 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. +Apresenta as diferenças entre o arquivo *index* (a versão corrente +do repositório) e o *commit* da *HEAD* atual. + ```bash -# Irá exibir o ramo, os arquivos não monitorados, as alterações e outras diferenças +# Apresenta o *branch*, arquivos não monitorados, alterações e outras +# difereças $ git status -# Para saber outras "tid bits" sobre git status +# Para aprender mais detalhes 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! +Adiciona arquivos ao repositório corrente. Se os arquivos novos não forem +adicionados através de `git add` ao repositório, então eles não serão +incluidos nos commits! ```bash -# Adicionar um arquivo no seu diretório de trabalho atual +# adiciona um arquivo no diretório do projeto atual $ git add HelloWorld.java -# Adicionar um arquivo em um diretório aninhado +# adiciona um arquivo num sub-diretório $ git add /path/to/file/HelloWorld.c -# Suporte a expressões regulares! +# permite usar expressões regulares! $ git add ./*.java ``` ### branch -Gerenciar seus ramos. Você pode visualizar, editar, criar, apagar ramos usando este comando. +Gerencia os *branches*. É possível ver, editar, criar e apagar branches com este +comando. ```bash -# Lista ramos e controles remotos existentes +# listar *branches* existentes e remotos $ git branch -a -# Criar um novo ramo +# criar um novo *branch* $ git branch myNewBranch -# Apagar um ramo +# apagar um *branch* $ git branch -d myBranch -# Renomear um ramo +# alterar o nome de um *branch* # git branch -m <oldname> <newname> $ git branch -m myBranchName myNewBranchName -# Editar a descrição de um ramo +# editar a descrição de um *branch* $ git branch myBranchName --edit-description ``` ### checkout -Atualiza todos os arquivos na árvore de trabalho para corresponder à versão no -índice, ou árvore especificada. +Atualiza todos os arquivos no diretório do projeto para que fiquem iguais +à versão do index ou do *branch* especificado. ```bash -# Finalizar um repo - padrão de ramo mestre +# Checkout de um repositório - por padrão para o branch master $ git checkout -# Checa um ramo especificado +# Checkout de um branch especifico $ git checkout branchName -# Criar um novo ramo e mudar para ela, como: "<nome> git branch; git checkout <nome>" +# Cria um novo branch e faz checkout para ele. +# Equivalente a: "git branch <name>; git checkout <name>" $ 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. +Clona ou copia um repositório existente para um novo diretório. Também +adiciona *branches* de monitoramento remoto para cada *branch* no repositório +clonado o que permite enviar alterações para um *branch* remoto. ```bash -# Clone learnxinyminutes-docs +# Clona 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. +Guarda o conteudo atual do index num novo *commit*. Este *commit* contém +as alterações feitas e a mensagem criada pelo usuário. ```bash # commit com uma mensagem @@ -222,170 +234,170 @@ $ 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. +Apresenta as diferenças entre um arquivo no repositório do projeto, *index* +e *commits* ```bash -# Mostrar diferença entre o seu diretório de trabalho e o índice. +# Apresenta a diferença entre o diretório atual e o index $ git diff -# Mostrar diferenças entre o índice e o commit mais recente. +# Apresenta a diferença entre o index e os commits mais recentes $ git diff --cached -# Mostrar diferenças entre o seu diretório de trabalho e o commit mais recente. +# Apresenta a diferença entre o diretório atual e o commit mais recente $ git diff HEAD ``` ### grep -Permite procurar rapidamente um repositório. +Permite procurar facilmente num 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 +# Define a apresentação de números de linha nos resultados do grep $ git config --global grep.lineNumber true -# Fazer resultados de pesquisa mais legível, incluindo agrupamento +# Agrupa os resultados da pesquisa para facilitar a leitura $ git config --global alias.g "grep --break --heading --line-number" ``` ```bash -# Procure por "variableName" em todos os arquivos java +# Pesquisa 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 \) +# Pesquisa por uma linha que contém "arrayListName" e "add" ou "remove" +$ 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) +O Google é seu amigo; para mais exemplos: +[Git Grep Ninja (EN)](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) ### log -Mostrar commits para o repositório. +Apresenta commits do repositório. ```bash -# Mostrar todos os commits +# Apresenta todos os commits $ git log -# Mostrar um número X de commits +# Apresenta X commits $ git log -n 10 -# Mostrar somente commits mesclados +# Apresenta apenas commits de merge $ git log --merges ``` ### merge -"Merge" em mudanças de commits externos no branch atual. +"Merge" junta as alterações de commits externos com o *branch* atual. ```bash -# Mesclar o ramo especificado para o atual. +# Junta o branch especificado com o atual $ git merge branchName -# Gera sempre uma mesclagem commit ao mesclar +# Para gerar sempre um commit ao juntar os branches $ git merge --no-ff branchName ``` ### mv -Renomear ou mover um arquivo +Alterar o nome ou mover um arquivo. ```bash -# Renomear um arquivo +# Alterar o nome de 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 +# Forçar a alteração de nome ou mudança local +# "existingFile" já existe no directório, será sobrescrito. $ git mv -f myFile existingFile ``` ### pull -Puxa de um repositório e se funde com outro ramo. +Puxa alterações de um repositório e as junta com outro branch ```bash -# Atualize seu repo local, através da fusão de novas mudanças -# A partir da "origem" remoto e ramo "master (mestre)". +# Atualiza o repositório local, juntando as novas alterações +# do repositório remoto 'origin' e branch 'master' # git pull <remote> <branch> -# git pull => implícito por padrão => git pull origin master +# git pull => aplica a predefiniçã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>" +# Juntar alterações do branch remote e fazer rebase commits do branch +# no repositório 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. +Enviar e juntar alterações de um branch para o seu branch correspondente +num repositório remoto. ```bash -# Pressione e mesclar as alterações de um repo local para um -# Chamado remoto "origem" e ramo de "mestre". +# Envia e junta as alterações de um repositório local +# para um remoto denominado "origin" no branch "master". # git push <remote> <branch> -# git push => implícito por padrão => git push origin master +# git push => aplica a predefiniçã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) +### 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 *. +Pega em todas as alterações que foram registadas num branch e volta a +aplicá-las em outro branch. +*Não deve ser feito rebase de commits que foram enviados para um repositório +público* ```bash -# Rebase experimentBranch para mestre +# Faz Rebase de experimentBranch para master # git rebase <basebranch> <topicbranch> $ git rebase master experimentBranch ``` -[Leitura Adicional.](http://git-scm.com/book/en/Git-Branching-Rebasing) +[Leitura adicional (EN).](http://git-scm.com/book/en/Git-Branching-Rebasing) -### reset (CAUTELA) +### reset (cuidado!) -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. +Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, +*pulls*, *commits*, *adds* e outros. É um comando muito poderoso mas também +perigoso quando não há certeza do que se está fazendo. ```bash -# Repor a área de teste, para coincidir com o último commit (deixa diretório inalterado) +# Restabelece a camada intermediária de registo para o último +# commit (o directório fica sem alterações) $ git reset -# Repor a área de teste, para coincidir com o último commit, e substituir diretório trabalhado +# Restabelece a camada intermediária de registo para o último commit, e +# sobrescreve o projeto atual $ 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. +# Move a head do branch atual para o commit especificado, sem alterar o projeto. +# todas as alterações ainda existem no projeto $ 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). +# Inverte a head do branch atual para o commit especificado +# fazendo com que este esteja em sintonia com o diretório do projeto +# Remove alterações não registadas 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. +O oposto de git add, git rm remove arquivos do branch atual. ```bash # remove HelloWorld.c $ git rm HelloWorld.c -# Remove um arquivo de um diretório aninhado +# Remove um arquivo de um sub-directório $ git rm /pather/to/the/file/HelloWorld.c ``` -# # Mais informações +## Informação complementar (EN) * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) @@ -398,5 +410,3 @@ $ 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 - guia prático](http://rogerdudler.github.io/git-guide/index.pt_BR.html)
\ No newline at end of file diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index 885d5b27..2ec7d967 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -9,7 +9,7 @@ translators: lang: pt-br --- -Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://groovy.codehaus.org) +Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://www.groovy-lang.org/) ```groovy @@ -236,7 +236,7 @@ for ( e in map ) { Sobrecarregamento de Operadores para uma lsita dos operadores comuns que Grooby suporta: - http://groovy.codehaus.org/Operator+Overloading + http://www.groovy-lang.org/operators.html#Operator-Overloading Operadores Groovy úteis */ @@ -255,7 +255,7 @@ def nomeUsuario = usuario?.nomeUsuario Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método. É um pedação de código que é definido e executado em um momento posterior. - Mais informação em: http://groovy.codehaus.org/Closures+-+Formal+Definition + Mais informação em: http://www.groovy-lang.org/closures.html */ //Exemplo: def clos = { println "Hello World!" } @@ -413,11 +413,11 @@ assert soma(2,5) == 7 ## Referências -[Groovy documentation](http://groovy.codehaus.org/Documentation) +[Groovy documentation](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -Junte-se a um [grupo de usuários Groovy](http://groovy.codehaus.org/User+Groups) +Junte-se a um [grupo de usuários Groovy](http://www.groovy-lang.org/usergroups.html) ## Livro diff --git a/pt-br/hack-pt.html.markdown b/pt-br/hack-pt.html.markdown new file mode 100644 index 00000000..7c938149 --- /dev/null +++ b/pt-br/hack-pt.html.markdown @@ -0,0 +1,316 @@ +--- +language: Hack +contributors: + - ["Stephen Holdaway", "https://github.com/stecman"] + - ["David Lima", "https://github.com/davelima"] +translators: + - ["David Lima", "https://github.com/davelima"] +lang: pt-br +filename: learnhack-pt.hh +--- + +Hack é uma linguagem baseada no PHP e roda numa máquina virtual chamada HHVM. +Hack é quase completamente interoperável com códigos PHP existentes e adiciona +alguns recursos úteis de linguagens estaticamente tipadas. + +Somente recursos específicos da linguagem Hack serão abordados aqui. Detalhes +sobre a sintaxe do PHP estão disponíveis no +[artigo PHP](http://learnxinyminutes.com/docs/php/) neste site. + +```php +<?hh + +// A sintaxe do Hack é ativada apenas em arquivos que comecem com <?hh +// Marcadores <?hh não podem ser incluídos em páginas HTML, diferente de <?php. +// Usar o marcador "<?hh //strict" coloca o verificador de tipo no modo estrito. + + +// Indução de tipo de parâmetros escalares +function repeat(string $palavra, int $contagem) +{ + $palavra = trim($palavra); + return str_repeat($palavra . ' ', $contagem); +} + +// Indução de tipo para valores de retorno +function add(...$numeros) : int +{ + return array_sum($numeros); +} + +// Funções que não retornam nada são induzidas com "void" +function truncate(resource $recurso) : void +{ + // ... +} + +// Induções de tipo devem permitir nulos de forma explícita +function identity(?string $stringOuNulo) : ?string +{ + return $stringOuNulo; +} + +// Induções de tipo podem ser especificadas em propriedades de classes +class PropriedadesComTipos +{ + public ?string $nome; + + protected int $id; + + private float $pontuacao = 100.0; + + // O verificador de tipos do Hack reforça que propriedades tipadas devem + // ter um valor padrão ou devem ser definidos no construtor + public function __construct(int $id) + { + $this->id = $id; + } +} + + +// Funções anônimas (lambdas) +$multiplicador = 5; +array_map($y ==> $y * $multiplicador, [1, 2, 3]); + + +// Genéricos +class Caixa<T> +{ + protected T $dados; + + public function __construct(T $dados) { + $this->dados = $dados; + } + + public function pegaDados(): T { + return $this->dados; + } +} + +function abreCaixa(Caixa<int> $caixa) : int +{ + return $caixa->pegaDados(); +} + + +// Formas +// +// Hack adiciona o conceito de formas para definir arrays com uma estrutura +// e tipos de dados garantidos +type Point2D = shape('x' => int, 'y' => int); + +function distancia(Point2D $a, Point2D $b) : float +{ + return sqrt(pow($b['x'] - $a['x'], 2) + pow($b['y'] - $a['y'], 2)); +} + +distancia( + shape('x' => -1, 'y' => 5), + shape('x' => 2, 'y' => 50) +); + + +// Pseudônimos de tipos +// +// Hack adiciona vários recursos para criação de pseudônimos, tornando tipos complexos +// mais fáceis de entender +newtype VectorArray = array<int, Vector<int>>; + +// Um tuple contendo dois inteiros +newtype Point = (int, int); + +function adicionaPontos(Point $p1, Point $p2) : Point +{ + return tuple($p1[0] + $p2[0], $p1[1] + $p2[1]); +} + +adicionaPontos( + tuple(1, 2), + tuple(5, 6) +); + + +// enums em classes +enum TipoDePista : int +{ + Estrada = 0; + Rua = 1; + Alameda = 2; + Avenida = 3; +} + +function getTipoDePista() : TipoDePista +{ + return TipoDePista::Alameda; +} + + +// Especificação de argumentos no construtor (Argument Promotion) +// +// Para evitar que propriedades sejam definidas em mais de um lugar, e +// construtores que só definem propriedades, o Hack adiciona uma sintaxe para +// definir as propriedades e o construtor ao mesmo tempo. +class ArgumentPromotion +{ + public function __construct(public string $nome, + protected int $idade, + private bool $legal) {} +} + +class SemArgumentPromotion +{ + public string $nome; + + protected int $idade; + + private bool $legal; + + public function __construct(string $nome, int $idade, bool $legal) + { + $this->nome = $nome; + $this->idade = $idade; + $this->legal = $legal; + } +} + + +// Multi-tarefas cooperativo +// +// Duas novas palavras-chave ("async" e "await") podem ser usadas para +// trabalhar com multi-tarefas. +// Obs. Isto não envolve threads - apenas permite a transferência de controle +async function printCooperativo(int $inicio, int $fim) : Awaitable<void> +{ + for ($i = $inicio; $i <= $fim; $i++) { + echo "$i "; + + // Permite que outras tarefas façam algo + await RescheduleWaitHandle::create(RescheduleWaitHandle::QUEUE_DEFAULT, 0); + } +} + +// Imprime "1 4 7 2 5 8 3 6 9" +AwaitAllWaitHandle::fromArray([ + printCooperativo(1, 3), + printCooperativo(4, 6), + printCooperativo(7, 9) +])->getWaitHandle()->join(); + + +// Atributos +// +// Atributos são uma forma de definir metadados para funções. +// Hack tem alguns atributos especiais que possuem comportamentos úteis. + +// O atributo especial __Memoize faz com que o resultado da função fique em cache +<<__Memoize>> +function tarefaDemorada() : ?string +{ + return file_get_contents('http://exemplo.com'); +} + +// O corpo da função só é executado uma vez aqui: +tarefaDemorada(); +tarefaDemorada(); + + +// O atributo especial __ConsistentConstruct faz com que o Hack certifique-se +// de que a assinatura do construtor seja a mesma em todas as subclasses +<<__ConsistentConstruct>> +class FooConsistente +{ + public function __construct(int $x, float $y) + { + // ... + } + + public function algumMetodo() + { + // ... + } +} + +class BarConsistente extends FooConsistente +{ + public function __construct(int $x, float $y) + { + // O verificador de tipos do Hack exige que os construtores pai + // sejam chamados + parent::__construct($x, $y); + + // ... + } + + // A anotação __Override é uma anotação opcional que faz com que o + // verificador de tipos do Hack sobrescreva um método em uma classe pai + // ou um trait. Sem __Override, definir este método causará um erro, + // pois ele já foi definido na classe pai (FooConsistente): + <<__Override>> + public function algumMetodo() + { + // ... + } +} + +class SubclasseFooInvalida extends FooConsistente +{ + // Caso o construtor não combine com o construtor da classe pai, o + // verificador de tipos acusará um erro: + // + // "Este objeto é incompatível com o objeto FooConsistente porque algum(ns) + // dos seus métodos são incompatíveis" + // + public function __construct(float $x) + { + // ... + } + + // Usar a anotação __Override em um método que não existe na classe pai + // causará um erro do verificador de tipos: + // "SubclasseFooInvalida::outroMetodo() está marcada para sobrescrever; + // nenhuma definição não-privada foi encontrada ou a classe pai foi + // definida em código não-<?hh" + // + <<__Override>> + public function outroMetodo() + { + // ... + } +} + + +// Traits podem implementar interfaces (não suportado pelo PHP) +interface InterfaceGatinho +{ + public function brinca() : void; +} + +trait TraitGato implements InterfaceGatinho +{ + public function brinca() : void + { + // ... + } +} + +class Samuel +{ + use TraitGato; +} + + +$gato = new Samuel(); +$gato instanceof InterfaceGatinho === true; // True + +``` + +## Mais informações + +Visite a [documentação do Hack](http://docs.hhvm.com/manual/en/hacklangref.php) +para ver explicações detalhadas dos recursos que Hack adiciona ao PHP, ou o [site oficial do Hack](http://hanlang.org/) +para outras informações. + +Visite o [site oficial do HHVM](http://hhvm.com/) para aprender a instalar o HHVM. + +Visite [este artigo](http://docs.hhvm.com/manual/en/hack.unsupported.php) para ver +os recursos do PHP que o Hack não suporta e ver incompatibilidades entre Hack e PHP. diff --git a/pt-br/hy-pt.html.markdown b/pt-br/hy-pt.html.markdown new file mode 100644 index 00000000..4230579d --- /dev/null +++ b/pt-br/hy-pt.html.markdown @@ -0,0 +1,176 @@ +--- +language: hy +filename: learnhy.hy +contributors: + - ["Abhishek L", "http://twitter.com/abhishekl"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Hy é um dialeto de Lisp escrito sobre Python. Isto é possível convertendo +código Hy em árvore sintática abstrata python (ast). Portanto, isto permite +hy chamar código python nativo e vice-versa. + +Este tutorial funciona para hy ≥ 0.9.12 + +```clojure +;; Isso dá uma introdução básica em hy, como uma preliminar para o link abaixo +;; http://try-hy.appspot.com +;; +; Comentários em ponto-e-vírgula, como em outros LISPS + +;; s-noções básicas de expressão +; programas Lisp são feitos de expressões simbólicas ou sexps que se assemelham +(some-function args) +; agora o essencial "Olá mundo" +(print "hello world") + +;; Tipos de dados simples +; Todos os tipos de dados simples são exatamente semelhantes aos seus homólogos +; em python que +42 ; => 42 +3.14 ; => 3.14 +True ; => True +4+10j ; => (4+10j) um número complexo + +; Vamos começar com um pouco de aritmética muito simples +(+ 4 1) ;=> 5 +; o operador é aplicado a todos os argumentos, como outros lisps +(+ 4 1 2 3) ;=> 10 +(- 2 1) ;=> 1 +(* 4 2) ;=> 8 +(/ 4 1) ;=> 4 +(% 4 2) ;=> 0 o operador módulo +; exponenciação é representado pelo operador ** como python +(** 3 2) ;=> 9 +; formas aninhadas vão fazer a coisa esperada +(+ 2 (* 4 2)) ;=> 10 +; também operadores lógicos e ou não e igual etc. faz como esperado +(= 5 4) ;=> False +(not (= 5 4)) ;=> True + +;; variáveis +; variáveis são definidas usando SETV, nomes de variáveis podem usar utf-8, exceto +; for ()[]{}",'`;#| +(setv a 42) +(setv π 3.14159) +(def *foo* 42) +;; outros tipos de dados de armazenamento +; strings, lists, tuples & dicts +; estes são exatamente os mesmos tipos de armazenamento de python +"hello world" ;=> "hello world" +; operações de string funcionam semelhante em python +(+ "hello " "world") ;=> "hello world" +; Listas são criadas usando [], a indexação começa em 0 +(setv mylist [1 2 3 4]) +; tuplas são estruturas de dados imutáveis +(setv mytuple (, 1 2)) +; dicionários são pares de valores-chave +(setv dict1 {"key1" 42 "key2" 21}) +; :nome pode ser utilizado para definir palavras-chave em hy que podem ser utilizados para as chaves +(setv dict2 {:key1 41 :key2 20}) +; usar 'get' para obter o elemento em um índice/key +(get mylist 1) ;=> 2 +(get dict1 "key1") ;=> 42 +; Alternativamente, se foram utilizadas palavras-chave que podem ser chamadas diretamente +(:key1 dict2) ;=> 41 + +;; funções e outras estruturas de programa +; funções são definidas usando defn, o último sexp é devolvido por padrão +(defn greet [name] + "A simple greeting" ; uma docstring opcional + (print "hello " name)) + +(greet "bilbo") ;=> "hello bilbo" + +; funções podem ter argumentos opcionais, bem como argumentos-chave +(defn foolists [arg1 &optional [arg2 2]] + [arg1 arg2]) + +(foolists 3) ;=> [3 2] +(foolists 10 3) ;=> [10 3] + +; funções anônimas são criados usando construtores 'fn' ou 'lambda' +; que são semelhantes para 'defn' +(map (fn [x] (* x x)) [1 2 3 4]) ;=> [1 4 9 16] + +;; operações de sequência +; hy tem algumas utils embutidas para operações de sequência, etc. +; recuperar o primeiro elemento usando 'first' ou 'car' +(setv mylist [1 2 3 4]) +(setv mydict {"a" 1 "b" 2}) +(first mylist) ;=> 1 + +; corte listas usando 'slice' +(slice mylist 1 3) ;=> [2 3] + +; obter elementos de uma lista ou dict usando 'get' +(get mylist 1) ;=> 2 +(get mydict "b") ;=> 2 +; lista de indexação começa a partir de 0, igual em python +; assoc pode definir elementos em chaves/índices +(assoc mylist 2 10) ; faz mylist [1 2 10 4] +(assoc mydict "c" 3) ; faz mydict {"a" 1 "b" 2 "c" 3} +; há toda uma série de outras funções essenciais que torna o trabalho com +; sequências uma diversão + +;; Python interop +;; importação funciona exatamente como em python +(import datetime) +(import [functools [partial reduce]]) ; importa fun1 e fun2 do module1 +(import [matplotlib.pyplot :as plt]) ; fazendo uma importação em foo como em bar +; todos os métodos de python embutidas etc. são acessíveis a partir hy +; a.foo(arg) is called as (.foo a arg) +(.split (.strip "hello world ")) ;=> ["hello" "world"] + +;; Condicionais +; (if condition (body-if-true) (body-if-false) +(if (= passcode "moria") + (print "welcome") + (print "Speak friend, and Enter!")) + +; aninhe múltiplas cláusulas 'if else if' com cond +(cond + [(= someval 42) + (print "Life, universe and everything else!")] + [(> someval 42) + (print "val too large")] + [(< someval 42) + (print "val too small")]) + +; declarações de grupo com 'do', essas são executadas sequencialmente +; formas como defn tem um 'do' implícito +(do + (setv someval 10) + (print "someval is set to " someval)) ;=> 10 + +; criar ligações lexicais com 'let', todas as variáveis definidas desta forma +; tem escopo local +(let [[nemesis {"superman" "lex luther" + "sherlock" "moriarty" + "seinfeld" "newman"}]] + (for [(, h v) (.items nemesis)] + (print (.format "{0}'s nemesis was {1}" h v)))) + +;; classes +; classes são definidas da seguinte maneira +(defclass Wizard [object] + [[--init-- (fn [self spell] + (setv self.spell spell) ; init a mágica attr + None)] + [get-spell (fn [self] + self.spell)]]) + +;; acesse hylang.org +``` + +### Outras Leituras + +Este tutorial é apenas uma introdução básica para hy/lisp/python. + +Docs Hy: [http://hy.readthedocs.org](http://hy.readthedocs.org) + +Repo Hy no Github: [http://github.com/hylang/hy](http://github.com/hylang/hy) + +Acesso ao freenode irc com #hy, hashtag no twitter: #hylang diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index a884f273..3c9512aa 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -405,6 +405,219 @@ class Velocipede extends Bicicleta { } +// Interfaces +// Sintaxe de declaração de Interface +// <nível de acesso> Interface <nome-da-interface> extends <super-interfaces> { +// // Constantes +// // Declarações de método +//} + +// Exemplo - Comida: +public interface Comestivel { + public void comer(); // Qualquer classe que implementa essa interface, deve + // Implementar este método. +} + +public interface Digestivel { + public void digerir(); +} + + +// Agora podemos criar uma classe que implementa ambas as interfaces. +public class Fruta implements Comestivel, Digestivel { + + @Override + public void comer() { + // ... + } + + @Override + public void digerir() { + // ... + } +} + +// Em Java, você pode estender somente uma classe, mas você pode implementar muitas +// Interfaces. Por exemplo: +public class ClasseExemplo extends ExemploClassePai implements InterfaceUm, + InterfaceDois { + + @Override + public void InterfaceUmMetodo() { + } + + @Override + public void InterfaceDoisMetodo() { + } + +} + +// Classes abstratas + +// Sintaxe de declaração de classe abstrata +// <Nível de acesso> abstract <nome-da-classe-abstrata> extends <estende super-abstratas-classes> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Marcar uma classe como abstrata significa que ela contém métodos abstratos que devem +// ser definido em uma classe filha. Semelhante às interfaces, classes abstratas não podem +// ser instanciadas, ao invés disso devem ser extendidas e os métodos abstratos +// definidos. Diferente de interfaces, classes abstratas podem conter uma mistura de +// métodos concretos e abstratos. Métodos em uma interface não podem ter um corpo, +// a menos que o método seja estático, e as variáveis sejam finais, por padrão, ao contrário de um +// classe abstrata. Classes abstratas também PODEM ter o método "main". + +public abstract class Animal +{ + public abstract void fazerSom(); + + // Método pode ter um corpo + public void comer() + { + System.out.println("Eu sou um animal e estou comendo."); + //Nota: Nós podemos acessar variáveis privadas aqui. + idade = 30; + } + + // Não há necessidade de inicializar, no entanto, em uma interface + // a variável é implicitamente final e, portanto, tem + // de ser inicializado. + protected int idade; + + public void mostrarIdade() + { + System.out.println(idade); + } + + //Classes abstratas podem ter o método main. + public static void main(String[] args) + { + System.out.println("Eu sou abstrata"); + } +} + +class Cachorro extends Animal +{ + + // Nota: ainda precisamos substituir os métodos abstratos na + // classe abstrata + @Override + public void fazerSom() + { + System.out.println("Bark"); + // idade = 30; ==> ERRO! idade é privada de Animal + } + + // NOTA: Você receberá um erro se usou a + // anotação Override aqui, uma vez que java não permite + // sobrescrita de métodos estáticos. + // O que está acontecendo aqui é chamado de "esconder o método". + // Vejá também este impressionante SO post: http://stackoverflow.com/questions/16313649/ + public static void main(String[] args) + { + Cachorro pluto = new Cachorro(); + pluto.fazerSom(); + pluto.comer(); + pluto.mostrarIdade(); + } +} + +// Classes Finais + +// Sintaxe de declaração de classe final +// <nível de acesso> final <nome-da-classe-final> { +// // Constantes e variáveis +// // Declarações de método +//} + +// Classes finais são classes que não podem ser herdadas e são, portanto, um +// filha final. De certa forma, as classes finais são o oposto de classes abstratas +// Porque classes abstratas devem ser estendidas, mas as classes finais não pode ser +// estendidas. +public final class TigreDenteDeSabre extends Animal +{ + // Nota: Ainda precisamos substituir os métodos abstratos na + // classe abstrata. + @Override + public void fazerSom(); + { + System.out.println("Roar"); + } +} + +// Métodos Finais +public abstract class Mamifero() +{ + // Sintaxe de Métodos Finais: + // <modificador-de-acesso> final <tipo-de-retorno> <nome-do-método>(<argumentos>) + + // Métodos finais, como, classes finais não podem ser substituídas por uma classe filha, + // e são, portanto, a implementação final do método. + public final boolean EImpulsivo() + { + return true; + } +} + + +// Tipo Enum +// +// Um tipo enum é um tipo de dado especial que permite a uma variável ser um conjunto de constantes predefinidas. A +// variável deve ser igual a um dos valores que foram previamente definidos para ela. +// Por serem constantes, os nomes dos campos de um tipo de enumeração estão em letras maiúsculas. +// Na linguagem de programação Java, você define um tipo de enumeração usando a palavra-chave enum. Por exemplo, você poderia +// especificar um tipo de enum dias-da-semana como: + +public enum Dia { + DOMINGO, SEGUNDA, TERÇA, QUARTA, + QUINTA, SEXTA, SABADO +} + +// Nós podemos usar nosso enum Dia assim: + +public class EnumTeste { + + // Variável Enum + Dia dia; + + public EnumTeste(Dia dia) { + this.dia = dia; + } + + public void digaComoE() { + switch (dia) { + case SEGUNDA: + System.out.println("Segundas são ruins."); + break; + + case SEXTA: + System.out.println("Sextas são melhores."); + break; + + case SABADO: + case DOMINGO: + System.out.println("Finais de semana são os melhores."); + break; + + default: + System.out.println("Dias no meio da semana são mais ou menos."); + break; + } + } + + public static void main(String[] args) { + EnumTeste primeiroDia = new EnumTeste(Dia.SEGUNDA); + primeiroDia.digaComoE(); // => Segundas-feiras são ruins. + EnumTeste terceiroDia = new EnumTeste(Dia.QUARTA); + terceiroDia.digaComoE(); // => Dias no meio da semana são mais ou menos. + } +} + +// Tipos Enum são muito mais poderosos do que nós mostramos acima. +// O corpo de um enum pode incluir métodos e outros campos. +// Você pode ver mais em https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html + ``` ## Leitura Recomendada diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown new file mode 100644 index 00000000..406042fa --- /dev/null +++ b/pt-br/javascript-pt.html.markdown @@ -0,0 +1,547 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["Willian Justen", "http://willianjusten.com.br"] +lang: pt-br +--- + +JavaScript foi criada por Brendan Eich, funcionário da Netscape na época, em 1995. Ela +foi originalmente criada para ser uma linguagem de script para websites, +complementando o uso de Java para aplicações web mais complexas, mas a sua +integração com páginas web e seu suporte nativo nos browsers fez com que +ela se tornasse mais comum que Java no frontend web. + +Javascript não é somente limitada a browsers web, existindo o Node.js, +que é um projeto que fornece um interpretador baseado no motor V8 do Google +Chrome e está se tornando cada vez mais famoso. + +Feedback são muito apreciados! Você me encontrar em +[@adambrenecki](https://twitter.com/adambrenecki), ou +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// Comentários são como em C. Comentários de uma linha começam com duas barras, +/* e comentários de múltplas linhas começam com barra-asterisco + e fecham com asterisco-barra */ + +// comandos podem ser terminados com ; +facaAlgo(); + +// ... mas eles não precisam ser, o ponto-e-vírgula é automaticamente +// inserido quando há uma nova linha, exceto alguns casos. +facaAlgo() + +// Como esses casos podem causar resultados inesperados, vamos continuar +// a usar ponto-e-vírgula neste guia. + +/////////////////////////////////// +// 1. Números, Strings e Operadores + +// Javascript tem um tipo de número (que é o 64-bit IEEE 754 double). +// Doubles tem uma mantissa 52-bit, que é suficiente para guardar inteiros +// acima de 9✕10¹⁵ precisamente. +3; // = 3 +1.5; // = 1.5 + +// A aritmética básica funciona como seria de se esperar. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Inclusive divisão desigual. +5 / 2; // = 2.5 + +// Operadores Bitwise também funcionam; quando você faz uma operação bitwise +// seu float é convertido para um int de até 32 bits. +1 << 2; // = 4 + +// A precedência é aplicada com parênteses. +(1 + 3) * 2; // = 8 + +// Existem três especiais valores não-é-número-real: +Infinity; // resultado de 1/0 +-Infinity; // resultado de -1/0 +NaN; // resultado de 0/0 + +// Existe também o tipo booleano. +true; +false; + +// Strings são criados com ' ou ". +'abc'; +"Olá, mundo"; + +// Negação usa o símbolo ! +!true; // = false +!false; // = true + +// Igualdade é o sinal de === +1 === 1; // = true +2 === 1; // = false + +// Desigualdade é o sinal de !== +1 !== 1; // = false +2 !== 1; // = true + +// Mais comparações +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings são concatenadas com + +"Olá " + "mundo!"; // = "Olá mundo!" + +// e comparadas com < e > +"a" < "b"; // = true + +// A comparação de tipos não é feita com o uso de ==... +"5" == 5; // = true +null == undefined; // = true + +// ...a menos que use === +"5" === 5; // = false +null === undefined; // = false + +// ...isso pode resultar em comportamentos estranhos... +13 + !0; // 14 +"13" + !0; // '13true' + +// Você pode acessar caracteres de uma String usando o `charAt` +"Isto é uma String".charAt(0); // = 'I' + +// ...ou usar `substring` para pegar pedaços maiores. +"Olá mundo".substring(0, 3); // = "Olá" + +// `length` é uma propriedade, portanto não use (). +"Olá".length; // = 3 + +// Existe também o `null` e o `undefined`. +null; // usado para indicar um valor não considerado +undefined; // usado para indicar um valor que não é a atualmente definido + // (entretando `undefined` é considerado de fato um valor + +// false, null, undefined, NaN, 0 and "" são valores falsos; +// qualquer outro valor é verdadeiro +// Note que 0 é falso e "0" é verdadeiro, até mesmo 0 == "0". + +/////////////////////////////////// +// 2. Variáveis, Arrays e Objetos + +// Variáveis são declaradas com a palavra-chave `var`. O Javascript é +// dinâmicamente tipado, portanto você não precisa especificar o tipo. +// Atribuições usam um simples caracter de `=`. +var someVar = 5; + +// se você deixar de colocar a palavra-chave var, você não irá receber um erro... +someOtherVar = 10; + +// ...mas sua variável será criada no escopo global, não no escopo em que você +// definiu ela. + +// Variáveis declaradas sem receberem um valor são definidas como `undefined`. +var someThirdVar; // = undefined + +// Existe um shorthand para operações matemáticas em variáveis: +someVar += 5; // equivalente a someVar = someVar + 5; someVar é 10 agora +someVar *= 10; // agora someVar é 100 + +// e um para adição e subtração de 1 +someVar++; // agora someVar é 101 +someVar--; // volta para 100 + +// Arrays são listas ordenadas de valores, de qualquer tipo. +var myArray = ["Olá", 45, true]; + +// Seus membros podem ser acessados usando a sintaxe de colchetes. +// O indíce de um Array começa pelo 0. +myArray[1]; // = 45 + +// Arrays são mutáveis e de tamanho variável. +myArray.push("World"); +myArray.length; // = 4 + +// Adicionar/modificar em um índice específico +myArray[3] = "Hello"; + +// Objetos de Javascript são equivalentes aos dicionários ou maps de outras +// linguagens: uma coleção não ordenada de pares chave-valor. +var myObj = {chave1: "Olá", chave2: "Mundo"}; + +// Chaves são strings, mas as aspas não são necessárias se elas são +// identificadores válidos no Javascript. Valores podem ser de qualquer tipo. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Atributos de objetos também podem ser acessados com a sintaxe de colchetes. +myObj["my other key"]; // = 4 + +// ... ou usando a sintaxe de ponto, passando a chave que é um identificador +// válido. +myObj.myKey; // = "myValue" + +// Objetos são mutáveis, valores podem ser modificados e novas chaves +// adicionadas. +myObj.myThirdKey = true; + +// Se você tentar acessar um valor que não foi determinado ainda, você irá +// receber `undefined`. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Lógica e Estruturas de Controle + +// A sintaxe para essa seção é quase idêntica a maioria das linguagens. + +// The `if` structure works as you'd expect. +// A estrutura `if` funciona como deveria ser. +var count = 1 +if (count == 3){ + // executa se count é 3 +} else if (count == 4){ + // executa se count é 4 +} else { + // executa se count não é 3 nem 4 +} + +// Como se faz um `while`. +while (true){ + // Um loop infinito! +} + +// Os loops do-while são como os loops de while, exceto quando eles sempre +// executam pelo menos uma vez. +do { + input = getInput(); +} while (!isValid(input)) + +// The `for` loop is the same as C and Java: +// initialisation; continue condition; iteration. + +// O loop `for` é o mesmo de C e Java: +// inicialização, condição para continuar; iteração +for (var i = 0; i < 5; i++){ + // vai rodar cinco vezes +} + +// && é o `e` lógico , || é o `ou` lógico +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (cor == "red" || cor == "blue"){ + // cor é vermelha OU azul +} + +// && e || "pequeno circuito", é útil para determinar valores padrões. +var name = otherName || "padrão"; + +// O `switch` checa pela igualdade com `===`. +// Use `break` após cada `case` +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Funções, Escopos e Closures + +// Funções Javascript são declaradas com a palavra-chave `function`. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Repare que o valor a ser retornado deve começar na mesma linha que +// a palavra-chave `return`, senão você sempre irá retornar `undefined` +// visto que o ponto-e-vírgula é inserido automáticamente nas quebras de +// linha. Preste atenção quando usar o estilo Allman. +function myFunction() +{ + return // <- ponto-e-vírgula adicionado automaticamente aqui + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// Funções Javascript são objetos de primeira classe, portanto elas podem +// ser atribuídas a nomes de variáveis e serem passadas para outras funções +// como argumentos - por exemplo, quando criamos um manipulador de eventos: +function myFunction(){ + // este código será chamado em 5 segundos +} +setTimeout(myFunction, 5000); +// Nota: `setTimeout` não é parte da linguagem Javascript, mas é provido pelos +// browsers e o Node.js. + +// Objetos de funções não precisam nem serem declarados com nome - você pode +// escrever a definição de uma função anônima diretamente nos argumentos de +// outra função. +setTimeout(function(){ + // este código será chamado em 5 segundos +}, 5000); + +// O Javascript tem escopo de função; as funções tem seu próprio escopo, +// mas outros blocos não. +if (true){ + var i = 5; +} +i; // = 5 - não `undefined` como você esperaria numa linguagem de blogo-escopo + +// Isso levou a padrão comum chamado de IIFE (Imediately Invoked Function +// Expression) ou (Expressão de Função Invocada Imediatamente), que previne +// que variáveis temporárias vazem para o escopo global. +(function(){ + var temporary = 5; + // Nós podemos acessar o escopo global definindo o "objeto global", que + // no browser vai ser sempre `window`. O objeto global pode ter um nome + // diferente para ambiente não-browser como o Node.js. + window.permanent = 10; +})(); +temporary; // levanta um erro de referência inexiste +permanent; // = 10 + +// Uma das principais características do Javascript é a closure. Que é +// uma função definida dentro de outra função, a função interna pode acessar +// todas as variáveis da função externa, mesmo depois da função de fora +// finalizar sua execução. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + + // Funções internas são colocadas no escopo local por padrão, assim como + // se fossem declaradas com `var`. + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // `setTimeout` é assíncrono, portanto a função `sayHelloInFiveSeconds` + // vai sair imediatamente, e o `setTimeout` irá chamar a interna depois. + // Entretanto. como a interna é fechada dentro de "sayHelloInFiveSeconds", + // a interna permanece podendo acessar a variável `prompt` quando depois + // de chamada. +} +sayHelloInFiveSeconds("Adam"); // Vai abrir um popup com "Hello, Adam!" em 5s + +/////////////////////////////////// +// 5. Mais sobre Objetos; Construtores e Prototypes + +// Objetos podem conter funções. +var myObj = { + myFunc: function(){ + return "Olá mundo!"; + } +}; +myObj.myFunc(); // = "Olá mundo!" + +// Quando uma função ligada a um objeto é chamada, ela pode acessar o objeto +// da qual foi ligada usando a palavra-chave `this`. +myObj = { + myString: "Olá mundo!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Olá mundo!" + +// O `this` só funciona para dentro do escopo do objeto, portanto, se chamarmos +// um método do objeto fora de seu escopo, este não irá funcionar. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Inversamente, uma função pode ser atribuída a um objeto e ganhar a acesso +// através do `this`, até mesmo se ela não for chamada quando foi definida. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "OLÁ MUNDO!" + +// Nós podemos também especificar um contexto onde a função irá executar, +// usando o `call` ou `apply`. + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " E Olá Lua!"); // = "Olá mundo! E Olá Lua!" + +// A função `apply` é praticamente a mesma coisa, mas ela pega um array +// como lista de argumentos. + +anotherFunc.apply(myObj, [" E Olá Sol!"]); // = "Olá mundo! E Olá Sol!" + +// Isto é util quando trabalhamos com uma função que aceita uma sequência de +// argumentos e você quer passar um array. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Mas, o `call` e `apply` são somente temporários. Quando você quiser que +// permaneça sempre no escopo, use `bind`. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" E Olá Saturno!"); // = "Olá mundo! E Olá Saturno!" + +// `bind` também pode ser usado para parcialmente aplicar (curry) uma função. + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Quando você invoca uma função com a palavra-chave `new`, um novo objeto +// é criado, e fica disponível para a função pela palavra-chave `this`. +// Funções são desenhadas para serem invocadas como se invocam os construtores. + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Todo objeto JavaScript possui um `prototype`. Quando você tenta acessar +// uma propriedade de um objeto que não existe no objeto atual, o interpretador +// vai olhar imediatamente para o seu prototype. + +// Algumas implementações em JS deixam você acessar o objeto prototype com a +// propriedade mágica `__proto__`. Enquanto isso é util para explicar +// prototypes, não é parte de um padrão; nós vamos falar de algumas formas de +// usar prototypes depois. + +var myObj = { + myString: "Olá Mundo!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +// Isto funciona para funções, também. +myObj.myFunc(); // = "olá mundo!" + +// É claro, se sua propriedade não está em seu prototype, +// o prototype do prototype será procurado e por aí vai. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Não há cópia envolvida aqui; cada objeto guarda uma referência do +// prototype. Isso significa que podemos alterar o prototype e nossas mudanças +// serão refletidas em qualquer lugar. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + + +// Nós mencionamos que o `__proto__` não é uma forma padrão, e não há uma +// forma padrão de mudar o prototype de um objeto já existente. Entretanto, +// existem duas formas de se criar um objeto com um dado prototype. + +// A primeira forma é `Object.create`, que é uma adição recente do JS, +// e ainda não está disponível em todas as implementações. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// A segunda forma, que funciona em qualquer lugar, é feita com construtores. +// Construtores tem uma propriedade chamada prototype. Este *não* é o prototype +// do construtor em si; ao invés disso, ele é o prototype dos novos objetos +// criados pelo construtor. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Tipos originais da linguagem como strings e números também possuem +// construtores equivalentes. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Exceto, que eles não são totalmente equivalentes. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // O código não vai executar, porque 0 é um valor falso. +} + +// Entretanto, esses objetos encapsulados e as funções originais compartilham +// um mesmo prototype, portanto você pode adicionar funcionalidades a uma string, +// por exemplo. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Esse fato é usado para criar os chamados `polyfills`, que implementam +// uma nova característica do Javascript em uma versão mais velha, para que +// assim funcionem em ambientes mais velhos como browsers ultrapassados. + +// Havíamos mencionado que `Object.create` não estava ainda disponível em +// todos as implementações, mas nós podemos usá-lo com esse polyfill: +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // faz um construtor temporário com o prototype certo + var Constructor = function(){}; + Constructor.prototype = proto; + // então utiliza o new para criar um objeto prototype apropriado + return new Constructor(); + } +} +``` + +## Leitura Adicional + +O [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) dispõe de uma +excelente documentação sobre Javascript e seu uso nos browsers. E mais, +é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando +os outros compartilhando do seu conhecimento. + +[Uma re-introdução do JavaScript pela MDN] +(https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala +somente sobre a linguagem JavaScript em si; se você quiser aprender mais +sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Aprenda Javascript por Exemplos e com Desafios](http://www.learneroo.com/modules/64/nodes/350) é uma +variação desse guia com desafios. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia +profundo de todas as partes do JavaScript. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) é o guia clássico +/ livro de referência. + +Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está +nesse site e do [Tutorial de JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +da Mozilla Developer Network. diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index fc63b126..fd822c03 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -3,6 +3,7 @@ language: json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Francisco Marques", "https://github.com/ToFran"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -12,10 +13,16 @@ 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 na sua forma mais pura não tem comentários, mas a maioria dos analisadores +aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. +Um valor JSON pode ser um numero, uma string, um array, um objeto, um booleano (true, false) ou null. + +Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, Opera 10.0+, e Safari 4.0+. + +A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”. + +Mais informação em: http://www.json.org/ ```json { @@ -35,7 +42,7 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. "array": [0, 1, 2, 3, "Arrays podem ter qualquer coisa em si.", 5], "outro objeto": { - "ccomentário": "Estas coisas podem ser aninhadas, muito úteis." + "comentário": "Estas coisas podem ser aninhadas, muito úteis." } }, @@ -57,6 +64,6 @@ tudo o que é vai ser 100% JSON válido. Felizmente, isso meio que fala por si. , "outro comentário": "que bom" }, - "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer.". + "que foi curto": "E, você está feito. Você já sabe tudo que JSON tem para oferecer." } ``` diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown new file mode 100644 index 00000000..eb660d4c --- /dev/null +++ b/pt-br/matlab-pt.html.markdown @@ -0,0 +1,540 @@ +--- +language: Matlab +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] + - ["Colton Kohnke", "http://github.com/voltnor"] +translators: + - ["Claudson Martins", "https://github.com/claudsonm"] +lang: pt-br +filename: learnmatlab-pt.mat + +--- + +MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. + +Se você tem algum feedback, por favor fique a vontade para me contactar via +[@the_ozzinator](https://twitter.com/the_ozzinator), ou +[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). + +```matlab +% Comentários iniciam com um sinal de porcentagem + +%{ +Comentários de múltiplas linhas +parecem +com +algo assim +%} + +% Comandos podem ocupar várinhas linhas, usando '...': + a = 1 + 2 + ... + + 4 + +% Comandos podem ser passados para o sistema operacional +!ping google.com + +who % Exibe todas as variáveis na memória +whos % Exibe todas as variáveis na memória, com seus tipos +clear % Apaga todas as suas variáveis da memória +clear('A') % Apaga uma variável em particular +openvar('A') % Abre a variável no editor de variável + +clc % Apaga o conteúdo escrito na sua janela de comando +diary % Alterna o conteúdo escrito na janela de comando para um arquivo de texto +ctrl-c % Aborta a computação atual + +edit('minhafuncao.m') % Abre a função/script no editor +type('minhafuncao.m') % Imprime o código-fonte da função/script na janela de comando + +profile on % Ativa o perfil de código +profile off % Desativa o perfil de código +profile viewer % Visualiza os resultados na janela de Profiler + +help comando % Exibe a documentação do comando na janela de comando +doc comando % Exibe a documentação do comando na janela de ajuda +lookfor comando % Procura por comando na primeira linha comentada de todas as funções +lookfor comando -all % Procura por comando em todas as funções + + +% Formatação de saída +format short % 4 casas decimais em um número flutuante +format long % 15 casas decimais +format bank % 2 dígitos após o ponto decimal - para cálculos financeiros +fprintf('texto') % Imprime na tela "texto" +disp('texto') % Imprime na tela "texto" + +% Variáveis & Expressões +minhaVariavel = 4 % O painel Workspace mostra a variável recém-criada +minhaVariavel = 4; % Ponto e vírgula suprime a saída para a janela de comando +4 + 6 % Resposta = 10 +8 * minhaVariavel % Resposta = 32 +2 ^ 3 % Resposta = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + +% A chamada de funções pode ser feita por uma das duas maneiras: +% Sintaxe de função padrão: +load('arquivo.mat', 'y') % Argumentos entre parênteses, separados por vírgula +% Sintaxe de comando: +load arquivo.mat y % Sem parênteses, e espaços ao invés de vírgulas +% Observe a falta de aspas na forma de comando: entradas são sempre passadas +% como texto literal - não pode passar valores de variáveis. +% Além disso, não pode receber saída: +[V,D] = eig(A); % Isto não tem um equivalente na forma de comando +[~,D] = eig(A); % Se você só deseja D e não V + + + +% Operadores Lógicos e Relacionais +1 > 5 % Resposta = 0 +10 >= 10 % Resposta = 1 +3 ~= 4 % Diferente de -> Resposta = 1 +3 == 3 % Igual a -> Resposta = 1 +3 > 1 && 4 > 1 % E -> Resposta = 1 +3 > 1 || 4 > 1 % OU -> Resposta = 1 +~1 % NOT -> Resposta = 0 + +% Operadores Lógicos e Relacionais podem ser aplicados a matrizes +A > 5 +% Para cada elemento, caso seja verdade, esse elemento será 1 na matriz retornada +A( A > 5 ) +% Retorna um vetor com os elementos de A para os quais a condição é verdadeira + +% Cadeias de caracteres (Strings) +a = 'MinhaString' +length(a) % Resposta = 11 +a(2) % Resposta = i +[a,a] % Resposta = MinhaStringMinhaString + + +% Vetores de células +a = {'um', 'dois', 'três'} +a(1) % Resposta = 'um' - retorna uma célula +char(a(1)) % Resposta = um - retorna uma string + +% Estruturas +A.b = {'um','dois'}; +A.c = [1 2]; +A.d.e = false; + +% Vetores +x = [4 32 53 7 1] +x(2) % Resposta = 32, índices no Matlab começam por 1, não 0 +x(2:3) % Resposta = 32 53 +x(2:end) % Resposta = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % Vetor coluna + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + +% Matrizes +A = [1 2 3; 4 5 6; 7 8 9] +% Linhas são separadas por um ponto e vírgula; +% Elementos são separados com espaço ou vírgula +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % Resposta = 6, A(linha, coluna) +A(6) % Resposta = 8 +% (implicitamente encadeia as colunas do vetor, e então as indexa) + + +A(2,3) = 42 % Atualiza a linha 2 coluna 3 com o valor 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % Cria uma nova matriz a partir da antiga +%Resposta = + +% 5 42 +% 8 9 + +A(:,1) % Todas as linhas na coluna 1 +%Resposta = + +% 1 +% 4 +% 7 + +A(1,:) % Todas as colunas na linha 1 +%Resposta = + +% 1 2 3 + +[A ; A] % Concatenação de matrizes (verticalmente) +%Resposta = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% Isto é o mesmo de +vertcat(A,A); + + +[A , A] % Concatenação de matrizes (horizontalmente) + +%Resposta = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% Isto é o mesmo de +horzcat(A,A); + + +A(:, [3 1 2]) % Reorganiza as colunas da matriz original +%Resposta = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % Resposta = 3 3 + +A(1, :) =[] % Remove a primeira linha da matriz +A(:, 1) =[] % Remove a primeira coluna da matriz + +transpose(A) % Transposta a matriz, que é o mesmo de: +A one +ctranspose(A) % Transposta a matriz +% (a transposta, seguida pelo conjugado complexo de cada elemento) + + + + +% Aritmética Elemento por Elemento vs. Aritmética com Matriz +% Naturalmente, os operadores aritméticos agem em matrizes inteiras. Quando +% precedidos por um ponto, eles atuam em cada elemento. Por exemplo: +A * B % Multiplicação de matrizes +A .* B % Multiplica cada elemento em A por seu correspondente em B + +% Existem vários pares de funções nas quais uma atua sob cada elemento, e a +% outra (cujo nome termina com m) age na matriz por completo. +exp(A) % Exponencia cada elemento +expm(A) % Calcula o exponencial da matriz +sqrt(A) % Tira a raiz quadrada de cada elemento +sqrtm(A) % Procura a matriz cujo quadrado é A + + +% Gráficos +x = 0:.10:2*pi; % Vetor que começa em 0 e termina em 2*pi com incrementos de 0,1 +y = sin(x); +plot(x,y) +xlabel('eixo x') +ylabel('eixo y') +title('Gráfico de y = sin(x)') +axis([0 2*pi -1 1]) % x vai de 0 a 2*pi, y vai de -1 a 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % Para várias funções em um só gráfico +legend('Descrição linha 1', 'Descrição linha 2') % Curvas com uma legenda + +% Método alternativo para traçar várias funções em um só gráfico: +% Enquanto 'hold' estiver ativo, os comandos serão adicionados ao gráfico +% existente ao invés de o substituirem. +plot(x, y) +hold on +plot(x, z) +hold off + +loglog(x, y) % Plotar em escala loglog +semilogx(x, y) % Um gráfico com eixo x logarítmico +semilogy(x, y) % Um gráfico com eixo y logarítmico + +fplot (@(x) x^2, [2,5]) % Plotar a função x^2 para x=2 até x=5 + +grid on % Exibe as linhas de grade; Oculta com 'grid off' +axis square % Torna quadrada a região dos eixos atuais +axis equal % Taxa de proporção onde as unidades serão as mesmas em todas direções + +scatter(x, y); % Gráfico de dispersão ou bolha +hist(x); % Histograma + +z = sin(x); +plot3(x,y,z); % Plotar em espaço em 3D + +pcolor(A) % Mapa de calor da matriz: traça uma grade de retângulos, coloridos pelo valor +contour(A) % Plotar de contorno da matriz +mesh(A) % Plotar malha 3D + +h = figure % Cria uma nova figura objeto, com identificador h +figure(h) % Cria uma nova janela de figura com h +close(h) % Fecha a figura h +close all % Fecha todas as janelas de figuras abertas +close % Fecha a janela de figura atual + +shg % Traz uma janela gráfica existente para frente, ou cria uma nova se necessário +clf clear % Limpa a janela de figura atual e redefine a maioria das propriedades da figura + +% Propriedades podem ser definidas e alteradas através de um identificador. +% Você pode salvar um identificador para uma figura ao criá-la. +% A função gcf retorna o identificador da figura atual +h = plot(x, y); % Você pode salvar um identificador para a figura ao criá-la +set(h, 'Color', 'r') +% 'y' amarelo; 'm' magenta, 'c' ciano, 'r' vermelho, 'g' verde, 'b' azul, 'w' branco, 'k' preto +set(h, 'LineStyle', '--') + % '--' linha sólida, '---' tracejada, ':' pontilhada, '-.' traço-ponto, 'none' sem linha +get(h, 'LineStyle') + + +% A função gca retorna o identificador para os eixos da figura atual +set(gca, 'XDir', 'reverse'); % Inverte a direção do eixo x + +% Para criar uma figura que contém vários gráficos use subplot, o qual divide +% a janela de gráficos em m linhas e n colunas. +subplot(2,3,1); % Seleciona a primeira posição em uma grade de 2-por-3 +plot(x1); title('Primeiro Plot') % Plota algo nesta posição +subplot(2,3,2); % Seleciona a segunda posição na grade +plot(x2); title('Segundo Plot') % Plota algo ali + + +% Para usar funções ou scripts, eles devem estar no caminho ou na pasta atual +path % Exibe o caminho atual +addpath /caminho/para/pasta % Adiciona o diretório ao caminho +rmpath /caminho/para/pasta % Remove o diretório do caminho +cd /caminho/para/mudar % Muda o diretório + + +% Variáveis podem ser salvas em arquivos *.mat +save('meuArquivo.mat') % Salva as variáveis do seu Workspace +load('meuArquivo.mat') % Carrega as variáveis em seu Workspace + +% Arquivos M (M-files) +% Um arquivo de script é um arquivo externo contendo uma sequência de instruções. +% Eles evitam que você digite os mesmos códigos repetidamente na janela de comandos. +% Possuem a extensão *.m + +% Arquivos M de Funções (M-file Functions) +% Assim como scripts e têm a mesma extensão *.m +% Mas podem aceitar argumentos de entrada e retornar uma saída. +% Além disso, possuem seu próprio workspace (ex. diferente escopo de variáveis). +% O nome da função deve coincidir com o nome do arquivo (salve o exemplo como dobra_entrada.m) +% 'help dobra_entrada.m' retorna os comentários abaixo da linha de início da função +function output = dobra_entrada(x) + %dobra_entrada(x) retorna duas vezes o valor de x + output = 2*x; +end +dobra_entrada(6) % Resposta = 12 + + +% Você também pode ter subfunções e funções aninhadas. +% Subfunções estão no mesmo arquivo da função primária, e só podem ser chamados +% por funções dentro do arquivo. Funções aninhadas são definidas dentro de +% outras funções, e têm acesso a ambos workspaces. + +% Se você quer criar uma função sem criar um novo arquivo, você pode usar uma +% função anônima. Úteis para definir rapidamente uma função para passar a outra +% função (ex. plotar com fplot, avaliar uma integral indefinida com quad, +% procurar raízes com fzero, ou procurar mínimo com fminsearch). +% Exemplo que retorna o quadrado de sua entrada, atribuído ao identificador sqr: +sqr = @(x) x.^2; +sqr(10) % Resposta = 100 +doc function_handle % Saiba mais + +% Entrada do usuário +a = input('Digite o valor: ') + +% Para a execução do arquivo e passa o controle para o teclado: o usuário pode +% examinar ou alterar variáveis. Digite 'return' para continuar a execução, ou 'dbquit' para sair +keyboard + +% Leitura de dados (ou xlsread/importdata/imread para arquivos excel/CSV/imagem) +fopen(nomedoarquivo) + +% Saída +disp(a) % Imprime o valor da variável a +disp('Olá Mundo') % Imprime a string +fprintf % Imprime na janela de comandos com mais controle + +% Estruturas Condicionais (os parênteses são opicionais, porém uma boa prática) +if (a > 15) + disp('Maior que 15') +elseif (a == 23) + disp('a é 23') +else + disp('Nenhuma condição reconheceu') +end + +% Estruturas de Repetição +% Nota: fazer o loop sobre elementos de um vetor/matriz é lento! +% Sempre que possível, use funções que atuem em todo o vetor/matriz de uma só vez. +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + +% Tempo de Execução de Código (Timing Code Execution): 'toc' imprime o tempo +% passado desde que 'tic' foi chamado. +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + +% Conectando a uma base de dados MySQL +dbname = 'nome_base_de_dados'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +%Abaixo, o xx depende da versão, download disponível em http://dev.mysql.com/downloads/connector/j/ +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * FROM nome_tabela WHERE id = 22'] % Exemplo de uma consulta SQL +a = fetch(conn, sql) %a will contain your data + + +% Funções Matemáticas Comuns +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % Números pseudo-aleatórios uniformemente distribuídos +randi % Inteiros pseudo-aleatórios uniformemente distribuídos +randn % Números pseudo-aleatórios normalmente distribuídos + +% Constantes Comuns +pi +NaN +inf + +% Resolvendo equações matriciais (se não houver solução, retorna uma solução de mínimos quadrados) +% Os operadores \ e / são equivalentes às funções mldivide e mrdivide +x=A\b % Resolve Ax=b. Mais rápido e numericamente mais preciso do que inv(A)*b. +x=b/A % Resolve xA=b + +inv(A) % Calcula a matriz inversa +pinv(A) % Calcula a pseudo-inversa + +% Funções Matriciais Comuns +zeros(m,n) % Matriz de zeros m x n +ones(m,n) % Matriz de 1's m x n +diag(A) % Extrai os elementos diagonais da matriz A +diag(x) % Constrói uma matriz com os elementos diagonais listados em x, e zero nas outras posições +eye(m,n) % Matriz identidade +linspace(x1, x2, n) % Retorna n pontos igualmente espaçados, com min x1 e max x2 +inv(A) % Inverso da matriz A +det(A) % Determinante da matriz A +eig(A) % Valores e vetores próprios de A +trace(A) % Traço da matriz - equivalente a sum(diag(A)) +isempty(A) % Testa se a matriz está vazia +all(A) % Testa se todos os elementos são diferentes de zero ou verdadeiro +any(A) % Testa se algum elemento é diferente de zero ou verdadeiro +isequal(A, B) % Testa a igualdade de duas matrizes +numel(A) % Número de elementos na matriz +triu(x) % Retorna a parte triangular superior de x +tril(x) % Retorna a parte triangular inferior de x +cross(A,B) % Retorna o produto cruzado das matrizes A e B +dot(A,B) % Retorna o produto escalar de duas matrizes (devem possuir mesmo tamanho) +transpose(A) % Retorna a matriz transposta de A +fliplr(A) % Inverte a matriz da esquerda para a direita +flipud(A) % Inverte a matriz de cima para baixo + +% Fatorações de Matrizes +% Decomposição LU: PA = LU,L é triangular inferior, U é triangular superior, P é a matriz de permutação +[L, U, P] = lu(A) +% Decomposição em Autovalores: AP = PD, colunas de P são autovetores e as diagonais de D são autovalores +[P, D] = eig(A) +% SVD: XV = US, U e V são matrizes unitárias, S possui elementos não negativos na diagonal em ordem decrescente +[U,S,V] = svd(X) + +% Funções Vetoriais Comuns +max % Maior componente +min % Menor componente +length % Tamanho do vetor +sort % Ordena em orcer ascendente +sum % Soma de elementos +prod % Produto de elementos +mode % Valor modal +median % Valor mediano +mean % Valor médio +std % Desvio padrão +perms(x) % Lista todas as permutações de elementos de x + + +% Classes +% Matlab pode suportar programação orientada a objetos. +% Classes devem ser colocadas em um arquivo de mesmo nome com a extensão *.m +% Para começar, criamos uma simples classe que armazena posições de GPS +% Início ClassePosicoesGPS.m +classdef ClassePosicoesGPS % O nome da classe. + properties % As propriedades da classe comportam-se como estruturas + latitude + longitude + end + methods + % Este método que tem o mesmo nome da classe é o construtor. + function obj = ClassePosicoesGPS(lat, lon) + obj.latitude = lat; + obj.longitude = lon; + end + + % Outras funções que usam os objetos de PosicoesGPS + function r = multiplicarLatPor(obj, n) + r = n*[obj.latitude]; + end + + % Se quisermos somar dois objetos de PosicoesGPS juntos sem chamar + % uma função especial nós podemos sobrepor a aritmética do Matlab, desta maneira: + function r = plus(o1,o2) + r = ClassePosicoesGPS([o1.latitude] +[o2.latitude], ... + [o1.longitude]+[o2.longitude]); + end + end +end +% End ClassePosicoesGPS.m + +% Podemos criar um objeto da classe usando o construtor +a = ClassePosicoesGPS(45.0, 45.0) + +% Propriedades da classe se comportam exatamente como estruturas Matlab +a.latitude = 70.0 +a.longitude = 25.0 + +% Métodos podem ser chamados da mesma forma que funções +ans = multiplicarLatPor(a,3) + +% O método também pode ser chamado usando a notação de ponto. Neste caso, +% o objeto não precisa ser passado para o método. +ans = a.multiplicarLatPor(a,1/3) + +% Funções do Matlab podem ser sobrepostas para lidar com objetos. +% No método abaixo, nós sobrepomos a forma como o Matlab lida com a soma de +% dois objetos PosicoesGPS. +b = ClassePosicoesGPS(15.0, 32.0) +c = a + b + +``` + +## Mais sobre Matlab + +* O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) +* O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) + diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown new file mode 100644 index 00000000..cc07a2ec --- /dev/null +++ b/pt-br/perl-pt.html.markdown @@ -0,0 +1,166 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-pt.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento. + +Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala. + +```perl +# Comentários de uma linha começam com um sinal de número. + +#### Tipos de variáveis em Perl + +# Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo. +# Um nome de variável válido começa com uma letra ou sublinhado, +# seguido por qualquer número de letras, números ou sublinhados. + +### Perl has three main variable types: $scalar, @array, e %hash. + +## Scalars +# Um scalar representa um valor único: +my $animal = "camelo"; +my $resposta = 42; + +# Valores scalar podem ser strings, inteiros ou números ponto-flutuantes e +# Perl vai automaticamente converter entre eles quando for preciso. + +## Arrays +# Um array representa uma lista de valores: +my @animais = ("camelo", "vaca", "boi"); +my @números = (23, 42, 69); +my @misturado = ("camelo", 42, 1.23); + +## Hashes +# Um hash representa um conjunto de pares chave/valor: + +my %fruta_cor = ("maçã", "vermelho", "banana", "amarelo"); + +# Você pode usar o espaço em branco e o operador "=>" para colocá-los de +# maneira mais agradável: + +my %fruta_cor = ( + maçã => "vermelho", + banana => "amarelo", +); + +# Scalars, arrays and hashes são documentados mais profundamentes em perldata. +# (perldoc perldata). + +# Mais tipos de dados complexos podem ser construídas utilizando referências, +# o que permite que você crie listas e hashes dentro de listas e hashes. + +#### Condicionais e construtores de iteração + +# Perl possui a maioria das construções condicionais e de iteração habituais. + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (condição) { + ... +} +# Isto é fornecido como uma versão mais legível de "if (!condition)" + +# A forma Perlish pós-condição +print "Yow!" if $zippy; +print "Nós não temos nenhuma banana" unless $bananas; + +# while +while (condição) { + ... +} + +# for +for (my $i = 0; $i < $max; $i++) { + print "valor é $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "Elemento atual é " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# implícito + +for (@elements) { + print; +} + +#### Expressões regulares + +# O suporte a expressões regulares do Perl é ao mesmo tempo amplo e profundo, +# e é objeto de longa documentação em perlrequick, perlretut, e em outros +# lugares. No entanto, em suma: + +# Casamento simples +if (/foo/) { ... } # verdade se $_ contém "foo" +if ($a =~ /foo/) { ... } # verdade se $a contém "foo" + +# Substituição simples + +$a =~ s/foo/bar/; # substitui foo com bar em $a +$a =~ s/foo/bar/g; # substitui TODAS AS INSTÂNCIAS de foo com bar em $a + +#### Arquivos e I/O + +# Você pode abrir um arquivo para entrada ou saída usando a função "open()". + +open(my $in, "<", "input.txt") ou desistir "Não pode abrir input.txt: $!"; +open(my $out, ">", "output.txt") ou desistir "Não pode abrir output.txt: $!"; +open(my $log, ">>", "my.log") ou desistir "Não pode abrir my.log: $!"; + +# Você pode ler de um arquivo aberto usando o operador "<>". No contexto +# scalar, ele lê uma única linha do arquivo, e em contexto de lista lê o +# arquivo inteiro, atribuindo cada linha a um elemento da lista: + +my $linha = <$in>; +my @linhas = <$in>; + +#### Escrevendo subrotinas + +# Escrever subrotinas é fácil: + +sub logger { + my $mensagem = shift; + + open my $arquivo, ">>", "my.log" or die "Não poderia abrir my.log: $!"; + + print $arquivo $ensagem; +} + +# Agora nós podemos usar a subrotina como qualquer outra função construída: + +logger("Nós temos uma subrotina de log!"); +``` + +#### Usando módulos Perl + +Módulos Perl provê uma lista de recursos para lhe ajudar a evitar redesenhar +a roda, e tudo isso pode ser baixado do CPAN (http://www.cpan.org/). Um número +de módulos populares podem ser incluídos com a própria distribuição do Perl. + +perlfaq contém questões e respostas relacionadas a muitas tarefas comuns, e frequentemente provê sugestões para um bom números de módulos CPAN. + +#### Leitura Adicional + + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` diff --git a/pt-br/sass-pt.html.markdown b/pt-br/sass-pt.html.markdown new file mode 100644 index 00000000..3d91f1ca --- /dev/null +++ b/pt-br/sass-pt.html.markdown @@ -0,0 +1,452 @@ +--- +language: sass +filename: learnsass-pt.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] +translators: + - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] + - ["Cássio Böck", "https://github.com/cassiobsilva"] +lang: pt-br +--- + +Sass é uma linguagem de extensão CSS que adiciona recursos, como variáveis, aninhamento, mixins e muito mais. +Sass (e outros pré-processadores, como [Less](http://lesscss.org/)) ajudam os desenvolvedores a escrever código de fácil manutenção e DRY (Do not Repeat Yourself). + +Sass tem duas opções de sintaxe diferentes para escolher. SCSS, que tem a mesma sintaxe de CSS, mas com os recursos adicionais de Sass. Ou Sass (a sintaxe original), que usa o recuo, em vez de chaves e ponto e vírgula. +Este tutorial é escrito usando SCSS. + +Se você já está familiarizado com CSS3, você será capaz de pegar Sass de forma relativamente rápida. Ele não fornece quaisquer novas opções de estilo, mas sim as ferramentas para escrever sua CSS de forma mais eficiente e fazer a manutenção mais fácilmente. + +```scss + + +// Comentários de linha única são removidos quando Sass é compilado para CSS. + +/* Comentários multi-line são preservados. */ + + + +/*Variáveis +==============================*/ + + + +/* É possível armazenar um valor CSS (tais como a cor) de uma variável. +Use o símbolo "$" para criar uma variável. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* Você pode usar as variáveis em toda a sua folha de estilo. +Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* Quando compilar ficaria assim: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/ * Este é muito mais fácil de manter do que ter de mudar a cor +cada vez que aparece em toda a sua folha de estilo. * / + + + + +/*Mixins +==============================*/ + + + +/* Se você achar que você está escrevendo o mesmo código para mais de um +elemento, você pode querer armazenar esse código em um mixin. + +Use a diretiva '@mixin', além de um nome para o seu mixin. */ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* Você pode usar o mixin com '@include' e o nome mixin. */ + +div { + @include center; + background-color: $primary-color; +} + +/* Apoś compilar ficaria assim: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* Você pode usar mixins para criar uma propriedade estenográfica. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/* O que você pode invocar passando argumentos de largura e altura. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* Isso compilado ficará assim: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/*Funções +==============================*/ + + + +/* Sass fornece funções que podem ser utilizados para realizar uma variedade de + tarefas. Considere o seguinte */ + +/* Funções pode ser chamado usando seu nome e passando o + argumentos necessários */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* Você também pode definir suas próprias funções. As funções são muito semelhantes aos + mixins. Ao tentar escolher entre uma função ou um mixin, lembre- + que mixins são os melhores para gerar CSS enquanto as funções são melhores para + lógica que pode ser usado em todo o seu código Sass. Os exemplos + seção Operadores Math 'são candidatos ideais para se tornar um reutilizável + função. */ + +/* Esta função terá um tamanho de destino eo tamanho do pai e calcular + e voltar a percentagem */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Compila para: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/* Extend (Herança) +============================== */ + + + +/*Extend é uma maneira de compartilhar as propriedades de um seletor com outro. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Ampliando uma declaração CSS é preferível a criação de um mixin + por causa da maneira agrupa as classes que todos compartilham + o mesmo estilo base. Se isso for feito com um mixin, a largura, + altura, e a borda seria duplicado para cada instrução que + o chamado mixin. Enquanto isso não irá afetar o seu fluxo de trabalho, será + adicionar inchaço desnecessário para os arquivos criados pelo compilador Sass. */ + + + +/*Assentamento +==============================*/ + + + +/ * Sass permite seletores ninhos dentro seletores * / + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' será substituído pelo selector pai. */ +/* Você também pode aninhar pseudo-classes. */ +/* Tenha em mente que o excesso de nidificação vai fazer seu código menos sustentável. +Essas práticas também recomendam não vai mais de 3 níveis de profundidade quando nidificação. +Por exemplo: */ + + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compila para: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Parciais e Importações +==============================*/ + + +/* Sass permite criar arquivos parciais. Isso pode ajudar a manter seu Sass + código modularizado. Arquivos parciais deve começar com um '_', por exemplo, _reset.css. + Parciais não são geradas em CSS. */ + + + +/* Considere o seguinte CSS que nós vamos colocar em um arquivo chamado _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass oferece @import que pode ser usado para importar parciais em um arquivo. + Isso difere da declaração CSS @import tradicional, que faz + outra solicitação HTTP para buscar o arquivo importado. Sass converte os + importadas arquivo e combina com o código compilado. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Placeholder Selectors +==============================*/ + + +/* Os espaços reservados são úteis na criação de uma declaração CSS para ampliar. Se você + queria criar uma instrução CSS que foi usado exclusivamente com @extend, + Você pode fazer isso usando um espaço reservado. Espaços reservados começar com um '%' em vez + de '.' ou '#'. Espaços reservados não aparece no CSS compilado. * / + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Compilado para: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/*Operações Math +============================== * / + + +/* Sass fornece os seguintes operadores: +, -, *, /, e %. estes podem + ser úteis para calcular os valores diretamente no seu Sass arquivos em vez + de usar valores que você já calculados pela mão. Abaixo está um exemplo + de uma criação de um projeto simples de duas colunas. * / + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + + + +## SASS ou Sass? +Alguma vez você já se perguntou se Sass é um acrônimo ou não? Você provavelmente não tem, mas vou dizer-lhe de qualquer maneira. O nome do idioma é uma palavra, "Sass", e não uma sigla. +Porque as pessoas estavam constantemente a escrevê-lo como "SASS", o criador da linguagem de brincadeira chamou de "StyleSheets Sintaticamente Incríveis". + + +## Prática Sass +Se você quiser jogar com Sass em seu navegador, vá para [SassMeister](http://sassmeister.com/). +Você pode usar uma sintaxe, basta ir para as configurações e selecionar Sass ou SCSS. + + +## Compatibilidade + +Sass pode ser usado em qualquer projeto, desde que você tenha um programa para compilá-lo +em CSS. Você vai querer verificar se o CSS que você está usando é compatível +com os seus navegadores de destino. + +[QuirksMode CSS](http://www.quirksmode.org/css/) e [CanIUse](http://caniuse.com) são ótimos recursos para verificação de compatibilidade. + + +## Leitura +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) fornece tutoriais (iniciante avançados) e artigos. diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown index a29490b0..e840b8cf 100644 --- a/pt-br/swift-pt.html.markdown +++ b/pt-br/swift-pt.html.markdown @@ -1,7 +1,7 @@ --- language: swift contributors: - - ["Grant Timmerman", "http://github.com/grant"], + - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] translators: - ["Mariane Siqueira Machado", "https://twitter.com/mariane_sm"] @@ -9,14 +9,14 @@ lang: pt-br filename: learnswift.swift --- -Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para +Swift é uma linguagem de programação para desenvolvimento de aplicações no iOS e OS X criada pela Apple. Criada para coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta. O livro oficial [Swift Programming Language] (https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple já está disponível via IBooks (apenas em inglês). -Confira também o tutorial completo de Swift da Apple [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), também disponível apenas em inglês. +Confira também o tutorial completo de Swift da Apple [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), também disponível apenas em inglês. ```swift // importa um módulo @@ -59,9 +59,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Interpolação de strings println("Build value: \(buildValue)") // Build value: 7 /* - Optionals fazem parte da linguagem e permitem que você armazene um + Optionals fazem parte da linguagem e permitem que você armazene um valor `Some` (algo) ou `None` (nada). - + Como Swift requer que todas as propriedades tenham valores, até mesmo nil deve ser explicitamente armazenado como um valor Optional. @@ -76,7 +76,7 @@ if someOptionalString != nil { if someOptionalString!.hasPrefix("opt") { println("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil @@ -221,7 +221,7 @@ println("Gas price: \(price)") // Número variável de argumentos func setup(numbers: Int...) { - // its an array + // é um array let number = numbers[0] let argCount = numbers.count } @@ -289,7 +289,7 @@ print(numbers) // [3, 6, 18] // Estruturas e classes tem funcionalidades muito similares struct NamesTable { let names: [String] - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -319,7 +319,7 @@ public class Shape { internal class Rect: Shape { var sideLength: Int = 1 - + // Getter e setter personalizado private var perimeter: Int { get { @@ -330,13 +330,13 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - + // Carregue uma propriedade sob demanda (lazy) // subShape permanece nil (não inicializado) até seu getter ser chamado lazy var subShape = Rect(sideLength: 4) - + // Se você não precisa de um getter e setter personalizado, - // mas ainda quer roda código antes e depois de configurar + // mas ainda quer roda código antes e depois de configurar // uma propriedade, você pode usar `willSet` e `didSet` var identifier: String = "defaultID" { // o argumento `willSet` será o nome da variável para o novo valor @@ -344,25 +344,25 @@ internal class Rect: Shape { print(someIdentifier) } } - + init(sideLength: Int) { self.sideLength = sideLength // sempre chame super.init por último quand inicializar propriedades personalizadas (custom) super.init() } - + func shrink() { if sideLength > 0 { --sideLength } } - + override func getArea() -> Int { return sideLength * sideLength } } -// Uma classe básica `Square` que estende `Rect` +// Uma classe básica `Square` que estende `Rect` class Square: Rect { convenience init() { self.init(sideLength: 5) @@ -420,10 +420,10 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 - + if let allow = self.delegate?.canReshape?() { // test for delegate then for method // testa por delegação e então por método @@ -439,7 +439,7 @@ class MyShape: Rect { // `extension`s: Adicionam uma funcionalidade extra para um tipo já existente. -// Square agora "segue" o protocolo `Printable` +// Square agora "segue" o protocolo `Printable` extension Square: Printable { var description: String { return "Area: \(self.getArea()) - ID: \(self.identifier)" @@ -453,7 +453,7 @@ extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } diff --git a/pt-br/tmux-pt.html.markdown b/pt-br/tmux-pt.html.markdown new file mode 100644 index 00000000..9d5bf292 --- /dev/null +++ b/pt-br/tmux-pt.html.markdown @@ -0,0 +1,254 @@ +--- +category: tool +tool: tmux +contributors: + - ["mdln", "https://github.com/mdln"] +translators: + - ["Luis Custodio", "http://luiscustodio.com"] +lang: pt-br +filename: LearnTmux-pt.txt +--- + +O [tmux](http://tmux.sourceforge.net) +é um multiplexador de terminal, ele permite que terminais sejam criados, +acessados e controlados a partir de uma unica instância. tmux pode ser separado +de uma tela e continuar rodando no plano de fundo e depois ser reacoplado à +instância (ou tela original). + +``` + + tmux [command] # Roda um [comando] + # 'tmux' sem comandos irá criar uma nova seção + + new # Cria uma nova seção + -s "Nome" # Cria uma nova seção com nome "Nome" + -n "Janela" # Cria uma janela com o nome "Janela" + -c "/dir" # Inícia em uma pasta específica + + attach # Reacopla a última seção disponível + -t "#" # Reacopla a seção com nome "#" + -d # Separa (Desacopla) a sessaão de outras instâncias. + + ls # Lista todas as seções + -a # Lista todas as seções abertas + + lsw # Lista as janelas + -a # Lista todas as janelas + -s # Lista todas janleas em uma seção + + lsp # Lista os painéis + -a # Lista todos os painéis + -s # Lista todos os painéis em uma seção + -t "#" # Lista os painéis baseado no nome "#" + + kill-window # Encerrar a janela corrente + -t "#" # Encerrar a janela baseado no nome "#" + -a # Encerrar todas as janelas + -a -t "#" # Encerrar todas as janelas exceto a com nome "#" + + kill-session # Encerrar seção corrente + -t "#" # Encerrar seção com nome "#" + -a # Encerrar todas as seções + -a -t "#" # Encerrar todas as seções exceto a com nome "#" + +``` + + +### Teclas de atalhos (comandos) + +A maneira de controllar uma seção tmux acoplada é através de uma +combinação de teclas de prefixo. + +``` +---------------------------------------------------------------------- + (C-b) = Ctrl + b # Combinação de prefixos para usar comandos(atalhos). + + (M-1) = Meta + 1 -or- Alt + 1 +---------------------------------------------------------------------- + + ? # Lista todos os comandos. + : # Acessa o lugar (prompt command) para receber comandos do tmux + r # Força a redefiniçao do cliente acoplado. + c # Cria uma nova janela. + + ! # Retira o painel corrente da janela. + % # Divide o painel corrente em dois para a esquerda e direita. + " # Divide o painel corrente em dois para cima e para baixo. + + n # Move para a próxima janela. + p # Move para a janela anterior. + { # Troca o painel corrente pelo anterior. + } # Troca o painel corrent pelo posterior. + + s # Seleciona uma nova seção para o cliente acoplado iterativamente. + w # Seleciona a janela corrente iterativamente. + 0 to 9 # Seleciona a janela de 0 à 9. + + d # Separa o cliente atual. + D # Seleciona um cliente a ser separado. + + & # Encerra a janela corrente. + x # Encerra o painel corrente. + + Up, Down # Move para o painel acima, abaixo, a esquerda ou a direita. + Left, Right + + M-1 to M-5 # Organiza os paines: + # 1) Horizontalmente de maneira igual + # 2) Verticalmente de maineira igual. + # 3) Principal horizontalmente + # 4) Principal verticamente. + # 5) Mosaico + + C-Up, C-Down # Altera o tamanho do painel corrente baseado em uma célula. + C-Left, C-Right + + M-Up, M-Down # Altera o tamanho do painel corrente baseado em cinco células. + M-Left, M-Right + +``` + + +### Configurando ~/.tmux.conf + +Existe um arquivo chamado tmux.conf, ele pode ser usado para definir opções no + momento de inicialização, da mesma maneira que .vimrc, init.el, .bash_profile são usados. + + +``` +# Exemplo de tmux.conf +# 2014.10 + + +### General +########################################################################### + +# Habilita UTF-8 +setw -g utf8 on +set-option -g status-utf8 on + +# Limite da história de comandos +set -g history-limit 2048 + +# Indíce de inicialização +set -g base-index 1 + +# Mouse +set-option -g mouse-select-pane on + +# Recarregar o arquivo de configuração sem a necessidade de reiniciar o programa +unbind r +bind r source-file ~/.tmux.conf + + +### Teclas de atalho +########################################################################### + +# Desvincular C-b como prefixo padrão. +unbind C-b + +# Define um novo prefixo padrão. +set-option -g prefix ` + +# Definir prefixos que podem ser usados para voltar para a janela anterior. +bind C-a last-window +bind ` last-window + +# Fazer com que F11 e F12 alterem o comportamento de C-a e ` +bind F11 set-option -g prefix C-a +bind F12 set-option -g prefix ` + +# Preferencia de teclas de atalho +setw -g mode-keys vi +set-option -g status-keys vi + +# Mover enter paineis com teclas de orientaçao do vim +bind h select-pane -L +bind j select-pane -D +bind k select-pane -U +bind l select-pane -R + +# Iterar entre as Janelas +bind e previous-window +bind f next-window +bind E swap-window -t -1 +bind F swap-window -t +1 + +# Iterar entre os painéis +bind = split-window -h +bind - split-window -v +unbind '"' +unbind % + +# Habilitar a sub-seção a enviar comandos. +bind a send-prefix + + +### Theme +########################################################################### + +# Paleta de cores para a barra de status +set-option -g status-justify left +set-option -g status-bg black +set-option -g status-fg white +set-option -g status-left-length 40 +set-option -g status-right-length 80 + +# Paleta de cores para bordas do painel +set-option -g pane-active-border-fg green +set-option -g pane-active-border-bg black +set-option -g pane-border-fg white +set-option -g pane-border-bg black + +# Palta de cores para mensagem +set-option -g message-fg black +set-option -g message-bg green + +# Paleta de cores para janela de status +setw -g window-status-bg black +setw -g window-status-current-fg green +setw -g window-status-bell-attr default +setw -g window-status-bell-fg red +setw -g window-status-content-attr default +setw -g window-status-content-fg yellow +setw -g window-status-activity-attr default +setw -g window-status-activity-fg yellow + + +### UI +########################################################################### + +# Notificações +setw -g monitor-activity on +set -g visual-activity on +set-option -g bell-action any +set-option -g visual-bell off + +# Definir automaticamente o título de janelas +set-option -g set-titles on +set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) + +# Ajustes na barra de status +set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" + +# Mostrar indicativos de performance na barra de status +# Requires https://github.com/thewtex/tmux-mem-cpu-load/ +set -g status-interval 4 +set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" + +``` + + +### Referências + +[Tmux | Início](http://tmux.sourceforge.net) + +[Manual Tmux (em inglês)](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Mostrar CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +Possui uma sugestão? Uma correção, talvez? Abra um issue no Repositório GitHub, ou então faça um pull request. diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown new file mode 100644 index 00000000..f347f8ef --- /dev/null +++ b/pt-br/xml-pt.html.markdown @@ -0,0 +1,133 @@ +--- +language: xml +filename: learnxml-pt.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +XML é uma linguagem de marcação projetada para armazenar e transportar dados. + +Ao contrário de HTML, XML não especifica como exibir ou formatar os dados, +basta carregá-lo. + +* Sintaxe XML + +```xml +<!-- Comentários em XML são feitos desta forma --> + +<?xml version="1.0" encoding="UTF-8"?> +<livraria> + <livro category="COZINHA"> + <titulo lang="en">Everyday Italian</titulo> + <autor>Giada De Laurentiis</autor> + <year>2005</year> + <preco>30.00</preco> + </livro> + <livro category="CRIANÇAS"> + <titulo lang="en">Harry Potter</titulo> + <autor>J K. Rowling</autor> + <year>2005</year> + <preco>29.99</preco> + </livro> + <livro category="WEB"> + <titulo lang="en">Learning XML</titulo> + <autor>Erik T. Ray</autor> + <year>2003</year> + <preco>39.95</preco> + </livro> +</livraria> + +<!-- Um típico arquivo XML é mostrado acima. + Ele começa com uma declaração, informando alguns metadados (opcional). + + XML usa uma estrutura de árvore. Acima, o nó raiz é "Livraria", que tem + três nós filhos, todos os 'Livros'. Esses nós tem mais nós filhos, + e assim por diante... + + Nós são criados usando tags abre/fecha, filhos são justamente os nós que + estão entre estes nós. --> + + +<!-- XML traz dois tipos de dados: + 1 - Atributos -> Isso é metadados sobre um nó. + Normalmente, o parser XML usa esta informação para armazenar os dados + corretamente. Caracteriza-se por aparecer em parênteses dentro da tag + de abertura. + 2 - Elementos -> É dados puros. + Isso é o que o analisador irá recuperar a partir do arquivo XML. + Elementos aparecem entre as tags de abertura e fechamento, + sem parênteses. --> + + +<!-- Abaixo, um elemento com dois atributos --> +<arquivo type="gif" id="4293">computer.gif</arquivo> + + +``` + +* Documento bem formatado x Validação + +Um documento XML é bem formatado se estiver sintaticamente correto.No entanto, +é possível injetar mais restrições no documento, utilizando definições de +documentos, tais como DTD e XML Schema. + +Um documento XML que segue uma definição de documento é chamado válido, sobre +esse documento. + +Com esta ferramenta, você pode verificar os dados XML fora da lógica da aplicação. + +```xml + +<!-- Abaixo, você pode ver uma versão simplificada do documento livraria, +com a adição de definição DTD.--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "livraria.dtd"> +<livraria> + <livro category="COOKING"> + <titulo >Everyday Italian</titulo> + <preco>30.00</preco> + </livro> +</livraria> + +<!-- Este DTD poderia ser algo como:--> + +<!DOCTYPE note +[ +<!ELEMENT livraria (livro+)> +<!ELEMENT livro (titulo,preco)> +<!ATTLIST livro category CDATA "Literature"> +<!ELEMENT titulo (#PCDATA)> +<!ELEMENT preco (#PCDATA)> +]> + + +<!-- O DTD começa com uma declaração. + Na sequência, o nó raiz é declarado, o que requer uma ou mais crianças nós + 'Livro'. Cada 'Livro' deve conter exatamente um 'titulo' e um 'preco' e um + atributo chamado "categoria", com "Literatura", como o valor padrão. + Os nós "título" e "preço" contêm um conjunto de dados de caráter analisados.--> + +<!-- O DTD poderia ser declarado dentro do próprio arquivo XML .--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT livraria (livro+)> +<!ELEMENT livro (titulo,preco)> +<!ATTLIST livro category CDATA "Literature"> +<!ELEMENT titulo (#PCDATA)> +<!ELEMENT preco (#PCDATA)> +]> + +<livraria> + <livro category="COOKING"> + <titulo >Everyday Italian</titulo> + <preco>30.00</preco> + </livro> +</livraria> +``` diff --git a/pt-pt/git-pt.html.markdown b/pt-pt/git-pt.html.markdown index 66cda07f..a85c9704 100644 --- a/pt-pt/git-pt.html.markdown +++ b/pt-pt/git-pt.html.markdown @@ -74,8 +74,7 @@ maior controlo sobre o que é registado no repositório git. ### *Commit* -Um *commit** de git é um registo de um cojunto de alterações ou manipulações -no nos ficheiros do projecto. +Um *commit** de git é um registo de um cojunto de alterações ou manipulações nos ficheiros do projecto. Por exemplo, ao adicionar cinco ficheiros e remover outros 2, estas alterações serão gravadas num *commit* (ou registo). Este *commit* pode então ser enviado para outros repositórios ou não! @@ -83,7 +82,7 @@ para outros repositórios ou não! ### *Branch* Um *branch* é essencialmente uma referência que aponta para o último *commit* -efetuado. à medida que são feitos novos commits, esta referência é atualizada +efetuado. À medida que são feitos novos commits, esta referência é atualizada automaticamente e passa a apontar para o commit mais recente. ### *HEAD* e *head* (componentes do directório .git) @@ -115,7 +114,7 @@ Permite configurar as definições, sejam as definições do repositório, siste ou configurações globais. ```bash -# Imprime & Define Algumas Variáveis de Configuração Básicas (Global) +# Imprime e define algumas variáveis de configuração básicas (global) $ git config --global user.email $ git config --global user.name @@ -123,7 +122,7 @@ $ git config --global user.email "MyEmail@Zoho.com" $ git config --global user.name "My Name" ``` -[Aprenda Mais Sobre git config. (EN)](http://git-scm.com/docs/git-config) +[Aprenda mais sobre git config. (EN)](http://git-scm.com/docs/git-config) ### help @@ -166,7 +165,7 @@ adicionados através de `git add` ao repositório, então eles não serão incluidos nos commits! ```bash -# adiciona um ficheiro no directório do project atual +# adiciona um ficheiro no directório do projecto atual $ git add HelloWorld.java # adiciona um ficheiro num sub-directório @@ -371,7 +370,7 @@ Restabelece a HEAD atual ao estado definido. Isto permite reverter *merges*, perigoso se não há certeza quanto ao que se está a fazer. ```bash -# Restabelece a camada intermediária dr registo para o último +# Restabelece a camada intermediária de registo para o último # commit (o directório fica sem alterações) $ git reset diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown new file mode 100644 index 00000000..a4c1c02b --- /dev/null +++ b/pt-pt/scala-pt.html.markdown @@ -0,0 +1,651 @@ +--- +language: Scala +filename: learnscala-pt.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["João Costa", "http://joaocosta.eu"] +lang: pt-pt +--- + +Scala - a linguagem escalável + +```scala + +/* + Prepare tudo: + + 1) Faça Download do Scala - http://www.scala-lang.org/downloads + 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na + variável de ambiente `PATH` + 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer: + + scala> + + Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete). + Pode escrever qualquer expressão de Scala e o resultado será imprimido. + Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já, + vamos começar com os básicos. + +*/ + + +///////////////////////////////////////////////// +// 1. Basicos +///////////////////////////////////////////////// + +// Uma linha de comentários é marcada com duas barras + +/* + Comentários de multiplas linhas, como se pode ver neste exemplo, são assim. +*/ + +// Imprimir, forçando uma nova linha no final +println("Hello world!") +println(10) + +// Imprimir, sem forçar uma nova linha no final +print("Hello world") + +// Valores são declarados com var ou val. +// As declarações val são imutáveis, enquanto que vars são mutáveis. +// A immutabilidade é uma propriedade geralmente vantajosa. +val x = 10 // x é agora 10 +x = 20 // erro: reatribuição de um val +var y = 10 +y = 20 // y é agora 12 + +/* + Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima + não especificamos um tipo. Isto é devido a uma funcionalidade chamada + inferência de tipos. Na maior parte dos casos, o compilador de scala consegue + inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre. + Podemos declarar o tipo de uma variável da seguinte forma: +*/ +val z: Int = 10 +val a: Double = 1.0 + +// Note a conversão automática de Int para Double: o resultado é 10.0, não 10 +val b: Double = 10 + +// Valores booleanos +true +false + +// Operações booleanas +!true // false +!false // true +true == false // false +10 > 5 // true + +// A matemática funciona da maneira habitual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +// Avaliar expressões na REPL dá o tipo e valor do resultado + +1 + 7 + +/* A linha acima resulta em: + + scala> 1 + 7 + res29: Int = 8 + + Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com + o valor 8. + + Note que "res29" é um nome de uma variavel gerado sequencialmente para + armazenar os resultados das expressões que escreveu, por isso o resultado + pode ser ligeiramente diferente. +*/ + +"Strings em scala são rodeadas por aspas" +'a' // Um caracter de Scala +// 'Strings entre plicas não existem' <= Isto causa um erro + +// Strings tem os métodos de Java habituais definidos +"olá mundo".length +"olá mundo".substring(2, 6) +"olá mundo".replace("á", "é") + +// Para além disso, também possuem métodos de Scala. +// Ver: scala.collection.immutable.StringOps +"olá mundo".take(5) +"olá mundo".drop(5) + +// Interpolação de Strings: repare no prefixo "s" +val n = 45 +s"Temos $n maçãs" // => "Temos 45 maçãs" + +// Expressões dentro de Strings interpoladas também são possíveis +val a = Array(11, 9, 6) +s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos." +s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs." +s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4" + +// Strings interpoladas são formatadas com o prefixo "f" +f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25" +f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454" + +// Strings prefixadas com "raw" ignoram caracteres especiais +raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r." + +// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string: +"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown"" + +// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas +val html = """<form id="daform"> + <p>Carrega aqui, Zé</p> + <input type="submit"> + </form>""" + + +///////////////////////////////////////////////// +// 2. Funções +///////////////////////////////////////////////// + +// Funções são definidas como: +// +// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... } +// +// Se vem de linugagens mais tradicionais, repare na omissão da palavra +// return keyword. Em Scala, a ultima expressão de um bloco é o seu +// valor de retorno +def somaQuadrados(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// As { } podem ser omitidas se o corpo da função for apenas uma expressão: +def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y + +// A sintaxe para chamar funções deve ser familiar: +somaQuadrados(3, 4) // => 25 + +// Na maior parte dos casos (sendo funções recursivas a principal excepção), o +// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos +// é aplicada aos valores de retorno +def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int + +// Funções podem ter parâmetros por omissão: +def somaComOmissão(x: Int, y: Int = 5) = x + y +somaComOmissão(1, 2) // => 3 +somaComOmissão(1) // => 6 + + +// Funções anónimas são definidas da seguinte forma: +(x: Int) => x * x + +// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido +// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma +// funão que recebe Int e retorna Int. +val quadrado: Int => Int = x => x * x + +// Funcões anónimas são chamadas como funções normais: +quadrado(10) // => 100 + +// Se cada argumento de uma função anónima for usado apenas uma vez, existe +// uma forma ainda mais curta de os definir. Estas funções anónumas são +// extremamente comuns, como será visto na secção sobre estruturas de dados. +val somaUm: Int => Int = _ + 1 +val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3) + +somaUm(5) // => 6 +somaEstranha(2, 4) // => 16 + + +// O código return existe em Scala, mas apenas retorna do def mais interior +// que o rodeia. +// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros. +// Não tem qualquer efeito em funções anónimas, por exemplo: +def foo(x: Int): Int = { + val funcAnon: Int => Int = { z => + if (z > 5) + return z // Esta linha faz com que z seja o retorno de foo! + else + z + 2 // Esta linha define o retorno de funcAnon + } + funcAnon(x) // Esta linha define o valor de retorno de foo +} + + +///////////////////////////////////////////////// +// 3. Controlo de fluxo +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach(println) + +r foreach println +// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as +// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis + +(5 to 1 by -1) foreach (println) + +// Ciclos while +var i = 0 +while (i < 10) { println("i " + i); i += 1 } + +while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê? + +i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico - + // executa sequencialmente enquanto muda uma variável. Ciclos while são + // rápidos, por vezes até mais que ciclos de Java, mas combinadores e + // compreensões (usados anteriormente) são mais fáceis de entender e + // paralelizar + +// Um ciclo do while +i = 0 +do { + println("i ainda é menor que 10") + i += 1 +} while (i < 10) + +// A forma idiomática em Scala de definir acções recorrentes é através de +// recursão em cauda. +// Funções recursivas necessitam de um tipo de retorno definido explicitamente. +// Neste caso, é Unit. +def mostraNumerosEntre(a: Int, b: Int): Unit = { + print(a) + if (a < b) + mostraNumerosEntre(a + 1, b) +} +mostraNumerosEntre(1, 14) + + +// Condicionais + +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" + + +///////////////////////////////////////////////// +// 4. Estruturas de dados +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Lança uma excepção + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Lança uma excepção + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Veja a documentação de mapas de scala em - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * e verifique que a consegue aceder + */ + + +// Tuplos + +(1, 2) + +(4, 3, 2) + +(1, 2, "três") + +(a, 2, "três") + +// Porquê ter isto? +val divideInts = (x: Int, y: Int) => (x / y, x % y) + +divideInts(10, 3) // A função divideInts returna o resultado e o resto + +// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice +// (começado em 1) do elemento +val d = divideInts(10, 3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Programação Orientada a Objectos +///////////////////////////////////////////////// + +/* + Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples + (valores, funções, etc). Estas expressões são suficientes para executar no + interpretador da linha de comandos para testes rápidos, mas não podem existir + isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um + ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas + construções de topo permitidas são: + + - object + - class + - case class + - trait + + Vamos agora explicar o que são: +*/ + +// Classes são semelhantes a classes noutras linguagens. Os argumentos do +// construtor são declarados após o nome da classe, sendo a inicialização feita +// no corpo da classe. +class Cão(rc: String) { + // Código de construção + var raça: String = rc + + // Define um método chamado "ladra", que retorna uma String + def ladra = "Woof, woof!" + + // Valores e métodos são assumidos como públicos, mas é possivel usar + // os códigos "protected" and "private". + private def dormir(horas: Int) = + println(s"Vou dormir por $horas horas") + + // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima + // linha, a classe Cão é declarada como abstracta + // abstract class Cão(...) { ... } + // def persegue(oQue: String): String +} + +val oMeuCão = new Cão("greyhound") +println(oMeuCão.raça) // => "greyhound" +println(oMeuCão.ladra) // => "Woof, woof!" + + +// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum +// que classes de Scala possuam um "objecto companheiro", onde o comportamento +// por instância é capturado nas classes, equanto que o comportamento +// relacionado com todas as instancias dessa classe ficam no objecto. +// A diferença é semelhante a métodos de classes e métodos estáticos noutras +// linguagens. Note que objectos e classes podem ter o mesmo nome. +object Cão { + def raçasConhecidas = List("pitbull", "shepherd", "retriever") + def criarCão(raça: String) = new Cão(raça) +} + + +// Case classes são classes com funcionalidades extra incluidas. Uma questão +// comum de iniciantes de scala é quando devem usar classes e quando devem usar +// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se +// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes +// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal +// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos +// métods, sendo que estes raramente possuem efeitos secundários. +case class Pessoa(nome: String, telefone: String) + +// Cria uma nova instancia. De notar que case classes não precisam de "new" +val jorge = Pessoa("Jorge", "1234") +val cátia = Pessoa("Cátia", "4567") + +// Case classes trazem algumas vantagens de borla, como acessores: +jorge.telefone // => "1234" + +// Igualdade por campo (não é preciso fazer override do .equals) +Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false + +// Cópia simples +// outroJorge == Person("jorge", "9876") +val outroJorge = jorge.copy(telefone = "9876") + +// Entre outras. Case classes também suportam correspondência de padrões de +// borla, como pode ser visto de seguida. + + +// Traits em breve! + + +///////////////////////////////////////////////// +// 6. Correspondência de Padrões +///////////////////////////////////////////////// + +// A correspondência de padrões é uma funcionalidade poderosa e bastante +// utilizada em Scala. Eis como fazer correspondência de padrões numa case class: +// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de +// breaks, a computação termina no primeiro sucesso. + +def reconhecePessoa(pessoa: Pessoa): String = pessoa match { + // Agora, especifique os padrões: + case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel + case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel + case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel +} + +val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo. + +// A correspondência de padrões pode parecer familiar aos switches em linguagens +// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer +// correspondências com muito mais: +def correspondeTudo(obj: Any): String = obj match { + // Pode-se corresponder valores: + case "Olá mundo" => "Recebi uma string Olá mundo." + + // Corresponder por tipo: + case x: Double => "Recebi um Double: " + x + + // Corresponder tendo em conta condições especificas: + case x: Int if x > 10000 => "Recebi um número bem grande!" + + // Fazer correspondências com case classes (visto anteriormente): + case Pessoa(nome, tel) => s"Recebi o contacto para $nome!" + + // Fazer correspondência com expressões regulares: + case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio" + + // Corresponder tuplos: + case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c" + + // Corresponder estruturas de dados: + case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c" + + // Combinar padrões: + case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo" +} + +// Na realidade, é possível fazer correspondência com qualquer objecto que +// defina o método "unapply". Esta funcionalidade é tão poderosa que permite +// definir funções sob a forma de padrões: +val funcPaddrao: Pessoa => String = { + case Pessoa("Jorge", tel) => s"Número do Jorge: $tel" + case Pessoa(nome, tel) => s"Número de alguém: $tel" +} + + +///////////////////////////////////////////////// +// 7. Programação Funcional +///////////////////////////////////////////////// + +// Scala permite que funções e métodos retornem, ou recebam como parámetros, +// outras funções ou métodos + +val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int +List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento + +// Funções anónimas também podem ser usadas +List(1, 2, 3) map (x => x + 10) + +// Sendo que o símbolo _ também pode ser usado se a função anónima só receber +// um argumento. Este fica com o valor da variável +List(1, 2, 3) map (_ + 10) + +// Se tanto o bloco como a função apenas receberem um argumento, o próprio +// _ pode ser omitido +List("Dom", "Bob", "Natalia") foreach println + + +// Combinadores + +s.map(quadrado) + +val sQuadrado = s.map(quadrado) + +sQuadrado.filter(_ < 10) + +sQuadrado.reduce (_+_) + +// O método filter recebe um predicado (uma função de A => Boolean) e escolhe +// todos os elementos que satisfazem o predicado +List(1, 2, 3) filter (_ > 2) // List(3) +case class Pessoa(nome: String, idade: Int) +List( + Pessoa(nome = "Dom", idade = 23), + Pessoa(nome = "Bob", idade = 30) +).filter(_.idade > 25) // List(Pessoa("Bob", 30)) + + +// O método foreach recebe uma função de A => Unit, executando essa função em +// cada elemento da colecção +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// Compreensões For + +for { n <- s } yield quadrado(n) + +val nQuadrado2 = for { n <- s } yield quadrado(n) + +for { n <- nQuadrado2 if n < 10 } yield n + +for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado + +/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto + que uma compreensão define a relação entre dois conjuntos de dados. */ + + +///////////////////////////////////////////////// +// 8. Implicitos +///////////////////////////////////////////////// + +/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito + * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem + * resistir a tentação de usá-los até que compreendam não só como funcionam, + * mas também as melhores práticas. Apenas incluimos esta secção no tutorial + * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas + * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve + * para compreender como trabalhar com implicitos, não como declará-los. +*/ + +// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como +// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5 +// nestes exemplos + +implicit val oMeuIntImplicito = 100 +implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça) + +// Por si só, a palavra implicit não altera o comportamento de um valor, sendo +// que estes podem ser usados da forma habitual. +oMeuIntImplicito + 2 // => 102 +aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull" + +// A diferença é que estes valores podem ser utilizados quando outro pedaço de +// código "necessite" de uma valor implicito. Um exemplo são argumentos +// implicitos de funções: +def enviaCumprimentos(aQuem: String)(implicit quantos: Int) = + s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!" + +// Se dermos um valor a "quantos", a função comporta-se normalmente +enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!" + +// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é +// usado, neste caso, "oMeuInteiroImplicito" +enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!" + +// Parâmentros implicitos de funções permitem-nos simular classes de tipos de +// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação. +// As seguintes linhas representam a mesma coisa +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... + + +// Outra situação em que o compilador prouca um implicito é se encontrar uma +// expressão +// obj.método(...) +// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma +// conversão implicita A => B, onde A é o tipo de obj, e B possui um método +// chamado "método", a conversão é aplicada. Ou seja, tendo +// aMinhaFunçãoImplicita definida, podemos dizer +"Retriever".raça // => "Golden Retriever" +"Sheperd".ladra // => "Woof, woof!" + +// Neste caso, a String é primeiro convertida para Cão usando a nossa funão, +// sendo depois chamado o método apropriado. Esta é uma funcionalidade +// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade, +// ao definir a função implicita, o compilador deve lançar um aviso a insisitir +// que só deve definir a função se souber o que está a fazer. + + +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// + +// Importar coisas +import scala.collection.immutable.List + +// Importar todos os "sub pacotes" +import scala.collection.immutable._ + +// Importar multiplas classes numa linha +import scala.collection.immutable.{List, Map} + +// Renomear uma classe importada usando '=>' +import scala.collection.immutable.{List => ImmutableList} + +// Importar todas as classes excepto algumas. Set e Map são excluidos: +import scala.collection.immutable.{Map => _, Set => _, _} + +// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala +// com um método main: +object Aplicação { + def main(args: Array[String]): Unit = { + // código aqui. + } +} + +// Ficheiros podem conter várias classes o objectos. Compilar com scalac + + + + +// Input e output + +// Ler um ficheiro linha a linha +import scala.io.Source +for(linha <- Source.fromFile("ficheiro.txt").getLines()) + println(linha) + +// Escrever um ficheiro usando o PrintWriter de Java +val writer = new PrintWriter("ficheiro.txt") +writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator) +writer.write("Outra linha aqui" + util.Properties.lineSeparator) +writer.close() + +``` + +## Mais recursos + +* [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/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/purescript.html.markdown b/purescript.html.markdown index 6bff7545..6d8cfbb9 100644 --- a/purescript.html.markdown +++ b/purescript.html.markdown @@ -2,40 +2,49 @@ language: purescript contributors: - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] + - ["Thimoteus", "https://github.com/Thimoteus"] --- PureScript is a small strongly, statically typed language compiling to Javascript. * Learn more at [http://www.purescript.org/](http://www.purescript.org/) -* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Documentation: [http://pursuit.purescript.org/](http://pursuit.purescript.org/) * Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) +All the noncommented lines of code can be run in the PSCI REPL, though some will +require the `--multi-line-mode` flag. + ```haskell -- -- 1. Primitive datatypes that corresponds to their Javascript -- equivalents at runtime. +import Prelude -- Numbers -1 + 7*5 :: Number -- 36 +1.0 + 7.2*5.5 :: Number -- 40.6 +-- Ints +1 + 2*5 :: Int -- 11 -- Types are inferred, so the following works fine -9 / 2.5 + 4.4 -- 8 +9.0/2.5 + 4.4 -- 8.0 +-- But Ints and Numbers don't mix, so the following won't +5/2 + 2.5 -- Expression 2.5 does not have type Int -- Hexadecimal literals 0xff + 1 -- 256 -- Unary negation 6 * -3 -- -18 6 * negate 3 -- -18 --- Modulus -3 % 2 -- 1 -4 % 2 -- 0 +-- Modulus, from purescript-math (Math) +3.0 % 2.0 -- 1.0 +4.0 % 2.0 -- 0.0 -- Inspect the type of an expression in psci -:t 9 / 2.5 + 4.4 -- Prim.Number +:t 9.5/2.5 + 4.4 -- Prim.Number -- Booleans true :: Boolean -- true false :: Boolean -- false -- Negation -not true --false +not true -- false 23 == 23 -- true 1 /= 4 -- true 1 >= 4 -- false @@ -49,19 +58,22 @@ true && (9 >= 19 || 1 < 2) -- true -- Strings "Hellow" :: String -- "Hellow" --- Multiline string +-- Multiline string without newlines, to run in psci use the --multi-line-mode flag "Hellow\ \orld" -- "Helloworld" +-- Multiline string with newlines +"""Hello +world""" -- "Hello\nworld" -- Concatenate "such " ++ "amaze" -- "such amaze" -- -- 2. Arrays are Javascript arrays, but must be homogeneous -[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] -[true, true, false] :: [Boolean] -- [true,true,false] +[1,1,2,3,5,8] :: Array Number -- [1,1,2,3,5,8] +[true, true, false] :: Array Boolean -- [true,true,false] -- [1,2, true, "false"] won't work --- `Cannot unify Prim.Number with Prim.Boolean` +-- `Cannot unify Prim.Int with Prim.Boolean` -- Cons (prepend) 1 : [2,4,3] -- [1,2,4,3] @@ -70,12 +82,12 @@ true && (9 >= 19 || 1 < 2) -- true -- Safe access return Maybe a head [1,2,3] -- Just (1) -tail [3,2,1] -- Just ([2,1]) +tail [3,2,1] -- Just ([2,1]) init [1,2,3] -- Just ([1,2]) last [3,2,1] -- Just (1) -- Random access - indexing [3,4,5,6,7] !! 2 -- Just (5) --- Range +-- Range 1..5 -- [1,2,3,4,5] length [2,2,2] -- 3 drop 3 [5,4,3,2,1] -- [2,1] @@ -84,91 +96,95 @@ append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] -- -- 3. Records are Javascript objects, with zero or more fields, which --- can have different types +-- can have different types. +-- In psci you have to write `let` in front of the function to get a +-- top level binding. let book = {title: "Foucault's pendulum", author: "Umberto Eco"} -- Access properties book.title -- "Foucault's pendulum" -getTitle b = b.title +let getTitle b = b.title -- Works on all records with a title (but doesn't require any other field) getTitle book -- "Foucault's pendulum" getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Can use underscores as shorthand +_.title book -- "Foucault's pendulum" -- Update a record -changeTitle b t = b {title = t} -changeTitle book "Ill nome della rosa" -- {title: "Ill nome della - -- rosa", author: "Umberto Eco"} +let changeTitle b t = b {title = t} +getTitle (changeTitle book "Ill nome della rosa") -- "Ill nome della rosa" -- -- 4. Functions -sumOfSquares x y = x*x+y*y +-- In psci's multiline mode +let sumOfSquares :: Int -> Int -> Int + sumOfSquares x y = x*x + y*y sumOfSquares 3 4 -- 25 --- In psci you have to write `let` in front of the function to get a --- top level binding -mod x y = x % y -mod 3 2 -- 1 +let myMod x y = x % y +myMod 3.0 2.0 -- 1.0 -- Infix application of function 3 `mod` 2 -- 1 --- function application have higher precedence than all other +-- function application has higher precedence than all other -- operators sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 -- Conditional -abs' n = if n>=0 then n else -n +let abs' n = if n>=0 then n else -n abs' (-3) -- 3 -- Guarded equations -abs n | n >= 0 = n - | otherwise = -n +let abs'' n | n >= 0 = n + | otherwise = -n -- Pattern matching --- Note the type signature, input is an array of numbers The pattern --- matching destructures and binds the array into parts -first :: [Number] -> Number -first (x:_) = x -first [3,4,5] -- 3 -second :: [Number] -> Number -second (_:y:_) = y -second [3,4,5] -- 4 -sumTwo :: [Number] -> [Number] -sumTwo (x:y:rest) = (x+y) : rest -sumTwo [2,3,4,5,6] -- [5,4,5,6] - --- sumTwo doesn't handle when the array is empty or just have one --- element in which case you get an error +-- Note the type signature, input is a list of numbers. The pattern matching +-- destructures and binds the list into parts. +-- Requires purescript-lists (Data.List) +let first :: forall a. List a -> a + first (Cons x _) = x +first (toList [3,4,5]) -- 3 +let second :: forall a. List a -> a + second (Cons _ (Cons y _)) = y +second (toList [3,4,5]) -- 4 +let sumTwo :: List Int -> List Int + sumTwo (Cons x (Cons y rest)) = x + y : rest +fromList (sumTwo (toList [2,3,4,5,6])) :: Array Int -- [5,4,5,6] + +-- sumTwo doesn't handle when the list is empty or there's only one element in +-- which case you get an error. sumTwo [1] -- Failed pattern match -- Complementing patterns to match -- Good ol' Fibonacci -fib 1 = 1 -fib 2 = 2 -fib x = fib (x-1) + fib (x-2) +let fib 1 = 1 + fib 2 = 2 + fib x = fib (x-1) + fib (x-2) fib 10 -- 89 -- Use underscore to match any, where you don't care about the binding name -isZero 0 = true -isZero _ = false +let isZero 0 = true + isZero _ = false -- Pattern matching on records -ecoTitle {author = "Umberto Eco", title = t} = Just t -ecoTitle _ = Nothing +let ecoTitle {author = "Umberto Eco", title = t} = Just t + ecoTitle _ = Nothing ecoTitle book -- Just ("Foucault's pendulum") ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing -- ecoTitle requires both field to type check: -ecoTitle {title: "The Quantum Thief"} -- Object does not have property author +ecoTitle {title: "The Quantum Thief"} -- Object lacks required property "author" -- Lambda expressions (\x -> x*x) 3 -- 9 -(\x y -> x*x + y*y) 4 5 -- 41 -sqr = \x -> x*x +(\x y -> x*x + y*y) 4 5 -- 41 +let sqr = \x -> x*x -- Currying -add x y = x + y -- is equivalent with -add = \x -> (\y -> x+y) -add3 = add 3 -:t add3 -- Prim.Number -> Prim.Number +let myAdd x y = x + y -- is equivalent with +let myAdd' = \x -> \y -> x + y +let add3 = myAdd 3 +:t add3 -- Prim.Int -> Prim.Int -- Forward and backward function composition -- drop 3 followed by taking 5 @@ -177,9 +193,9 @@ add3 = add 3 (drop 3 <<< take 5) (1..20) -- [4,5] -- Operations using higher order functions -even x = x % 2 == 0 +let even x = x `mod` 2 == 0 filter even (1..10) -- [2,4,6,8,10] -map (\x -> x+11) (1..5) -- [12,13,14,15,16] +map (\x -> x + 11) (1..5) -- [12,13,14,15,16] -- Requires purescript-foldable-traversabe (Data.Foldable) @@ -187,7 +203,7 @@ foldr (+) 0 (1..10) -- 55 sum (1..10) -- 55 product (1..10) -- 3628800 --- Testing with predicate +-- Testing with predicate any even [1,2,3] -- true all even [1,2,3] -- false diff --git a/python.html.markdown b/python.html.markdown index 53381f32..f8f712d3 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] filename: learnpython.py --- @@ -14,7 +15,13 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] Note: This article applies to Python 2.7 specifically, but should be applicable -to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. +to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, +it is though recommended to start learning Python with Python 3. +For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). + +It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, +using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. ```python @@ -46,12 +53,18 @@ to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better -# Result of integer division truncated down both for positive and negative. +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 +# Note that we can also import division module(Section 6 Modules) +# to carry out normal division with just one '/'. +from __future__ import division +11/4 # => 2.75 ...normal division +11//4 # => 2 ...floored division + # Modulo operation 7 % 3 # => 1 @@ -101,6 +114,8 @@ not False # => True # Strings can be added too! "Hello " + "world!" # => "Hello world!" +# Strings can be added without using '+' +"Hello " "world!" # => "Hello world!" # ... or multiplied "Hello" * 3 # => "HelloHelloHello" @@ -108,11 +123,16 @@ not False # => True # A string can be treated like a list of characters "This is a string"[0] # => 'T' -# % can be used to format strings, like this: -"%s can be %s" % ("strings", "interpolated") +#String formatting with % +#Even though the % string operator will be deprecated on Python 3.1 and removed +#later at some time, it may still be good to know how it works. +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y) # A newer way to format strings is the format method. # This method is the preferred way +"{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") @@ -129,8 +149,16 @@ None is None # => True # very useful when dealing with primitive values, but is # very useful when dealing with objects. -# None, 0, and empty strings/lists all evaluate to False. -# All other values are True +# Any object can be used in a Boolean context. +# The following values are considered falsey: +# - None +# - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +# - empty sequences (e.g., '', (), []) +# - empty containers (e.g., {}, set()) +# - instances of user-defined classes meeting certain conditions +# see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False @@ -139,12 +167,14 @@ bool("") # => False ## 2. Variables and Collections #################################################### -# Python has a print statement, in all 2.x versions but removed from 3. -print "I'm Python. Nice to meet you!" -# Python also has a print function, available in versions 2.7 and 3... -# but for 2.7 you need to add the import (uncommented): -# from __future__ import print_function -print("I'm also Python! ") +# Python has a print statement +print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! + +# Simple way to get input data from console +input_string_var = raw_input("Enter some data: ") # Returns the data as a string +input_var = input("Enter some data: ") # Evaluates the data as python code +# Warning: Caution is recommended for input() method usage +# Note: In python 3, input() is deprecated and raw_input() is renamed to input() # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores @@ -155,6 +185,7 @@ some_var # => 5 some_other_var # Raises a name error # if can be used as an expression +# Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" # Lists store sequences @@ -193,7 +224,7 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list +# Reverse a copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] @@ -208,6 +239,17 @@ li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3, 4, 5, 6] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again + +# Get the index of the first item found +li.index(2) # => 1 +li.index(7) # Raises a ValueError as 7 is not in the list + # Check for existence in a list with "in" 1 in li # => True @@ -228,8 +270,9 @@ tup[:2] # => (1, 2) # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +d, e, f = 4, 5, 6 # you can leave out the parentheses # Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 +g = 4, 5, 6 # => (4, 5, 6) # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 @@ -264,7 +307,7 @@ filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 -# note that filled_dict.get("four") is still => 4 +# note that filled_dict.get("four") is still => None # (get doesn't set the value in the dictionary) # set the value of a key with a syntax similar to lists @@ -299,6 +342,15 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True + # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False @@ -314,11 +366,11 @@ some_var = 5 # Here is an if statement. Indentation is significant in python! # prints "some_var is smaller than 10" if some_var > 10: - print("some_var is totally bigger than 10.") + print "some_var is totally bigger than 10." elif some_var < 10: # This elif clause is optional. - print("some_var is smaller than 10.") + print "some_var is smaller than 10." else: # This is optional too. - print("some_var is indeed 10.") + print "some_var is indeed 10." """ @@ -329,8 +381,8 @@ prints: mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use % to interpolate formatted strings - print("%s is a mammal" % animal) + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) """ "range(number)" returns a list of numbers @@ -342,7 +394,19 @@ prints: 3 """ for i in range(4): - print(i) + print i + +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i """ While loops go until a condition is no longer met. @@ -354,7 +418,7 @@ prints: """ x = 0 while x < 4: - print(x) + print x x += 1 # Shorthand for x = x + 1 # Handle exceptions with a try/except block @@ -369,7 +433,13 @@ except (TypeError, NameError): pass # Multiple exceptions can be handled together, if required. else: # Optional clause to the try/except block. Must follow all except blocks print "All good!" # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print "We can clean up resources here" +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line #################################################### ## 4. Functions @@ -377,7 +447,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks # Use "def" to create new functions def add(x, y): - print("x is %s and y is %s" % (x, y)) + print "x is {0} and y is {1}".format(x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -388,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple if you do not use the * +# positional args, which will be interpreted as a tuple by using * def varargs(*args): return args @@ -396,7 +466,7 @@ varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a map if you do not use ** +# keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): return kwargs @@ -406,8 +476,8 @@ keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like def all_the_args(*args, **kwargs): - print(args) - print(kwargs) + print args + print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) @@ -429,22 +499,22 @@ def pass_all_the_args(*args, **kwargs): print varargs(*args) print keyword_args(**kwargs) -# Function Scope +# Function Scope x = 5 -def setX(num): +def set_x(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 - -def setGlobalX(num): + +def set_global_x(num): global x print x # => 5 x = num # global var x is now set to 6 print x # => 6 -setX(43) -setGlobalX(6) +set_x(43) +set_global_x(6) # Python has first class functions def create_adder(x): @@ -457,9 +527,12 @@ add_10(3) # => 13 # There are also anonymous functions (lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # There are built-in higher order functions map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters @@ -485,9 +558,13 @@ class Human(object): # Assign the argument to the instance's name attribute self.name = name + # Initialize property + self.age = 0 + + # An instance method. All methods take "self" as the first argument def say(self, msg): - return "%s: %s" % (self.name, msg) + return "{0}: {1}".format(self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument @@ -500,13 +577,30 @@ class Human(object): def grunt(): return "*grunt*" + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + # Instantiate a class i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +print i.say("hi") # prints out "Ian: hi" j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" +print j.say("hello") # prints out "Joel: hello" # Call our class method i.get_species() # => "H. sapiens" @@ -519,6 +613,16 @@ j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + #################################################### ## 6. Modules @@ -526,12 +630,12 @@ Human.grunt() # => "*grunt*" # You can import modules import math -print(math.sqrt(16)) # => 4 +print math.sqrt(16) # => 4 # You can get specific functions from a module from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print ceil(3.7) # => 4.0 +print floor(3.7) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended @@ -577,7 +681,7 @@ xrange_ = xrange(1, 900000000) # will double all numbers until a result >=30 found for i in double_numbers(xrange_): - print(i) + print i if i >= 30: break @@ -606,24 +710,25 @@ def say(say_please=False): return msg, say_please -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( +print say() # Can you buy me a beer? +print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ``` ## Ready For More? ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) -* [The Official Docs](http://docs.python.org/2.6/) +* [The Official Docs](http://docs.python.org/2/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/python3.html.markdown b/python3.html.markdown index 0b4feccc..1f9d0e42 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -4,6 +4,8 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] filename: learnpython3.py --- @@ -13,7 +15,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 3 specifically. Check out the other tutorial if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/python/) if you want to learn the old Python 2.7 ```python @@ -32,50 +34,50 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria 3 # => 3 # Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 +1 + 1 # => 2 +8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats by default +# Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 -# Result of integer division truncated down both for positive and negative. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 +# Result of integer division truncated down both for positive and negative. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # When you use a float, results are floats -3 * 2.0 # => 6.0 +3 * 2.0 # => 6.0 # Modulo operation -7 % 3 # => 1 +7 % 3 # => 1 -# Exponentiation (x to the yth power) -2**4 # => 16 +# Exponentiation (x**y, x to the yth power) +2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -# Boolean values are primitives +# Boolean values are primitives (Note: the capitalization) True False # negate with not -not True # => False +not True # => False not False # => True # Boolean Operators # Note "and" and "or" are case-sensitive -True and False #=> False -False or True #=> True +True and False # => False +False or True # => True # Note using Bool operators with ints -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True # Equality is == 1 == 1 # => True @@ -95,29 +97,41 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False +# (is vs. ==) is checks if two variable refer to the same object, but == checks +# if the objects pointed to have the same values. +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal + # Strings are created with " or ' "This is a string." 'This is also a string.' # Strings can be added too! But try not to do this. "Hello " + "world!" # => "Hello world!" +# Strings can be added without using '+' +"Hello " "world!" # => "Hello world!" # A string can be treated like a list of characters "This is a string"[0] # => 'T' # .format can be used to format strings, like this: -"{} can be {}".format("strings", "interpolated") +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" # You can repeat the formatting arguments to save some typing. "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +"{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") +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" # None is an object @@ -126,14 +140,14 @@ None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead. This checks for equality of object identity. "etc" is None # => False -None is None # => True +None is None # => True # None, 0, and empty strings/lists/dicts all evaluate to False. # All other values are True -bool(0) # => False +bool(0) # => False bool("") # => False -bool([]) #=> False -bool({}) #=> False +bool([]) # => False +bool({}) # => False #################################################### @@ -141,9 +155,17 @@ bool({}) #=> False #################################################### # Python has a print function -print("I'm Python. Nice to meet you!") +print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! + +# By default the print function also prints out a newline at the end. +# Use the optional argument end to change the end character. +print("Hello, World", end="!") # => Hello, World! + +# Simple way to get input data from console +input_string_var = input("Enter some data: ") # Returns the data as a string +# Note: In earlier versions of Python, input() method was named as raw_input() -# No need to declare variables before assigning to them. +# No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores some_var = 5 some_var # => 5 @@ -168,7 +190,7 @@ li.pop() # => 3 and li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array -li[0] # => 1 +li[0] # => 1 # Look at the last element li[-1] # => 3 @@ -177,52 +199,74 @@ li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) -li[1:3] # => [2, 4] +li[1:3] # => [2, 4] # Omit the beginning -li[2:] # => [4, 3] +li[2:] # => [4, 3] # Omit the end -li[:3] # => [1, 2, 4] +li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list -li[::-1] # => [3, 4, 2, 1] +# Return a reversed copy of the list +li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] +# Make a one layer deep copy using slices +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + # Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +del li[2] # li is now [1, 2, 3] + +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3] again + +# Get the index of the first item found +li.index(2) # => 3 +li.index(4) # Raises a ValueError as 4 is not in the list # You can add lists # Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Check for existence in a list with "in" -1 in li # => True +1 in li # => True # Examine the length with "len()" -len(li) # => 6 +len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) -tup[0] # => 1 +tup[0] # => 1 tup[0] = 3 # Raises a TypeError -# You can do all those list thingies on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => <class 'int'> +type((1,)) # => <class 'tuple'> +type(()) # => <class 'tuple'> + +# You can do most of the list operations on tuples too +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True # You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# You can also do extended unpacking +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings @@ -230,71 +274,96 @@ empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} +# Note keys for dictionaries have to be immutable types. This is to ensure that +# the key can be converted to a constant hash value for quick look-ups. +# Immutable types include ints, floats, strings, tuples. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. + # Look up values with [] -filled_dict["one"] # => 1 +filled_dict["one"] # => 1 -# Get all keys as a list with "keys()". -# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - Dictionary key +# ordering is not guaranteed. Your results might not match this exactly. +list(filled_dict.keys()) # => ["three", "two", "one"] -# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. -# Note - Same as above regarding key ordering. -list(filled_dict.values()) # => [3, 2, 1] +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. +list(filled_dict.values()) # => [3, 2, 1] # Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +"one" in filled_dict # => True +1 in filled_dict # => False # Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +filled_dict.get("four", 4) # => 4 # "setdefault()" inserts into a dictionary only if the given key isn't present filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Adding to a dictionary -filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 #another way to add to dict # Remove keys from a dictionary with del del filled_dict["one"] # Removes the key "one" from filled dict +# From Python 3.5 you can also use the additional unpacking options +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + # Sets store ... well sets empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} -#Can set new variables to a set +# Similar to keys of a dictionary, elements of a set have to be immutable. +invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Can set new variables to a set filled_set = some_set -# Add one more item to the set -filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} +# Add one more item to the set +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +filled_set & other_set # => {3, 4, 5} # Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True # Check for existence in a set with in 2 in filled_set # => True -10 in filled_set # => False +10 in filled_set # => False + #################################################### @@ -326,7 +395,7 @@ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal)) """ -"range(number)" returns a list of numbers +"range(number)" returns an iterable of numbers from zero to the given number prints: 0 @@ -338,6 +407,30 @@ for i in range(4): print(i) """ +"range(lower, upper)" returns an iterable of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" returns an iterable of numbers +from the lower number to the upper number, while incrementing +by step. If step is not indicated, the default value is 1. +prints: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + While loops go until a condition is no longer met. prints: 0 @@ -355,11 +448,18 @@ try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Pass is just a no-op. Usually you would do recovery here. except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks + pass # Multiple exceptions can be handled together, if required. +else: # Optional clause to the try/except block. Must follow all except blocks print("All good!") # Runs only if the code in try raises no exceptions +finally: # Execute under all circumstances + print("We can clean up resources here") + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print(line) # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. @@ -367,11 +467,11 @@ else: # Optional clause to the try/except block. Must follow all except blocks filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. # We can loop over it. for i in our_iterable: - print(i) # Prints one, two, three + print(i) # Prints one, two, three # However we cannot address elements by index. our_iterable[1] # Raises a TypeError @@ -380,19 +480,18 @@ our_iterable[1] # Raises a TypeError our_iterator = iter(our_iterable) # Our iterator is an object that can remember the state as we traverse through it. -# We get the next object by calling the __next__ function. -our_iterator.__next__() #=> "one" +# We get the next object with "next()". +next(our_iterator) # => "one" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# It maintains state as we iterate. +next(our_iterator) # => "two" +next(our_iterator) # => "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - +list(filled_dict.keys()) # => Returns ["one", "two", "three"] #################################################### @@ -402,22 +501,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] # Use "def" to create new functions def add(x, y): print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement + return x + y # Return values with a return statement # Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. - +add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of # positional arguments def varargs(*args): return args -varargs(1, 2, 3) # => (1, 2, 3) - +varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of # keyword arguments, as well @@ -425,7 +522,7 @@ def keyword_args(**kwargs): return kwargs # Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like @@ -442,27 +539,36 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -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) +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) + +# Returning multiple values (with tuple assignments) +def swap(x, y): + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. -# Function Scope +# Function Scope x = 5 -def setX(num): +def set_x(num): # Local var x not the same as global variable x - x = num # => 43 - print (x) # => 43 - -def setGlobalX(num): + x = num # => 43 + print (x) # => 43 + +def set_global_x(num): global x - print (x) # => 5 - x = num # global var x is now set to 6 - print (x) # => 6 + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 -setX(43) -setGlobalX(6) +set_x(43) +set_global_x(6) # Python has first class functions @@ -475,25 +581,28 @@ add_10 = create_adder(10) add_10(3) # => 13 # There are also anonymous functions -(lambda x: x > 2)(3) # => True +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # TODO - Fix for iterables # There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters # List comprehension stores the output as a list which can itself be a nested list -[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] #################################################### ## 5. Classes #################################################### -# We subclass from object to get a class. -class Human(object): +# We use the "class" operator to get a class +class Human: # A class attribute. It is shared by all instances of this class species = "H. sapiens" @@ -501,11 +610,16 @@ class Human(object): # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled - # namespaces. You should not invent such names on your own. + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name + # Initialize property + self.age = 0 + # An instance method. All methods take "self" as the first argument def say(self, msg): return "{name}: {message}".format(name=self.name, message=msg) @@ -521,6 +635,23 @@ class Human(object): def grunt(): return "*grunt*" + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + # Instantiate a class i = Human(name="Ian") @@ -530,15 +661,26 @@ j = Human("Joel") print(j.say("hello")) # prints out "Joel: hello" # Call our class method -i.get_species() # => "H. sapiens" +i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # Call the static method -Human.grunt() # => "*grunt*" +Human.grunt() # => "*grunt*" + +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + #################################################### @@ -547,12 +689,12 @@ Human.grunt() # => "*grunt*" # You can import modules import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # You can get specific functions from a module from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended @@ -560,7 +702,7 @@ from math import * # You can shorten module names import math as m -math.sqrt(16) == m.sqrt(16) # => True +math.sqrt(16) == m.sqrt(16) # => True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the @@ -585,9 +727,7 @@ def double_numbers(iterable): # Instead of generating and returning all values at once it creates one in each # iteration. This means values bigger than 15 wont be processed in # double_numbers. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made -# We use a trailing underscore in variable names when we want to use a name that +# We use a trailing underscore in variable names when we want to use a name that # would normally collide with a python keyword range_ = range(1, 900000000) # will double all numbers until a result >=30 found @@ -621,7 +761,7 @@ def say(say_please=False): return msg, say_please -print(say()) # Can you buy me a beer? +print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` @@ -629,18 +769,21 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) - * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) - diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown new file mode 100644 index 00000000..78b62e33 --- /dev/null +++ b/pythonstatcomp.html.markdown @@ -0,0 +1,234 @@ +--- +language: Statistical computing with Python +contributors: + - ["e99n09", "https://github.com/e99n09"] +filename: pythonstatcomp.py +--- + +This is a tutorial on how to do some typical statistical programming tasks using Python. It's intended for people basically familiar with Python and experienced at statistical programming in a language like R, Stata, SAS, SPSS, or MATLAB. + +```python + +# 0. Getting set up ==== + +""" Get set up with IPython and pip install the following: numpy, scipy, pandas, + matplotlib, seaborn, requests. + Make sure to do this tutorial in the IPython notebook so that you get + the inline plots and easy documentation lookup. +""" + +# 1. Data acquisition ==== + +""" One reason people choose Python over R is that they intend to interact a lot + with the web, either by scraping pages directly or requesting data through + an API. You can do those things in R, but in the context of a project + already using Python, there's a benefit to sticking with one language. +""" + +import requests # for HTTP requests (web scraping, APIs) +import os + +# web scraping +r = requests.get("https://github.com/adambard/learnxinyminutes-docs") +r.status_code # if 200, request was successful +r.text # raw page source +print(r.text) # prettily formatted +# save the page source in a file: +os.getcwd() # check what's the working directory +f = open("learnxinyminutes.html","wb") +f.write(r.text.encode("UTF-8")) +f.close() + +# downloading a csv +fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" +fn = "pets.csv" +r = requests.get(fp + fn) +print(r.text) +f = open(fn,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +""" for more on the requests module, including APIs, see + http://docs.python-requests.org/en/latest/user/quickstart/ +""" + +# 2. Reading a CSV file ==== + +""" Wes McKinney's pandas package gives you 'DataFrame' objects in Python. If + you've used R, you will be familiar with the idea of the "data.frame" already. +""" + +import pandas as pd, numpy as np, scipy as sp +pets = pd.read_csv(fn) +pets +# name age weight species +# 0 fluffy 3 14 cat +# 1 vesuvius 6 23 fish +# 2 rex 5 34 dog + +""" R users: note that Python, like most normal programming languages, starts + indexing from 0. R is the unusual one for starting from 1. +""" + +# two different ways to print out a column +pets.age +pets["age"] + +pets.head(2) # prints first 2 rows +pets.tail(1) # prints last row + +pets.name[1] # 'vesuvius' +pets.species[0] # 'cat' +pets["weight"][2] # 34 + +# in R, you would expect to get 3 rows doing this, but here you get 2: +pets.age[0:2] +# 0 3 +# 1 6 + +sum(pets.age)*2 # 28 +max(pets.weight) - min(pets.weight) # 20 + +""" If you are doing some serious linear algebra and number-crunching, you may + just want arrays, not DataFrames. DataFrames are ideal for combining columns + of different types. +""" + +# 3. Charts ==== + +import matplotlib as mpl, matplotlib.pyplot as plt +%matplotlib inline + +# To do data vizualization in Python, use matplotlib + +plt.hist(pets.age); + +plt.boxplot(pets.weight); + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# seaborn sits atop matplotlib and makes plots prettier + +import seaborn as sns + +plt.scatter(pets.age, pets.weight); plt.xlabel("age"); plt.ylabel("weight"); + +# there are also some seaborn-specific plotting functions +# notice how seaborn automatically labels the x-axis on this barplot +sns.barplot(pets["age"]) + +# R veterans can still use ggplot +from ggplot import * +ggplot(aes(x="age",y="weight"), data=pets) + geom_point() + labs(title="pets") +# source: https://pypi.python.org/pypi/ggplot + +# there's even a d3.js port: https://github.com/mikedewar/d3py + +# 4. Simple data cleaning and exploratory analysis ==== + +""" Here's a more complicated example that demonstrates a basic data + cleaning workflow leading to the creation of some exploratory plots + and the running of a linear regression. + The data set was transcribed from Wikipedia by hand. It contains + all the Holy Roman Emperors and the important milestones in their lives + (birth, death, coronation, etc.). + The goal of the analysis will be to explore whether a relationship + exists between emperor birth year and emperor lifespan. + data source: https://en.wikipedia.org/wiki/Holy_Roman_Emperor +""" + +# load some data on Holy Roman Emperors +url = "https://raw.githubusercontent.com/e99n09/R-notes/master/data/hre.csv" +r = requests.get(url) +fp = "hre.csv" +f = open(fp,"wb") +f.write(r.text.encode("UTF-8")) +f.close() + +hre = pd.read_csv(fp) + +hre.head() +""" + Ix Dynasty Name Birth Death Election 1 +0 NaN Carolingian Charles I 2 April 742 28 January 814 NaN +1 NaN Carolingian Louis I 778 20 June 840 NaN +2 NaN Carolingian Lothair I 795 29 September 855 NaN +3 NaN Carolingian Louis II 825 12 August 875 NaN +4 NaN Carolingian Charles II 13 June 823 6 October 877 NaN + + Election 2 Coronation 1 Coronation 2 Ceased to be Emperor +0 NaN 25 December 800 NaN 28 January 814 +1 NaN 11 September 813 5 October 816 20 June 840 +2 NaN 5 April 823 NaN 29 September 855 +3 NaN Easter 850 18 May 872 12 August 875 +4 NaN 29 December 875 NaN 6 October 877 + + Descent from whom 1 Descent how 1 Descent from whom 2 Descent how 2 +0 NaN NaN NaN NaN +1 Charles I son NaN NaN +2 Louis I son NaN NaN +3 Lothair I son NaN NaN +4 Louis I son NaN NaN +""" + +# clean the Birth and Death columns + +import re # module for regular expressions + +rx = re.compile(r'\d+$') # match trailing digits + +""" This function applies the regular expression to an input column (here Birth, + Death), flattens the resulting list, converts it to a Series object, and + finally converts the type of the Series object from string to integer. For + more information into what different parts of the code do, see: + - https://docs.python.org/2/howto/regex.html + - http://stackoverflow.com/questions/11860476/how-to-unlist-a-python-list + - http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.html +""" +def extractYear(v): + return(pd.Series(reduce(lambda x,y: x+y,map(rx.findall,v),[])).astype(int)) + +hre["BirthY"] = extractYear(hre.Birth) +hre["DeathY"] = extractYear(hre.Death) + +# make a column telling estimated age +hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) + +# simple scatterplot, no trend line, color represents dynasty +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); + +# use scipy to run a linear regression +from scipy import stats +(slope,intercept,rval,pval,stderr)=stats.linregress(hre.BirthY,hre.EstAge) +# code source: http://wiki.scipy.org/Cookbook/LinearRegression + +# check the slope +slope # 0.0057672618839073328 + +# check the R^2 value: +rval**2 # 0.020363950027333586 + +# check the p-value +pval # 0.34971812581498452 + +# use seaborn to make a scatterplot and plot the linear regression trend line +sns.lmplot("BirthY", "EstAge", data=hre); + +""" For more information on seaborn, see + - http://web.stanford.edu/~mwaskom/software/seaborn/ + - https://github.com/mwaskom/seaborn + For more information on SciPy, see + - http://wiki.scipy.org/SciPy + - http://wiki.scipy.org/Cookbook/ + To see a version of the Holy Roman Emperors analysis using R, see + - http://github.com/e99n09/R-notes/blob/master/holy_roman_emperors_dates.R +""" +``` + +If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. + +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's <a href="http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/" Title="Probabilistic Programming and Bayesian Methods for Hackers">Probabilistic Programming and Bayesian Methods for Hackers</a>. + +Some more modules to research: + - text analysis and natural language processing: nltk, http://www.nltk.org + - social network analysis: igraph, http://igraph.org/python/ diff --git a/r.html.markdown b/r.html.markdown index c555d748..8539b10e 100644 --- a/r.html.markdown +++ b/r.html.markdown @@ -3,6 +3,7 @@ language: R contributors: - ["e99n09", "http://github.com/e99n09"] - ["isomorphismes", "http://twitter.com/isomorphisms"] + - ["kalinn", "http://github.com/kalinn"] filename: learnr.r --- @@ -15,7 +16,8 @@ R is a statistical computing language. It has lots of libraries for uploading an # You can't make multi-line comments, # but you can stack multiple comments like so. -# in Windows or Mac, hit COMMAND-ENTER to execute a line +# in Windows you can use CTRL-ENTER to execute a line. +# on Mac it is COMMAND-ENTER @@ -36,8 +38,8 @@ head(rivers) # peek at the data set length(rivers) # how many rivers were measured? # 141 summary(rivers) # what are some summary statistics? -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 135.0 310.0 425.0 591.2 680.0 3710.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 135.0 310.0 425.0 591.2 680.0 3710.0 # make a stem-and-leaf plot (a histogram-like data visualization) stem(rivers) @@ -54,14 +56,14 @@ stem(rivers) # 14 | 56 # 16 | 7 # 18 | 9 -# 20 | +# 20 | # 22 | 25 # 24 | 3 -# 26 | -# 28 | -# 30 | -# 32 | -# 34 | +# 26 | +# 28 | +# 30 | +# 32 | +# 34 | # 36 | 1 stem(log(rivers)) # Notice that the data are neither normal nor log-normal! @@ -70,7 +72,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # The decimal point is 1 digit(s) to the left of the | # # 48 | 1 -# 50 | +# 50 | # 52 | 15578 # 54 | 44571222466689 # 56 | 023334677000124455789 @@ -85,7 +87,7 @@ stem(log(rivers)) # Notice that the data are neither normal nor log-normal! # 74 | 84 # 76 | 56 # 78 | 4 -# 80 | +# 80 | # 82 | 2 # make a histogram: @@ -108,7 +110,7 @@ sort(discoveries) # [76] 4 4 4 4 5 5 5 5 5 5 5 6 6 6 6 6 6 7 7 7 7 8 9 10 12 stem(discoveries, scale=2) -# +# # The decimal point is at the | # # 0 | 000000000 @@ -122,14 +124,14 @@ stem(discoveries, scale=2) # 8 | 0 # 9 | 0 # 10 | 0 -# 11 | +# 11 | # 12 | 0 max(discoveries) # 12 summary(discoveries) -# Min. 1st Qu. Median Mean 3rd Qu. Max. -# 0.0 2.0 3.0 3.1 4.0 12.0 +# Min. 1st Qu. Median Mean 3rd Qu. Max. +# 0.0 2.0 3.0 3.1 4.0 12.0 # Roll a die a few times round(runif(7, min=.5, max=6.5)) @@ -196,6 +198,14 @@ class(NaN) # "numeric" # You can do arithmetic on two vectors with length greater than 1, # so long as the larger vector's length is an integer multiple of the smaller c(1,2,3) + c(1,2,3) # 2 4 6 +# Since a single number is a vector of length one, scalars are applied +# elementwise to vectors +(4 * c(1,2,3) - 2) / 2 # 1 3 5 +# Except for scalars, use caution when performing arithmetic on vectors with +# different lengths. Although it can be done, +c(1,2,3,1,2,3) * c(1,2) # 1 4 3 2 2 6 +# Matching lengths is better practice and easier to read +c(1,2,3,1,2,3) * c(1,2,1,2,1,2) # CHARACTERS # There's no difference between strings and characters in R @@ -229,6 +239,16 @@ FALSE != FALSE # FALSE FALSE != TRUE # TRUE # Missing data (NA) is logical, too class(NA) # "logical" +# Use | and & for logic operations. +# OR +TRUE | FALSE # TRUE +# AND +TRUE & FALSE # FALSE +# Applying | and & to vectors returns elementwise logic operations +c(TRUE,FALSE,FALSE) | c(FALSE,TRUE,FALSE) # TRUE TRUE FALSE +c(TRUE,FALSE,TRUE) & c(FALSE,TRUE,TRUE) # FALSE FALSE TRUE +# You can test if x is TRUE +isTRUE(TRUE) # TRUE # Here we get a logical vector with many elements: c('Z', 'o', 'r', 'r', 'o') == "Zorro" # FALSE FALSE FALSE FALSE FALSE c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE @@ -252,9 +272,10 @@ levels(infert$education) # "0-5yrs" "6-11yrs" "12+ yrs" # NULL # "NULL" is a weird one; use it to "blank out" a vector class(NULL) # NULL +parakeet = c("beak", "feathers", "wings", "eyes") parakeet # => -# [1] "beak" "feathers" "wings" "eyes" +# [1] "beak" "feathers" "wings" "eyes" parakeet <- NULL parakeet # => @@ -271,7 +292,7 @@ as.numeric("Bilbo") # => # [1] NA # Warning message: -# NAs introduced by coercion +# NAs introduced by coercion # Also note: those were just the basic data types # There are many more data types, such as for dates, time series, etc. @@ -411,10 +432,10 @@ mat %*% t(mat) mat2 <- cbind(1:4, c("dog", "cat", "bird", "dog")) mat2 # => -# [,1] [,2] -# [1,] "1" "dog" -# [2,] "2" "cat" -# [3,] "3" "bird" +# [,1] [,2] +# [1,] "1" "dog" +# [2,] "2" "cat" +# [3,] "3" "bird" # [4,] "4" "dog" class(mat2) # matrix # Again, note what happened! @@ -656,15 +677,101 @@ write.csv(pets, "pets2.csv") # to make a new .csv file ######################### +# Statistical Analysis +######################### + +# Linear regression! +linearModel <- lm(price ~ time, data = list1) +linearModel # outputs result of regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Coefficients: +# (Intercept) time +# 0.1453 0.4943 +summary(linearModel) # more verbose output from the regression +# => +# Call: +# lm(formula = price ~ time, data = list1) +# +# Residuals: +# Min 1Q Median 3Q Max +# -8.3134 -3.0131 -0.3606 2.8016 10.3992 +# +# Coefficients: +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.14527 1.50084 0.097 0.923 +# time 0.49435 0.06379 7.749 2.44e-09 *** +# --- +# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 +# +# Residual standard error: 4.657 on 38 degrees of freedom +# Multiple R-squared: 0.6124, Adjusted R-squared: 0.6022 +# F-statistic: 60.05 on 1 and 38 DF, p-value: 2.44e-09 +coef(linearModel) # extract estimated parameters +# => +# (Intercept) time +# 0.1452662 0.4943490 +summary(linearModel)$coefficients # another way to extract results +# => +# Estimate Std. Error t value Pr(>|t|) +# (Intercept) 0.1452662 1.50084246 0.09678975 9.234021e-01 +# time 0.4943490 0.06379348 7.74920901 2.440008e-09 +summary(linearModel)$coefficients[,4] # the p-values +# => +# (Intercept) time +# 9.234021e-01 2.440008e-09 + +# GENERAL LINEAR MODELS +# Logistic regression +set.seed(1) +list1$success = rbinom(length(list1$time), 1, .5) # random binary +glModel <- glm(success ~ time, data = list1, + family=binomial(link="logit")) +glModel # outputs result of logistic regression +# => +# Call: glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) +# +# Coefficients: +# (Intercept) time +# 0.17018 -0.01321 +# +# Degrees of Freedom: 39 Total (i.e. Null); 38 Residual +# Null Deviance: 55.35 +# Residual Deviance: 55.12 AIC: 59.12 +summary(glModel) # more verbose output from the regression +# => +# Call: +# glm(formula = success ~ time, +# family = binomial(link = "logit"), data = list1) + +# Deviance Residuals: +# Min 1Q Median 3Q Max +# -1.245 -1.118 -1.035 1.202 1.327 +# +# Coefficients: +# Estimate Std. Error z value Pr(>|z|) +# (Intercept) 0.17018 0.64621 0.263 0.792 +# time -0.01321 0.02757 -0.479 0.632 +# +# (Dispersion parameter for binomial family taken to be 1) +# +# Null deviance: 55.352 on 39 degrees of freedom +# Residual deviance: 55.121 on 38 degrees of freedom +# AIC: 59.121 +# +# Number of Fisher Scoring iterations: 3 + + +######################### # Plots ######################### # BUILT-IN PLOTTING FUNCTIONS # Scatterplots! plot(list1$time, list1$price, main = "fake data") -# Regressions! -linearModel <- lm(price ~ time, data = list1) -linearModel # outputs result of regression # Plot regression line on existing plot abline(linearModel, col = "red") # Get a variety of nice diagnostics diff --git a/racket.html.markdown b/racket.html.markdown index 6abc8759..0fe3f030 100644 --- a/racket.html.markdown +++ b/racket.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Eli Barzilay", "https://github.com/elibarzilay"] - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] - ["Duong H. Nguyen", "https://github.com/cmpitg"] + - ["Keyan Zhang", "https://github.com/keyanzhang"] --- Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. @@ -282,16 +283,49 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no `d' ;; for numbers use `=' (= 3 3.0) ; => #t -(= 2 1) ; => #f +(= 2 1) ; => #f + +;; `eq?' returns #t if 2 arguments refer to the same object (in memory), +;; #f otherwise. +;; In other words, it's a simple pointer comparison. +(eq? '() '()) ; => #t, since there exists only one empty list in memory +(let ([x '()] [y '()]) + (eq? x y)) ; => #t, same as above -;; for object identity use `eq?' -(eq? 3 3) ; => #t -(eq? 3 3.0) ; => #f (eq? (list 3) (list 3)) ; => #f +(let ([x (list 3)] [y (list 3)]) + (eq? x y)) ; => #f — not the same list in memory! + +(let* ([x (list 3)] [y x]) + (eq? x y)) ; => #t, since x and y now point to the same stuff + +(eq? 'yes 'yes) ; => #t +(eq? 'yes 'no) ; => #f + +(eq? 3 3) ; => #t — be careful here + ; It’s better to use `=' for number comparisons. +(eq? 3 3.0) ; => #f + +(eq? (expt 2 100) (expt 2 100)) ; => #f +(eq? (integer->char 955) (integer->char 955)) ; => #f + +(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; `eqv?' supports the comparison of number and character datatypes. +;; for other datatypes, `eqv?' and `eq?' return the same result. +(eqv? 3 3.0) ; => #f +(eqv? (expt 2 100) (expt 2 100)) ; => #t +(eqv? (integer->char 955) (integer->char 955)) ; => #t + +(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f -;; for collections use `equal?' -(equal? (list 'a 'b) (list 'a 'b)) ; => #t -(equal? (list 'a 'b) (list 'b 'a)) ; => #f +;; `equal?' supports the comparison of the following datatypes: +;; strings, byte strings, pairs, mutable pairs, vectors, boxes, +;; hash tables, and inspectable structures. +;; for other datatypes, `equal?' and `eqv?' return the same result. +(equal? 3 3.0) ; => #f +(equal? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #t +(equal? (list 3) (list 3)) ; => #t ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 5. Control Flow diff --git a/red.html.markdown b/red.html.markdown index 73a13606..05da3c3f 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -8,31 +8,31 @@ contributors: --- -Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks. +Red was created out of the need to get work done, and the tool the author wanted to use, the language of REBOL, had a couple of drawbacks. It was not Open Sourced at that time and it is an interpreted language, what means that it is on average slow compared to a compiled language. Red, together with its C-level dialect Red/System, provides a language that covers the entire programming space you ever need to program something in. -Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, -Red/System, covers the more basic needs of programming like C can, being closer to the metal. +Red is a language heavily based on the language of REBOL. Where Red itself reproduces the flexibility of the REBOL language, the underlying language Red will be built upon, +Red/System, covers the more basic needs of programming like C can, being closer to the metal. -Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level -from the metal to the meta without the aid of other stack tools. -Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain +Red will be the world's first Full Stack Programming Language. This means that it will be an effective tool to do (almost) any programming task on every level +from the metal to the meta without the aid of other stack tools. +Furthermore Red will be able to cross-compile Red source code without using any GCC like toolchain from any platform to any other platform. And it will do this all from a binary executable that is supposed to stay under 1 MB. Ready to learn your first Red? ``` -All text before the header will be treated as comment, as long as you avoid using the -word "red" starting with a capital "R" in this pre-header text. This is a temporary -shortcoming of the used lexer but most of the time you start your script or program -with the header itself. -The header of a red script is the capitalized word "red" followed by a +All text before the header will be treated as comment, as long as you avoid using the +word "red" starting with a capital "R" in this pre-header text. This is a temporary +shortcoming of the used lexer but most of the time you start your script or program +with the header itself. +The header of a red script is the capitalized word "red" followed by a whitespace character followed by a block of square brackets []. -The block of brackets can be filled with useful information about this script or +The block of brackets can be filled with useful information about this script or program: the author's name, the filename, the version, the license, a summary of what the program does or any other files it needs. -The red/System header is just like the red header, only saying "red/System" and +The red/System header is just like the red header, only saying "red/System" and not "red". Red [] @@ -49,21 +49,21 @@ comment { ; Your program's entry point is the first executable code that is found ; no need to restrict this to a 'main' function. -; Valid variable names start with a letter and can contain numbers, -; variables containing only capital A thru F and numbers and ending with 'h' are -; forbidden, because that is how hexadecimal numbers are expressed in Red and +; Valid variable names start with a letter and can contain numbers, +; variables containing only capital A thru F and numbers and ending with 'h' are +; forbidden, because that is how hexadecimal numbers are expressed in Red and ; Red/System. ; assign a value to a variable using a colon ":" my-name: "Red" -reason-for-using-the-colon: {Assigning values using the colon makes - the equality sign "=" exclusively usable for comparisons purposes, - exactly what "=" was intended for in the first place! +reason-for-using-the-colon: {Assigning values using the colon makes + the equality sign "=" exclusively usable for comparisons purposes, + exactly what "=" was intended for in the first place! Remember this y = x + 1 and x = 1 => y = 2 stuff from school? } is-this-name-valid?: true -; print output using print, or prin for printing without a newline or linefeed at the +; print output using print, or prin for printing without a newline or linefeed at the ; end of the printed text. prin " My name is " print my-name @@ -77,20 +77,20 @@ My name is Red ; ; Datatypes ; -; If you know Rebol, you probably have noticed it has lots of datatypes. Red -; does not have yet all those types, but as Red want to be close to Rebol it +; If you know Rebol, you probably have noticed it has lots of datatypes. Red +; does not have yet all those types, but as Red want to be close to Rebol it ; will have a lot of datatypes. -; You can recognize types by the exclamation sign at the end. But beware -; names ending with an exclamation sign are allowed. -; Some of the available types are integer! string! block! - -; Declaring variables before using them? -; Red knows by itself what variable is best to use for the data you want to use it -; for. -; A variable declaration is not always necessary. +; You can recognize types by the exclamation sign at the end. But beware +; names ending with an exclamation sign are allowed. +; Some of the available types are integer! string! block! + +; Declaring variables before using them? +; Red knows by itself what variable is best to use for the data you want to use it +; for. +; A variable declaration is not always necessary. ; It is considered good coding practise to declare your variables, ; but it is not forced upon you by Red. -; You can declare a variable and specify its type. a variable's type determines its +; You can declare a variable and specify its type. a variable's type determines its ; size in bytes. ; Variables of integer! type are usually 4 bytes or 32 bits @@ -101,7 +101,7 @@ my-integer: 0 type? my-integer integer! -; A variable can be initialized using another variable that gets initialized +; A variable can be initialized using another variable that gets initialized ; at the same time. i2: 1 + i1: 1 @@ -111,9 +111,9 @@ i2 - i1 ; result 1 i2 * i1 ; result 2 i1 / i2 ; result 0 (0.5, but truncated towards 0) -; Comparison operators are probably familiar, and unlike in other languages you +; Comparison operators are probably familiar, and unlike in other languages you ; only need a single '=' sign for comparison. -; There is a boolean like type in Red. It has values true and false, but also the +; There is a boolean like type in Red. It has values true and false, but also the ; values on/off or yes/no can be used 3 = 2 ; result false @@ -125,15 +125,15 @@ i1 / i2 ; result 0 (0.5, but truncated towards 0) ; ; Control Structures -; +; ; if -; Evaluate a block of code if a given condition is true. IF does not return any value, +; Evaluate a block of code if a given condition is true. IF does not return any value, ; so cannot be used in an expression. if a < 0 [print "a is negative"] ; either -; Evaluate a block of code if a given condition is true, else evaluate an alternative -; block of code. If the last expressions in both blocks have the same type, EITHER can +; Evaluate a block of code if a given condition is true, else evaluate an alternative +; block of code. If the last expressions in both blocks have the same type, EITHER can ; be used inside an expression. either a < 0 [ either a = 0 [ @@ -147,7 +147,7 @@ either a < 0 [ print ["a is " msg lf] -; There is an alternative way to write this +; There is an alternative way to write this ; (Which is allowed because all code paths return a value of the same type): msg: either a < 0 [ @@ -162,7 +162,7 @@ msg: either a < 0 [ print ["a is " msg lf] ; until -; Loop over a block of code until the condition at end of block, is met. +; Loop over a block of code until the condition at end of block, is met. ; UNTIL does not return any value, so it cannot be used in an expression. c: 5 until [ @@ -172,11 +172,11 @@ until [ ] ; will output: ooooo -; Note that the loop will always be evaluated at least once, even if the condition is +; Note that the loop will always be evaluated at least once, even if the condition is ; not met from the beginning. ; while -; While a given condition is met, evaluate a block of code. +; While a given condition is met, evaluate a block of code. ; WHILE does not return any value, so it cannot be used in an expression. c: 5 while [c > 0][ @@ -206,14 +206,16 @@ print twice b ; will output 6. ## Further Reading -The main source for information about Red is the [Red language homepage](http://www.red-lang.org). +The main source for information about Red is the [Red language homepage](http://www.red-lang.org). The source can be found on [github](https://github.com/red/red). The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). -To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). You will need 20 points to chat but if you ask or answer questions about Red or Rebol we will help you get those points. And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). +To learn more about Rebol and Red join the [chat on Gitter](https://gitter.im/red/red). And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). + +Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/red). Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html). +You can also learn Red by learning some [Rebol](http://www.rebol.com/docs.html). diff --git a/ro-ro/clojure-ro.html.markdown b/ro-ro/clojure-ro.html.markdown new file mode 100644 index 00000000..32ba9620 --- /dev/null +++ b/ro-ro/clojure-ro.html.markdown @@ -0,0 +1,386 @@ +--- +language: clojure +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Bogdan Paun", "http://twitter.com/bgdnpn"] +filename: learnclojure-ro.clj +lang: ro-ro +--- + +Clojure este un limbaj din familia Lisp dezvoltat pentru Masina Virtuala Java +(Java Virtual Machine - JVM). Pune un accent mult mai puternic pe +[programarea funcionala](https://en.wikipedia.org/wiki/Functional_programming) +pura decat Common Lisp, dar include utilitare [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) +pentru a gestiona starea, atunci cand aceasta apare. + +Combinatia aceasta ii permite sa gestioneze procese concurente foarte usor, +de multe ori in mod automat. + +(Aveti nevoie deo versiune Clojure 1.2 sau mai noua) + + +```clojure +; Comentariile incep cu punct si virgula. + +; Clojure se scrie in "forme", care nu sunt decat +; liste de lucruri in interiorul unor paranteze, separate prin spatii. +; +; Reader-ul Clojure presupune ca primul lucru este o +; functie sau un macro de apelat, iar restul sunt argumente. + +; Prima apelare intr-un fisier ar trebui sa fie ns, pentru a configura namespace-ul +(ns learnclojure) + +; Mai multe exemple de baza: + +; str va crea un string folosint toate argumentele sale +(str "Hello" " " "World") ; => "Hello World" + +; Matematica este simpla +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; Egalitatea este = +(= 1 1) ; => true +(= 2 1) ; => false + +; Folosim si not pentru logica +(not true) ; => false + +; Formele imbricate functioneaza asa +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Tipuri +;;;;;;;;;;;;; + +; Clojure foloseste sistemul de obiecte Java pentru boolean, string si numere. +; Folositi `class` pentru a le inspecta. +(class 1) ; Numere intregi sunt jaba.lang.Long, in mod normal +(class 1.); Numelere reale sunt java.lang.Double +(class ""); Sirurile de caractere sunt mere intre apostrofuri duble, si sunt java.lang.String +(class false) ; Booleanele sunt java.lang.Boolean +(class nil); Valoarea "null" este numita nil + +; Daca doriti sa creati o lista de date literale, folositi ' pentru a preveni +; evaluarea ei +'(+ 1 2) ; => (+ 1 2) +; (prescurtare pentru (quote (+ 1 2))) + +; Puteti evalua o lista cu apostrof +(eval '(+ 1 2)) ; => 3 + +; Colectii & Secvente +;;;;;;;;;;;;;;;;;;; + +; Listele sunt structuri de date lista-inlantuita, spre deosebire de Vectori +; Vectorii si Listele sunt si ele clase Java! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; O liste ar putea fi scrisa direct ca (1 2 3), dar trebuie sa folosim apostrof +; pentru a preveni reader-ul din a crede ca e o functie. +; De asemenea, (list 1 2 3) este acelasi lucru cu '(1 2 3) + +; "Colectiile" sunt grupuri de date +; Atat listele cat si vectorii sunt colectii: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "Sequences" (seqs) are abstract descriptions of lists of data. +; Only lists are seqs. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; O secventa necesita un punct de intrare doar cand este accesata. +; Deci, secventele, care pot fi "lazy" -- pot defini serii infinite: +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (o serie infinita) +(take 4 (range)) ; (0 1 2 3) + +; Folositi cons pentru a adauga un element la inceputul unei liste sau unui vector +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Conj va adauga un element unei colectii in modul cel mai eficient. +; Pentru liste, aceastea sunt inserate la inceput. Pentru vectori, sunt inserate la final. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Folositi concat pentru a uni liste sau vectori +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Folositi filter, map pentru a interactiona cu colectiile +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Folositi reduce pentru a le reduce +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Reduce poate lua un argument valoare-initiala +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Functii +;;;;;;;;;;;;;;;;;;;;; + +; Folositi fn pentru a crea functii noi. O functie returneaza intotdeauna +; ultima sa instructiune. +(fn [] "Hello World") ; => fn + +; (Necesita paranteze suplimentare pentru a fi apelata) +((fn [] "Hello World")) ; => "Hello World" + +; Puteti crea o variabila folosind def +(def x 1) +x ; => 1 + +; Atribuiti o functie unei variabile +(def hello-world (fn [] "Hello World")) +(hello-world) ; => "Hello World" + +; Puteti scurta acest proces folosind defn +(defn hello-world [] "Hello World") + +; Elementul [] este lista de argumente a functiei. +(defn hello [name] + (str "Hello " name)) +(hello "Steve") ; => "Hello Steve" + +; Puteti, de asemenea, folosi aceasta prescurtare pentru a crea functii: +(def hello2 #(str "Hello " %1)) +(hello2 "Fanny") ; => "Hello Fanny" + +; Puteti avea si functii cu mai multe variabile +(defn hello3 + ([] "Hello World") + ([name] (str "Hello " name))) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" + +; Functiile pot primi mai mult argumente dintr-o secventa +(defn count-args [& args] + (str "Ati specificat " (count args) " argumente: " args)) +(count-args 1 2 3) ; => "Ati specificat 3 argumente: (1 2 3)" + +; Puteti interschimba argumente normale si argumente-secventa +(defn hello-count [name & args] + (str "Salut " name ", ati specificat " (count args) " argumente extra")) +(hello-count "Finn" 1 2 3) +; => "Salut Finn, ai specificat 3 argumente extra" + + +; Maps (Dictionare) +;;;;;;;;;; + +; Hash maps si Array maps impart o interfata. Hash maps au cautari mai rapide +; dar nu retin ordinea cheilor. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Arraymaps de vin automat hashmaps prin majoritatea operatiilor +; daca sunt suficient de mari, asa ca nu trebuie sa va preocupe acest aspect. + +; Dictionarele pot folosi orice tip hashable ca si cheie, dar cuvintele cheie +; (keywords) sunt, de obicei, cele mai indicate. Cuvintele cheie sunt ca niste +; siruri de caractere cu un plus de eficienta +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Apropo, virgulele sunt intotdeauna considerate echivalente cu spatiile. + +; Apelati un dictionar (map) ca pe o functie pentru a primi o valoare anume +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; Cuvintele cheie pot fi folosite si ele pentru a "cere" dictionarului valorile lor! +(:b keymap) ; => 2 + +; Nu incercati asta cu siruri de caractere. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Recuperarea unei chei inexistente returneaza nil +(stringmap "d") ; => nil + +; Folositi assoc pentru a adauga nou chei unui ductionar +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Dar retineti ca tipurile sunt imuabile in clojure +keymap ; => {:a 1, :b 2, :c 3} + +; Folositi dissoc pentru a elimina chei +(dissoc keymap :a :b) ; => {:c 3} + +; Seturi (multimi) +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Adaugati un membru cu conj +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Eliminati unul cu disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Testati existenta unuia folosing setul ca o functie: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Exista mai multe functii in namespace-ul clojure.sets. + +; Forme utile +;;;;;;;;;;;;;;;;; + +; In Clojure constructiile logice sunt macro-uri, si arata ca +; oricare alta forma +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Folositi let pentru a crea atribuiri temporare +(let [a 1 b 2] + (> a b)) ; => false + +; Grupati instructiuni impreuna folosind do +(do + (print "Hello") + "World") ; => "World" (prints "Hello") + +; Functiile contin un do implicit +(defn print-and-say-hello [name] + (print "Saying hello to " name) + (str "Hello " name)) +(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff") + +; Asemanator pentru let +(let [name "Urkel"] + (print "Saying hello to " name) + (str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel") + +; Module +;;;;;;;;;;;;;;; + +; Folositi "use" pentru a recupera toate functiile dintr-un modul +(use 'clojure.set) + +; Acum putem folosi operatiuni pe seturi +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Puteri de asemenea alege un subset al functiilor de importat +(use '[clojure.set :only [intersection]]) + +; Folositi require pentru a importa un modul +(require 'clojure.string) + +; Folositi / pentru a apela functii dintr-un modul +; In acest caz, modulul este clojure.string, iar functia este blank? +(clojure.string/blank? "") ; => true + +; Puteti atribui un nume mai scurt unui modul in momentul importului +(require '[clojure.string :as str]) +(str/replace "Acesta este un test." #"[a-o]" str/upper-case) ; => "ACEstA EstE un tEst." +; (#"" denota o expresie regulata) + +; Puteti folsi require (sau use, contraindicat) dintr-un namespace folosind :require. +; Nu trebuie sa folositi apostrof pentru module daca procedati astfel. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java are o biblioteca standard imensa si folositoare, deci +; ar fi util sa stiti cum sa o folositi. + +; Folositi import pentru a incarca un modul Java +(import java.util.Date) + +; Puteti importa si dintr-un namesopace. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Folositi numele clasei cu "." la final pentru a crea o noua instanta +(Date.) ; <a date object> + +; Folositi . pentru a apela metode. Pe scurt, folositi ".method" +(. (Date.) getTime) ; <a timestamp> +(.getTime (Date.)) ; exact acelasi lucru. + +; Folositi / pentru a apela metode statice +(System/currentTimeMillis) ; <a timestamp> (System este prezent intotdeauna) + +; Folositi doto pentru a gestiona clase (mutable) mai usor +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory este un mecanism folost de Clojure pentru +; a gestiona stari persistente. Sunt putine instante in care este folosit. + +; Un atom este cel mai simplu exemplu. Dati-i o valoare initiala +(def my-atom (atom {})) + +; Modificati-l cu swap!. +; swap! primeste o functie si o apeleaza cu valoarea actuala a atomului +; ca prim argument si orice argumente suplimentare ca al doilea +(swap! my-atom assoc :a 1) ; Atomul ia valoarea rezultata din (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Atomul ia valoarea rezultata din (assoc {:a 1} :b 2) + +; Folositi '@' pentru a dereferentia atomul si a-i recupera valoarea +my-atom ;=> Atom<#...> (Returmeaza obiectul Atom) +@my-atom ; => {:a 1 :b 2} + +; Aici avem un contor simplu care foloseste un atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Alte utilizari ale STM sunt referintele (refs) si agentii (agents). +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Lectura suplimentara + +Lista nu este in niciun caz exhaustiva, dar speram ca este suficienta pentru +a va oferi un inceput bun in Clojure. + +Clojure.org contine multe articole: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org contine documentatie cu exemple pentru majoritatea functiilor de baza: +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure este o metoda excelenta pentru a exersa Clojure/FP (Programarea Functionala): +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org are un numar de article pentru incepatori: +[http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown new file mode 100644 index 00000000..21377b6c --- /dev/null +++ b/ru-ru/bash-ru.html.markdown @@ -0,0 +1,284 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] +translators: + - ["Andrey Samsonov", "https://github.com/kryzhovnik"] + - ["Andre Polykanine", "https://github.com/Oire"] +filename: LearnBash-ru.sh +lang: ru-ru +--- + +Bash - это командная оболочка unix (unix shell), которая распространялась как оболочка для операционной системы GNU и используется в качестве оболочки по умолчанию для Linux и Mac OS X. +Почти все нижеприведенные примеры могут быть частью shell-скриптов или исполнены напрямую в shell. + +[Подробнее.](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# Первая строка скрипта - это shebang, который сообщает системе, как исполнять +# этот скрипт: http://en.wikipedia.org/wiki/Shebang_(Unix) +# Как вы уже поняли, комментарии начинаются с #. Shebang - тоже комментарий. + +# Простой пример hello world: +echo Hello world! + +# Отдельные команды начинаются с новой строки или разделяются точкой с запятой: +echo 'Это первая строка'; echo 'Это вторая строка' + +# Вот так объявляется переменная: +VARIABLE="Просто строка" + +# но не так: +VARIABLE = "Просто строка" +# Bash решит, что VARIABLE - это команда, которую он должен исполнить, +# и выдаст ошибку, потому что не сможет найти ее. + +# и не так: +VARIABLE= 'Просто строка' +# Тут Bash решит, что 'Просто строка' - это команда, которую он должен исполнить, +# и выдаст ошибку, потому что не сможет найти такой команды +# (здесь 'VARIABLE=' выглядит как присвоение значения переменной, +# но только в контексте исполнения команды 'Просто строка'). + +# Использование переменой: +echo $VARIABLE +echo "$VARIABLE" +echo '$VARIABLE' +# Когда вы используете переменную - присваиваете, экспортируете и т.д. - +# пишите её имя без $. А для получения значения переменной используйте $. +# Заметьте, что ' (одинарные кавычки) не раскрывают переменные в них. + +# Подстановка строк в переменные +echo ${VARIABLE/Просто/A} +# Это выражение заменит первую встреченную подстроку "Просто" на "A" + +# Взять подстроку из переменной +LENGTH=7 +echo ${VARIABLE:0:LENGTH} +# Это выражение вернет только первые 7 символов переменной VARIABLE + +# Значение по умолчанию +echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"} +# Это сработает при отсутствующем значении (FOO=) и пустой строке (FOO=""); +# ноль (FOO=0) вернет 0. +# Заметьте, что в любом случае значение самой переменной FOO не изменится. + +# Встроенные переменные: +# В bash есть полезные встроенные переменные, например +echo "Последнее возвращенное значение: $?" +echo "PID скрипта: $$" +echo "Количество аргументов: $#" +echo "Аргументы скрипта: $@" +echo "Аргументы скрипта, распределённые по отдельным переменным: $1 $2..." + +# Чтение аргументов из устройста ввода: +echo "Как Вас зовут?" +read NAME # Обратите внимание, что нам не нужно определять новую переменную +echo Привет, $NAME! + +# У нас есть обычная структура if: +# наберите 'man test' для получения подробной информации о форматах условия +if [ $NAME -ne $USER ] +then + echo "Имя не совпадает с именем пользователя" +else + echo "Имя совпадает с именем пользователя" +fi + +# Также есть условное исполнение +echo "Исполнится всегда" || echo "Исполнится, если первая команда завершится ошибкой" +echo "Исполнится всегда" && echo "Исполнится, если первая команда выполнится удачно" + +# Можно использовать && и || в выражениях if, когда нужно несколько пар скобок: +if [ $NAME == "Steve" ] && [ $AGE -eq 15 ] +then + echo "Исполнится, если $NAME равно Steve И $AGE равно 15." +fi + +if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ] +then + echo "Исполнится, если $NAME равно Daniya ИЛИ Zach." +fi + +# Выражения обозначаются таким форматом: +echo $(( 10 + 5 )) + +# В отличие от других языков программирования, Bash - это командная оболочка, +# а значит, работает в контексте текущей директории. +# Вы можете просматривать файлы и директории в текущей директории командой ls: +ls + +# У этой команды есть опции: +ls -l # Показать каждый файл и директорию на отдельной строке + +# Результат предыдущей команды может быть направлен на вход следующей. +# Команда grep фильтрует ввод по шаблону. +# Так мы можем просмотреть только *.txt файлы в текущей директории: +ls -l | grep "\.txt" + +# Вы можете перенаправить ввод и вывод команды (stdin, stdout и stderr). +# Следующая команда означает: читать из stdin, пока не встретится ^EOF$, и +# перезаписать hello.py следующим строками (до строки "EOF"): +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# Запуск hello.py с разными вариантами перенаправления потоков +# стандартных ввода, вывода и ошибок: +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# Поток ошибок перезапишет файл, если этот файл существует, +# поэтому, если вы хотите дописывать файл, используйте ">>": +python hello.py >> "output.out" 2>> "error.err" + +# Переписать output.txt, дописать error.err и сосчитать строки: +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# Запустить команду и вывести ее файловый дескриптор (смотрите: man fd) +echo <(echo "#helloworld") + +# Перезаписать output.txt строкой "#helloworld": +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# Подчистить временные файлы с подробным выводом ('-i' - интерактивый режим) +rm -v output.out error.err output-and-error.log + +# Команды могут быть подставлены в строку с помощью $( ): +# следующие команды выводят число файлов и директорий в текущей директории. +echo "Здесь $(ls | wc -l) элементов." + +# То же самое можно сделать с использованием обратных кавычек, +# но они не могут быть вложенными, поэтому предпочтительно использовать $( ). +echo "Здесь `ls | wc -l` элементов." + +# В Bash есть структура case, которая похожа на switch в Java и C++: +case "$VARIABLE" in + # Перечислите шаблоны для условий, которые хотите отловить + 0) echo "Тут ноль.";; + 1) echo "Тут один.";; + *) echo "Это не пустое значение.";; +esac + +# Цикл for перебирает элементы переданные в аргументе: +# Содержимое $VARIABLE будет напечатано три раза. +for VARIABLE in {1..3} +do + echo "$VARIABLE" +done + +# Или с использованием "традиционного" синтаксиса цикла for: +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# Цикл for можно использовать для действий с файлами. +# Запустим команду 'cat' для файлов file1 и file2 +for VARIABLE in file1 file2 +do + cat "$VARIABLE" +done + +# ... или выводом из команд +# Запустим cat для вывода из ls. +for OUTPUT in $(ls) +do + cat "$OUTPUT" +done + +# Цикл while: +while [ true ] +do + echo "тело цикла здесь..." + break +done + +# Вы можете определять функции +# Определение: +function foo () +{ + echo "Аргументы работают также, как аргументы скрипта: $@" + echo "и: $1 $2..." + echo "Это функция" + return 0 +} + +# или просто +bar () +{ + echo "Другой способ определить функцию!" + return 0 +} + +# Вызов функции +foo "Мое имя" $NAME + +# Есть много полезных команд, которые нужно знать: +# напечатать последние 10 строк файла file.txt +tail -n 10 file.txt +# напечатать первые 10 строк файла file.txt +head -n 10 file.txt +# отсортировать строки file.txt +sort file.txt +# отобрать или наоборот пропустить повторяющиеся строки (с опцией -d отбирает) +uniq -d file.txt +# напечатать только первую колонку перед символом ',' +cut -d ',' -f 1 file.txt +# заменить каждое 'okay' на 'great' в файле file.txt (regex поддерживается) +sed -i 's/okay/great/g' file.txt +# вывести в stdout все строки из file.txt, совпадающие с шаблоном regex; +# этот пример выводит строки, которые начинаются на "foo" и оканчиваются "bar" +grep "^foo.*bar$" file.txt +# передайте опцию -c чтобы вывести число строк, в которых совпал шаблон +grep -c "^foo.*bar$" file.txt +# чтобы искать по строке, а не шаблону regex, используйте fgrep (или grep -F) +fgrep "^foo.*bar$" file.txt + +# Читайте встроенную документацию оболочки Bash командой 'help': +help +help help +help for +help return +help source +help . + +# Читайте Bash man-документацию +apropos bash +man 1 bash +man bash + +# Читайте документацию info (? для помощи) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# Читайте bash info документацию: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown new file mode 100644 index 00000000..fcee185f --- /dev/null +++ b/ru-ru/brainfuck-ru.html.markdown @@ -0,0 +1,85 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень +маленький Тьюринг-полный язык программирования лишь с 8 командами. + +Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). + +``` +Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. + +Brainfuck представлен массивом из 30000 ячеек, инициализированных нулями, +и указателем с позицией в текущей ячейке. + +Всего восемь команд: ++ : Увеличивает значение на единицу в текущей ячейке. +- : Уменьшает значение на единицу в текущей ячейке. +> : Смещает указатель данных на следующую ячейку (ячейку справа). +< : Смещает указатель данных на предыдущую ячейку (ячейку слева). +. : Печатает ASCII символ из текущей ячейки (напр. 65 = 'A'). +, : Записывает один входной символ в текущую ячейку. +[ : Если значение в текущей ячейке равно нулю, то пропустить все команды + до соответствующей ] . В противном случае, перейти к следующей инструкции. +] : Если значение в текущей ячейке равно нулю, то перейти к следующей инструкции. + В противном случае, вернуться назад к соответствующей [ . + +[ и ] образуют цикл while. Естественно, они должны быть сбалансированы. + +Давайте рассмотрим некоторые базовые brainfuck-программы. + +++++++ [ > ++++++++++ < - ] > +++++ . + +Эта программа выводит букву 'A'. Сначала программа увеличивает значение +ячейки №1 до 6. Ячейка №1 будет использоваться циклом. Затем программа входит +в цикл ([) и переходит к ячейке №2. Ячейка №2 увеличивается до 10, переходим +назад к ячейке №1 и уменьшаем ячейку №1. Этот цикл проходит 6 раз (ячейка №1 +уменьшается до нуля, и с этого места пропускает инструкции до соответствующей ] +и идет дальше). + +В этот момент мы находимся в ячейке №1, которая имеет значение 0, значение +ячейки №2 пока 60. Мы переходим на ячейку №2, увеличиваем 5 раз, до значения 65, +и затем выводим значение ячейки №2. Код 65 является символом 'A' в кодировке ASCII, +так что 'A' выводится на терминал. + + +, [ > + < - ] > . + +Данная программа считывает символ из пользовательского ввода и копирует символ +в ячейку №1. Затем мы начинаем цикл. Переходим к ячейке №2, увеличиваем значение +ячейки №2, идем назад к ячейке №1 и уменьшаем значение ячейки №1. Это продолжается +до тех пор, пока ячейка №1 не равна 0, а ячейка №2 сохраняет старое значение +ячейки №1. Мы завершаем цикл на ячейке №1, поэтому переходим в ячейку №2 и +затем выводим символ ASCII. + +Также имейте в виду, что пробелы здесь исключительно для читабельности. Вы можете +легко написать и так: + +,[>+<-]>. + +Попытайтесь разгадать, что следующая программа делает: + +,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >> + +Программа принимает два числа на вход и умножает их. + +Суть в том, что программа сначала читает два ввода. Затем начинается внешний цикл, +сохраняя ячейку №1. Затем программа перемещается в ячейку №2, и начинается +внутренний цикл с сохранением ячейки №2, увеличивая ячейку №3. Однако появляется +проблема: В конце внутреннего цикла ячейка №2 равна нулю. В этом случае, +внутренний цикл не будет работать уже в следующий раз. Чтобы решить эту проблему, +мы также увеличим ячейку №4, а затем копируем ячейку №4 в ячейку №2. +Итак, ячейка №3 - результат. +``` + +Это и есть brainfuck. Не так уж сложно, правда? Забавы ради, вы можете написать +свою собственную brainfuck-программу или интерпретатор на другом языке. +Интерпретатор достаточно легко реализовать, но если вы мазохист, попробуйте +написать brainfuck-интерпретатор... на языке brainfuck. diff --git a/ru-ru/clojure-ru.html.markdown b/ru-ru/clojure-ru.html.markdown index 2f508a00..451da312 100644 --- a/ru-ru/clojure-ru.html.markdown +++ b/ru-ru/clojure-ru.html.markdown @@ -144,7 +144,7 @@ Clojure, это представитель семейства Lisp-подобн ;;;;;;;;;;;;;;;;;;;;; ; Функция создается специальной формой fn. -; "Тело"" функции может состоять из нескольких форм, +; "Тело" функции может состоять из нескольких форм, ; но результатом вызова функции всегда будет результат вычисления ; последней из них. (fn [] "Hello World") ; => fn diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown new file mode 100644 index 00000000..2e2d40b7 --- /dev/null +++ b/ru-ru/css-ru.html.markdown @@ -0,0 +1,250 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] +filename: learncss-ru.css +lang: ru-ru +--- + +В свои ранние дни веб состоял в основном из чистого текста. С развитием браузеров +веб-страницы с графическими элементами стали обычным делом. +CSS - язык, разграничивающий содержимое (HTML) и внешний вид веб-страниц. + +Если коротко, то CSS предоставляет синтаксис, позволяющий выбирать различные +HTML элементы и определять их внешний вид. + +Как и у других языков, у CSS много версий. Мы описываем CSS2.0 - не самую новую, +но самую поддерживаемую и распространенную версию. + +**ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида +элементов, постарайтесь использовать CSS-песочницы при изучении языка. +Например [dabblet](http://dabblet.com/). +В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации. + + +```css +/* Для комментариев используется слеш-астериск, как на этой строчке. + В CSS нет однострочных комментариев; все комментарии записываются таким способом */ + +/* #################### + ## СЕЛЕКТОРЫ + #################### */ + +/* Выражения в CSS очень просты */ +селектор { атрибут: значение; /* другие атрибуты...*/ } + +/* селекторы используются для выбора элементов на странице + +Чтобы выбрать все элементы, используйте астериск: */ +* { color:red; } + +/* +Если на странице присутствует такой элемент: + +<div class='some-class class2' id='someId' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* его можно выбрать по одному классу */ +.some-class { } + +/* или по обоим классам */ +.some-class.class2 { } + +/* по названию тега */ +div { } + +/* по идентификатору */ +#someId { } + +/* по имеющемуся атрибуту */ +[attr] { font-size:smaller; } + +/* или по атрибуту с определенным значением */ +[attr='value'] { font-size:smaller; } + +/* можно выбрать атрибуты, начинающиеся с определенного значения (CSS3) */ +[attr^='val'] { font-size:smaller; } + +/* или заканчивающиеся определенным значением (CSS3) */ +[attr$='ue'] { font-size:smaller; } + +/* содержащие отделенное пробелами значение в названии атрибута (CSS3) */ +[otherAttr~='foo'] { font-size:smaller; } + +/* можно выбрать атрибут как с точным, так и со стоящим после значения “-” (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* Более того, все это можно использовать вместе - между разными частями +не должно быть пробелов, иначе селектор будет иметь совершенно иное значение */ +div.some-class[attr$='ue'] { } + +/* Вы можете выбрать элемент по его родителю */ + +/* прямой потомок другого элемента (выбранного с помощью селектора) */ +div.some-parent > .class-name {} + +/* потомок любого родителя в дереве элементов + следующая строка означает: "любой элемент класса "class-name", + являющийся потомком div-элемента класса "some-parent" + НЕЗАВИСИМО ОТ УРОВНЯ ВЛОЖЕННОСТИ" */ +div.some-parent .class-name {} + +/* важно: этот же селектор без пробелов имеет иное значение + можете догадаться, какое? */ +div.some-parent.class-name {} + +/* вы можете выбрать элемент по первому предшествующему + родственному элементу */ +.i-am-before + .this-element { } + +/* или любому предшествующему родственнику перед элементом */ +.i-am-any-before ~ .this-element {} + + +/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента + в зависимости от событий, произошедших с элементом */ + +/* например, когда курсор наведен на элемент */ +element:hover {} + +/* когда пользователь проходил по ссылке ранее */ +element:visited {} + +/* или еще не проходил по ней */ +element:link {} + +/* выбранное поле воода (input) */ +element:focus {} + + +/* #################### + ## АТРИБУТЫ + #################### */ + +selector { + + /* Единицы измерения */ + width: 50%; /* проценты */ + font-size: 2em; /* умножается на высоту шрифта (2em - в два раза больше) */ + width: 200px; /* пиксели */ + font-size: 20pt; /* пункты */ + width: 5cm; /* сантиметры */ + min-width: 50mm; /* милиметры */ + max-width: 5in; /* дюймы */ + height: 0.2vh; /* умножается на высоту окна браузера (CSS3) */ + width: 0.4vw; /* умножается на ширину окна браузера (CSS3) */ + min-height: 0.1vmin; /* наименьшее из vh и vw (CSS3) */ + max-width: 0.3vmax; /* наибольшее из vh и vw (CSS3) */ + + /* Цвета */ + background-color: #F6E; /* сокращенная запись шестнадцатеричного кода */ + background-color: #F262E2; /* стандартная запись шестнадцатеричного кода */ + background-color: tomato; /* название цвета */ + background-color: rgb(255, 255, 255); /* цветовая модель rgb */ + background-color: rgb(10%, 20%, 50%); /* цветовая модель rgb в процентах */ + background-color: rgba(255, 0, 0, 0.3); /* цветовая модель rgb (последний аргумент отвечает за прозрачность цвета) (CSS3) */ + background-color: transparent; /* прозрачный цвет */ + background-color: hsl(0, 100%, 50%); /* в формате hsl (CSS3) */ + background-color: hsla(0, 100%, 50%, 0.3); /* в формате hsl (последний аргумент отвечает за непрозрачность цвета) (CSS3) */ + + + /* Изображения */ + background-image: url(/path-to-image/image.jpg); /* кавычки внутри url() опциональны */ + + /* Шрифты */ + font-family: Arial; + font-family: "Courier New"; /* если в названии есть пробелы, заключите его в кавычки */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; /* если шрифт не найден, + будет использован следующий за ним в списке */ +} + +``` + +## Использование + +Сохраните готовый файл с расширением .css + +```xml +<!-- добавьте css файл в тег <head> на странице: --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- Можно использовать встроенные стили. Рекомендуется избегать подобного подхода. --> +<body> + <style> + a { color: purple; } + </style> +</body> + +<!-- Можно установить стиль элемента напрямую. +Используйте этот способ только в случае крайней необходимости. --> +<div style="border: 1px solid red;"> +</div> + +``` + +## Приоритет + +Как вы заметили, внешний вид элемента может определяться несколькими селекторами, +а значение атрибута элемента может быть установлено больше одного раза. +В подобных случаях одно из значений оказывается приоритетнее остальных. + +Если взять следующую таблицу стилей: + +```css +/*A*/ +p.class1[attr='value'] + +/*B*/ +p.class1 {} + +/*C*/ +p.class2 {} + +/*D*/ +p {} + +/*E*/ +p { property: value !important; } + +``` + +и следующую разметку: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value'> +</p> +``` + +Приоритет стилей будет таким: +Помните: приоритет выставляется для **атрибута**, а не для всего блока стилей. + +* `E` имеет наивысший приоритет благодаря ключевому слову `!important`. + Используйте только в случае крайней необходимости. +* `F` идет следующим, так как является встроенным стилем. +* `A` следующий, как самый конкретизированный. + конкретизированный == большее количество определителей. + В этом примере 3 определителя: 1 тег `p` + + название класса `class1` + 1 атрибут `attr='value'` +* `C` следующий. Несмотря на одинаковое с `B` количество определителей, + `C` определен позже. +* Затем `B` +* И последний `D`. + +## Совместимость + +Несмотря на то, что большая часть функций CSS2 (а также CSS3) подеррживается всеми +браузерами и устройствами, не забывайте проверять совместимость CSS-правил +с современными браузерами. + +[QuirksMode CSS](http://www.quirksmode.org/css/) замечательно подходит для этого. + +To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource. + +## Ресурсы для самостоятельного изучения + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 44a22b45..e06ae9bd 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -65,7 +65,7 @@ func beyondHello() { learnTypes() // < y minutes, learn more! } -// Функция имеющая входные параметры и возврат нескольких значений. +// Функция, имеющая входные параметры и возвращающая несколько значений. func learnMultiple(x, y int) (sum, prod int) { return x + y, x * y // Возврат двух значений. } diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown index 005495cc..b24ad555 100644 --- a/ru-ru/java-ru.html.markdown +++ b/ru-ru/java-ru.html.markdown @@ -451,7 +451,7 @@ public class Fruit implements Edible, Digestible { } } -// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать +// В Java Вы можете наследовать только один класс, однако можете реализовывать // несколько интерфейсов. Например: public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { public void InterfaceOneMethod() { diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown new file mode 100644 index 00000000..54499f46 --- /dev/null +++ b/ru-ru/javascript-ru.html.markdown @@ -0,0 +1,513 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] +lang: ru-ru +--- + +JavaScript был создан в 1995 году Бренданом Айком, работавшим в компании Netscape. +Изначально он был задуман как простой язык сценариев для веб-сайтов, дополняющий +Java для более сложных веб-приложений, но его тесная интеграция с веб-страницами +и встроенная поддержка браузерами привели к тому, что он стал более распространённым, +чем Java в веб-интерфейсах. + +JavaScript не ограничивается только веб-браузером: например, Node.js, программная +платформа, позволяющая выполнять JavaScript, основанная на движке V8 от браузера +Google Chrome, становится все более популярной. + +```js +// Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, +/* а многострочные комментарии начинаются с последовательности слэш-звёздочка + и заканчиваются символами звёздочка-слэш */ + +// Инструкции могут заканчиваться точкой с запятой ; +doStuff(); + +// ... но она необязательна, так как точки с запятой автоматически вставляются +// везде, где есть символ новой строки, за некоторыми исключениями. +doStuff() + +// Так как эти исключения могут привести к неожиданным результатам, мы будем всегда +// использовать точку с запятой в этом руководстве. + +/////////////////////////////////// +// 1. Числа, Строки и Операторы + +// В JavaScript только один тип числа (64-bit IEEE 754 double). +// Он имеет 52-битную мантиссу, которой достаточно для хранения целых чисел +// с точностью вплоть до 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Некоторые простые арифметические операции работают так, как вы ожидаете. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 (а некоторые - нет) +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Включая деление с остатком. +5 / 2; // = 2.5 + +// Побитовые операции также имеются; когда вы проводите такую операцию, +// ваше число с плавающей запятой переводится в целое со знаком +// длиной *до* 32 разрядов. +1 << 2; // = 4 + +// Приоритет в выражениях можно явно задать скобками. +(1 + 3) * 2; // = 8 + +// Есть три специальных значения, которые не являются реальными числами: +Infinity; // "бесконечность", например, результат деления на 0 +-Infinity; // "минус бесконечность", результат деления отрицательного числа на 0 +NaN; // "не число", например, результат деления 0/0 + +// Существует также логический тип. +true; +false; + +// Строки создаются при помощи двойных или одинарных кавычек. +'абв'; +"Привет, мир!"; + +// Для логического отрицания используется восклицательный знак. +!true; // = false +!false; // = true + +// Строгое равенство === +1 === 1; // = true +2 === 1; // = false + +// Строгое неравенство !== +1 !== 1; // = false +2 !== 1; // = true + +// Другие операторы сравнения +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Строки объединяются при помощи оператора + +"привет, " + "мир!"; // = "Привет, мир!" + +// и сравниваются при помощи < и > +"a" < "b"; // = true + +// Проверка равенства с приведением типов осуществляется двойным символом равно +"5" == 5; // = true +null == undefined; // = true + +// ...если только не использовать === +"5" === 5; // = false +null === undefined; // = false + +// ...приведение типов может привести к странному поведению... +13 + !0; // 14 +"13" + !0; // '13true' + +// Вы можете получить доступ к любому символу строки, используя метод charAt +"Это строка".charAt(0); // = 'Э' + +// ...или используйте метод substring, чтобы получить более крупные части +"Привет, мир".substring(0, 6); // = "Привет" + +// length - это свойство, для его получения не нужно использовать () +"Привет".length; // = 6 + +// Также есть null и undefined +null; // Намеренное отсутствие значения +undefined; // используется для обозначения переменных, не имеющих + // присвоенного значения (хотя непосредственно undefined + // является значением) + +// false, null, undefined, NaN, 0 и "" — это ложь; всё остальное - истина. +// Следует отметить, что 0 — это ложь, а "0" — истина, несмотря на то, что +// 0 == "0". + +/////////////////////////////////// +// 2. Переменные, Массивы и Объекты + +// Переменные объявляются при помощи ключевого слова var. JavaScript — язык с +// динамической типизацией, поэтому не нужно явно указывать тип. Для присваивания +// значения переменной используется символ = +var someVar = 5; + +// если вы пропустите слово var, вы не получите сообщение об ошибке, ... +someOtherVar = 10; + +// ...но ваша переменная будет создана в глобальном контексте, а не в текущем, +// где вы ее объявили. + +// Переменным, объявленным без присвоения, устанавливается значение undefined. +var someThirdVar; // = undefined + +// У математических операций есть сокращённые формы: +someVar += 5; // как someVar = someVar + 5; someVar теперь имеет значение 10 +someVar *= 10; // теперь someVar имеет значение 100 + +// Ещё более краткая запись увеличения и уменьшения на единицу: +someVar++; // теперь someVar имеет значение 101 +someVar--; // вернулись к 100 + +// Массивы — это нумерованные списки, содержащие значения любого типа. +var myArray = ["Привет", 45, true]; + +// Их элементы могут быть доступны при помощи синтаксиса с квадратными скобками. +// Индексы массивов начинаются с нуля. +myArray[1]; // = 45 + +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); +myArray.length; // = 4 + +// добавлять и редактировать определённый элемент +myArray[3] = "Привет"; + +// Объекты в JavaScript похожи на словари или ассоциативные массивы в других +// языках: неупорядоченный набор пар ключ-значение. +var myObj = {key1: "Привет", key2: "Мир"}; + +// Ключи — это строки, но кавычки необязательны, если строка удовлетворяет +// ограничениям для имён переменных. Значения могут быть любых типов. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Атрибуты объектов можно также получить, используя квадратные скобки +myObj["my other key"]; // = 4 + +// или через точку, при условии, что ключ является допустимым идентификатором. +myObj.myKey; // = "myValue" + +// Объекты изменяемы; можно изменять значения и добавлять новые ключи. +myObj.myThirdKey = true; + +// Если вы попытаетесь получить доступ к несуществующему значению, +// вы получите undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Логика и управляющие конструкции. + +// Синтаксис для этого раздела почти такой же, как в Java. + +// Условная конструкция работает, как и следовало ожидать, +var count = 1; +if (count == 3) { + // выполняется, если count равен 3 +} else if (count == 4) { + // выполняется, если count равен 4 +} else { + // выполняется, если не 3 и не 4 +} + +// ...как и цикл while. +while (true){ + // Бесконечный цикл! +} + +// Цикл do-while такой же, как while, но он всегда выполняется хотя бы раз. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// цикл for такой же, как в C и Java: +// инициализация; условие; шаг. +for (var i = 0; i < 5; i++) { + // выполнится 5 раз +} + +// && — это логическое И, || — это логическое ИЛИ +if (house.size == "big" && house.color == "blue") { + house.contains = "bear"; +} +if (color == "red" || color == "blue") { + // цвет красный или синий +} + +// && и || используют сокращённое вычисление, что полезно +// для задания значений по умолчанию. +var name = otherName || "default"; + +// Оператор switch выполняет проверку на равенство при помощи === +// используйте break, чтобы прервать выполнение после каждого case, +// или выполнение пойдёт далее даже после правильного варианта. +grade = 4; +switch (grade) { + case 5: + console.log("Отлично"); + break; + case 4: + console.log("Хорошо"); + break; + case 3: + console.log("Можете и лучше"); + break; + default: + console.log("Ой-вей!"); + break; +} + + +/////////////////////////////////// +// 4. Функции, Область видимости и Замыкания + +// Функции в JavaScript объявляются при помощи ключевого слова function. +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Обратите внимание, что значение, которое будет возвращено, должно начинаться +// на той же строке, что и ключевое слово return, в противном случае вы будете +// всегда возвращать undefined по причине автоматической вставки точки с запятой. +// Следите за этим при использовании стиля форматирования Allman. +function myFunction() +{ + return // <- здесь точка с запятой вставится автоматически + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// В JavaScript функции — это объекты первого класса, поэтому они могут быть +// присвоены различным именам переменных и передаваться другим функциям +// в качестве аргументов, например, когда назначается обработчик события: +function myFunction() { + // этот код будет вызван через 5 секунд +} +setTimeout(myFunction, 5000); +// Примечание: setTimeout не является частью языка, но реализован в браузерах и Node.js + +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. +setTimeout(function() { + // этот код будет вызван через 5 секунд +}, 5000); + +// В JavaScript есть область видимости; функции имеют свою область +// видимости, а другие блоки — нет. +if (true) { + var i = 5; +} +i; // = 5, а не undefined, как ожидалось бы в языках с блочной областью видимости + +// Это привело к общепринятому шаблону "самозапускающихся анонимных функций", +// которые препятствуют проникновению переменных в глобальную область видимости +(function() { + var temporary = 5; + // Мы можем получить доступ к глобальной области для записи в «глобальный объект», + // который в веб-браузере всегда window. Глобальный объект может иметь другое + // имя в таких платформах, как Node.js + window.permanent = 10; +})(); +temporary; // вызовет сообщение об ошибке с типом ReferenceError +permanent; // = 10 + +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции даже после того, как контекст выполнения выйдет из +// внешней функции. +function sayHelloInFiveSeconds(name) { + var prompt = "Привет, " + name + "!"; + // Внутренние функции по умолчанию помещаются в локальную область видимости, + // как если бы они были объявлены с помощью var. + function inner() { + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout асинхронна, поэтому функция sayHelloInFiveSeconds сразу выйдет, + // после чего setTimeout вызовет функцию inner. Однако поскольку функция inner + // «замкнута» вокруг sayHelloInFiveSeconds, она по-прежнему имеет доступ к переменной prompt + // на то время, когда она наконец будет вызвана. +} +sayHelloInFiveSeconds("Адам"); // Через 5 с откроется окно «Привет, Адам!» + +/////////////////////////////////// +// 5. Подробнее об объектах; Конструкторы и Прототипы + +// Объекты могут содержать в себе функции. +var myObj = { + myFunc: function() { + return "Привет, мир!"; + } +}; +myObj.myFunc(); // = "Привет, мир!" + +// Когда вызываются функции, прикреплённые к объекту, они могут получить доступ +// к этому объекту с помощью ключевого слова this. +myObj = { + myString: "Привет, мир!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // = "Привет, мир!" + +// Значение this зависит от того, как функция вызывается, +// а не от того, где она определена. Таким образом, наша функция не работает, +// если она вызывается не в контексте объекта. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// И наоборот, функция может быть присвоена объекту и получать доступ к нему +// через this, даже если она не была прикреплена к нему при объявлении. +var myOtherFunc = function() { +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "ПРИВЕТ, МИР!" + +// Мы можем также указать контекст для выполнения функции при её вызове, +// используя call или apply. +var anotherFunc = function(s) { + return this.myString + s; +} +anotherFunc.call(myObj, " И привет, Луна!"); // = "Привет, мир! И привет, Луна!" + +// Функция apply почти такая же, но принимает в качестве списка аргументов массив. +anotherFunc.apply(myObj, [" И привет, Солнце!"]); // = "Привет, мир! И привет, Солнце!" + +// Это полезно при работе с функцией, которая принимает последовательность +// аргументов, а вы хотите передать массив. +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Ой-ой!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Но call и apply — только временные. Когда мы хотим связать функцию с объектом, +// мы можем использовать bind. +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" И привет, Сатурн!"); // = "Привет, мир! И привет, Сатурн!" + +// Bind также может использоваться для частичного применения (каррирования) функции +var product = function(a, b) { return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Когда вы вызываете функцию с помощью ключевого слова new, создается новый объект, +// доступный функции при помощи this. Такие функции называют конструкторами. +var MyConstructor = function() { + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// У каждого объекта в JavaScript есть прототип. Когда вы хотите получить +// доступ к свойству объекта, которое не существует в этом объекте, интерпретатор +// будет искать это свойство в прототипе. + +// Некоторые реализации языка позволяют получить доступ к прототипу объекта +// через «магическое» свойство __proto__. Несмотря на то, что это может быть полезно +// для понимания прототипов, это не часть стандарта; мы увидим стандартные способы +// использования прототипов позже. +var myObj = { + myString: "Привет, мир!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Для функций это тоже работает. +myObj.myFunc(); // = "Привет, мир!" + +// Если интерпретатор не найдёт свойство в прототипе, то продожит поиск +// в прототипе прототипа и так далее. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Здесь не участвует копирование; каждый объект хранит ссылку на свой прототип. +// Это означает, что мы можем изменить прототип, и наши изменения будут отражены везде. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Мы упомянули, что свойство __proto__ нестандартно, и нет никакого стандартного +// способа, чтобы изменить прототип существующего объекта. Однако есть два +// способа создать новый объект с заданным прототипом. + +// Первый способ — это Object.create, который появился в JavaScript недавно, +// а потому доступен ещё не во всех реализациях языка. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Второй способ, который работает везде, имеет дело с конструкторами. +// У конструкторов есть свойство с именем prototype. Это *не* прототип +// функции-конструктора; напротив, это прототип для новых объектов, которые +// будут созданы с помощью этого конструктора и ключевого слова new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function() { + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// У встроенных типов, таких, как строки и числа, также есть конструкторы, которые +// создают эквивалентные объекты-обёртки. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// За исключением того, что они не в точности равны. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0) { + // Этот код не выполнится, потому что 0 - это ложь. +} + +// Впрочем, объекты-обёртки и встроенные типы имеют общие прототипы, +// поэтому вы можете расширить функционал строк, например: +String.prototype.firstCharacter = function() { + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Это часто используется в т.н. полифилах, которые реализуют новые возможности +// JavaScript в старой реализации языка, так что они могут быть использованы в +// старых средах, таких, как устаревшие браузеры. + +// Например, мы упомянули, что Object.create доступен не во всех реализациях, но +// мы сможем использовать его с помощью такого полифила: +if (Object.create === undefined) { // не перезаписываем метод, если он существует + Object.create = function(proto) { + // создаём временный конструктор с правильным прототипом + var Constructor = function(){}; + Constructor.prototype = proto; + // затем используем его для создания нового, + // правильно прототипированного объекта + return new Constructor(); + } +} +``` + +## Что ещё почитать + +[Современный учебник JavaScript (Илья Кантор)](http://learn.javascript.ru) — +качественный учебник по JavaScript на русском языке. + +[Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) — +предоставляет отличную документацию для JavaScript, как он используется в браузерах. +Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, +делясь своими знаниями. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это +подробное руководство по всем неинтуитивным особенностей языка. + +[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) — можно +найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. diff --git a/ru-ru/json-ru.html.markdown b/ru-ru/json-ru.html.markdown new file mode 100644 index 00000000..52af3696 --- /dev/null +++ b/ru-ru/json-ru.html.markdown @@ -0,0 +1,61 @@ +--- +language: json +filename: learnjson-ru.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +JSON - это очень простой формат обмена данными, и это будет самый легкий +курс из когда-либо представленных "Learn X in Y Minutes". + +В чистом виде у JSON нет фактических комментариев, но большинство парсеров примут +комментарии в Си-стиле (//, /\* \*/). Для таких целей, конечно, все правильно +будет на 100% с точки зрения JSON. К счастью, в нашем случае данные скажут сами за себя. + +```json +{ + "ключ": "значение", + + "ключи": "должны всегда заключаться в двойные кавычки", + "числа": 0, + "строки": "Пρивет, миρ. Допускаются все unicode-символы вместе с \"экранированием\".", + "содержит логический тип?": true, + "ничего": null, + + "большое число": 1.2e+100, + + "объекты": { + "комментарий": "Большинство ваших структур будут представлять из себя объекты.", + + "массив": [0, 1, 2, 3, "Массивы могут содержать в себе любой тип.", 5], + + "другой объект": { + "комментарий": "Они могут быть вложенными, и это очень полезно." + } + }, + + "бессмыслие": [ + { + "источники калия": ["бананы"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "нео"], + [0, 0, 0, 1] + ] + ], + + "альтернативный стиль": { + "комментарий": "проверьте это!" + , "позиция запятой": "неважна, хоть и перед значением, все равно правильно" + , "еще один комментарий": "как хорошо" + }, + + "это было недолго": "И вы справились. Теперь вы знаете все о JSON." +} +``` diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index 6f515975..da9ced6a 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua filename: learnlua-ru.lua contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index 3246de82..8eac4ddb 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -1,106 +1,171 @@ --- language: Objective-C -filename: LearnObjectiveC.m +filename: LearnObjectiveC-ru.m contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] translators: - ["Evlogy Sutormin", "http://evlogii.com"] + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] lang: ru-ru --- -Objective-C — компилируемый объектно-ориентированный язык программирования, используемый корпорацией Apple, -построенный на основе языка Си и парадигм Smalltalk. -В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. +Objective-C — основной язык программирования, используемый корпорацией Apple +для операционных систем OS X и iOS и их соответствующих фреймворках Cocoa и +Cocoa Touch. +Он является объектно-ориентированным языком программирования общего назначения, +который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. -```objective_c -// Однострочный комментарий +```objective-c +// Однострочные комментарии начинаются с // /* -Многострочный -комментарий +Так выглядят многострочные комментарии */ -// Импорт файлов фреймворка Foundation с помощью #import +// Импорт заголовочных файлов фреймворка Foundation с помощью #import +// Используйте <>, чтобы импортировать глобальные файлы (обычно фреймворки) +// Используйте "", чтобы импортировать локальные файлы (из проекта) #import <Foundation/Foundation.h> #import "MyClass.h" -// Точка входа в программу это функция main, -// которая возвращает целый тип integer +// Если вы включили модули для iOS >= 7.0 или OS X >= 10.9 проектов в +// Xcode 5, вы можете импортировать фреймворки подобным образом: +@import Foundation; + +// Точка входа в программу - это функция main, +// которая возвращает целый тип int main (int argc, const char * argv[]) { - // Создание autorelease pool для управления памятью + // Создание autorelease pool для управления памятью в программе NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - + // В место этого воспользуйтесь @autoreleasepool, если вы используете + // автоматический подсчет ссылок (ARC) + @autoreleasepool { + // Используйте NSLog для печати в консоль - NSLog(@"Hello World!"); // Напечатает строку "Hello World!" + NSLog(@"Привет Мир!"); // Напечатает строку "Привет Мир!" /////////////////////////////////////// // Типы и переменные /////////////////////////////////////// - // Простое объявление + // Объявление простых типов int myPrimitive1 = 1; long myPrimitive2 = 234554664565; + // Объявление объектов // Помещайте * в начало названия объекта для строго типизированного объявления MyClass *myObject1 = nil; // Строгая типизация id myObject2 = nil; // Слабая типизация - - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // %@ – это объект - // 'description' это общий для всех объектов метод вывода данных + // 'description' - это общий для всех объектов метод вывода данных + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // Строка - NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // напечатает "Hello World!" + NSString *worldString = @"Мир"; + NSLog(@"Привет %@!", worldString); // напечатает "Привет Мир!" + // NSMutableString - это изменяемая версия NSString-объекта + NSMutableString *mutableString = [NSMutableString stringWithString:@"Привет"]; + [mutableString appendString:@" Мир!"]; + NSLog(@"%@", mutableString); // напечатает => "Привет Мир!" // Символьные литералы NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; + char theLetterZ = [theLetterZNumber charValue]; // или 'Z' NSLog(@"%c", theLetterZ); - // Целочисленный литералы + // Целочисленные литералы NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; + int fortyTwo = [fortyTwoNumber intValue]; // или '42' NSLog(@"%i", fortyTwo); // Беззнаковый целочисленный литерал NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // или 42 NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // или 42 NSLog(@"%hi", fortyTwoShort); + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // или 41 + NSLog(@"%u", fortyOneUnsigned); + NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // или 42 NSLog(@"%li", fortyTwoLong); + + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // или 53 + NSLog(@"%lu", fiftyThreeUnsigned); // Вещественный литерал NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); + float piFloat = [piFloatNumber floatValue]; // или 3.141592654f + NSLog(@"%f", piFloat); // напечатает 3.141592654 + NSLog(@"%5.2f", piFloat); // напечатает " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; // или 3.1415926535 NSLog(@"%f", piDouble); - + NSLog(@"%4.2f", piDouble); // напечатает "3.14" + + // NSDecimalNumber - это класс с фиксированной точкой, который является + // более точным, чем float или double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber не способен использовать стандартные +, -, *, / операторы, + // поэтому он предоставляет свои собственные: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // напечатает "10.99", т.к. NSDecimalNumber - изменяемый + // BOOL (булевый) литерал NSNumber *yesNumber = @YES; NSNumber *noNumber = @NO; - + // или + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // напечатает 1 + // Массив + // Может содержать различные типы данных, но должен быть объектом Objective-C NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + NSLog(@"Третье число = %@", thirdNumber); // Напечатает "Третье число = 3" + // NSMutableArray - это изменяемая версия NSArray, допускающая вам изменять + // элементы в массиве и расширять или сокращать массив. + // Удобный, но не эффективный как NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Привет"]; + [mutableArray addObject:@"Мир"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // напечатает "Мир" // Словарь - NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; - NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Напечатает "Object = (null)" - + NSDictionary *aDictionary = @{ @"ключ1" : @"значение1", @"ключ2" : @"значение2" }; + NSObject *valueObject = aDictionary[@"Ключ"]; + NSLog(@"Объект = %@", valueObject); // Напечатает "Объект = (null)" + // NSMutableDictionary тоже доступен, как изменяемый словарь + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"значение1" forKey:@"ключ1"]; + [mutableDictionary setObject:@"значение2" forKey:@"ключ2"]; + [mutableDictionary removeObjectForKey:@"ключ1"]; + + // Множество + NSSet *set = [NSSet setWithObjects:@"Привет", @"Привет", @"Мир", nil]; + NSLog(@"%@", set); // напечатает {(Hello, World)} (порядок может отличаться) + // NSMutableSet тоже доступен, как изменяемое множество + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Привет"]; + [mutableSet addObject:@"Привет"]; + NSLog(@"%@", mutableSet); // напечатает => {(Привет)} + /////////////////////////////////////// // Операторы /////////////////////////////////////// @@ -124,13 +189,13 @@ int main (int argc, const char * argv[]) // Условный оператор if (NO) { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } else if (0) { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } else { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } // Ветвление с множественным выбором @@ -138,15 +203,15 @@ int main (int argc, const char * argv[]) { case 0: { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } break; case 1: { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } break; default: { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } break; } @@ -170,7 +235,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // // Цикл просмотра + // Цикл просмотра NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { @@ -180,20 +245,32 @@ int main (int argc, const char * argv[]) // "2," // "3," + // Цикл for для объектов. Может использоваться с любым объектом Objective-C + for (id item in values) { + NSLog(@"%@,", item); + } // напечатает => "0," + // "1," + // "2," + // "3," + // Обработка исключений @try { // Ваше исключение здесь @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"File Not Found on System" userInfo:nil]; + reason:@"Файл не найден в системе" userInfo:nil]; } @catch (NSException * e) { - NSLog(@"Exception: %@", e); + NSLog(@"Исключение: %@", e); } @finally { - NSLog(@"Finally"); - } // => напечатает "Exception: File Not Found on System" - // "Finally" + NSLog(@"В конце отводится время для очистки."); + } // => напечатает "Исключение: Файл не найден в системе" + // "В конце отводится время для очистки." + + // NSError - это полезные объекты для аргументов функции, чтобы заполнить их + // пользовательскими ошибками. + NSError *error = [NSError errorWithDomain:@"Неправильный эл. адрес." code:4 userInfo:nil]; /////////////////////////////////////// // Объекты @@ -203,13 +280,16 @@ int main (int argc, const char * argv[]) // Объект не является полнофункциональным пока обе части не выполнятся. MyClass *myObject = [[MyClass alloc] init]; - // В Objective-C можель ООП базируется на передаче сообщений. + // В Objective-C модель ООП базируется на передаче сообщений. // В Objective-C Вы не просто вызваете метод; вы посылаете сообщение. - [myObject instanceMethodWithParameter:@"Steve Jobs"]; + [myObject instanceMethodWithParameter:@"Стив Джобс"]; // Очищайте память, перед завершением работы программы. [pool drain]; + // Конец @autoreleasepool + } + // Конец программы. return 0; } @@ -222,63 +302,144 @@ int main (int argc, const char * argv[]) // Синтаксис объявления: // @interface ИмяКласса : ИмяКлассаРодителя <ИмплементируемыеПротоколы> // { -// Объявление переменных; +// тип имя; <= Объявление переменных; // } +// @property тип имя; <= объявление свойств // -/+ (тип) Объявление метода(ов). // @end - - -@interface MyClass : NSObject <MyProtocol> +@interface MyClass : NSObject <MyProtocol> // NSObject - это базовый класс в Objective-C. { - int count; - id data; + // Объявления экземпляров переменных (может существовать в файлах интерфейса или реализвации) + int count; // По умолчанию защищенный доступ. + @private id data; // Приватный доступ (Намного удобнее объявлять в файле реализации) NSString *name; } -// При объявлении свойств сразу генерируются геттер и сеттер -@property int count; -@property (copy) NSString *name; // Скопировать объект в ходе присвоения. -@property (readonly) id data; // Генерация только геттера +// Удобное обозначение для переменных с открытым (public) доступом +// автоматически генерируется сеттер-метод +// По умолчанию название сеттер-метода начинается с 'set' с последующим именем +// переменной из @property +@property int propInt; // Имя сеттер-метода = 'setPropInt' +@property (copy) id copyId; // (copy) => Скопировать объект в ходе присвоения. +// (readonly) => Не позволяет установить значение вне @interface +@property (readonly) NSString *roString; // Используйте @synthesize + // в @implementation, чтобы создать аксессор +// Вы можете настроить геттер и сеттер имена вместо используемого 'set'-имени по умолчанию: +@property (getter=lengthGet, setter=lengthSet:) int length; // Методы -+/- (return type)methodSignature:(Parameter Type *)parameterName; ++/- (возвращаемый тип)сигнатураМетода:(Параметр типа *)имяПараметра; // + для методов класса + (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - для метода объекта +// - для методов объекта - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -@end +// Методы-конструктор с аргументом: +- (id)initWithDistance:(int)defaultDistance; +// В Objective-C имена методов очень описательные. Всегда имена методов соответствуют своим аргументам + +@end // Устанавливает конец интерфейса (interface) + + +// Чтобы обратиться к открытым (public) переменным из файла реализации, @property генерирует сеттер-метод +// автоматически. Название метода - это 'set' с последующим именем переменной из @property: +MyClass *myClass = [[MyClass alloc] init]; // создает экземпляр объекта класса MyClass +[myClass setCount:10]; +NSLog(@"%d", [myClass count]); // напечатает => 10 +// Или используйте свой геттер и сеттер методы, которые определены в @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // напечатает => 32 +// Для удобства вы можете использовать точечную нотацию, +// чтобы установить и получить доступ к переменным объекта: +myClass.count = 45; +NSLog(@"%i", myClass.count); // напечатает => 45 + +// Вызов методов класса: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Привет"]; + +// Вызов методов экземпляра: +MyClass *myClass = [[MyClass alloc] init]; // Создает экземпляр объекта MyClass +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Привет"]; + +// Селекторы +// Это способ динамически представить методы. Используйте для вызова методов класса, передайте методы +// через функции, чтобы сказать другим классам, что они должны вызвать их и сохранить методы +// как переменные +// SEL - это тип данных. @selector() вернет селектор из предоставленного имени метода +// methodAParameterAsString:andAParameterAsNumber: - это название метода в MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Проверяет содержит ли класс метод + // Необходимо установить все аргументы метода в один объект, что отправить его в performSelector-функцию + NSArray *arguments = [NSArray arrayWithObjects:@"Привет", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Вызывает метод +} else { + // NSStringFromSelector() вернет NSString название метода полученного селектором + NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar)); +} // Имплементируйте методы в файле МойКласс.m: +@implementation MyClass { + long distance; // Переменная экземпляра с закрытым (private) доступом + NSNumber height; +} -@implementation MyClass +// To access a public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation + +// Called before calling any class methods or instantiating any objects ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} // Вызывается при высвобождении памяти под объектом - (void)dealloc { + [height release]; // Если не используется ARC, убедитесь в освобождении переменных объекта класса + [super dealloc]; // and call parent class dealloc } -// Конструкторы – это способ осздания объектов класса. -// Это обычный конструктор вызываемый при создании объекта клсааа. +// Конструкторы – это способ создания объектов класса. +// Это конструктор по умолчанию, который вызывается, когда объект инициализируется. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' используется для того, чтобы обратиться к методам родительского класса { - self.count = 1; + self.count = 1; // 'self' используется для вызова самого себя } return self; } +// Можно создать конструкторы, которые содержат аргументы: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { - return @"New string"; + return @"Новая строка"; } - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number @@ -286,23 +447,364 @@ int main (int argc, const char * argv[]) return @42; } +// Objective-C не содержит объявление приватных методов, но вы можете имитировать их. +// Чтобы сымитировать приватный метод, создайте метод в @implementation, но не в @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Вызывает приватный метод + // Методы объявленные в МyProtocol (см. далее) - (void)myProtocolMethod { - // имплементация + // операторы } +@end // Устанавливает конец реализации (implementation) + +/////////////////////////////////////// +// Категории +/////////////////////////////////////// +// Категория - это группа методов предназначенные для того, чтобы расширить класс. Они позволяют вам добавить новые методы +// к существующему классу для организационных целей. Это не стоит путать с подклассами. +// Подклассы предназначены для ИЗМЕНЕНИЯ функциональности объекта пока как категории ДОБАВЛЯЮТ +// функциональность в объект. +// Категории позволяют вам: +// -- Добавлять методы в существующий класс для организационных целей. +// -- Допускает вам расширять объекты Objective-C классов (напр.: NSString) добавить ваши собственные методы. +// -- Добавляет возможность создать защищенные и закрытые методы классов. +// ПРИМЕЧАНИЕ: Не переопределяйте методы базового класса в категории даже если у вас есть возможность это сделать +// to. Переопределение методов может привести к ошибкам компиляции позднее между различными категориями и это +// нарушает цель категорий, чтобы добавлять только функциональность. Вместо этого подклассы переопределяют методы. + +// Здесь простой базовый класс Car. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + @end -/* - * Протокол объявляет методы которые должны быть имплементированы - * Протокол не является классом. Он просто определяет интерфейс, - * который должен быть имплементирован. - */ +// И реализация базового класса Car: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Машина заведена."); +} +- (void)accelerate { + NSLog(@"Ускорение."); +} -@protocol MyProtocol - - (void)myProtocolMethod; @end + +// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет +// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить +// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим +// категорию для добавления его очистительных методов: +// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h) +#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения. + +@interface Car (Clean) // Имя категории внутри (), следующие после имени базового класса. + +- (void)washWindows; // Названия новых методов, которые мы добавляем в наш объект Car. +- (void)wax; + +@end + +// @implementation имя файла: Car+Clean.m (ИмяБазовогоКласса+ИмяКатегории.m) +#import "Car+Clean.h" // Импортируйте Очистку файл @interface категории. + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Окна промыли."); +} +- (void)wax { + NSLog(@"Воском натерли."); +} + +@end + +// Любой экземпляр объекта Car имеет возможность воспользоваться категорией. Все, что нужно сделать, это импортировать ее: +#import "Car+Clean.h" // Импортировать как множество различных категорий, как вы хотите использовать. +#import "Car.h" // Кроме того, необходимо импортировать базовый класс для использования его оригинальные функциональные возможности. + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Красный"; + mustang.make = @"Форд"; + + [mustang turnOn]; // Используйте методы из базового класса Car. + [mustang washWindows]; // Используйте методы категории Clean из класса Car. + } + return 0; +} + +// Objective-C не поддерживает объявление защищенных методов, но вы можете имитировать их. +// Создайте категорию, содержащую все защищенные методы, затем импортируйте ее только в +// @implementation-файле класса, относящегося к классу Car: +@interface Car (Protected) // Наименование категории с помощью 'Protected' +// дает знать, что методы защищенные. + +- (void)lockCar; // Здесь перечисляются методы, которые должны быть созданы +// только с помощью объектов класса Car. + +@end +// Чтобы воспользоваться защищенными методами, импортируйте категорию, затем реализуйте методы: +#import "Car+Protected.h" // Запомните, делайте импорт только в файле с @implementation. + +@implementation Car + +- (void)lockCar { + NSLog(@"Машина закрыта."); // Экземпляры класса Car не могут использовать +// метод lockCar, потому что он объявлен не в @interface. +} + +@end + +/////////////////////////////////////// +// Расширения +/////////////////////////////////////// +// Расширения позволяют вам переопределять атрибуты свойств и методов +// с открытым доступом в @interface. +// @interface имя файла: Shape.h +@interface Shape : NSObject // Расширение базового класса Shape переопределяет + // свои поля ниже. + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// Вы можете переопределить numOfSides-переменную или getNumOfSides-метод +// Внесение изменений с помощью расширения делается следующим образом: +// @implementation имя файла: Shape.m +#import "Shape.h" +// Расширения "живут" в том же файле, где и @implementation класса. +@interface Shape () // После имени базового класса скобки () объявляют расширение. + +@property (copy) NSNumber *numOfSides; // Делает numOfSides-свойство + // копирующим (copy) вместо свойства только для чтения (readonly). +-(NSNumber)getNumOfSides; // Изменяет метод getNumOfSides так, + // чтобы он возвращал объект NSNumber вместо типа int. +-(void)privateMethod; // Вы также можете создать новый закрытый метод + // внутри расширения. + +@end +// Главный @implementation: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // Все операторы внутри расширения + // должны быть в @implementation. + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Закрытый метод созданный с помощью расширения."); + NSLog(@"Экземпляр Shape не может вызвать этот метод."); +} + +@end + +/////////////////////////////////////// +// Протоколы +/////////////////////////////////////// +// Протокол объявляет методы, которые могут быть реализованы с помощью +// любого класса. Протоколы сами по себе не являются классами. Они просто +// определяют интерфейс, который должен быть реализован другими объектами. +// @protocol имя файла: "CarUtilities.h" +@protocol CarUtilities <NSObject> // <NSObject> => Имя другого протокола, +// который включен в этот протокол. + @property BOOL engineOn; // Адаптирующий класс должен определить +// все @synthesize для @property и + - (void)turnOnEngine; // определить все методы. +@end +// Ниже пример класса, реализующий протокол. +#import "CarUtilities.h" // Импорт файла с @protocol. + +@interface Car : NSObject <CarUtilities> // Внутри <> имя протокола +// Здесь вам не нужно указывать @property или имена методов для CarUtilities. +// Они нужны только для @implementation. +- (void)turnOnEngineWithUtilities:(id <CarUtilities>)car; // Вы также можете +// указать тип протоколов. +@end +// В @implementation нужно реализовать все @property и методы для протокола. +@implementation Car : NSObject <CarUtilities> + +@synthesize engineOn = _engineOn; // Создайте @synthesize-оператор +// для "@property engineOn". + +- (void)turnOnEngine { // Реализуйте turnOnEngine как вам угодно. Протоколы +// не определят, + _engineOn = YES; // как вам реализовать метод, он только требует, +// чтобы вы реализовали его. +} +// Вы можете использовать протокол как данные, если вы знаете, что он реализует +// методы и переменные. +- (void)turnOnEngineWithCarUtilities:(id <CarUtilities>)objectOfSomeKind { + [objectOfSomeKind engineOn]; // У вас есть доступ к переменным объекта + [objectOfSomeKind turnOnEngine]; // и методам. + [objectOfSomeKind engineOn]; // Может или не может быть значение YES. Класс +// реализует как нужно. +} + +@end +// Экземпляры класса Car сейчас имеют доступ к протоколу. +Car *carInstance = [[Car alloc] init]; +[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Двигатель запущен."); // напечатает => "Двигатель запущен." +} +// Убедитись в том, что объект типа 'id' реализует протокол перед вызовом методов протокола: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Не работает, т.к. класс MyClass не реализует протокол CarUtilities."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Работает как класс Car, который реализует протокол CarUtilities."); +} +// Категории тоже могут реализовать протоколы: +// @interface Car (CarCategory) <CarUtilities> +// Вы можете реализовать много протоколов: +// @interface Car : NSObject <CarUtilities, CarCleaning> +// ЗАМЕЧАНИЕ: Если два или более протоколов полагаются друг на друга, +// убедитесь, что они ранее объявлены: +#import "Brother.h" + +@protocol Brother; // Оператор раннего объявления. Без него компилятор +// выдаст ошибку. + +@protocol Sister <NSObject> + +- (void)beNiceToBrother:(id <Brother>)brother; + +@end + +// Рассмотрите проблему, где протокол Sister полагается на протокол Brother, +// а Brother полагается на Sister. +#import "Sister.h" + +@protocol Sister; // Эти строки предотвращают рекурсию, решая этим проблему. + +@protocol Brother <NSObject> + +- (void)beNiceToSister:(id <Sister>)sister; + +@end + + +/////////////////////////////////////// +// Блоки +/////////////////////////////////////// +// Блоки - это операторы кода, наподобие функции, которую возможно использовать +// как данные. +// Ниже простой блок с целочисленным аргументом, и возвращает аргумент плюс 4. +int (^addUp)(int n); // Объявите переменную, чтобы сохранить блок. +void (^noParameterBlockVar)(void); // Пример объявления блока-переменной +// без аргументов. +// Блоки имею доступ к переменным в той же области видимости. Но переменные +// будут только для чтения, и значения переданных в блок станут значением +// переменной, когда блок создастся. +int outsideVar = 17; // Если мы редактируем outsideVar после объявления addUp, +// outsideVar остается равным 17. +__block long mutableVar = 3; // __block делают переменные перезаписываемыми +// в блоках, в отличие от outsideVar. +addUp = ^(int n) { // Удалите (int n) в блоке, чтобы не принимать +// какие-либо параметры. + NSLog(@"Вы можете иметь столько строк в блоке, сколько вы хотели."); + NSSet *blockSet; // Также вы можете объявить локальные переменные. + mutableVar = 32; // Присвоить новое значение к __block-переменной. + return n + outsideVar; // Необязательный оператор возврата. +} +int addUp = add(10 + 16); // Вызывает блок кода с аргументами. +// Блоки часто используются как аргументы функции, чтобы позже их вызвать, или +// как функции обратного вызова (callbacks). +@implementation BlockExample : NSObject + +- (void)runBlock:(void (^)(NSString))block { + NSLog(@"В аргументе блок ничего не возвращает и принимает NSString-объект."); + block(@"Аргумент передан блоку на исполнение."); // Вызов блока. +} + +@end + + +/////////////////////////////////////// +// Управление памятью +/////////////////////////////////////// +/* +Для каждого объекта, используемого в приложении, должна быть выделена память +для таких объектов. Когда приложение прекращает использование объекта, память +должна быть освобождена, чтобы гарантировать эффективность приложения. +Objective-C не использует сборщик мусора, а вместо этого применяет подсчет ссылок. +Пока существует по крайней мере одна ссылка на объект (также называется +"владение" объектом), то объект будет доступен к использованию (еще известно +как "право владения"). + +Когда экземпляр владеет объектом, его ссылка увеличивается на один. Когда +объекта освобождается, счетчик ссылки уменьшается на один. Когда счетчик ссылки +равен нулю, объект удаляется из памяти. + +Над всеми объектами взаимодействуют, следуя паттерну: +(1) создание объекта, (2) использование объекта, (3) затем освобождение объекта из памяти. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' устанавливает счетчик ссылки +// объекта classVar на 1 и возвращает указатель на объект. +[classVar release]; // Уменьшает счетчик ссылки объекта classVar +// 'retain' заявляет право собственности на существующий экземпляр объекта +// и увеличивает счетчик ссылки. Затем вернет указатель на объект. +MyClass *newVar = [classVar retain]; // Если classVar освободится, объект +// останется в памяти, потому что newVar - владелец +[classVar autorelease]; // Удалит право на владение объектом +// в конце @autoreleasepool блока. Вернет указатель на объект. + +// @property может использовать 'retain' и 'assign' тоже для маленького +// удобного определения +@property (retain) MyClass *instance; // Освободит старое значение и сохранит +// одно новое (строгая ссылка) +@property (assign) NSSet *set; // Укажет на новое значение +// без сохранения/освобождения старого значения (слабая ссылка) + +// Автоматический подсчет ссылок (ARC) +// Управление памятью может быть трудным, поэтому в Xcode 4.2 и iOS 4 введен +// автоматический подсчет ссылок (ARC). +// ARC - это особенность компилятора, который помещает "retain", "release" +// и "autorelease" автоматически за вас тогда, когда используется ARC, +// вам не нужно больше обращаться к "retain", "relase" или "autorelease" +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... код, использующий объект arcMyClass +// Без ARC, вам нужно было бы вызвать: [arcMyClass release] после того, как вы +// завершите работу с объектом arcMyClass. Но с ARC, +// теперь этого не нужно делать. Он будет помещать release-вызов за вас + +// Что касается 'assign' и 'retain' @property атрибутов, в ARC вы должны +// использовать 'weak' и 'strong' +@property (weak) MyClass *weakVar; // 'weak' не принимает право на владение +// объектом. Если исходный счетчик ссылки экземпляра обнуляется, +// weakVar-свойство автоматически примет значение nil, +// во избежание падения приложения +@property (strong) MyClass *strongVar; // 'strong' принимает право на владение +// объектом. Гарантирует, что объект останится в памяти для использования + +// Для обычных переменных (не объявленных с помощью @property), используйте +// следующий способ: +__strong NSString *strongString; // По умолчанию. Переменная сохраняется в памяти, +// пока она не покинет область видимости +__weak NSSet *weakSet; // Слабая ссылка на существующий объект. Когда существующий +// объект освобождается, weakSet принимает nil +__unsafe_unretained NSArray *unsafeArray; // Похож на __weak, но unsafeArray +// не принимает nil, когда существующий объект освобождается + ``` ## На почитать diff --git a/ru-ru/paren-ru.html.markdown b/ru-ru/paren-ru.html.markdown new file mode 100644 index 00000000..9b801e46 --- /dev/null +++ b/ru-ru/paren-ru.html.markdown @@ -0,0 +1,196 @@ +--- +language: Paren +filename: learnparen-ru.paren +contributors: + - ["KIM Taegyoon", "https://github.com/kimtg"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +[Paren](https://bitbucket.org/ktg/paren) - это диалект языка Лисп. Он спроектирован как встроенный язык. + +Примеры взяты <http://learnxinyminutes.com/docs/racket/>. + +```scheme +;;; Комментарии +# комментарии + +;; Однострочные комментарии начинаются с точки с запятой или символа решетки + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Примитивные типы данных и операторы +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Числа +123 ; int +3.14 ; double +6.02e+23 ; double +(int 3.14) ; => 3 : int +(double 123) ; => 123 : double + +;; Обращение к функции записывается так: (f x y z ...), +;; где f - функция, а x, y, z, ... - операнды +;; Если вы хотите создать буквальный список данных, используйте (quote), чтобы +;; предотвратить ненужные вычисления +(quote (+ 1 2)) ; => (+ 1 2) +;; Итак, некоторые арифметические операции +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(^ 2 3) ; => 8 +(/ 5 2) ; => 2 +(% 5 2) ; => 1 +(/ 5.0 2) ; => 2.5 + +;;; Логический тип +true ; обозначает истину +false ; обозначает ложь +(! true) ; => false +(&& true false (prn "досюда не доходим")) ; => false +(|| false true (prn "досюда не доходим")) ; => true + +;;; Символы - это числа (int). +(char-at "A" 0) ; => 65 +(chr 65) ; => "A" + +;;; Строки - это массив символов с фиксированной длиной. +"Привет, мир!" +"Benjamin \"Bugsy\" Siegel" ; обратная косая черта экранирует символ +"Foo\tbar\r\n" ; включает управляющие символы в стиле Cи: \t \r \n + +;; Строки тоже могут объединяться! +(strcat "Привет " "мир!") ; => "Привет мир!" + +;; Строка может трактоваться подобно списку символов +(char-at "Apple" 0) ; => 65 + +;; Выводить информацию достаточно легко +(pr "Я" "Paren. ") (prn "Приятно познакомиться!") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Переменные +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Вы можете создать или инициализировать переменную, используя (set) +;; имя переменной может содержать любой символ, исключая: ();#" +(set some-var 5) ; => 5 +some-var ; => 5 + +;; Обращение к переменной, прежде не определенной, вызовет исключение +; x ; => Неизвестная переменная: x : nil + +;; Локальное связывание: Используйте лямбда-вычисление! `a' и `b' связывается +;; с `1' и `2' только в пределах (fn ...) +((fn (a b) (+ a b)) 1 2) ; => 3 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Коллекции +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Списки + +;; Списки подобны динамическому массиву (vector). (произвольный доступ равен O(1).) +(cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) +;; `list' - это удобный конструктор списков с переменным числом элементов +(list 1 2 3) ; => (1 2 3) +;; и quote может также использоваться для литеральных значений списка +(quote (+ 1 2)) ; => (+ 1 2) + +;; Можно еще использовать `cons', чтобы добавить элемент в начало списка +(cons 0 (list 1 2 3)) ; => (0 1 2 3) + +;; Списки являются основным типом, поэтому для них предусмотрено *много* функций +;; немного примеров из них: +(map inc (list 1 2 3)) ; => (2 3 4) +(filter (fn (x) (== 0 (% x 2))) (list 1 2 3 4)) ; => (2 4) +(length (list 1 2 3 4)) ; => 4 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Функции +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Используйте `fn' для создания функций. +;; Функция всегда возвращает значение своего последнего выражения +(fn () "Привет Мир") ; => (fn () Привет Мир) : fn + +;; Используйте скобки, чтобы вызвать все функции, в том числе лямбда-выражение +((fn () "Привет Мир")) ; => "Привет Мир" + +;; Назначить функцию переменной +(set hello-world (fn () "Привет Мир")) +(hello-world) ; => "Привет Мир" + +;; Вы можете сократить это, используя синтаксический сахар определения функции: +(defn hello-world2 () "Привет Мир") + +;; Как и выше, () - это список аргументов для функции +(set hello + (fn (name) + (strcat "Привет " name))) +(hello "Стив") ; => "Привет Стив" + +;; ... или, что эквивалентно, используйте синтаксический сахар определения: +(defn hello2 (name) + (strcat "Привет " name)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Равенство +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; для чисел используйте `==' +(== 3 3.0) ; => true +(== 2 1) ; => false + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Поток управления +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Условный оператор + +(if true ; проверка выражения + "это - истина" ; тогда это выражение + "это - ложь") ; иначе другое выражение +; => "это - истина" + +;;; Циклы + +;; Цикл for для чисел +;; (for ИДЕНТИФИКАТОР НАЧАЛО КОНЕЦ ШАГ ВЫРАЖЕНИЕ ..) +(for i 0 10 2 (pr i "")) ; => печатает 0 2 4 6 8 10 +(for i 0.0 10 2.5 (pr i "")) ; => печатает 0 2.5 5 7.5 10 + +;; Цикл while +((fn (i) + (while (< i 10) + (pr i) + (++ i))) 0) ; => печатает 0123456789 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Изменение +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Используйте `set', чтобы назначить новое значение переменной или памяти +(set n 5) ; => 5 +(set n (inc n)) ; => 6 +n ; => 6 +(set a (list 1 2)) ; => (1 2) +(set (nth 0 a) 3) ; => 3 +a ; => (3 2) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Макросы +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Макросы позволяют вам расширять синтаксис языка. +;; Paren-макросы легкие. +;; Фактически, (defn) - это макрос. +(defmacro setfn (name ...) (set name (fn ...))) +(defmacro defn (name ...) (def name (fn ...))) + +;; Давайте добавим инфиксную нотацию +(defmacro infix (a op ...) (op a ...)) +(infix 1 + 2 (infix 3 * 4)) ; => 15 + +;; Макросы приводят к неясному коду, т.е. вы можете затереть существующие переменные! +;; Они являются кодопреобразующей конструкцией. +``` diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown index 53b2f916..37b6a86e 100644 --- a/ru-ru/php-ru.html.markdown +++ b/ru-ru/php-ru.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Trismegiste", "https://github.com/Trismegiste"] translators: - ["SlaF", "https://github.com/SlaF"] + - ["Corpsee", "https://github.com/corpsee"] lang: ru-ru filename: learnphp-ru.php --- @@ -14,8 +15,8 @@ filename: learnphp-ru.php ```php <?php // PHP код должен быть заключен в теги <?php -// Если ваш файл содержит только PHP код, то можно -// пропустить закрывающийся ?> +// Если ваш файл содержит только PHP-код, то можно +пропустить закрывающий ?> // А так начинаются комментарии @@ -30,10 +31,10 @@ filename: learnphp-ru.php print('Hello '); // Напечатать "Hello " без перевода строки // () необязательно применять для print и echo -echo "World\n"; // Печатать "World" и перейти на новую строку. +echo "World\n"; // Напечатать "World" и перейти на новую строку. // (все утверждения должны заканчиваться ;) -// Любые символы за пределами закрывающегося тега выводятся автоматически: +// Любые символы за пределами закрывающего тега выводятся автоматически: ?> Hello World Again! <?php @@ -46,7 +47,7 @@ Hello World Again! // Переменные начинаются с символа $. // Правильное имя переменной начинается с буквы или знака подчеркивания, // и может содержать любые цифры, буквы, или знаки подчеркивания. -// Не рекомендуется использовать кирилические символы в именах (прим. пер.) +// Не рекомендуется использовать кириллические символы в именах (прим. пер.) // Логические значения нечувствительны к регистру $boolean = true; // или TRUE или True @@ -56,7 +57,7 @@ $boolean = false; // или FALSE или False $int1 = 12; // => 12 $int2 = -12; // => -12- $int3 = 012; // => 10 (ведущий 0 обозначает восьмеричное число) -$int4 = 0x0F; // => 15 (ведущие символы 0x означает шестнадцатеричное число) +$int4 = 0x0F; // => 15 (ведущие символы 0x означают шестнадцатеричное число) // Дробные числа $float = 1.234; @@ -126,7 +127,7 @@ echo 'This outputs '.FOO; // Все массивы в PHP - это ассоциативные массивы или хеши, -// Ассоциативные массивы, известные в других языках как хеш-карты. +// Ассоциативные массивы, известные в других языках как HashMap. // Работает во всех версиях РHP $associative = array('One' => 1, 'Two' => 2, 'Three' => 3); @@ -199,13 +200,13 @@ assert($c > $b); // больше assert($a <= $b); // меньше или равно assert($c >= $d); // больше или равно -// Следующие утверждения истинны если переменные имеют одинаковый тип. +// Следующие утверждения истинны, если переменные имеют одинаковый тип. assert($c === $d); assert($a !== $d); assert(1 == '1'); assert(1 !== '1'); -// Переменные могут изменять тип, в зависимости от их использования. +// Переменные могут изменять тип в зависимости от их использования. $integer = 1; echo $integer + $integer; // => 2 @@ -235,7 +236,7 @@ $var = null; // Null $integer = 10; $boolen = settype($integer, "string") // теперь $integer имеет строковый тип -// settype возвращает true - если преобразование удалось и false в противном случае +// settype возвращает true, если преобразование удалось и false в противном случае /******************************** * Управляющие структуры @@ -311,7 +312,7 @@ echo "\n"; for ($x = 0; $x < 10; $x++) { echo $x; -} // Prints "0123456789" +} // Напечатает "0123456789" echo "\n"; @@ -320,7 +321,7 @@ $wheels = ['bicycle' => 2, 'car' => 4]; // Циклы foreach могут обходить массивы foreach ($wheels as $wheel_count) { echo $wheel_count; -} // Prints "24" +} // Напечатает "24" echo "\n"; @@ -337,14 +338,14 @@ while ($i < 5) { break; // Exit out of the while loop } echo $i++; -} // Prints "012" +} // Напечатает "012" for ($i = 0; $i < 5; $i++) { if ($i === 3) { continue; // Skip this iteration of the loop } echo $i; -} // Prints "0124" +} // Напечатает "0124" /******************************** @@ -369,7 +370,7 @@ function add ($x, $y = 1) { // $y по умолчанию равно 1 echo add(4); // => 5 echo add(4, 2); // => 6 -// $result недоступна за пределами функции +// $result недоступен за пределами функции // print $result; // Выдает предупреждение // Начиная с PHP 5.3 вы можете объявлять анонимные функции: @@ -402,27 +403,25 @@ echo $function_name(1, 2); // => 3 /******************************** - * Includes + * Включения */ <?php // PHP код внутри включаемого файла должен начинаться с тега PHP. include 'my-file.php'; -// Код в файле my-file.php теперь доступен в текущем в текущем пространстве имен. -// Если файл не удалось включить, будет выдано предупреждение. +// Код в файле my-file.php теперь доступен в текущем пространстве имен. +// Если файл не удалось подключить, то будет выдано предупреждение. include_once 'my-file.php'; -// Если код в файле my-file.php уже был включен, он не будет включен повторно. -// Это предотвращает ошибку повторного включения файла. +// Если код в файле my-file.php уже был подключен, он не будет подключен повторно. +// Это предотвращает ошибку повторного подключения файла. require 'my-file.php'; require_once 'my-file.php'; -// Same as include(), except require() will cause a fatal error if the -// file cannot be included. // Действует также как и include(), но если файл не удалось подключить, -// функция выдает неисправимую ошибку +// функция выдает фатальную ошибку // Содержимое файла my-include.php: <?php @@ -452,19 +451,19 @@ class MyClass static $staticVar = 'static'; - // Properties must declare their visibility + // Свойства объявляются с указанием их видимости public $property = 'public'; public $instanceProp; - protected $prot = 'protected'; // Accessible from the class and subclasses - private $priv = 'private'; // Accessible within the class only + protected $prot = 'protected'; // Свойство доступно только потомкам и самому классу + private $priv = 'private'; // Свойство доступно только самому классу - // Create a constructor with __construct + // Конструктор описывается с помощью __construct public function __construct($instanceProp) { - // Access instance variables with $this + // Доступ к эземпляру класса с помощью $this $this->instanceProp = $instanceProp; } - // Methods are declared as functions inside a class + // Методы объявляются как функции принадлежащие классу public function myMethod() { print 'MyClass'; @@ -484,7 +483,7 @@ echo MyClass::MY_CONST; // Выведет 'value'; echo MyClass::$staticVar; // Выведет 'static'; MyClass::myStaticMethod(); // Выведет 'I am static'; -// Новый экземпляр класса используя new +// Создание нового экземпляра класса используя new $my_class = new MyClass('An instance property'); // Если аргументы отсутствуют, можно не ставить круглые скобки @@ -502,7 +501,7 @@ class MyOtherClass extends MyClass echo $this->prot; } - // Override a method + // Переопределение родительского метода function myMethod() { parent::myMethod(); @@ -595,7 +594,7 @@ class SomeOtherClass implements InterfaceOne, InterfaceTwo * Трейты */ -// Трейты появились в PHP 5.4.0 и объявляются при помощи ключевого слова trait +// Трейты появились в PHP 5.4 и объявляются при помощи ключевого слова trait trait MyTrait { @@ -611,7 +610,7 @@ class MyTraitfulClass } $cls = new MyTraitfulClass(); -$cls->myTraitMethod(); // Prints "I have MyTrait" +$cls->myTraitMethod(); // Напечатает "I have MyTrait" /******************************** diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown index d59d3e21..43142eff 100644 --- a/ru-ru/python-ru.html.markdown +++ b/ru-ru/python-ru.html.markdown @@ -10,20 +10,20 @@ filename: learnpython-ru.py --- Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из -самых популярных языков. Я люблю его за понятный и доходчивый синтаксис — это -почти что исполняемый псевдокод. +самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это +почти исполняемый псевдокод. С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [почтовый сервис Google] -Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x. -Скоро будет версия и для Python 3! +Замечание: Эта статья относится к Python 2.7, но должно работать и в других версиях Python 2.x. +Чтобы изучить Python 3.x, обратитесь к статье по Python 3. ```python # Однострочные комментарии начинаются с символа решётки. """ Многострочный текст может быть записан, используя 3 знака " и обычно используется - в качестве комментария + в качестве встроенной документации """ #################################################### @@ -43,7 +43,7 @@ filename: learnpython-ru.py # целых чисел, и результат автоматически округляется в меньшую сторону. 5 / 2 #=> 2 -# Чтобы научиться делить, сначала нужно немного узнать о числах +# Чтобы делить правильно, сначала нужно немного узнать о числах # с плавающей запятой. 2.0 # Это число с плавающей запятой 11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше @@ -59,14 +59,22 @@ filename: learnpython-ru.py 7 % 3 # => 1 # Возведение в степень -2 ** 4 # => 16 +2**4 # => 16 # Приоритет операций указывается скобками (1 + 3) * 2 #=> 8 -# Логические (булевы) значения являются примитивами -True -False +# Логические операторы +# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв +True and False #=> False +False or True #=> True + +# Обратите внимание, что логические операторы используются и с целыми числами +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True # Для отрицания используется ключевое слово not not True #=> False @@ -86,7 +94,7 @@ not False #=> True 2 <= 2 #=> True 2 >= 2 #=> True -# Сравнения могут быть соединены в цепь! +# Сравнения могут быть записаны цепочкой! 1 < 2 < 3 #=> True 2 < 3 < 2 #=> False @@ -94,9 +102,12 @@ not False #=> True "Это строка." 'Это тоже строка.' -# И строки тоже могут складываться! +# И строки тоже можно складывать! "Привет " + "мир!" #=> "Привет мир!" +# ... или умножать +"Привет" * 3 # => "ПриветПриветПривет" + # Со строкой можно работать, как со списком символов "Это строка"[0] #=> 'Э' @@ -122,7 +133,7 @@ None is None #=> True # очень полезен при работе с примитивными типами, но # зато просто незаменим при работе с объектами. -# None, 0, и пустые строки/списки равны False. +# None, 0 и пустые строки/списки равны False. # Все остальные значения равны True 0 == False #=> True "" == False #=> True @@ -132,12 +143,14 @@ None is None #=> True ## 2. Переменные и коллекции #################################################### -# У Python есть функция Print, доступная в версиях 2.7 и 3, -print("Я Python. Приятно познакомиться!") -# ...и старый оператор print, доступный в версиях 2.x, но удалённый в версии 3. -print "И я тоже Python!" +# В Python есть оператор print, доступный в версиях 2.x, но удалённый в версии 3 +print "Я Python. Приятно познакомиться!" +# В Python также есть функция print(), доступная в версиях 2.7 и 3, +# Но для версии 2.7 нужно добавить следующий импорт модуля (раскомментируйте)): +# from __future__ import print_function +print("Я тоже Python! ") -# Необязательно объявлять переменные перед их инициализацией. +# Объявлять переменные перед инициализацией не нужно. some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями some_var #=> 5 @@ -151,9 +164,13 @@ some_other_var # Выбрасывает ошибку именования # Списки хранят последовательности li = [] -# Можно сразу начать с заполненным списком +# Можно сразу начать с заполненного списка other_li = [4, 5, 6] +# строка разделена в список +a="adambard" +list(a) #=> ['a','d','a','m','b','a','r','d'] + # Объекты добавляются в конец списка методом append li.append(1) # [1] li.append(2) # [1, 2] @@ -166,13 +183,17 @@ li.append(3) # [1, 2, 4, 3]. # Обращайтесь со списком, как с обычным массивом li[0] #=> 1 +# Присваивайте новые значения уже инициализированным индексам с помощью = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Обратите внимание: возвращаемся на исходное значение # Обратимся к последнему элементу li[-1] #=> 3 # Попытка выйти за границы массива приведёт к ошибке индекса li[4] # Выдаёт IndexError -# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax) +# Можно обращаться к диапазону, используя так называемые срезы # (Для тех, кто любит математику, это называется замкнуто-открытый интервал). li[1:3] #=> [2, 4] # Опускаем начало @@ -183,14 +204,15 @@ li[:3] #=> [1, 2, 4] li[::2] # =>[1, 4] # Переворачиваем список li[::-1] # => [3, 4, 2, 1] -# Используйте сочетания всего вышеназванного для выделения более сложных кусков +# Используйте сочетания всего вышеназванного для выделения более сложных срезов # li[начало:конец:шаг] # Удаляем произвольные элементы из списка оператором del -del li[2] # [1, 2, 3] +del li[2] # li теперь [1, 2, 3] -# Вы можете складывать списки +# Вы можете складывать, или, как ещё говорят, конкатенировать списки li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются +# Обратите внимание: значения li и other_li при этом не изменились. # Объединять списки можно методом extend li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6] @@ -220,13 +242,13 @@ d, e, f = 4, 5, 6 # Обратите внимание, как легко поменять местами значения двух переменных e, d = d, e # теперь d == 5, а e == 4 - # Словари содержат ассоциативные массивы empty_dict = {} # Вот так описывается предзаполненный словарь filled_dict = {"one": 1, "two": 2, "three": 3} -# Значения ищутся по ключу с помощью оператора [] +# Значения извлекаются так же, как из списка, с той лишь разницей, +# что индекс — у словарей он называется ключом — не обязан быть числом filled_dict["one"] #=> 1 # Можно получить все ключи в виде списка с помощью метода keys @@ -245,24 +267,33 @@ filled_dict.values() #=> [3, 2, 1] # Попытка получить значение по несуществующему ключу выбросит ошибку ключа filled_dict["four"] # KeyError -# Чтобы избежать этого, используйте метод get +# Чтобы избежать этого, используйте метод get() filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None # Метод get также принимает аргумент по умолчанию, значение которого будет # возвращено при отсутствии указанного ключа filled_dict.get("one", 4) #=> 1 filled_dict.get("four", 4) #=> 4 +# Обратите внимание, что filled_dict.get("four") всё ещё => None +# (get не устанавливает значение элемента словаря) -# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет +# Присваивайте значение ключам так же, как и в списках +filled_dict["four"] = 4 # теперь filled_dict["four"] => 4 + +# Метод setdefault() вставляет пару ключ-значение, только если такого ключа нет filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 # Множества содержат... ну, в общем, множества +# (которые похожи на списки, только в них не может быть дублирующихся элементов) empty_set = set() # Инициализация множества набором значений some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4]) +# Порядок сортировки не гарантируется, хотя иногда они выглядят отсортированными +another_set = set([4, 3, 2, 2, 1]) # another_set теперь set([1, 2, 3, 4]) + # Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} @@ -345,7 +376,7 @@ try: # Чтобы выбросить ошибку, используется raise raise IndexError("Это ошибка индекса") except IndexError as e: - # pass это просто отсутствие оператора. Обычно здесь происходит + # pass — это просто отсутствие оператора. Обычно здесь происходит # восстановление после ошибки. pass except (TypeError, NameError): @@ -362,7 +393,7 @@ else: # Необязательное выражение. Должно след # Используйте def для создания новых функций def add(x, y): print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат выражением return + return x + y # Возвращайте результат с помощью ключевого слова return # Вызов функции с аргументами add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 @@ -370,15 +401,17 @@ add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвр # Другой способ вызова функции — вызов с именованными аргументами add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. -# Вы можете определить функцию, принимающую изменяемое число аргументов +# Вы можете определить функцию, принимающую переменное число аргументов, +# которые будут интерпретированы как кортеж, если вы не используете * def varargs(*args): return args varargs(1, 2, 3) #=> (1,2,3) -# А также можете определить функцию, принимающую изменяемое число -# именованных аргументов +# А также можете определить функцию, принимающую переменное число +# именованных аргументов, которые будут интерпретированы как словарь, +# если вы не используете ** def keyword_args(**kwargs): return kwargs @@ -396,13 +429,21 @@ all_the_args(1, 2, a=3, b=4) выводит: """ # Вызывая функции, можете сделать наоборот! -# Используйте символ * для передачи кортежей и ** для передачи словарей +# Используйте символ * для распаковки кортежей и ** для распаковки словарей args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) all_the_args(**kwargs) # эквивалентно foo(a=3, b=4) all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4) +# вы можете передавать переменное число позиционных или именованных аргументов +# другим функциям, которые их принимают, распаковывая их с помощью +# * или ** соответственно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + # Область определения функций x = 5 @@ -420,7 +461,7 @@ def setGlobalX(num): setX(43) setGlobalX(6) -# В Python есть функции первого класса +# В Python функции — «объекты первого класса» def create_adder(x): def adder(y): return x + y @@ -514,6 +555,9 @@ from math import * # Можете сокращать имена модулей import math as m math.sqrt(16) == m.sqrt(16) #=> True +# Вы также можете убедиться, что функции эквивалентны +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True # Модули в Python — это обычные Python-файлы. Вы # можете писать свои модули и импортировать их. Название @@ -544,7 +588,7 @@ def double_numbers(iterable): # мы используем подчёркивание в конце xrange_ = xrange(1, 900000000) -# Будет удваивать все числа, пока результат не будет >= 30 +# Будет удваивать все числа, пока результат не превысит 30 for i in double_numbers(xrange_): print(i) if i >= 30: diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index 637c0157..2a7b3f7b 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -10,7 +10,7 @@ filename: learnpython3-ru.py --- Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из -самых популярных языков. Я люблю его за понятный и доходчивый синтаксис — это +самых популярных языков. Я влюбился в Python за понятный и доходчивый синтаксис — это почти что исполняемый псевдокод. С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) @@ -56,7 +56,7 @@ filename: learnpython3-ru.py 7 % 3 # => 1 # Возведение в степень -2 ** 4 # => 16 +2**4 # => 16 # Приоритет операций указывается скобками (1 + 3) * 2 #=> 8 @@ -69,6 +69,18 @@ False not True #=> False not False #=> True +# Логические операторы +# Обратите внимание: ключевые слова «and» и «or» чувствительны к регистру букв +True and False #=> False +False or True #=> True + +# Обратите внимание, что логические операторы используются и с целыми числами +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + # Равенство — это == 1 == 1 #=> True 2 == 1 #=> False @@ -91,7 +103,7 @@ not False #=> True "Это строка." 'Это тоже строка.' -# И строки тоже могут складываться! Хотя лучше этого не делайте. +# И строки тоже могут складываться! Хотя лучше не злоупотребляйте этим. "Привет " + "мир!" #=> "Привет мир!" # Со строкой можно работать, как со списком символов @@ -134,10 +146,10 @@ bool({}) #=> False ## 2. Переменные и коллекции #################################################### -# У Python есть функция Print +# В Python есть функция Print print("Я Python. Приятно познакомиться!") -# Необязательно объявлять переменные перед их инициализацией. +# Объявлять переменные перед инициализацией не нужно. # По соглашению используется нижний_регистр_с_подчёркиваниями some_var = 5 some_var #=> 5 @@ -149,7 +161,7 @@ some_unknown_var # Выбрасывает ошибку именования # Списки хранят последовательности li = [] -# Можно сразу начать с заполненным списком +# Можно сразу начать с заполненного списка other_li = [4, 5, 6] # Объекты добавляются в конец списка методом append @@ -170,7 +182,7 @@ li[-1] #=> 3 # Попытка выйти за границы массива приведёт к ошибке индекса li[4] # Выдаёт IndexError -# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax) +# Можно обращаться к диапазону, используя так называемые срезы # (Для тех, кто любит математику, это называется замкнуто-открытый интервал). li[1:3] #=> [2, 4] # Опускаем начало @@ -181,13 +193,14 @@ li[:3] #=> [1, 2, 4] li[::2] # =>[1, 4] # Переворачиваем список li[::-1] # => [3, 4, 2, 1] -# Используйте сочетания всего вышеназванного для выделения более сложных кусков +# Используйте сочетания всего вышеназванного для выделения более сложных срезов # li[начало:конец:шаг] # Удаляем произвольные элементы из списка оператором del del li[2] # [1, 2, 3] -# Вы можете складывать списки +# Вы можете складывать, или, как ещё говорят, конкатенировать списки +# Обратите внимание: значения li и other_li при этом не изменились. li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются # Объединять списки можно методом extend @@ -224,10 +237,11 @@ empty_dict = {} # Вот так описывается предзаполненный словарь filled_dict = {"one": 1, "two": 2, "three": 3} -# Значения ищутся по ключу с помощью оператора [] +# Значения извлекаются так же, как из списка, с той лишь разницей, +# что индекс — у словарей он называется ключом — не обязан быть числом filled_dict["one"] #=> 1 -# Все значения в виде списка получаются с помощью метода keys(). +# Все ключи в виде списка получаются с помощью метода keys(). # Его вызов нужно обернуть в list(), так как обратно мы получаем # итерируемый объект, о которых поговорим позднее. list(filled_dict.keys()) # => ["three", "two", "one"] @@ -247,7 +261,7 @@ list(filled_dict.values()) # => [3, 2, 1] # Попытка получить значение по несуществующему ключу выбросит ошибку ключа filled_dict["four"] # KeyError -# Чтобы избежать этого, используйте метод get +# Чтобы избежать этого, используйте метод get() filled_dict.get("one") #=> 1 filled_dict.get("four") #=> None # Метод get также принимает аргумент по умолчанию, значение которого будет @@ -259,6 +273,10 @@ filled_dict.get("four", 4) #=> 4 filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5 filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5 +# Добавление элементов в словарь +filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4} +#filled_dict["four"] = 4 # Другой способ добавления элементов + # Удаляйте ключи из словаря с помощью оператора del del filled_dict["one"] # Удаляет ключ «one» из словаря @@ -345,7 +363,7 @@ try: # Чтобы выбросить ошибку, используется raise raise IndexError("Это ошибка индекса") except IndexError as e: - # pass это просто отсутствие оператора. Обычно здесь происходит + # pass — это просто отсутствие оператора. Обычно здесь происходит # восстановление после ошибки. pass except (TypeError, NameError): @@ -393,7 +411,7 @@ list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"] # Используйте def для создания новых функций def add(x, y): print("x равен %s, а y равен %s" % (x, y)) - return x + y # Возвращайте результат выражением return + return x + y # Возвращайте результат с помощью ключевого слова return # Вызов функции с аргументами add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11 @@ -401,14 +419,14 @@ add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвр # Другой способ вызова функции — вызов с именованными аргументами add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке. -# Вы можете определить функцию, принимающую изменяемое число аргументов +# Вы можете определить функцию, принимающую переменное число аргументов def varargs(*args): return args varargs(1, 2, 3) #=> (1,2,3) -# А также можете определить функцию, принимающую изменяемое число +# А также можете определить функцию, принимающую переменное число # именованных аргументов def keyword_args(**kwargs): return kwargs @@ -427,7 +445,7 @@ all_the_args(1, 2, a=3, b=4) выводит: """ # Вызывая функции, можете сделать наоборот! -# Используйте символ * для передачи кортежей и ** для передачи словарей +# Используйте символ * для распаковки кортежей и ** для распаковки словарей args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # эквивалентно foo(1, 2, 3, 4) @@ -451,7 +469,7 @@ def setGlobalX(num): setX(43) setGlobalX(6) -# В Python функции — «объекты первого класса». Это означает, что их можно использовать наравне с любыми другими значениями +# В Python функции — «объекты первого класса» def create_adder(x): def adder(y): return x + y @@ -575,7 +593,7 @@ def double_numbers(iterable): range_ = range(1, 900000000) # Будет удваивать все числа, пока результат не превысит 30 -for i in double_numbers(xrange_): +for i in double_numbers(range_): print(i) if i >= 30: break diff --git a/ru-ru/ruby-ru.html.markdown b/ru-ru/ruby-ru.html.markdown index 318e0e09..69b5fb46 100644 --- a/ru-ru/ruby-ru.html.markdown +++ b/ru-ru/ruby-ru.html.markdown @@ -158,6 +158,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6] hash = {'color' => 'green', 'number' => 5} hash.keys #=> ['color', 'number'] +hash.values #=> ['green', 5] # Значение в хэше легко может быть найдено по ключу: hash['color'] #=> 'green' diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown new file mode 100644 index 00000000..77987bb3 --- /dev/null +++ b/ru-ru/swift-ru.html.markdown @@ -0,0 +1,589 @@ +--- +language: swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] + - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] +filename: learnswift-ru.swift +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +Swift - это язык программирования, созданный компанией Apple, для приложений +под iOS и OS X. Разработанный, чтобы сосуществовать с Objective-C и +быть более устойчивым к ошибочному коду, Swift был представлен в 2014 году на +конференции разработчиков Apple, WWDC. Приложения на Swift собираются +с помощью LLVM-компилятора, включенного в Xcode 6+. + +Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в iBooks. + +Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) Apple, которое содержит полное учебное пособие по Swift. + +```swift +// импорт модуля +import UIKit + +// +// MARK: Основы +// + +// Xcode поддерживает маркеры, чтобы давать примечания своему коду +// и вносить их в список обозревателя (Jump Bar) +// MARK: Метка раздела +// TODO: Сделайте что-нибудь вскоре +// FIXME: Исправьте этот код + +println("Привет, мир") + +// переменные (var), значение которых можно изменить после инициализации +// константы (let), значение которых нельзя изменить после инициализации + +var myVariable = 42 +let øπΩ = "значение" // именование переменной символами unicode +let π = 3.1415926 +let convenience = "Ключевое слово" // контекстное имя переменной +let weak = "Ключевое слово"; let override = "еще ключевое слово" // операторы + // могут быть отделены точкой с запятой +let `class` = "Ключевое слово" // обратные апострофы позволяют использовать + // ключевые слова в именовании переменных +let explicitDouble: Double = 70 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "некоторый текст " + String(myVariable) // Приведение типа +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // Вставка переменных в строку + +// Сборка особых значений +// используя ключ -D сборки конфигурации +#if false + println("Не печатается") + let buildValue = 3 +#else + let buildValue = 7 +#endif +println("Значение сборки: \(buildValue)") // Значение сборки: 7 + +/* + Опционалы - это особенность языка Swift, которая допускает вам сохранять + `некоторое` или `никакое` значения. + + Язык Swift требует, чтобы каждое свойство имело значение, поэтому даже nil + должен быть явно сохранен как опциональное значение. + + Optional<T> является перечислением. +*/ +var someOptionalString: String? = "опционал" // Может быть nil +// как и выше, только ? - это постфиксный оператор (синтаксический сахар) +var someOptionalString2: Optional<String> = "опционал" + +if someOptionalString != nil { + // я не nil + if someOptionalString!.hasPrefix("opt") { + println("содержит префикс") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +// неявная развертка опциональной переменной +var unwrappedString: String! = "Ожидаемое значение." +// как и выше, только ! - постфиксный оператор (с еще одним синтаксическим сахаром) +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Ожидаемое значение." + +if let someOptionalStringConstant = someOptionalString { + // имеется некоторое значение, не nil + if !someOptionalStringConstant.hasPrefix("ok") { + // нет такого префикса + } +} + +// Swift поддерживает сохранение значения любого типа +// AnyObject == id +// В отличие от `id` в Objective-C, AnyObject работает с любым значением (Class, +// Int, struct и т.д.) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Изменять значение на строку не является хорошей практикой, но возможно." + +/* + Комментируйте здесь + + /* + Вложенные комментарии тоже поддерживаются + */ +*/ + +// +// MARK: Коллекции +// + +/* + Массив (Array) и словарь (Dictionary) являются структурами (struct). Так + `let` и `var` также означают, что они изменяются (var) или не изменяются (let) + при объявлении переменных этих типов. +*/ + +// Массив +var shoppingList = ["сом", "вода", "лимоны"] +shoppingList[1] = "бутылка воды" +let emptyArray = [String]() // let == неизменный +let emptyArray2 = Array<String>() // как и выше +var emptyMutableArray = [String]() // var == изменяемый + + +// Словарь +var occupations = [ + "Malcolm": "Капитан", + "kaylee": "Техник" +] +occupations["Jayne"] = "Связи с общественностью" +let emptyDictionary = [String: Float]() // let == неизменный +let emptyDictionary2 = Dictionary<String, Float>() // как и выше +var emptyMutableDictionary = [String: Float]() // var == изменяемый + + +// +// MARK: Поток управления +// + +// цикл for для массива +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("Один!") + } else { + println("Не один!") + } +} + +// цикл for для словаря +var dict = ["один": 1, "два": 2] +for (key, value) in dict { + println("\(key): \(value)") +} + +// цикл for для диапазона чисел +for i in -1...shoppingList.count { + println(i) +} +shoppingList[1...2] = ["бифштекс", "орехи пекан"] +// используйте ..< для исключения последнего числа + +// цикл while +var i = 1 +while i < 1000 { + i *= 2 +} + +// цикл do-while +do { + println("привет") +} while 1 == 2 + +// Переключатель +// Очень мощный оператор, представляйте себе операторы `if` с синтаксическим +// сахаром +// Они поддерживают строки, объекты и примитивы (Int, Double, etc) +let vegetable = "красный перец" +switch vegetable { +case "сельдерей": + let vegetableComment = "Добавьте немного изюма, имитируя муравьев на бревнышке." +case "огурец", "кресс-салат": + let vegetableComment = "Было бы неплохо сделать бутерброд с чаем." +case let localScopeValue where localScopeValue.hasSuffix("перец"): + let vegetableComment = "Это острый \(localScopeValue)?" +default: // обязательный (чтобы предусмотреть все возможные вхождения) + let vegetableComment = "В супе все овощи вкусные." +} + + +// +// MARK: Функции +// + +// Функции являются типом первого класса, т.е. они могут быть вложены в функциях +// и могут передаваться между собой + +// Функция с документированным заголовком Swift (формат reStructedText) + +/** + Операция приветствия + + - Маркер в документировании + - Еще один маркер в документации + + :param: name - это имя + :param: day - это день + :returns: Строка, содержащая значения name и day. +*/ +func greet(name: String, day: String) -> String { + return "Привет \(name), сегодня \(day)." +} +greet("Боб", "вторник") + +// как и выше, кроме обращения параметров функции +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Привет \(requiredName), сегодня \(localParamName)" +} +greet2(requiredName:"Иван", externalParamName: "воскресенье") + +// Функция, которая возвращает множество элементов в кортеже +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// Пропускайте значения кортежей с помощью подчеркивания _ +let (_, price1, _) = pricesTuple // price1 == 3.69 +println(price1 == pricesTuple.1) // вывод: true +println("Цена газа: \(price)") + +// Переменное число аргументов +func setup(numbers: Int...) { + // это массив + let number = numbers[0] + let argCount = numbers.count +} + +// Передача и возврат функций +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + +// передача по ссылке +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +println(someIntB) // 7 + + +// +// MARK: Замыкания +// +var numbers = [1, 2, 6] + +// Функции - это частный случай замыканий ({}) + +// Пример замыкания. +// `->` отделяет аргументы и возвращаемый тип +// `in` отделяет заголовок замыкания от тела замыкания +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result +}) + +// Когда тип известен, как и выше, мы можем сделать так +numbers = numbers.map({ number in 3 * number }) +// Или даже так +//numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// Хвостовое замыкание +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Суперсокращение, поскольку оператор < выполняет логический вывод типов + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18] + +// +// MARK: Структуры +// + +// Структуры и классы имеют очень похожие характеристики +struct NamesTable { + let names = [String]() + + // Пользовательский индекс + subscript(index: Int) -> String { + return names[index] + } +} + +// У структур автогенерируемый (неявно) инициализатор +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +println("Name is \(name)") // Name is Them + +// +// MARK: Классы +// + +// Классы, структуры и их члены имеют трехуровневый контроль доступа +// Уровни: internal (по умолчанию), public, private + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// Все методы и свойства класса являются открытыми (public). +// Если вам необходимо содержать только данные +// в структурированном объекте, вы должны использовать `struct` + +internal class Rect: Shape { + var sideLength: Int = 1 + + // Пользовательский сеттер и геттер + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` - неявная переменная, доступная в сеттере + sideLength = newValue / 4 + } + } + + // Ленивая загрузка свойства + // свойство subShape остается равным nil (неинициализированным), + // пока не вызовется геттер + lazy var subShape = Rect(sideLength: 4) + + // Если вам не нужны пользовательские геттеры и сеттеры, + // но все же хотите запустить код перед и после вызовов геттера или сеттера + // свойств, вы можете использовать `willSet` и `didSet` + var identifier: String = "defaultID" { + // аргумент у `willSet` будет именем переменной для нового значения + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(sideLength: Int) { + self.sideLength = sideLength + // последним всегда вызывается super.init, когда init с параметрами + super.init() + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} + +// Простой класс `Square` наследует `Rect` +class Square: Rect { + convenience init() { + self.init(sideLength: 5) + } +} + +var mySquare = Square() +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// преобразование объектов +let aShape = mySquare as Shape + +// сравнение экземпляров, в отличие от ==, которая проверяет эквивалентность +if mySquare === mySquare { + println("Ага, это mySquare") +} + +// Опциональная инициализация (init) +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Поместите постфиксный знак вопроса после `init` - это и будет опциональная инициализация, + // которая может вернуть nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +println(myCircle?.getArea()) // Optional(3) +println(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +println(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // не будет выполняться, поскольку myEmptyCircle равен nil + println("circle не nil") +} + + +// +// MARK: Перечисления +// + +// Перечисления могут быть определенного или своего типа. +// Они могут содержать методы подобно классам. + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// Значения перечислений допускают сокращенный синтаксис, нет необходимости +// указывать тип перечисления, когда переменная объявляется явно +var suitValue: Suit = .Hearts + +// Нецелочисленные перечисления требуют прямого указания значений +enum BookName: String { + case John = "Иоанн" + case Luke = "Лука" +} +println("Имя: \(BookName.John.rawValue)") + +// Перечисление (enum) со связанными значениями +enum Furniture { + // Связать с типом Int + case Desk(height: Int) + // Связать с типами String и Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Письменный стол высотой \(height) см." + case .Chair(let brand, let height): + return "Стул марки \(brand) высотой \(height) см." + } + } +} + +var desk: Furniture = .Desk(height: 80) +println(desk.description()) // "Письменный стол высотой 80 см." +var chair = Furniture.Chair("Foo", 40) +println(chair.description()) // "Стул марки Foo высотой 40 см." + + +// +// MARK: Протоколы +// + +// `protocol` может потребовать, чтобы у соответствующих типов +// были определенные свойства экземпляра, методы экземпляра, тип методов, +// операторы и индексы. + +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// Протоколы, объявленные с @objc, допускают необязательные функции, +// которые позволяют вам проверять на соответствие +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + // Размещайте знак вопроса перед опционным свойством, методом + // или индексом, чтобы не учитывать nil-значение и возвратить nil + // вместо выбрасывания ошибки выполнения (т.н. "опционная цепочка") + if let allow = self.delegate?.canReshape?() { + // проверка делегата на выполнение метода + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: Прочее +// + +// `extension`s: Добавляет расширенный функционал к существующему типу + +// Класс Square теперь "соответствует" протоколу `Printable` +extension Square: Printable { + var description: String { + return "Площадь: \(self.getArea()) - ID: \(self.identifier)" + } +} + +println("Объект Square: \(mySquare)") + +// Вы также можете расширить встроенные типы +extension Int { + var customProperty: String { + return "Это \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +println(7.customProperty) // "Это 7" +println(14.multiplyBy(3)) // 42 + +// Обобщения: Подобно языкам Java и C#. Используйте ключевое слово `where`, +// чтобы определить условия обобщений. + +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // вывод: true + +// Операторы: +// Пользовательские операторы могут начинаться с символов: +// / = - + * % < > ! & | ^ . ~ +// или +// Unicode- знаков математики, символов, стрелок, декорации и линий/кубов, +// нарисованных символов. +prefix operator !!! {} + +// Префиксный оператор, который утраивает длину стороны, когда используется +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// текущее значение +println(mySquare.sideLength) // 4 + +// Используя пользовательский оператор !!!, изменится длина стороны +// путем увеличения размера в 3 раза +!!!mySquare +println(mySquare.sideLength) // 12 +``` diff --git a/ru-ru/xml-ru.html.markdown b/ru-ru/xml-ru.html.markdown new file mode 100644 index 00000000..b0096b75 --- /dev/null +++ b/ru-ru/xml-ru.html.markdown @@ -0,0 +1,130 @@ +--- +language: xml +filename: learnxml-ru.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] +lang: ru-ru +--- + +XML - это язык разметки, предназначенный для хранения и передачи данных. + +В отличие от HTML, XML не определяет, как отображать или форматировать данные, он только содержит их. + +* XML-Синтаксис + +```xml +<!-- Комментарии в XML выглядят вот так --> + +<?xml version="1.0" encoding="UTF-8"?> +<bookstore> + <book category="КУЛИНАРИЯ"> + <title lang="ru">Итальянская кухня каждый день</title> + <author>Giada De Laurentiis</author> + <year>2005</year> + <price>30.00</price> + </book> + <book category="ДЕТИ"> + <title lang="ru">Гарри Поттер</title> + <author>Дж. К. Роулинг</author> + <year>2005</year> + <price>29.99</price> + </book> + <book category="ВСЕМИРНАЯ ПАУТИНА"> + <title lang="ru">Изучаем XML</title> + <author>Эрик Рэй</author> + <year>2003</year> + <price>39.95</price> + </book> +</bookstore> + +<!-- Вышеописанный документ - типичный XML-файл. + Он начинается с определения, объявляющего о некоторых метаданных (необязательно). + + XML использует древовидную структуру. У вышеописанного документа + корневой узел - 'bookstore', который содержит три дочерних узла - все 'book'-узлы. + Такие узлы содержат еще дочерние узлы и т.д. + + Узлы создаются с помощью открывающих/закрывающих тегов, + а дочерние узлы - это узлы между открывающимися и закрывающимися тегами.--> + + +<!-- XML содержит в себе два типа данных: + 1 - Атрибуты -> Это метаданные узлов. + Обычно XML-парсер использует эту информацию, чтобы хранить свойства данных. + Атрибут изображается путем вписывания его в скобки в пределах открытого тега + 2 - Элементы -> Это чистые данные. + Это то, что парсер извлечет из XML-файла. + Элементы идут между открытыми и закрытыми тегами без скобок. --> + + +<!-- Ниже элемент с двумя атрибутами --> +<file type="gif" id="4293">компьютер.gif</file> + + +``` + +* Хорошо отформатированный документ x Проверка достоверности + +XML-документ хорошо отформатирован, если он синтаксически верный. +Впрочем, в документ возможно ввести больше ограничений, +используя определения документа, вроде DTD и XML-схемы. + +XML-документ, который следует описанию документа, называется корректным, +относительно этого документа. + +С таким инструментом вы можете проверить XML-данные вне логики приложения. + +```xml + +<!-- Ниже вы можете увидеть упрощенную версию документа книжного магазина, + с дополнением DTD-определения.--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<bookstore> + <book category="КУЛИНАРИЯ"> + <title >Итальянская кухня каждый день</title> + <price>30.00</price> + </book> +</bookstore> + +<!-- Этот DTD может быть чем-то вроде:--> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Литература"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + + +<!-- DTD начинается с объявления. + Затем объявляется корневой узел, требующий 1 или более дочерних узлов 'book'. + Каждый 'book' должен содержать точно один 'title' и 'price', и атрибут, + называемый 'category', со значением "Литература" по умолчанию. + Узлы 'title' и 'price' содержат анализируемые символьные данные.--> + +<!-- DTD может быть объявлен в самом XML-файле.--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Литература"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + +<bookstore> + <book category="КУЛИНАРИЯ"> + <title >Итальянская кухня каждый день</title> + <price>30.00</price> + </book> +</bookstore> +``` diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 8b292edd..1fbcc752 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -42,7 +42,7 @@ 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. * 1.9.3 - Released in October 2011. This is the version most rubyists use - currently. + currently. Also [retired](https://www.ruby-lang.org/en/news/2015/02/23/support-for-ruby-1-9-3-has-ended/) * 1.8.7 - Ruby 1.8.7 has been [retired](http://www.ruby-lang.org/en/news/2013/06/30/we-retire-1-8-7/). @@ -54,7 +54,7 @@ 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 -unique strengths and states of compatability. To be clear, the different +unique strengths and states of compatibility. To be clear, the different 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 diff --git a/ruby.html.markdown b/ruby.html.markdown index 7cf5bdc7..243f788b 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -11,7 +11,10 @@ contributors: - ["Ariel Krakowski", "http://www.learneroo.com"] - ["Dzianis Dashkevich", "https://github.com/dskecse"] - ["Levi Bostian", "https://github.com/levibostian"] - + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gabriel Halley", "https://github.com/ghalley"] + - ["Persa Zula", "http://persazula.com"] + - ["Jake Faris", "https://github.com/farisj"] --- ```ruby @@ -38,6 +41,12 @@ You shouldn't either 10 * 2 #=> 20 35 / 5 #=> 7 2**5 #=> 32 +5 % 3 #=> 2 + +# Bitwise operators +3 & 5 #=> 1 +3 | 5 #=> 7 +3 ^ 5 #=> 6 # Arithmetic is just syntactic sugar # for calling a method on an object @@ -45,7 +54,7 @@ You shouldn't either 10.* 5 #=> 50 # Special values are objects -nil # Nothing to see here +nil # equivalent to null in other languages true # truth false # falsehood @@ -60,8 +69,6 @@ false.class #=> FalseClass # Inequality 1 != 1 #=> false 2 != 1 #=> true -!true #=> false -!false #=> true # apart from false itself, nil is the only other 'falsey' value @@ -75,6 +82,26 @@ false.class #=> FalseClass 2 <= 2 #=> true 2 >= 2 #=> true +# Combined comparison operator +1 <=> 10 #=> -1 +10 <=> 1 #=> 1 +1 <=> 1 #=> 0 + +# Logical operators +true && false #=> false +true || false #=> true +!true #=> false + +# There are alternate versions of the logical operators with much lower +# precedence. These are meant to be used as flow-control constructs to chain +# statements together until one of them returns true or false. + +# `do_something_else` only called if `do_something` succeeds. +do_something() and do_something_else() +# `log_error` only called if `do_something` fails. +do_something() or log_error() + + # Strings are objects 'I am a string'.class #=> String @@ -92,8 +119,20 @@ placeholder = 'use string interpolation' 'hello ' + 3 #=> TypeError: can't convert Fixnum into String 'hello ' + 3.to_s #=> "hello 3" -# print to the output +# Combine strings and operators +'hello ' * 3 #=> "hello hello hello " + +# Append to string +'hello' << ' world' #=> "hello world" + +# print to the output with a newline at the end puts "I'm printing!" +#=> I'm printing! +#=> nil + +# print to the output without a newline +print "I'm printing!" +#=> I'm printing! => nil # Variables x = 25 #=> 25 @@ -140,6 +179,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Arrays can be indexed # From the front array[0] #=> 1 +array.first #=> 1 array[12] #=> nil # Like arithmetic, [var] access @@ -150,15 +190,25 @@ array.[] 12 #=> nil # From the end array[-1] #=> 5 +array.last #=> 5 # With a start index and length array[2, 3] #=> [3, 4, 5] +# Reverse an Array +a=[1,2,3] +a.reverse! #=> [3,2,1] + # Or with a range array[1..3] #=> [2, 3, 4] # Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] +# Or like this +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Check if an item exists in an array +array.include?(1) #=> true # Hashes are Ruby's primary dictionary with keys/value pairs. # Hashes are denoted with curly braces: @@ -179,6 +229,10 @@ new_hash = { defcon: 3, action: true } new_hash.keys #=> [:defcon, :action] +# Check existence of keys and values in hash +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + # Tip: Both Arrays and Hashes are Enumerable # They share a lot of useful methods such as each, map, count, and more @@ -231,6 +285,12 @@ hash.each do |key, value| puts "#{key} is #{value}" end +# If you still need and index you can use "each_with_index" and define an index +# variable +array.each_with_index do |element, index| + puts "#{element} is number #{index} in the array" +end + counter = 1 while counter <= 5 do puts "iteration #{counter}" @@ -242,6 +302,19 @@ end #=> iteration 4 #=> iteration 5 +# There are a bunch of other helpful looping functions in Ruby, +# for example "map", "reduce", "inject", the list goes on. Map, +# for instance, takes the array it's looping over, does something +# to it as defined in your block, and returns an entirely new array. +array = [1,2,3,4,5] +doubled = array.map do |element| + element * 2 +end +puts doubled +#=> [2,4,6,8,10] +puts array +#=> [1,2,3,4,5] + grade = 'B' case grade @@ -280,9 +353,9 @@ rescue NoMemoryError => exception_variable puts 'NoMemoryError was raised', exception_variable rescue RuntimeError => other_exception_variable puts 'RuntimeError was raised now' -else +else puts 'This runs if no exceptions were thrown at all' -ensure +ensure puts 'This code always runs no matter what' end diff --git a/rust.html.markdown b/rust.html.markdown index 3717a7d9..d0c56b4a 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -5,11 +5,22 @@ contributors: 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. +Rust is a programming language developed by Mozilla Research. +Rust combines low-level control over performance with high-level convenience and +safety guarantees. + +It achieves these goals without requiring a garbage collector or runtime, making +it possible to use Rust libraries as a "drop-in replacement" for C. + +Rust’s first release, 0.1, occurred in January 2012, and for 3 years development +moved so quickly that until recently the use of stable releases was discouraged +and instead the general advice was to use nightly builds. + +On May 15th 2015, Rust 1.0 was released with a complete guarantee of backward +compatibility. Improvements to compile times and other aspects of the compiler are +currently available in the nightly builds. Rust has adopted a train-based release +model with regular releases every six weeks. Rust 1.1 beta was made available at +the same time of the release of Rust 1.0. Although Rust is a relatively low-level language, Rust has some functional concepts that are generally found in higher-level languages. This makes @@ -24,7 +35,8 @@ Rust not only fast, but also easy and efficient to code in. /////////////// // Functions -fn add2(x: int, y: int) -> int { +// `i32` is the type for 32-bit signed integers +fn add2(x: i32, y: i32) -> i32 { // Implicit return (no semicolon) x + y } @@ -34,71 +46,90 @@ fn main() { // Numbers // // Immutable bindings - let x: int = 1; + let x: i32 = 1; // Integer/float suffixes - let y: int = 13i; + let y: i32 = 13i32; let f: f64 = 1.3f64; // Type inference - let implicit_x = 1i; - let implicit_f = 1.3f64; + // Most of the time, the Rust compiler can infer what type a variable is, so + // you don’t have to write an explicit type annotation. + // Throughout this tutorial, types are explicitly annotated in many places, + // but only for demonstrative purposes. Type inference can handle this for + // you most of the time. + let implicit_x = 1; + let implicit_f = 1.3; - // Maths - let sum = x + y + 13i; + // Arithmetic + let sum = x + y + 13; // Mutable variable let mut mutable = 1; + mutable = 4; mutable += 2; // Strings // - + // String literals - let x: &'static str = "hello world!"; + let x: &str = "hello world!"; // Printing println!("{} {}", f, x); // 1.3 hello world - // A `String` - a heap-allocated string + // 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 + // A string slice – an immutable view into another string + // This is basically an immutable pointer to a string – it doesn’t + // actually contain the contents of a string, just a pointer to // something that does (in this case, `s`) - let s_slice: &str = s.as_slice(); + let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world // Vectors/arrays // // A fixed-size array - let four_ints: [int, ..4] = [1, 2, 3, 4]; + let four_ints: [i32; 4] = [1, 2, 3, 4]; - // A dynamically-sized vector - let mut vector: Vec<int> = vec![1, 2, 3, 4]; + // A dynamic array (vector) + let mut vector: Vec<i32> = vec![1, 2, 3, 4]; vector.push(5); - // A slice - an immutable view into a vector or array + // 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(); + let slice: &[i32] = &vector; + + // Use `{:?}` to print something debug-style + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // + + // A tuple is a fixed-size set of values of possibly different types + let x: (i32, &str, f64) = (1, "hello", 3.4); - println!("{} {}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + // Destructuring `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // Indexing + println!("{}", x.1); // hello ////////////// // 2. Types // ////////////// - + // Struct struct Point { - x: int, - y: int, + x: i32, + y: i32, } let origin: Point = Point { x: 0, y: 0 }; - // Tuple struct - struct Point2(int, int); + // A struct with unnamed fields, called a ‘tuple struct’ + struct Point2(i32, i32); let origin2 = Point2(0, 0); @@ -110,16 +141,16 @@ fn main() { Down, } - let up = Up; + let up = Direction::Up; // Enum with fields - enum OptionalInt { - AnInt(int), + enum OptionalI32 { + AnI32(i32), Nothing, } - let two: OptionalInt = AnInt(2); - let nothing: OptionalInt = Nothing; + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; // Generics // @@ -140,10 +171,10 @@ fn main() { } } - let a_foo = Foo { bar: 1i }; + let a_foo = Foo { bar: 1 }; println!("{}", a_foo.get_bar()); // 1 - // Traits (interfaces) // + // Traits (known as interfaces or typeclasses in other languages) // trait Frobnicate<T> { fn frobnicate(self) -> Option<T>; @@ -155,30 +186,31 @@ fn main() { } } - println!("{}", a_foo.frobnicate()); // Some(1) + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) ///////////////////////// // 3. Pattern matching // ///////////////////////// - - let foo = AnInt(1); + + let foo = OptionalI32::AnI32(1); match foo { - AnInt(n) => println!("it’s an int: {}", n), - Nothing => println!("it’s nothing!"), + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), } // Advanced pattern matching - struct FooBar { x: int, y: OptionalInt } - let bar = FooBar { x: 15, y: AnInt(32) }; + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; match bar { - FooBar { x: 0, y: AnInt(0) } => + FooBar { x: 0, y: OptionalI32::AnI32(0) } => println!("The numbers are zero!"), - FooBar { x: n, y: AnInt(m) } if n == m => + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => println!("The numbers are the same"), - FooBar { x: n, y: AnInt(m) } => + FooBar { x: n, y: OptionalI32::AnI32(m) } => println!("Different numbers: {} {}", n, m), - FooBar { x: _, y: Nothing } => + FooBar { x: _, y: OptionalI32::Nothing } => println!("The second number is Nothing!"), } @@ -187,19 +219,20 @@ fn main() { ///////////////////// // `for` loops/iteration - let array = [1i, 2, 3]; + let array = [1, 2, 3]; for i in array.iter() { println!("{}", i); } - for i in range(0u, 10) { + // Ranges + for i in 0u32..10 { print!("{} ", i); } println!(""); // prints `0 1 2 3 4 5 6 7 8 9 ` // `if` - if 1i == 1 { + if 1 == 1 { println!("Maths is working!"); } else { println!("Oh no..."); @@ -213,7 +246,7 @@ fn main() { }; // `while` loop - while 1i == 1 { + while 1 == 1 { println!("The universe is operating normally."); } @@ -225,40 +258,49 @@ fn main() { ///////////////////////////////// // 5. Memory safety & pointers // ///////////////////////////////// - - // Owned pointer - only one thing can ‘own’ this pointer at a time - let mut mine: Box<int> = box 3; + + // Owned pointer – only one thing can ‘own’ this pointer at a time + // This means that when the `Box` leaves its scope, it can be automatically deallocated safely. + let mut mine: Box<i32> = Box::new(3); *mine = 5; // dereference + // Here, `now_its_mine` takes ownership of `mine`. In other words, `mine` is moved. let mut now_its_mine = mine; *now_its_mine += 2; + println!("{}", now_its_mine); // 7 - // println!("{}", mine); // this would error + // println!("{}", mine); // this would not compile because `now_its_mine` now owns the pointer - // Reference - an immutable pointer that refers to other data - let mut var = 4i; + // Reference – an immutable pointer that refers to other data + // When a reference is taken to a value, we say that the value has been ‘borrowed’. + // While a value is borrowed immutably, it cannot be mutated or moved. + // A borrow lasts until the end of the scope it was created in. + let mut var = 4; var = 3; - let ref_var: &int = &var; + let ref_var: &i32 = &var; + println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); - // var = 5; // this would error - // *ref_var = 6; // this would too + // var = 5; // this would not compile because `var` is borrowed + // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference // 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 + // While a value is mutably borrowed, it cannot be accessed at all. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' is used to point to the mutably borrowed var2 + + println!("{}", *ref_var2); // 6 , //var2 would not compile. //ref_var2 is of type &mut i32, so //stores a reference to an i32 not the value. + // var2 = 2; // this would not compile because `var2` is borrowed } ``` ## 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 -Guide](http://doc.rust-lang.org/guide.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. +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 Programming +Language](http://doc.rust-lang.org/book/index.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 diff --git a/sass.html.markdown b/sass.html.markdown new file mode 100644 index 00000000..02bec47f --- /dev/null +++ b/sass.html.markdown @@ -0,0 +1,447 @@ +--- +language: sass +filename: learnsass.scss +contributors: + - ["Laura Kyle", "https://github.com/LauraNK"] + - ["Sean Corrales", "https://github.com/droidenator"] +--- + +Sass is a CSS extension language that adds features such as variables, nesting, mixins and more. +Sass (and other preprocessors, such as [Less](http://lesscss.org/)) help developers to write maintainable and DRY (Don't Repeat Yourself) code. + +Sass has two different syntax options to choose from. SCSS, which has the same syntax as CSS but with the added features of Sass. Or Sass (the original syntax), which uses indentation rather than curly braces and semicolons. +This tutorial is written using SCSS. + +If you're already familiar with CSS3, you'll be able to pick up Sass relatively quickly. It does not provide any new styling options but rather the tools to write your CSS more efficiently and make maintenance much easier. + +```scss + + +//Single line comments are removed when Sass is compiled to CSS. + +/*Multi line comments are preserved. */ + + + +/*Variables +==============================*/ + + + +/* You can store a CSS value (such as a color) in a variable. +Use the '$' symbol to create a variable. */ + +$primary-color: #A3A4FF; +$secondary-color: #51527F; +$body-font: 'Roboto', sans-serif; + +/* You can use the variables throughout your stylesheet. +Now if you want to change a color, you only have to make the change once.*/ + +body { + background-color: $primary-color; + color: $secondary-color; + font-family: $body-font; +} + +/* This would compile to: */ +body { + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; +} + + +/* This is much more maintainable than having to change the color +each time it appears throughout your stylesheet. */ + + + +/*Mixins +==============================*/ + + + +/* If you find you are writing the same code for more than one +element, you might want to store that code in a mixin. + +Use the '@mixin' directive, plus a name for your mixin.*/ + +@mixin center { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; +} + +/* You can use the mixin with '@include' and the mixin name. */ + +div { + @include center; + background-color: $primary-color; +} + +/*Which would compile to: */ +div { + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; +} + + +/* You can use mixins to create a shorthand property. */ + +@mixin size($width, $height) { + width: $width; + height: $height; +} + +/*Which you can invoke by passing width and height arguments. */ + +.rectangle { + @include size(100px, 60px); +} + +.square { + @include size(40px, 40px); +} + +/* This compiles to: */ +.rectangle { + width: 100px; + height: 60px; +} + +.square { + width: 40px; + height: 40px; +} + + + +/*Functions +==============================*/ + + + +/* Sass provides functions that can be used to accomplish a variety of + tasks. Consider the following */ + +/* Functions can be invoked by using their name and passing in the + required arguments */ +body { + width: round(10.25px); +} + +.footer { + background-color: fade_out(#000000, 0.25) +} + +/* Compiles to: */ + +body { + width: 10px; +} + +.footer { + background-color: rgba(0, 0, 0, 0.75); +} + +/* You may also define your own functions. Functions are very similar to + mixins. When trying to choose between a function or a mixin, remember + that mixins are best for generating CSS while functions are better for + logic that might be used throughout your Sass code. The examples in + the Math Operators' section are ideal candidates for becoming a reusable + function. */ + +/* This function will take a target size and the parent size and calculate + and return the percentage */ + +@function calculate-percentage($target-size, $parent-size) { + @return $target-size / $parent-size * 100%; +} + +$main-content: calculate-percentage(600px, 960px); + +.main-content { + width: $main-content; +} + +.sidebar { + width: calculate-percentage(300px, 960px); +} + +/* Compiles to: */ + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + + + +/*Extend (Inheritance) +==============================*/ + + + +/*Extend is a way to share the properties of one selector with another. */ + +.display { + @include size(5em, 5em); + border: 5px solid $secondary-color; +} + +.display-success { + @extend .display; + border-color: #22df56; +} + +/* Compiles to: */ +.display, .display-success { + width: 5em; + height: 5em; + border: 5px solid #51527F; +} + +.display-success { + border-color: #22df56; +} + +/* Extending a CSS statement is preferable to creating a mixin + because of the way it groups together the classes that all share + the same base styling. If this was done with a mixin, the width, + height, and border would be duplicated for each statement that + called the mixin. While it won't affect your workflow, it will + add unnecessary bloat to the files created by the Sass compiler. */ + + + +/*Nesting +==============================*/ + + + +/*Sass allows you to nest selectors within selectors */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: #FF0000; + } +} + +/* '&' will be replaced by the parent selector. */ +/* You can also nest pseudo-classes. */ +/* Keep in mind that over-nesting will make your code less maintainable. +Best practices recommend going no more than 3 levels deep when nesting. +For example: */ + +ul { + list-style-type: none; + margin-top: 2em; + + li { + background-color: red; + + &:hover { + background-color: blue; + } + + a { + color: white; + } + } +} + +/* Compiles to: */ + +ul { + list-style-type: none; + margin-top: 2em; +} + +ul li { + background-color: red; +} + +ul li:hover { + background-color: blue; +} + +ul li a { + color: white; +} + + + +/*Partials and Imports +==============================*/ + + + +/* Sass allows you to create partial files. This can help keep your Sass + code modularized. Partial files should begin with an '_', e.g. _reset.css. + Partials are not generated into CSS. */ + +/* Consider the following CSS which we'll put in a file called _reset.css */ + +html, +body, +ul, +ol { + margin: 0; + padding: 0; +} + +/* Sass offers @import which can be used to import partials into a file. + This differs from the traditional CSS @import statement which makes + another HTTP request to fetch the imported file. Sass takes the + imported file and combines it with the compiled code. */ + +@import 'reset'; + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + +/* Compiles to: */ + +html, body, ul, ol { + margin: 0; + padding: 0; +} + +body { + font-size: 16px; + font-family: Helvetica, Arial, Sans-serif; +} + + + +/*Placeholder Selectors +==============================*/ + + + +/* Placeholders are useful when creating a CSS statement to extend. If you + wanted to create a CSS statement that was exclusively used with @extend, + you can do so using a placeholder. Placeholders begin with a '%' instead + of '.' or '#'. Placeholders will not appear in the compiled CSS. */ + +%content-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + @extend %content-window; + background-color: #0000ff; +} + +/* Compiles to: */ + +.message-window { + font-size: 14px; + padding: 10px; + color: #000; + border-radius: 4px; +} + +.message-window { + background-color: #0000ff; +} + + + +/*Math Operations +==============================*/ + + + +/* Sass provides the following operators: +, -, *, /, and %. These can + be useful for calculating values directly in your Sass files instead + of using values that you've already calculated by hand. Below is an example + of a setting up a simple two column design. */ + +$content-area: 960px; +$main-content: 600px; +$sidebar-content: 300px; + +$main-size: $main-content / $content-area * 100%; +$sidebar-size: $sidebar-content / $content-area * 100%; +$gutter: 100% - ($main-size + $sidebar-size); + +body { + width: 100%; +} + +.main-content { + width: $main-size; +} + +.sidebar { + width: $sidebar-size; +} + +.gutter { + width: $gutter; +} + +/* Compiles to: */ + +body { + width: 100%; +} + +.main-content { + width: 62.5%; +} + +.sidebar { + width: 31.25%; +} + +.gutter { + width: 6.25%; +} + + +``` + + + +## SASS or Sass? +Have you ever wondered whether Sass is an acronym or not? You probably haven't, but I'll tell you anyway. The name of the language is a word, "Sass", and not an acronym. +Because people were constantly writing it as "SASS", the creator of the language jokingly called it "Syntactically Awesome StyleSheets". + + +## Practice Sass +If you want to play with Sass in your browser, check out [SassMeister](http://sassmeister.com/). +You can use either syntax, just go into the settings and select either Sass or SCSS. + + +## Compatibility + +Sass can be used in any project as long as you have a program to compile it +into CSS. You'll want to verify that the CSS you're using is compatible +with your target browsers. + +[QuirksMode CSS](http://www.quirksmode.org/css/) and [CanIUse](http://caniuse.com) are great resources for checking compatibility. + + +## Further reading +* [Official Documentation](http://sass-lang.com/documentation/file.SASS_REFERENCE.html) +* [The Sass Way](http://thesassway.com/) provides tutorials (beginner-advanced) and articles. diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..bc8cd422 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -5,7 +5,7 @@ contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] -filename: learn.scala + - ["Ha-Duong Nguyen", "http://reference-error.org"] --- Scala - the scalable language @@ -16,15 +16,16 @@ Scala - the scalable language Set yourself up: 1) Download Scala - http://www.scala-lang.org/downloads - 2) unzip/untar in your favourite location and put the bin subdir on the path - 3) Start a scala REPL by typing scala. You should see the prompt: + 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable + 3) Start a Scala REPL by running `scala`. You should see the prompt: scala> - This is the so called REPL (Read-Eval-Print Loop). You may type any valid - Scala expression into it, and the result will be printed. We will explain what - Scala files look like further into this tutorial, but for now, let's start - with some basics. + This is the so called REPL (Read-Eval-Print Loop). You may type any Scala + expression, and the result will be printed. We will explain what Scala files + look like further into this tutorial, but for now, let's start with some + basics. + */ @@ -32,26 +33,30 @@ Scala - the scalable language // 1. Basics ///////////////////////////////////////////////// -// Single line comments start with two forward slashes +// Single-line comments start with two forward slashes /* - Multi line comments, as you can already see from above, look like this. + Multi-line comments, as you can already see from above, look like this. */ // Printing, and forcing a new line on the next print println("Hello world!") println(10) +// Hello world! +// 10 // Printing, without forcing a new line on next print print("Hello world") +print(10) +// Hello world!10 // Declaring values is done using either var or val. -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 -x = 20 // error: reassignment to val +x = 20 // error: reassignment to val var y = 10 -y = 20 // y is now 20 +y = 20 // y is now 20 /* Scala is a statically typed language, yet note that in the above declarations, @@ -71,17 +76,17 @@ true false // Boolean operations -!true // false -!false // true +!true // false +!false // true true == false // false -10 > 5 // true +10 > 5 // true // Math is as per usual -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 -6 / 4 // 1 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 6.0 / 4 // 1.5 @@ -120,12 +125,12 @@ s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." -s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" -f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. @@ -164,6 +169,12 @@ def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y // Syntax for calling functions is familiar: sumOfSquares(3, 4) // => 25 +// You can use parameters names to specify them in different order +def subtract(x: Int, y: Int): Int = x - y + +subtract(10, 3) // => 7 +subtract(y=10, x=3) // => -7 + // In most cases (with recursive functions the most notable exception), function // return type can be omitted, and the same type inference we saw with variables // will work with function return values: @@ -171,12 +182,12 @@ def sq(x: Int) = x * x // Compiler can guess return type is Int // Functions can have default parameters: def addWithDefault(x: Int, y: Int = 5) = x + y -addWithDefault(1, 2) // => 3 -addWithDefault(1) // => 6 +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 // Anonymous functions look like this: -(x:Int) => x * x +(x: Int) => x * x // Unlike defs, even the input type of anonymous functions can be omitted if the // context makes it clear. Notice the type "Int => Int" which means a function @@ -186,25 +197,27 @@ val sq: Int => Int = x => x * x // Anonymous functions can be called as usual: sq(10) // => 100 -// If your anonymous function has one or two arguments, and each argument is +// If each argument in your anonymous function is // used only once, Scala gives you an even shorter way to define them. These // anonymous functions turn out to be extremely common, as will be obvious in // the data structure section. val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) -addOne(5) // => 6 -weirdSum(2, 4) // => 16 +addOne(5) // => 6 +weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. It has no effect on anonymous functions. For example: -def foo(x: Int) = { +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. +// It has no effect on anonymous functions. For example: +def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of foo! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonFunc } anonFunc(x) // This line is the return value of foo } @@ -216,19 +229,19 @@ def foo(x: Int) = { 1 to 5 val r = 1 to 5 -r.foreach( println ) +r.foreach(println) r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English -(5 to 1 by -1) foreach ( println ) +(5 to 1 by -1) foreach (println) // A while loops var i = 0 -while (i < 10) { println("i " + i); i+=1 } +while (i < 10) { println("i " + i); i += 1 } -while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? +while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why? i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very @@ -236,20 +249,21 @@ i // Show the value of i. Note that while is a loop in the classical sense - // comprehensions above is easier to understand and parallelize // A do while loop +i = 0 do { - println("x is still less than 10"); - x += 1 -} while (x < 10) + println("i is still less than 10") + i += 1 +} while (i < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. -def showNumbersInRange(a:Int, b:Int):Unit = { +def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } -showNumbersInRange(1,14) +showNumbersInRange(1, 14) // Conditionals @@ -270,21 +284,21 @@ val text = if (x == 10) "yeah" else "nope" ///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) -a(0) -a(3) +a(0) // Int = 1 +a(3) // Int = 5 a(21) // Throws an exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") -m("fork") -m("spoon") +m("fork") // java.lang.String = tenedor +m("spoon") // java.lang.String = cuchara m("bottle") // Throws an exception val safeM = m.withDefaultValue("no lo se") -safeM("bottle") +safeM("bottle") // java.lang.String = no lo se val s = Set(1, 3, 7) -s(0) -s(1) +s(0) // Boolean = false +s(1) // Boolean = true /* Look up the documentation of map here - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map @@ -303,17 +317,18 @@ s(1) (a, 2, "three") // Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) +val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10,3) // The function divideInts gives you the result and the remainder +// The function divideInts gives you the result and the remainder +divideInts(10, 3) // (Int, Int) = (3,1) // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10,3) +val d = divideInts(10, 3) // (Int, Int) = (3,1) -d._1 +d._1 // Int = 3 -d._2 +d._2 // Int = 1 ///////////////////////////////////////////////// @@ -357,7 +372,7 @@ class Dog(br: String) { val mydog = new Dog("greyhound") println(mydog.breed) // => "greyhound" -println(mydog.bark) // => "Woof, woof!" +println(mydog.bark) // => "Woof, woof!" // The "object" keyword creates a type AND a singleton instance of it. It is @@ -405,41 +420,55 @@ val otherGeorge = george.copy(phoneNumber = "9876") // 6. Pattern Matching ///////////////////////////////////////////////// -val me = Person("George", "1234") +// Pattern matching is a powerful and commonly used feature in Scala. Here's how +// you pattern match a case class. NB: Unlike other languages, Scala cases do +// not need breaks, fall-through does not happen. -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} - -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val email = "(.*)@(.*)".r // Define a regex for the next example. -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +// Pattern matching might look familiar to the switch statements in the C family +// of languages, but this is much more powerful. In Scala, you can match much +// more: +def matchEverything(obj: Any): String = obj match { + // You can match values: + case "Hello world" => "Got the string Hello world" -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match by type: + case x: Double => "Got a Double: " + x -val kate = Person("Kate", "1234") + // You can specify conditions: + case x: Int if x > 10000 => "Got a pretty big number!" -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match case classes as before: + case Person(name, number) => s"Got contact info for $name!" + // You can match regular expressions: + case email(name, domain) => s"Got email address $name@$domain" + // You can match tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// Regular expressions -val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax + // You can match data structures: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -val matcher = (value: String) => { - println(value match { - case email(name, domain) => s"It was an email: $name" - case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" - case _ => s"No match on '$value'" // default if no match found - }) + // You can nest patterns: + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } -matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" -matcher("nope..") // => "No match on 'nope..'" -matcher("52917") // => "No match on '52917'" -matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" +// In fact, you can pattern match any object with an "unapply" method. This +// feature is so powerful that Scala lets you define whole functions as +// patterns: +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} ///////////////////////////////////////////////// @@ -449,6 +478,7 @@ matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917 // Scala allows methods and functions to return, or take as parameters, other // functions or methods. +val add10: Int => Int = _ + 10 // A function taking an Int and returning an Int List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element // Anonymous functions can be used instead of named functions: @@ -476,7 +506,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, phoneNumber:String) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -524,8 +554,8 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) // By itself, implicit keyword doesn't change the behavior of the value, so // above values can be used as usual. -myImplicitInt + 2 // => 102 -myImplicitFunction("Pitbull").breed // => "Golden Pitbull" +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" // The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit @@ -543,8 +573,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" // Implicit function parameters enable us to simulate type classes in other // functional languages. It is so often used that it gets its own shorthand. The // following two lines mean the same thing: -def foo[T](implicit c: C[T]) = ... -def foo[T : C] = ... +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... // Another situation in which the compiler looks for an implicit is if you have @@ -553,8 +583,8 @@ def foo[T : C] = ... // implicit conversion of type A => B, where A is the type of obj, and B has a // method called "method", that conversion is applied. So having // myImplicitFunction above in scope, we can say: -"Retriever".breed // => "Golden Retriever" -"Sheperd".bark // => "Woof, woof!" +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" // Here the String is first converted to Dog using our function above, and then // the appropriate method is called. This is an extremely powerful feature, but @@ -577,7 +607,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable.{ List => ImmutableList } +import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} @@ -612,13 +642,8 @@ writer.close() ## Further resources -[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/) - -Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) - +* [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/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/self.html.markdown b/self.html.markdown index 69524a84..9290a0c9 100644 --- a/self.html.markdown +++ b/self.html.markdown @@ -5,13 +5,13 @@ contributors: filename: learnself.self --- -Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. +Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger. Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots. # Constructing objects -The inbuild Self parser can construct objects, including method objects. +The inbuild Self parser can construct objects, including method objects. ``` "This is a comment" @@ -38,18 +38,18 @@ The inbuild Self parser can construct objects, including method objects. x <- 20. |) -"An object which understands the method 'doubleX' which +"An object which understands the method 'doubleX' which doubles the value of x and then returns the object" (| x <- 20. doubleX = (x: x * 2. self) |) -"An object which understands all the messages -that 'traits point' understands". The parser -looks up 'traits point' by sending the messages -'traits' then 'point' to a known object called -the 'lobby'. It looks up the 'true' object by +"An object which understands all the messages +that 'traits point' understands". The parser +looks up 'traits point' by sending the messages +'traits' then 'point' to a known object called +the 'lobby'. It looks up the 'true' object by also sending the message 'true' to the lobby." (| parent* = traits point. x = 7. @@ -63,19 +63,19 @@ also sending the message 'true' to the lobby." Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace. ``` -"unary message, sends 'printLine' to the object '23' +"unary message, sends 'printLine' to the object '23' which prints the string '23' to stdout and returns the receiving object (ie 23)" 23 printLine "sends the message '+' with '7' to '23', then the message '*' with '8' to the result" -(23 + 7) * 8 +(23 + 7) * 8 "sends 'power:' to '2' with '8' returns 256" -2 power: 8 +2 power: 8 -"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. +"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'. Returns 1, the index of 'e' in 'hello'." -'hello' keyOf: 'e' IfAbsent: -1 +'hello' keyOf: 'e' IfAbsent: -1 ``` # Blocks @@ -90,13 +90,13 @@ Examples of the use of a block: ``` "returns 'HELLO'" -'hello' copyMutable mapBy: [|:c| c capitalize] +'hello' copyMutable mapBy: [|:c| c capitalize] "returns 'Nah'" -'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] +'hello' size > 5 ifTrue: ['Yay'] False: ['Nah'] "returns 'HaLLO'" -'hello' copyMutable mapBy: [|:c| +'hello' copyMutable mapBy: [|:c| c = 'e' ifTrue: [c capitalize] False: ['a']] ``` @@ -105,7 +105,7 @@ Multiple expressions are separated by a period. ^ returns immediately. ``` "returns An 'E'! How icky!" -'hello' copyMutable mapBy: [|:c. tmp <- ''| +'hello' copyMutable mapBy: [|:c. tmp <- ''| tmp: c capitalize. tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!']. c capitalize @@ -119,7 +119,7 @@ Blocks are performed by sending them the message 'value' and inherit (delegate t x: 15. "Repeatedly sends 'value' to the first block while the result of sending 'value' to the second block is the 'true' object" - [x > 0] whileTrue: [x: x - 1]. + [x > 0] whileTrue: [x: x - 1]. x ] value ``` @@ -130,12 +130,12 @@ Methods are like blocks but they are not within a context but instead are stored ``` "Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'. -Sending the message 'reduceXTo: 10' to this object will put +Sending the message 'reduceXTo: 10' to this object will put the object '10' in the 'x' slot and return the original object" -(| +(| x <- 50. reduceXTo: y = ( - [x > y] whileTrue: [x: x - 1]. + [x > y] whileTrue: [x: x - 1]. self) |) . diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown new file mode 100644 index 00000000..3b388505 --- /dev/null +++ b/smalltalk.html.markdown @@ -0,0 +1,955 @@ +--- +language: smalltalk +contributors: + - ["Jigyasa Grover", "https://github.com/jig08"] +--- + +- Smalltalk is an object-oriented, dynamically typed, reflective programming language. +- Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." +- It was designed and created in part for educational use, more so for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by Alan Kay, Dan Ingalls, Adele Goldberg, Ted Kaehler, Scott Wallace, and others during the 1970s. + +Feedback highly appreciated! Reach me at [@jigyasa_grover](https://twitter.com/jigyasa_grover) or send me an e-mail at `grover.jigyasa1@gmail.com`. + + +##Allowable characters: +- a-z +- A-Z +- 0-9 +- .+/\*~<>@%|&? +- blank, tab, cr, ff, lf + +##Variables: +- variables must be declared before use +- shared vars must begin with uppercase +- local vars must begin with lowercase +- reserved names: `nil`, `true`, `false`, `self`, `super`, and `Smalltalk` + +##Variable scope: +- Global: defined in Dictionary Smalltalk and accessible by all objects in system - Special: (reserved) `Smalltalk`, `super`, `self`, `true`, `false`, & `nil` +- Method Temporary: local to a method +- Block Temporary: local to a block +- Pool: variables in a Dictionary object +- Method Parameters: automatic local vars created as a result of message call with params +- Block Parameters: automatic local vars created as a result of value: message call +- Class: shared with all instances of one class & its subclasses +- Class Instance: unique to each instance of a class +- Instance Variables: unique to each instance + +`"Comments are enclosed in quotes"` + +`"Period (.) is the statement seperator"` + +## Transcript: +``` +Transcript clear. "clear to transcript window" +Transcript show: 'Hello World'. "output string in transcript window" +Transcript nextPutAll: 'Hello World'. "output string in transcript window" +Transcript nextPut: $A. "output character in transcript window" +Transcript space. "output space character in transcript window" +Transcript tab. "output tab character in transcript window" +Transcript cr. "carriage return / linefeed" +'Hello' printOn: Transcript. "append print string into the window" +'Hello' storeOn: Transcript. "append store string into the window" +Transcript endEntry. "flush the output buffer" +``` + +##Assignment: +``` +| x y | +x _ 4. "assignment (Squeak) <-" +x := 5. "assignment" +x := y := z := 6. "compound assignment" +x := (y := 6) + 1. +x := Object new. "bind to allocated instance of a class" +x := 123 class. "discover the object class" +x := Integer superclass. "discover the superclass of a class" +x := Object allInstances. "get an array of all instances of a class" +x := Integer allSuperclasses. "get all superclasses of a class" +x := 1.2 hash. "hash value for object" +y := x copy. "copy object" +y := x shallowCopy. "copy object (not overridden)" +y := x deepCopy. "copy object and instance vars" +y := x veryDeepCopy. "complete tree copy using a dictionary" +``` + +##Constants: +``` +| b | +b := true. "true constant" +b := false. "false constant" +x := nil. "nil object constant" +x := 1. "integer constants" +x := 3.14. "float constants" +x := 2e-2. "fractional constants" +x := 16r0F. "hex constant". +x := -1. "negative constants" +x := 'Hello'. "string constant" +x := 'I''m here'. "single quote escape" +x := $A. "character constant" +x := $ . "character constant (space)" +x := #aSymbol. "symbol constants" +x := #(3 2 1). "array constants" +x := #('abc' 2 $a). "mixing of types allowed" + +``` + +## Booleans: +``` +| b x y | +x := 1. y := 2. +b := (x = y). "equals" +b := (x ~= y). "not equals" +b := (x == y). "identical" +b := (x ~~ y). "not identical" +b := (x > y). "greater than" +b := (x < y). "less than" +b := (x >= y). "greater than or equal" +b := (x <= y). "less than or equal" +b := b not. "boolean not" +b := (x < 5) & (y > 1). "boolean and" +b := (x < 5) | (y > 1). "boolean or" +b := (x < 5) and: [y > 1]. "boolean and (short-circuit)" +b := (x < 5) or: [y > 1]. "boolean or (short-circuit)" +b := (x < 5) eqv: (y > 1). "test if both true or both false" +b := (x < 5) xor: (y > 1). "test if one true and other false" +b := 5 between: 3 and: 12. "between (inclusive)" +b := 123 isKindOf: Number. "test if object is class or subclass of" +b := 123 isMemberOf: SmallInteger. "test if object is type of class" +b := 123 respondsTo: sqrt. "test if object responds to message" +b := x isNil. "test if object is nil" +b := x isZero. "test if number is zero" +b := x positive. "test if number is positive" +b := x strictlyPositive. "test if number is greater than zero" +b := x negative. "test if number is negative" +b := x even. "test if number is even" +b := x odd. "test if number is odd" +b := x isLiteral. "test if literal constant" +b := x isInteger. "test if object is integer" +b := x isFloat. "test if object is float" +b := x isNumber. "test if object is number" +b := $A isUppercase. "test if upper case character" +b := $A isLowercase. "test if lower case character" + +``` + +## Arithmetic expressions: +``` +| x | +x := 6 + 3. "addition" +x := 6 - 3. "subtraction" +x := 6 * 3. "multiplication" +x := 1 + 2 * 3. "evaluation always left to right (1 + 2) * 3" +x := 5 / 3. "division with fractional result" +x := 5.0 / 3.0. "division with float result" +x := 5.0 // 3.0. "integer divide" +x := 5.0 \\ 3.0. "integer remainder" +x := -5. "unary minus" +x := 5 sign. "numeric sign (1, -1 or 0)" +x := 5 negated. "negate receiver" +x := 1.2 integerPart. "integer part of number (1.0)" +x := 1.2 fractionPart. "fractional part of number (0.2)" +x := 5 reciprocal. "reciprocal function" +x := 6 * 3.1. "auto convert to float" +x := 5 squared. "square function" +x := 25 sqrt. "square root" +x := 5 raisedTo: 2. "power function" +x := 5 raisedToInteger: 2. "power function with integer" +x := 5 exp. "exponential" +x := -5 abs. "absolute value" +x := 3.99 rounded. "round" +x := 3.99 truncated. "truncate" +x := 3.99 roundTo: 1. "round to specified decimal places" +x := 3.99 truncateTo: 1. "truncate to specified decimal places" +x := 3.99 floor. "truncate" +x := 3.99 ceiling. "round up" +x := 5 factorial. "factorial" +x := -5 quo: 3. "integer divide rounded toward zero" +x := -5 rem: 3. "integer remainder rounded toward zero" +x := 28 gcd: 12. "greatest common denominator" +x := 28 lcm: 12. "least common multiple" +x := 100 ln. "natural logarithm" +x := 100 log. "base 10 logarithm" +x := 100 log: 10. "logarithm with specified base" +x := 100 floorLog: 10. "floor of the log" +x := 180 degreesToRadians. "convert degrees to radians" +x := 3.14 radiansToDegrees. "convert radians to degrees" +x := 0.7 sin. "sine" +x := 0.7 cos. "cosine" +x := 0.7 tan. "tangent" +x := 0.7 arcSin. "arcsine" +x := 0.7 arcCos. "arccosine" +x := 0.7 arcTan. "arctangent" +x := 10 max: 20. "get maximum of two numbers" +x := 10 min: 20. "get minimum of two numbers" +x := Float pi. "pi" +x := Float e. "exp constant" +x := Float infinity. "infinity" +x := Float nan. "not-a-number" +x := Random new next; yourself. x next. "random number stream (0.0 to 1.0) +x := 100 atRandom. "quick random number" + +``` + +##Bitwise Manipulation: +``` +| b x | +x := 16rFF bitAnd: 16r0F. "and bits" +x := 16rF0 bitOr: 16r0F. "or bits" +x := 16rFF bitXor: 16r0F. "xor bits" +x := 16rFF bitInvert. "invert bits" +x := 16r0F bitShift: 4. "left shift" +x := 16rF0 bitShift: -4. "right shift" +"x := 16r80 bitAt: 7." "bit at position (0|1) [!Squeak]" +x := 16r80 highbit. "position of highest bit set" +b := 16rFF allMask: 16r0F. "test if all bits set in mask set in receiver" +b := 16rFF anyMask: 16r0F. "test if any bits set in mask set in receiver" +b := 16rFF noMask: 16r0F. "test if all bits set in mask clear in receiver" + +``` + +## Conversion: +``` +| x | +x := 3.99 asInteger. "convert number to integer (truncates in Squeak)" +x := 3.99 asFraction. "convert number to fraction" +x := 3 asFloat. "convert number to float" +x := 65 asCharacter. "convert integer to character" +x := $A asciiValue. "convert character to integer" +x := 3.99 printString. "convert object to string via printOn:" +x := 3.99 storeString. "convert object to string via storeOn:" +x := 15 radix: 16. "convert to string in given base" +x := 15 printStringBase: 16. +x := 15 storeStringBase: 16. + +``` + +## Blocks: +- blocks are objects and may be assigned to a variable +- value is last expression evaluated unless explicit return +- blocks may be nested +- specification [ arguments | | localvars | expressions ] +- Squeak does not currently support localvars in blocks +- max of three arguments allowed +- `^`expression terminates block & method (exits all nested blocks) +- blocks intended for long term storage should not contain `^` + +``` +| x y z | +x := [ y := 1. z := 2. ]. x value. "simple block usage" +x := [ :argOne :argTwo | argOne, ' and ' , argTwo.]. "set up block with argument passing" +Transcript show: (x value: 'First' value: 'Second'); cr. "use block with argument passing" +"x := [ | z | z := 1.]. *** localvars not available in squeak blocks" +``` + +## Method calls: +- unary methods are messages with no arguments +- binary methods +- keyword methods are messages with selectors including colons standard categories/protocols: - initialize-release (methods called for new instance) +- accessing (get/set methods) +- testing (boolean tests - is) +- comparing (boolean tests with parameter +- displaying (gui related methods) +- printing (methods for printing) +- updating (receive notification of changes) +- private (methods private to class) +- instance-creation (class methods for creating instance) +``` +| x | +x := 2 sqrt. "unary message" +x := 2 raisedTo: 10. "keyword message" +x := 194 * 9. "binary message" +Transcript show: (194 * 9) printString; cr. "combination (chaining)" +x := 2 perform: #sqrt. "indirect method invocation" +Transcript "Cascading - send multiple messages to receiver" + show: 'hello '; + show: 'world'; + cr. +x := 3 + 2; * 100. "result=300. Sends message to same receiver (3)" +``` + +##Conditional Statements: +``` +| x | +x > 10 ifTrue: [Transcript show: 'ifTrue'; cr]. "if then" +x > 10 ifFalse: [Transcript show: 'ifFalse'; cr]. "if else" +x > 10 "if then else" + ifTrue: [Transcript show: 'ifTrue'; cr] + ifFalse: [Transcript show: 'ifFalse'; cr]. +x > 10 "if else then" + ifFalse: [Transcript show: 'ifFalse'; cr] + ifTrue: [Transcript show: 'ifTrue'; cr]. +Transcript + show: + (x > 10 + ifTrue: ['ifTrue'] + ifFalse: ['ifFalse']); + cr. +Transcript "nested if then else" + show: + (x > 10 + ifTrue: [x > 5 + ifTrue: ['A'] + ifFalse: ['B']] + ifFalse: ['C']); + cr. +switch := Dictionary new. "switch functionality" +switch at: $A put: [Transcript show: 'Case A'; cr]. +switch at: $B put: [Transcript show: 'Case B'; cr]. +switch at: $C put: [Transcript show: 'Case C'; cr]. +result := (switch at: $B) value. +``` + +## Iteration statements: +``` +| x y | +x := 4. y := 1. +[x > 0] whileTrue: [x := x - 1. y := y * 2]. "while true loop" +[x >= 4] whileFalse: [x := x + 1. y := y * 2]. "while false loop" +x timesRepeat: [y := y * 2]. "times repear loop (i := 1 to x)" +1 to: x do: [:a | y := y * 2]. "for loop" +1 to: x by: 2 do: [:a | y := y / 2]. "for loop with specified increment" +#(5 4 3) do: [:a | x := x + a]. "iterate over array elements" +``` + +## Character: +``` +| x y | +x := $A. "character assignment" +y := x isLowercase. "test if lower case" +y := x isUppercase. "test if upper case" +y := x isLetter. "test if letter" +y := x isDigit. "test if digit" +y := x isAlphaNumeric. "test if alphanumeric" +y := x isSeparator. "test if seperator char" +y := x isVowel. "test if vowel" +y := x digitValue. "convert to numeric digit value" +y := x asLowercase. "convert to lower case" +y := x asUppercase. "convert to upper case" +y := x asciiValue. "convert to numeric ascii value" +y := x asString. "convert to string" +b := $A <= $B. "comparison" +y := $A max: $B. + +``` + +## Symbol: +``` +| b x y | +x := #Hello. "symbol assignment" +y := 'String', 'Concatenation'. "symbol concatenation (result is string)" +b := x isEmpty. "test if symbol is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $e ifAbsent: [0]. "first position of character within string" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asString. "convert symbol to string" +y := x asText. "convert symbol to text" +y := x asArray. "convert symbol to array" +y := x asOrderedCollection. "convert symbol to ordered collection" +y := x asSortedCollection. "convert symbol to sorted collection" +y := x asBag. "convert symbol to bag collection" +y := x asSet. "convert symbol to set collection" +``` + +## String: +``` +| b x y | +x := 'This is a string'. "string assignment" +x := 'String', 'Concatenation'. "string concatenation" +b := x isEmpty. "test if string is empty" +y := x size. "string size" +y := x at: 2. "char at location" +y := x copyFrom: 2 to: 4. "substring" +y := x indexOf: $a ifAbsent: [0]. "first position of character within string" +x := String new: 4. "allocate string object" +x "set string elements" + at: 1 put: $a; + at: 2 put: $b; + at: 3 put: $c; + at: 4 put: $e. +x := String with: $a with: $b with: $c with: $d. "set up to 4 elements at a time" +x do: [:a | Transcript show: a printString; cr]. "iterate over the string" +b := x conform: [:a | (a >= $a) & (a <= $z)]. "test if all elements meet condition" +y := x select: [:a | a > $a]. "return all elements that meet condition" +y := x asSymbol. "convert string to symbol" +y := x asArray. "convert string to array" +x := 'ABCD' asByteArray. "convert string to byte array" +y := x asOrderedCollection. "convert string to ordered collection" +y := x asSortedCollection. "convert string to sorted collection" +y := x asBag. "convert string to bag collection" +y := x asSet. "convert string to set collection" +y := x shuffled. "randomly shuffle string" +``` + +## Array: Fixed length collection +- ByteArray: Array limited to byte elements (0-255) +- WordArray: Array limited to word elements (0-2^32) + +``` +| b x y sum max | +x := #(4 3 2 1). "constant array" +x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" +x := Array new: 4. "allocate an array with specified size" +x "set array elements" + at: 1 put: 5; + at: 2 put: 4; + at: 3 put: 3; + at: 4 put: 2. +b := x isEmpty. "test if array is empty" +y := x size. "array size" +y := x at: 4. "get array element at index" +b := x includes: 3. "test if element is in array" +y := x copyFrom: 2 to: 4. "subarray" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within array" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the array" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum array elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum array elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum array elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in array" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +"y := x asByteArray." "note: this instruction not available on Squeak" +y := x asWordArray. "convert to word array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +##OrderedCollection: acts like an expandable array +``` +| b x y sum max | +x := OrderedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := OrderedCollection new. "allocate collection" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +x at: 2 put: 3. "set element at index" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 5. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x shuffled. "randomly shuffle collection" +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +## SortedCollection: like OrderedCollection except order of elements determined by sorting criteria +``` +| b x y sum max | +x := SortedCollection with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := SortedCollection new. "allocate collection" +x := SortedCollection sortBlock: [:a :c | a > c]. "set sort criteria" +x add: 3; add: 2; add: 1; add: 4; yourself. "add element to collection" +y := x addFirst: 5. "add element at beginning of collection" +y := x removeFirst. "remove first element in collection" +y := x addLast: 6. "add element at end of collection" +y := x removeLast. "remove last element in collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 5 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: 2. "retrieve element at index" +y := x first. "retrieve first element in collection" +y := x last. "retrieve last element in collection" +b := x includes: 4. "test if element is in collection" +y := x copyFrom: 2 to: 3. "subcollection" +y := x indexOf: 3 ifAbsent: [0]. "first position of element within collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +## Bag: like OrderedCollection except elements are in no particular order +``` +| b x y sum max | +x := Bag with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Bag new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +x add: 3 withOccurrences: 2. "add multiple copies to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +b := x includes: 3. "test if element is in collection" +y := x occurrencesOf: 3. "number of times object in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +## Set: like Bag except duplicates not allowed +## IdentitySet: uses identity test (== rather than =) +``` +| b x y sum max | +x := Set with: 4 with: 3 with: 2 with: 1. "create collection with up to 4 elements" +x := Set new. "allocate collection" +x add: 4; add: 3; add: 1; add: 2; yourself. "add element to collection" +y := x addAll: #(7 8 9). "add multiple elements to collection" +y := x removeAll: #(7 8 9). "remove multiple elements from collection" +y := x remove: 4 ifAbsent: []. "remove element from collection" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 4. "test if element is in collection" +x do: [:a | Transcript show: a printString; cr]. "iterate over the collection" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +## Interval: +``` +| b x y sum max | +x := Interval from: 5 to: 10. "create interval object" +x := 5 to: 10. +x := Interval from: 5 to: 10 by: 2. "create interval object with specified increment" +x := 5 to: 10 by: 2. +b := x isEmpty. "test if empty" +y := x size. "number of elements" +x includes: 9. "test if element is in collection" +x do: [:k | Transcript show: k printString; cr]. "iterate over interval" +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 7]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := 0. 1 to: (x size) do: [:a | sum := sum + (x at: a)]. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" +``` + +##Associations: +``` +| x y | +x := #myVar->'hello'. +y := x key. +y := x value. +``` + +## Dictionary: +## IdentityDictionary: uses identity test (== rather than =) +``` +| b x y | +x := Dictionary new. "allocate collection" +x add: #a->4; add: #b->3; add: #c->1; add: #d->2; yourself. "add element to collection" +x at: #e put: 3. "set element at index" +b := x isEmpty. "test if empty" +y := x size. "number of elements" +y := x at: #a ifAbsent: []. "retrieve element at index" +y := x keyAtValue: 3 ifAbsent: []. "retrieve key for given value with error block" +y := x removeKey: #e ifAbsent: []. "remove element from collection" +b := x includes: 3. "test if element is in values collection" +b := x includesKey: #a. "test if element is in keys collection" +y := x occurrencesOf: 3. "number of times object in collection" +y := x keys. "set of keys" +y := x values. "bag of values" +x do: [:a | Transcript show: a printString; cr]. "iterate over the values collection" +x keysDo: [:a | Transcript show: a printString; cr]. "iterate over the keys collection" +x associationsDo: [:a | Transcript show: a printString; cr]."iterate over the associations" +x keysAndValuesDo: [:aKey :aValue | Transcript "iterate over keys and values" + show: aKey printString; space; + show: aValue printString; cr]. +b := x conform: [:a | (a >= 1) & (a <= 4)]. "test if all elements meet condition" +y := x select: [:a | a > 2]. "return collection of elements that pass test" +y := x reject: [:a | a < 2]. "return collection of elements that fail test" +y := x collect: [:a | a + a]. "transform each element for new collection" +y := x detect: [:a | a > 3] ifNone: []. "find position of first element that passes test" +sum := 0. x do: [:a | sum := sum + a]. sum. "sum elements" +sum := x inject: 0 into: [:a :c | a + c]. "sum elements" +max := x inject: 0 into: [:a :c | (a > c) "find max element in collection" + ifTrue: [a] + ifFalse: [c]]. +y := x asArray. "convert to array" +y := x asOrderedCollection. "convert to ordered collection" +y := x asSortedCollection. "convert to sorted collection" +y := x asBag. "convert to bag collection" +y := x asSet. "convert to set collection" + +Smalltalk at: #CMRGlobal put: 'CMR entry'. "put global in Smalltalk Dictionary" +x := Smalltalk at: #CMRGlobal. "read global from Smalltalk Dictionary" +Transcript show: (CMRGlobal printString). "entries are directly accessible by name" +Smalltalk keys do: [ :k | "print out all classes" + ((Smalltalk at: k) isKindOf: Class) + ifFalse: [Transcript show: k printString; cr]]. +Smalltalk at: #CMRDictionary put: (Dictionary new). "set up user defined dictionary" +CMRDictionary at: #MyVar1 put: 'hello1'. "put entry in dictionary" +CMRDictionary add: #MyVar2->'hello2'. "add entry to dictionary use key->value combo" +CMRDictionary size. "dictionary size" +CMRDictionary keys do: [ :k | "print out keys in dictionary" + Transcript show: k printString; cr]. +CMRDictionary values do: [ :k | "print out values in dictionary" + Transcript show: k printString; cr]. +CMRDictionary keysAndValuesDo: [:aKey :aValue | "print out keys and values" + Transcript + show: aKey printString; + space; + show: aValue printString; + cr]. +CMRDictionary associationsDo: [:aKeyValue | "another iterator for printing key values" + Transcript show: aKeyValue printString; cr]. +Smalltalk removeKey: #CMRGlobal ifAbsent: []. "remove entry from Smalltalk dictionary" +Smalltalk removeKey: #CMRDictionary ifAbsent: []. "remove user dictionary from Smalltalk dictionary" +``` + +## Internal Stream: +``` +| b x ios | +ios := ReadStream on: 'Hello read stream'. +ios := ReadStream on: 'Hello read stream' from: 1 to: 5. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +ios position. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. + +ios := ReadWriteStream on: 'Hello read stream'. +ios := ReadWriteStream on: 'Hello read stream' from: 1 to: 5. +ios := ReadWriteStream with: 'Hello read stream'. +ios := ReadWriteStream with: 'Hello read stream' from: 1 to: 10. +ios position: 0. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 6. +ios position. +ios nextPutAll: 'Chris'. +x := ios next. +x := ios peek. +x := ios contents. +b := ios atEnd. +``` + +## FileStream: +``` +| b x ios | +ios := FileStream newFileNamed: 'ios.txt'. +ios nextPut: $H; cr. +ios nextPutAll: 'Hello File'; cr. +'Hello File' printOn: ios. +'Hello File' storeOn: ios. +ios close. + +ios := FileStream oldFileNamed: 'ios.txt'. +[(x := ios nextLine) notNil] + whileTrue: [Transcript show: x; cr]. +ios position: 3. +x := ios position. +x := ios next. +x := ios peek. +b := ios atEnd. +ios close. +``` + +## Date: +``` +| x y | +x := Date today. "create date for today" +x := Date dateAndTimeNow. "create date from current time/date" +x := Date readFromString: '01/02/1999'. "create date from formatted string" +x := Date newDay: 12 month: #July year: 1999 "create date from parts" +x := Date fromDays: 36000. "create date from elapsed days since 1/1/1901" +y := Date dayOfWeek: #Monday. "day of week as int (1-7)" +y := Date indexOfMonth: #January. "month of year as int (1-12)" +y := Date daysInMonth: 2 forYear: 1996. "day of month as int (1-31)" +y := Date daysInYear: 1996. "days in year (365|366)" +y := Date nameOfDay: 1 "weekday name (#Monday,...)" +y := Date nameOfMonth: 1. "month name (#January,...)" +y := Date leapYear: 1996. "1 if leap year; 0 if not leap year" +y := x weekday. "day of week (#Monday,...)" +y := x previous: #Monday. "date for previous day of week" +y := x dayOfMonth. "day of month (1-31)" +y := x day. "day of year (1-366)" +y := x firstDayOfMonth. "day of year for first day of month" +y := x monthName. "month of year (#January,...)" +y := x monthIndex. "month of year (1-12)" +y := x daysInMonth. "days in month (1-31)" +y := x year. "year (19xx)" +y := x daysInYear. "days in year (365|366)" +y := x daysLeftInYear. "days left in year (364|365)" +y := x asSeconds. "seconds elapsed since 1/1/1901" +y := x addDays: 10. "add days to date object" +y := x subtractDays: 10. "subtract days to date object" +y := x subtractDate: (Date today). "subtract date (result in days)" +y := x printFormat: #(2 1 3 $/ 1 1). "print formatted date" +b := (x <= Date today). "comparison" +``` + +## Time: +``` +| x y | +x := Time now. "create time from current time" +x := Time dateAndTimeNow. "create time from current time/date" +x := Time readFromString: '3:47:26 pm'. "create time from formatted string" +x := Time fromSeconds: (60 * 60 * 4). "create time from elapsed time from midnight" +y := Time millisecondClockValue. "milliseconds since midnight" +y := Time totalSeconds. "total seconds since 1/1/1901" +y := x seconds. "seconds past minute (0-59)" +y := x minutes. "minutes past hour (0-59)" +y := x hours. "hours past midnight (0-23)" +y := x addTime: (Time now). "add time to time object" +y := x subtractTime: (Time now). "subtract time to time object" +y := x asSeconds. "convert time to seconds" +x := Time millisecondsToRun: [ "timing facility" + 1 to: 1000 do: [:index | y := 3.14 * index]]. +b := (x <= Time now). "comparison" +``` + +## Point: +``` +| x y | +x := 200@100. "obtain a new point" +y := x x. "x coordinate" +y := x y. "y coordinate" +x := 200@100 negated. "negates x and y" +x := (-200@-100) abs. "absolute value of x and y" +x := (200.5@100.5) rounded. "round x and y" +x := (200.5@100.5) truncated. "truncate x and y" +x := 200@100 + 100. "add scale to both x and y" +x := 200@100 - 100. "subtract scale from both x and y" +x := 200@100 * 2. "multiply x and y by scale" +x := 200@100 / 2. "divide x and y by scale" +x := 200@100 // 2. "divide x and y by scale" +x := 200@100 \\ 3. "remainder of x and y by scale" +x := 200@100 + 50@25. "add points" +x := 200@100 - 50@25. "subtract points" +x := 200@100 * 3@4. "multiply points" +x := 200@100 // 3@4. "divide points" +x := 200@100 max: 50@200. "max x and y" +x := 200@100 min: 50@200. "min x and y" +x := 20@5 dotProduct: 10@2. "sum of product (x1*x2 + y1*y2)" +``` + +## Rectangle: +``` +Rectangle fromUser. +``` + +## Pen: +``` +| myPen | +Display restoreAfter: [ + Display fillWhite. + +myPen := Pen new. "get graphic pen" +myPen squareNib: 1. +myPen color: (Color blue). "set pen color" +myPen home. "position pen at center of display" +myPen up. "makes nib unable to draw" +myPen down. "enable the nib to draw" +myPen north. "points direction towards top" +myPen turn: -180. "add specified degrees to direction" +myPen direction. "get current angle of pen" +myPen go: 50. "move pen specified number of pixels" +myPen location. "get the pen position" +myPen goto: 200@200. "move to specified point" +myPen place: 250@250. "move to specified point without drawing" +myPen print: 'Hello World' withFont: (TextStyle default fontAt: 1). +Display extent. "get display width@height" +Display width. "get display width" +Display height. "get display height" + +]. +``` + +## Dynamic Message Calling/Compiling: +``` +| receiver message result argument keyword1 keyword2 argument1 argument2 | +"unary message" +receiver := 5. +message := 'factorial' asSymbol. +result := receiver perform: message. +result := Compiler evaluate: ((receiver storeString), ' ', message). +result := (Message new setSelector: message arguments: #()) sentTo: receiver. + +"binary message" +receiver := 1. +message := '+' asSymbol. +argument := 2. +result := receiver perform: message withArguments: (Array with: argument). +result := Compiler evaluate: ((receiver storeString), ' ', message, ' ', (argument storeString)). +result := (Message new setSelector: message arguments: (Array with: argument)) sentTo: receiver. + +"keyword messages" +receiver := 12. +keyword1 := 'between:' asSymbol. +keyword2 := 'and:' asSymbol. +argument1 := 10. +argument2 := 20. +result := receiver + perform: (keyword1, keyword2) asSymbol + withArguments: (Array with: argument1 with: argument2). +result := Compiler evaluate: + ((receiver storeString), ' ', keyword1, (argument1 storeString) , ' ', keyword2, (argument2 storeString)). +result := (Message + new + setSelector: (keyword1, keyword2) asSymbol + arguments: (Array with: argument1 with: argument2)) + sentTo: receiver. +``` + +## Class/Meta-class: +``` +| b x | +x := String name. "class name" +x := String category. "organization category" +x := String comment. "class comment" +x := String kindOfSubclass. "subclass type - subclass: variableSubclass, etc" +x := String definition. "class definition" +x := String instVarNames. "immediate instance variable names" +x := String allInstVarNames. "accumulated instance variable names" +x := String classVarNames. "immediate class variable names" +x := String allClassVarNames. "accumulated class variable names" +x := String sharedPools. "immediate dictionaries used as shared pools" +x := String allSharedPools. "accumulated dictionaries used as shared pools" +x := String selectors. "message selectors for class" +x := String sourceCodeAt: #size. "source code for specified method" +x := String allInstances. "collection of all instances of class" +x := String superclass. "immediate superclass" +x := String allSuperclasses. "accumulated superclasses" +x := String withAllSuperclasses. "receiver class and accumulated superclasses" +x := String subclasses. "immediate subclasses" +x := String allSubclasses. "accumulated subclasses" +x := String withAllSubclasses. "receiver class and accumulated subclasses" +b := String instSize. "number of named instance variables" +b := String isFixed. "true if no indexed instance variables" +b := String isVariable. "true if has indexed instance variables" +b := String isPointers. "true if index instance vars contain objects" +b := String isBits. "true if index instance vars contain bytes/words" +b := String isBytes. "true if index instance vars contain bytes" +b := String isWords. true if index instance vars contain words" +Object withAllSubclasses size. "get total number of class entries" +``` + +## Debuging: +``` +| a b x | +x yourself. "returns receiver" +String browse. "browse specified class" +x inspect. "open object inspector window" +x confirm: 'Is this correct?'. +x halt. "breakpoint to open debugger window" +x halt: 'Halt message'. +x notify: 'Notify text'. +x error: 'Error string'. "open up error window with title" +x doesNotUnderstand: #cmrMessage. "flag message is not handled" +x shouldNotImplement. "flag message should not be implemented" +x subclassResponsibility. "flag message as abstract" +x errorImproperStore. "flag an improper store into indexable object" +x errorNonIntegerIndex. "flag only integers should be used as index" +x errorSubscriptBounds. "flag subscript out of bounds" +x primitiveFailed. "system primitive failed" + +a := 'A1'. b := 'B2'. a become: b. "switch two objects" +Transcript show: a, b; cr. +``` + +## Misc +``` +| x | +"Smalltalk condenseChanges." "compress the change file" +x := FillInTheBlank request: 'Prompt Me'. "prompt user for input" +Utilities openCommandKeyHelp +``` + + + + +## Ready For More? + +### Free Online + +* [GNU Smalltalk User's Guide](https://www.gnu.org/software/smalltalk/manual/html_node/Tutorial.html) +* [smalltalk dot org](http://www.smalltalk.org/smalltalk/learning.html) +* [Computer Programming using GNU Smalltalk](http://www.canol.info/books/computer_programming_using_gnu_smalltalk/) +* [Smalltalk Cheatsheet](http://www.angelfire.com/tx4/cus/notes/smalltalk.html) +* [Smalltalk-72 Manual](http://www.bitsavers.org/pdf/xerox/parc/techReports/Smalltalk-72_Instruction_Manual_Mar76.pdf) +* [BYTE: A Special issue on Smalltalk](https://archive.org/details/byte-magazine-1981-08) +* [Smalltalk, Objects, and Design](https://books.google.co.in/books?id=W8_Une9cbbgC&printsec=frontcover&dq=smalltalk&hl=en&sa=X&ved=0CCIQ6AEwAWoVChMIw63Vo6CpyAIV0HGOCh3S2Alf#v=onepage&q=smalltalk&f=false) +* [Smalltalk: An Introduction to Application Development Using VisualWorks](https://books.google.co.in/books?id=zalQAAAAMAAJ&q=smalltalk&dq=smalltalk&hl=en&sa=X&ved=0CCgQ6AEwAmoVChMIw63Vo6CpyAIV0HGOCh3S2Alf/) diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown index b545f3e1..143980e7 100644 --- a/standard-ml.html.markdown +++ b/standard-ml.html.markdown @@ -3,13 +3,15 @@ language: "Standard ML" contributors: - ["Simon Shine", "http://shine.eu.org/"] - ["David Pedersen", "http://lonelyproton.com/"] + - ["James Baker", "http://www.jbaker.io/"] + - ["Leo Zovic", "http://langnostic.inaimathi.ca/"] --- Standard ML is a functional programming language with type inference and some side-effects. Some of the hard parts of learning Standard ML are: Recursion, pattern matching, type inference (guessing the right types but never allowing -implicit type conversion). If you have an imperative background, not being able -to update variables can feel severely inhibiting. +implicit type conversion). Standard ML is distinguished from Haskell by including +references, allowing variables to be updated. ```ocaml (* Comments in Standard ML begin with (* and end with *). Comments can be @@ -135,9 +137,29 @@ val mixup = [ ("Alice", 39), val good_bad_stuff = (["ice cream", "hot dogs", "chocolate"], - ["liver", "paying the rent" ]) (* string list * string list *) + ["liver", "paying the rent" ]) (* : string list * string list *) +(* Records are tuples with named slots *) + +val rgb = { r=0.23, g=0.56, b=0.91 } (* : {b:real, g:real, r:real} *) + +(* You don't need to declare their slots ahead of time. Records with + different slot names are considered different types, even if their + slot value types match up. For instance... *) + +val Hsl = { H=310.3, s=0.51, l=0.23 } (* : {H:real, l:real, s:real} *) +val Hsv = { H=310.3, s=0.51, v=0.23 } (* : {H:real, s:real, v:real} *) + +(* ...trying to evaluate `Hsv = Hsl` or `rgb = Hsl` would give a type + error. While they're all three-slot records composed only of `real`s, + they each have different names for at least some slots. *) + +(* You can use hash notation to get values out of tuples. *) + +val H = #H Hsv (* : real *) +val s = #s Hsl (* : real *) + (* Functions! *) fun add_them (a, b) = a + b (* A simple function that adds two numbers *) val test_it = add_them (3, 4) (* gives 7 *) @@ -224,17 +246,26 @@ fun fibonacci 0 = 0 (* Base case *) | fibonacci 1 = 1 (* Base case *) | fibonacci n = fibonacci (n - 1) + fibonacci (n - 2) (* Recursive case *) -(* Pattern matching is also possible on composite types like tuples and lists. - Writing "fun solve2 (a, b, c) = ..." is in fact a pattern match on the one - three-tuple solve2 takes as argument. Similarly, but less intuitively, you - can match on a list consisting of elements in it (from the beginning of the - list only). *) +(* Pattern matching is also possible on composite types like tuples, lists and + records. Writing "fun solve2 (a, b, c) = ..." is in fact a pattern match on + the one three-tuple solve2 takes as argument. Similarly, but less intuitively, + you can match on a list consisting of elements in it (from the beginning of + the list only). *) fun first_elem (x::xs) = x fun second_elem (x::y::xs) = y fun evenly_positioned_elems (odd::even::xs) = even::evenly_positioned_elems xs | evenly_positioned_elems [odd] = [] (* Base case: throw away *) | evenly_positioned_elems [] = [] (* Base case *) +(* When matching on records, you must use their slot names, and you must bind + every slot in a record. The order of the slots doesn't matter though. *) + +fun rgbToTup {r, g, b} = (r, g, b) (* fn : {b:'a, g:'b, r:'c} -> 'c * 'b * 'a *) +fun mixRgbToTup {g, b, r} = (r, g, b) (* fn : {b:'a, g:'b, r:'c} -> 'c * 'b * 'a *) + +(* If called with {r=0.1, g=0.2, b=0.3}, either of the above functions + would return (0.1, 0.2, 0.3). But it would be a type error to call them + with {r=0.1, g=0.2, b=0.3, a=0.4} *) (* Higher order functions: Functions can take other functions as arguments. Functions are just other kinds of values, and functions don't need names @@ -383,6 +414,25 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,", "Violets are blue.", "I have a gun.", "Get in the van." ] *) + +(* We can create references to data which can be updated *) +val counter = ref 0 (* Produce a reference with the ref function *) + +(* Assign to a reference with the assignment operator *) +fun set_five reference = reference := 5 + +(* Read a reference with the dereference operator *) +fun equals_five reference = !reference = 5 + +(* We can use while loops for when recursion is messy *) +fun decrement_to_zero r = if !r < 0 + then r := 0 + else while !r >= 0 do r := !r - 1 + +(* This returns the unit value (in practical terms, nothing, a 0-tuple) *) + +(* To allow returning a value, we can use the semicolon to sequence evaluations *) +fun decrement_ret x y = (x := !x - 1; y) ``` ## Further learning diff --git a/swift.html.markdown b/swift.html.markdown index 5e6b76e6..f2e9d04c 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -3,6 +3,10 @@ language: swift contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] + - ["Clayton Walker", "https://github.com/cwalk"] + - ["Fernando Valverde", "http://visualcosita.xyz"] filename: learnswift.swift --- @@ -10,7 +14,7 @@ Swift is a programming language for iOS and OS X development created by Apple. D The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. -See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift. +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/), which has a complete tutorial on Swift. ```swift // import a module @@ -22,10 +26,13 @@ import UIKit // Xcode supports landmarks to annotate your code and lists them in the jump bar // MARK: Section mark +// MARK: - Section mark with a separator line // TODO: Do something soon // FIXME: Fix this code -println("Hello, world") +// In Swift 2, println and print were combined into one print method. Print automatically appends a new line. +print("Hello, world") // println is now print +print("Hello, world", appendNewLine: false) // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -45,16 +52,17 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values // uses -D build configuration #if false - println("Not printed") + print("Not printed") let buildValue = 3 #else let buildValue = 7 #endif -println("Build value: \(buildValue)") // Build value: 7 +print("Build value: \(buildValue)") // Build value: 7 /* - Optionals are a Swift language feature that allows you to store a `Some` or - `None` value. + Optionals are a Swift language feature that either contains a value, + or contains nil (no value) to indicate that a value is missing. + A question mark (?) after the type marks the value as optional. Because Swift requires every property to have a value, even nil must be explicitly stored as an Optional value. @@ -68,13 +76,19 @@ var someOptionalString2: Optional<String> = "optional" if someOptionalString != nil { // I am not nil if someOptionalString!.hasPrefix("opt") { - println("has the prefix") + print("has the prefix") } - + let empty = someOptionalString?.isEmpty } someOptionalString = nil +/* + Trying to use ! to access a non-existent optional value triggers a runtime + error. Always make sure that an optional contains a non-nil value before + using ! to force-unwrap its value. +*/ + // implicitly unwrapped optional var unwrappedString: String! = "Value is expected." // same as above, but ! is a postfix operator (more syntax candy) @@ -89,13 +103,13 @@ if let someOptionalStringConstant = someOptionalString { // Swift has support for storing a value of any type. // AnyObject == id -// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc) +// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc.) var anyObjectVar: AnyObject = 7 anyObjectVar = "Changed value to a string, not good practice, but possible." /* Comment here - + /* Nested comments are also supported */ @@ -116,6 +130,7 @@ shoppingList[1] = "bottle of water" let emptyArray = [String]() // let == immutable let emptyArray2 = Array<String>() // same as above var emptyMutableArray = [String]() // var == mutable +var explicitEmptyMutableStringArray: [String] = [] // same as above // Dictionary @@ -127,6 +142,7 @@ occupations["Jayne"] = "Public Relations" let emptyDictionary = [String: Float]() // let == immutable let emptyDictionary2 = Dictionary<String, Float>() // same as above var emptyMutableDictionary = [String: Float]() // var == mutable +var explicitEmptyMutableDictionary: [String: Float] = [:] // same as above // @@ -137,21 +153,21 @@ var emptyMutableDictionary = [String: Float]() // var == mutable let myArray = [1, 1, 2, 3, 5] for value in myArray { if value == 1 { - println("One!") + print("One!") } else { - println("Not one!") + print("Not one!") } } // for loop (dictionary) var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } // for loop (range) for i in -1...shoppingList.count { - println(i) + print(i) } shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number @@ -164,7 +180,7 @@ while i < 1000 { // do-while loop do { - println("hello") + print("hello") } while 1 == 2 // Switch @@ -221,8 +237,8 @@ let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 // Ignore Tuple (or other) values by using _ (underscore) let (_, price1, _) = pricesTuple // price1 == 3.69 -println(price1 == pricesTuple.1) // true -println("Gas price: \(price)") +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") // Named tuple params func getGasPrices2() -> (lowestPrice: Double, highestPrice: Double, midPrice: Double) { @@ -260,7 +276,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { var someIntA = 7 var someIntB = 3 swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7 // @@ -301,10 +317,10 @@ print(numbers) // [3, 6, 18] // MARK: Structures // -// Structures and classes have very similar capabilites +// Structures and classes have very similar capabilities struct NamesTable { let names = [String]() - + // Custom subscript subscript(index: Int) -> String { return names[index] @@ -314,7 +330,7 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] -println("Name is \(name)") // Name is Them +print("Name is \(name)") // Name is Them // // MARK: Classes @@ -335,7 +351,7 @@ public class Shape { internal class Rect: Shape { var sideLength: Int = 1 - + // Custom getter and setter property private var perimeter: Int { get { @@ -346,16 +362,16 @@ internal class Rect: Shape { sideLength = newValue / 4 } } - - // Computed properties must be declared as `var`, you know, cause they can change + + // Computed properties must be declared as `var`, you know, cause' they can change var smallestSideLength: Int { return self.sideLength - 1 } - + // Lazily load a property // subShape remains nil (uninitialized) until getter called lazy var subShape = Rect(sideLength: 4) - + // If you don't need a custom getter and setter, // but still want to run code before and after getting or setting // a property, you can use `willSet` and `didSet` @@ -365,19 +381,19 @@ internal class Rect: Shape { print(someIdentifier) } } - + init(sideLength: Int) { self.sideLength = sideLength // always super.init last when init custom properties super.init() } - + func shrink() { if sideLength > 0 { --sideLength } } - + override func getArea() -> Int { return sideLength * sideLength } @@ -400,7 +416,36 @@ let aShape = mySquare as Shape // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep, it's mySquare") + print("Yep, it's mySquare") +} + +// Optional init +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // Place a question mark postfix after `init` is an optional init + // which can return nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // will not execute since myEmptyCircle is nil + print("circle is not nil") } @@ -432,7 +477,29 @@ enum BookName: String { case John = "John" case Luke = "Luke" } -println("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.John.rawValue)") + +// Enum with associated Values +enum Furniture { + // Associate with Int + case Desk(height: Int) + // Associate with String and Int + case Chair(String, Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } + } +} + +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair("Foo", 40) +print(chair.description()) // "Chair of Foo with 40 cm" // @@ -457,10 +524,13 @@ protocol ShapeGenerator { class MyShape: Rect { var delegate: TransformShape? - + func grow() { sideLength += 2 - + + // Place a question mark after an optional property, method, or + // subscript to gracefully ignore a nil value and return nil + // instead of throwing a runtime error ("optional chaining"). if let allow = self.delegate?.canReshape?() { // test for delegate then for method self.delegate?.reshaped?() @@ -482,21 +552,21 @@ extension Square: Printable { } } -println("Square: \(mySquare)") +print("Square: \(mySquare)") // You can also extend built-in types extension Int { var customProperty: String { return "This is \(self)" } - + func multiplyBy(num: Int) -> Int { return num * self } } -println(7.customProperty) // "This is 7" -println(14.multiplyBy(2)) // 42 +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. @@ -510,7 +580,7 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { return nil } let foundAtIndex = findIndex([1, 2, 3, 4], 3) -println(foundAtIndex == 2) // true +print(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -526,9 +596,23 @@ prefix func !!! (inout shape: Square) -> Square { } // current value -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare -println(mySquare.sideLength) // 12 +print(mySquare.sideLength) // 12 + +// Operators can also be generics +infix operator <-> {} +func <-><T: Equatable> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" ``` diff --git a/ta_in/css-ta.html.markdown b/ta_in/css-ta.html.markdown new file mode 100644 index 00000000..56f94ed0 --- /dev/null +++ b/ta_in/css-ta.html.markdown @@ -0,0 +1,254 @@ +--- +language: css +contributors: + - ["Mohammad Valipour", "https://github.com/mvalipour"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["Geoffrey Liu", "https://github.com/g-liu"] + - ["Connor Shea", "https://github.com/connorshea"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: learncss.css +lang:in-ta +--- + + +இணையத்தின் ஆரம்ப காலத்தில் முழுமையாக உரைகளை மட்டுமே கொண்டிருந்தன. +ஆனால் உலாவிகளில் கொண்டு வரப்பட்ட மாற்றங்களில் முழுமையான காட்சிபடுத்தல்களுடன் +கூடிய இணையதளங்கள் உருவாகின. + + +CSS ஆனது HTML மற்றும் அதன் அழகுபடுத்கூடிய காரணிகளையும் வேறுபடுத்த உதவியது. + +ஒரு html இல் உள்ள உறுப்புகளை(elements) வெவ்வேறு வகையான காட்சி பண்புகளை வழங்க உதவுகிறது. + +இந்த வழிகாட்டி CSS2 உக்கு எழுதப்பட்டுள்ளது, இருப்பினும் தற்போது CSS 3 வேகமாக பிரபல்யமாகி வருகிறது. + +**குறிப்பு:** +CSS ஆனது முற்று முழுதாக visual(காட்சி) மாற்றங்களை தருவதால் அதை நீங்கள் முயற்சிக்க +இதை உபயோகபடுத்தலாம் [dabblet](http://dabblet.com/). +இந்த வழிகாட்டியின் பிரதான நோக்கம் CSS இன் syntax மற்றும் மேலும் சில வழிமுறைகளை +உங்களுக்கு கற்று தருவதாகும் + +```css +/* css இல் குறிப்புகளை இப்படி இடலாம் */ + +/* #################### + ## SELECTORS + #################### */ + +/* ஒரு HTML பக்கத்தில் இருக்கும் உறுப்பை நாம் selector மூலம் தெரிவு செய்யலாம் +selector { property: value; /* more properties...*/ } + +/* +கிழே ஒரு உதாரணம் காட்டப்பட்டுள்ளது: + +<div class='class1 class2' id='anID' attr='value' otherAttr='en-us foo bar' /> +*/ + +/* நீங்கள் அந்த உறுப்பை அதன் CSS class மூலம் தெரியலாம் */ +.class1 { } + +/* அல்லது இவ்வாறு இரண்டு class மூலம் தெரியலாம்! */ +.class1.class2 { } + +/* அல்லது அதன் பெயரை பாவித்து தெரியலாம் */ +div { } + +/* அல்லது அதன் id ஐ பயன்படுத்தி தெரியலாம்*/ +#anID { } + +/* அல்லது ஒரு உறுப்பின் பண்பு ஒன்றின் மூலம்! */ +[attr] { font-size:smaller; } + +/* அல்லது அந்த பண்பு ஒரு குறிப்பிட்ட பெறுமானத்தை கொண்டு இருப்பின் */ +[attr='value'] { font-size:smaller; } + +/* ஒரு பெறுமதியுடன் ஆரம்பமாகும் போது (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* அல்லது ஒரு பெறுமதியுடன் முடிவடையும் போது (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* அல்லது காற்புள்ளியால் பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின் */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* அல்லது `-` பிரிக்கப்பட்ட பெறுமானங்களை கொண்டு இருப்பின், உ.ம்:-, "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* நாம் இரண்டு selectors ஐ ஒன்றாக உபயோகித்தும் ஒரு உறுப்பை அணுக முடியும் , +அவற்றுக்கு இடயே இடைவெளி காணப்படகூடாது + */ +div.some-class[attr$='ue'] { } + +/*அல்லது ஒரு உறுப்பினுள் இருக்கும் இன்னொரு உறுப்பை (child element) அணுக */ +div.some-parent > .class-name { } + +/* ஒரு ஒரு பிரதான உறுப்பில் உள்ள உப உறுப்புகளை அணுக*/ +div.some-parent .class-name { } + +/* மேலே குறிபிட்ட அணுகுமுறையில் இடைவெளி காணப்படாது விடின் + அந்த selector வேலை செய்யாது + */ +div.some-parent.class-name { } + +/* அல்லது ஒரு உறுப்புக்கு அடுத்துள்ள */ +.i-am-just-before + .this-element { } + +/* or அல்லது அதற்கு முந்தய உறுப்பின் மூலம் */ +.i-am-any-element-before ~ .this-element { } + +/* + சில selectors ஐ pseudo class மூலம் அணுக முடியும் , எப்போது எனில் அவை + குறித்த ஒரு நிலையில் இருக்கும் போது ஆகும் + */ + +/* உதாரணமாக நாம் ஒரு உறுப்பின் மீதாக cursor ஐ நகர்த்தும் போது */ +selector:hover { } + +/* அல்லது ஒரு +பார்வையிட்ட இணைப்பு */ +selector:visited { } + +/* அல்லது ஒரு பார்வையிடபடாத இணைப்பு */ +selected:link { } + +/* அல்லது ஒரு element ஐ focus செய்யும் போது */ +selected:focus { } + +/* + எல்லா elementகளையும் ஒரே நேரத்தில் அணுக `*` +*/ +* { } /* all elements */ +.parent * { } /* all descendants */ +.parent > * { } /* all children */ + +/* #################### + ## பண்புகள் + #################### */ + +selector { + + /* நீளத்தின் அலகுகள் absolute அல்லது relative ஆக இருக்கலாம். */ + + /* Relative units */ + width: 50%; /* percentage of parent element width */ + font-size: 2em; /* multiples of element's original font-size */ + font-size: 2rem; /* or the root element's font-size */ + font-size: 2vw; /* multiples of 1% of the viewport's width (CSS 3) */ + font-size: 2vh; /* or its height */ + font-size: 2vmin; /* whichever of a vh or a vw is smaller */ + font-size: 2vmax; /* or greater */ + + /* Absolute units */ + width: 200px; /* pixels */ + font-size: 20pt; /* points */ + width: 5cm; /* centimeters */ + min-width: 50mm; /* millimeters */ + max-width: 5in; /* inches */ + + + /* Colors */ + color: #F6E; /* short hex format */ + color: #FF66EE; /* long hex format */ + color: tomato; /* a named color */ + color: rgb(255, 255, 255); /* as rgb values */ + color: rgb(10%, 20%, 50%); /* as rgb percentages */ + color: rgba(255, 0, 0, 0.3); /* as rgba values (CSS 3) Note: 0 < a < 1 */ + color: transparent; /* equivalent to setting the alpha to 0 */ + color: hsl(0, 100%, 50%); /* as hsl percentages (CSS 3) */ + color: hsla(0, 100%, 50%, 0.3); /* as hsla percentages with alpha */ + + /* Images as backgrounds of elements */ + background-image: url(/img-path/img.jpg); /* quotes inside url() optional */ + + /* Fonts */ + font-family: Arial; + /* if the font family name has a space, it must be quoted */ + font-family: "Courier New"; + /* if the first one is not found, the browser uses the next, and so on */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## Usage + +ஒரு css file ஐ save செய்ய `.css`. + +```xml +<!-- உங்கள் css file ஐ <head>. உள் குறிப்பிட வேண்டும் + சரியான முறையை பார்க்க http://stackoverflow.com/questions/8284365 --> +<link rel='stylesheet' type='text/css' href='path/to/style.css' /> + +<!-- நீங்கள் css ஐ html உள்ளும் எழுத முடியும் --> +<style> + a { color: purple; } +</style> + +<!-- அல்லது css ஐ நேரடியாக அந்த element இல் எழுத முடியும் --> +<div style="border: 1px solid red;"> +</div> +``` + +## Precedence அல்லது Cascade + +ஒரு element ஆனது ஒன்றுக்கு மேற்பட்ட selectors மூலம் அணுகபடலாம் ,இவ்வாறான சந்தர்பங்களில் +ஒரு குறிபிட்ட விதிமுறையை பின்பற்றுகிறது இது cascading என அழைக்கபடுகிறது, அதனால் தன +இது Cascading Style Sheets என அழைக்கபடுகிறது. + + +கிழே தரப்பட்டுள்ள css இன் படி: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +அத்துடன் கிழே தரப்பட்டுள்ள கட்டமைப்பின்படியும்: + +```xml +<p style='/*F*/ property:value;' class='class1 class2' attr='value' /> +``` + + +css முன்னுரிமை பின்வருமாறு +* `E` இதுவே அதிக முக்கியத்துவம் வாய்ந்தது காரணம் இது `!important` பயன்படுத்துகிறது. இதை பயன்படுத்துவதை தவிர்க்கவும் +* `F` இது இரண்டாவது காரணம் இது inline style. +* `A` இது மூன்றவதாக வருகிறது, காரணம் இது மூன்று காரணிகளை குறிக்கிறது : element(உறுப்பு) பெயர் `p`, அதன் class `class1`, an அதன் பண்பு(attribute) `attr='value'`. +* `C` இது அடுத்த நிலையில் உள்ளது கடைசி. +* `B` இது அடுத்தது. +* `D` இதுவே கடைசி . + +## css அம்சங்களின் பொருந்தகூடிய தன்மை + +பெரும்பாலான css 2 வின் அம்சங்கள் எல்லா உலாவிகளிலும் , கருவிகளிலும் உள்ளன. ஆனால் முன்கூட்டியே அந்த அம்சங்களை பரிசோதிப்பது நல்லது. + +## வளங்கள் + +* To run a quick compatibility check, [CanIUse](http://caniuse.com). +* CSS Playground [Dabblet](http://dabblet.com/). +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) + +## மேலும் வாசிக்க + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) and [LESS](http://lesscss.org/) for CSS pre-processing +* [CSS-Tricks](https://css-tricks.com) diff --git a/ta_in/javascript-ta.html.markdown b/ta_in/javascript-ta.html.markdown new file mode 100644 index 00000000..f0b0a36a --- /dev/null +++ b/ta_in/javascript-ta.html.markdown @@ -0,0 +1,594 @@ +--- +language: javascript +contributors: + - ['Adam Brenecki', 'http://adam.brenecki.id.au'] + - ['Ariel Krakowski', 'http://www.learneroo.com'] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +filename: javascript.js +lang:in-ta +--- + +javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich +என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான +ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது. +இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு +உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு +மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட +இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது. + +உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக +மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் +V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . + +உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள +[@adambrenecki](https://twitter.com/adambrenecki), or +[adam@brenecki.id.au](mailto:adam@brenecki.id.au). + +```js +// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் + +/* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */ + +// ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் . +doStuff(); + +// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் +// ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர . +doStuff() + +// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் + +// எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் . + +/////////////////////////////////// +// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) + +// JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double). +// தசமி எண்வகை (Doubles) 2^ 52 வரை சேமிக்க கூடியது +// முழு எண்வகையின் 9✕10¹⁵ சேமிக்க போதுமானது . +3; // = 3 +1.5; // = 1.5 + +// அடிப்படை கணித பொறிமுறைகள் +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// வகுத்தல் +5 / 2; // = 2.5 + + +//bitwise பொறிமுறையை உபயோகிக்கும் போது +//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக +//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் + +1 << 2; // = 4 + +// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது +(1 + 3) * 2; // = 8 + +// மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன : +Infinity; // result of e.g. 1/0 +-Infinity; // result of e.g. -1/0 +NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் + +// தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது . +true; +false; + +// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது +'abc'; +"Hello, world"; + +// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது +!true; // = false +!false; // = true + +// சமமா என பார்க்க === +1 === 1; // = true +2 === 1; // = false + +// சமனற்றவையா என பார்க்க !== +1 !== 1; // = false +2 !== 1; // = true + +// மேலும் சில ஒப்பீடுகள் +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// இரண்டு சரங்களை(Strings) ஒன்றாக இணைப்பதற்கு + +"Hello " + "world!"; // = "Hello world!" + +// இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and > +"a" < "b"; // = true + +// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க +"5" == 5; // = true +null == undefined; // = true + +// ...இல்லாவிடின் === +"5" === 5; // = false +null === undefined; // = false + +// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத +வெளியீடுகளை தரலாம் ... +13 + !0; // 14 +"13" + !0; // '13true' + +// ஒரு சரத்தில்(string ) உள்ள எழுத்தை பெற `charAt` +"This is a string".charAt(0); // = 'T' + + +//... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring +"Hello world".substring(0, 5); // = "Hello" + +// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய +"Hello".length; // = 5 + +// `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன . +null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் +undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் ( + // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது ) + +// ஆகியன தர்க்க ரீதியாக பிழையானவை(false) , மற்றவை யாவும் சரியானவை (true). +// 0 மானது பிழையை (false) குறிக்கும் "0" சரியை (true) குறிக்கும் எனினும் 0 == "0". + +/////////////////////////////////// +// 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects) + +// மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது . +//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript +//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க +var someVar = 5; + +// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் +//அது தவறில்லை ... +someOtherVar = 10; + +// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் +//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் +//மட்டுபடுத்தபடும் . + +//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் +//வழங்கப்படும் +var someThirdVar; // = undefined + +// மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன : +someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10 +someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100 + +//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை +//மேற்கொள்ள +someVar++; // someVar இன் பெறுமானம் இப்போது is 101 +someVar--; // someVar இன் பெறுமானம் இப்போது 100 + +// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது +var myArray = ["Hello", 45, true]; + +// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு +//அணுகமுடியும் . +// அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் . +myArray[1]; // = 45 + +// அணிகள் உள்ள உறுப்புகளை மாற்றமுடியும் அத்துடன் உறுப்புகளின் எண்ணிக்கையும் மாறலாம் . +myArray.push("World"); +myArray.length; // = 4 + +// அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற . +myArray[3] = "Hello"; + +// JavaScript's பொருள் (objects) அகராதியை ஒத்தன +// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) +//அதுக்குரிய பெறுமானமும்(value) காணப்படும் . +var myObj = {key1: "Hello", key2: "World"}; + +// விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை +//சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின் +//அவசியம் இல்லை +// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் +var myObj = {myKey: "myValue", "my other key": 4}; + +//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு +//அணுகமுடியும் , +myObj["my other key"]; // = 4 + +// ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier) +//பெயர் மூலம் அணுக முடியும் +myObj.myKey; // = "myValue" + +// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய +//சாவிகளை(keys) இடவும் முடியும் +myObj.myThirdKey = true; + +//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது +//அது வெளியிடும் பெறுமதி `undefined`. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு + +// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது + +// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் +//அல்லது என்ற வடிவமைப்பை +var count = 1; +if (count == 3){ + // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது +} else if (count == 4){ + // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது +} else { + // count ஆனது 3 அல்ல 4 அல்ல எனின் +} + +// ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`. +while (true){ + // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் ! +} + +// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் +var input; +do { + input = getInput(); +} while (!isValid(input)) + +// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது +//மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் , +//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் + +for (var i = 0; i < 5; i++){ + // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் +} + +//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + description += person[x] + " "; +} + +//ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது +//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க +var description = ""; +var person = {fname:"Paul", lname:"Ken", age:18}; +for (var x in person){ + if (person.hasOwnProperty(x)){ + description += person[x] + " "; + } +} + +//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் +//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் +//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் + +// && is logical and, || is logical or +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour is either red or blue +} + +// && and || "short circuit", which is useful for setting default values. +var name = otherName || "default"; + + + +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. Functions, Scope and Closures + +// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் +//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் +//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது +//அவதானமாக இருக்கவும் +function myFunction() +{ + return // <- semicolon automatically inserted here + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு +//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் +// உதாரணமாக ஒரு event handler: +function myFunction(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +} +setTimeout(myFunction, 5000); +// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி +//உலாவிகளிலும் ,Node .js காணப்படுகிறது + +// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை +// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் +setTimeout(function(){ + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் +}, 5000); + +// JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ; +//functions தமக்கென ஒரு scope கொண்டுள்ளன . + +if (true){ + var i = 5; +} +i; // = 5 - //இது undefined அல்ல + +// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன +//இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope +//இற்கு மாறுவதை தவிர்க்கலாம் . +(function(){ + var temporary = 5; + //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" + //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . + //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் + window.permanent = 10; +})(); +temporary; // raises ReferenceError +permanent; // = 10 + +//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் +//ஒரு function இன்னொரு function உள் உருவாக்கபடின் +//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // Inner functions ஆனது local scope இல் காணப்படும் + //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function, + //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். + +} +sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் + +/////////////////////////////////// +// 5. Objects; Constructors and Prototypes பற்றி மேலும் + +// Objects functions ஐ கொண்டிருக்கலாம் +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் +//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் +var myFunc = myObj.myFunc; +myFunc(); // = undefined + + +//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் +//`this` மூலம் +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் +//அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும் + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument +//ஆக எடுக்கிறது. + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண +//வேண்டும் எனில் மிகவும் உபயோகமானது + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை +//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் + +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + + +//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி +//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions +//constructors என அழைக்கப்படும் + +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது +//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது +//அந்த property இல்லாவிடின் interpreter ஆனது +//அதன் prototype உள்ளதா என பார்க்கும் + +//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ +//இலகுவாக `__proto__` மூலம் access செய்ய முடியும் . +//இது prototype பாவணை யை இலகுவாக்கினாலும் +//இது சரியான ஒரு முறை அல்ல +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// This works for functions, too. +myObj.myFunc(); // = "hello world!" + +//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் +//prototype search செய்யப்படும் +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் +//நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் ) +//பிரதிபலிக்கும் +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + + +//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல +//எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள் +//உள்ளன + +// முதல் முறை Object.create இது அண்மையில் அறிமுகம் செய்ய பட்ட ஒன்று +//எனவே சில இடங்களில் இந்த முறை இன்னும் அறிமுகம் ஆகவில்லை + +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + + +// இரண்டாவது முறை , இது சகல இடங்களிலும் வேலைசெய்யும், இது constructors மூலம். +//constructors prototype என்னும் ஒரு காரணியை கொண்டுள்ளது , இது constructor function +//இன் prototype அன்று. ,இது நாம் new என்ற குறியீட்டு சொல்லையும் அந்த constructor உபயோகித்து +//உருவாக்கபடுகிறது + +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// Built-in types like strings and numbers also have constructors that create +// equivalent wrapper objects. +// JavaScript இல் உள்ள strings மற்றும் numbers வகைகளும் constructors கொண்டுள்ளன +//இவை wrapper objects ஐ ஒத்தன + +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + + +//இவை மிக சிறிய அளவில் ஒத்தவை +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // இந்த கூற்றானது செயல்படுத்தபடாது ஏனெனில் ௦ false ஆகும் +} + +// However, the wrapper objects and the regular builtins share a prototype, so +// you can actually add functionality to a string, for instance. + +//இருப்பினும் wrapper objects மற்றும் regular builtins ஆகியன prototype ஒன்றை கொண்டுள்ளன +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// This fact is often used in "polyfilling", which is implementing newer +// features of JavaScript in an older subset of JavaScript, so that they can be +// used in older environments such as outdated browsers. + +//இந்த முறையானது "polyfilling" இல் உபயோகபடுத்தபடுகிறது. +//புதிய சில வசதிகளை JavaScript பழைய JavaScript பிரதிகளில் இல் உருவாக்குகிறது. +//இது பழைய சூழல்களில் உபயோகிகப்படும். + + +//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் +//அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க +//முடியும் + +if (Object.create === undefined){ // don't overwrite it if it exists + Object.create = function(proto){ + // make a temporary constructor with the right prototype + var Constructor = function(){}; + Constructor.prototype = proto; + // then use it to create a new, appropriately-prototyped object + return new Constructor(); + } +} +``` + +## மேலும் JavaScript பற்றி கற்க + +The [Mozilla Developer +Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) provides +excellent documentation for JavaScript as it's used in browsers. Plus, it's a +wiki, so as you learn more you can help others out by sharing your own +knowledge. + +MDN's [A re-introduction to +JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +covers much of the concepts covered here in more detail. This guide has quite +deliberately only covered the JavaScript language itself; if you want to learn +more about how to use JavaScript in web pages, start by learning about the +[Document Object +Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) + +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +guide of all the counter-intuitive parts of the language. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. + +In addition to direct contributors to this article, some content is adapted +from Louie Dinh's Python tutorial on this site, and the [JS +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +on the Mozilla Developer Network. diff --git a/ta_in/json-ta.html.markdown b/ta_in/json-ta.html.markdown new file mode 100644 index 00000000..d85e0d82 --- /dev/null +++ b/ta_in/json-ta.html.markdown @@ -0,0 +1,86 @@ +--- +language: json +filename: learnjson.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang: ta-in +--- + +ஜேசன் ஒரு ஒரு மிக எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். +Learn X in Y Minutes இதுவே மிகவும் இலகுவான பகுதியாக அமைய போகிறது. + + +ஜேசன் இன் எளிமையான கட்டமைப்பில் குறிப்புக்கள் (Comments) இல்லை , எனினும் +பெரும்பாலான பாகுபடுத்திகளில் C - style முறையிலான (`//`, `/* */`) குறிப்புகளை இட முடியும். +சில பாகுபடுத்திகள்(interpreter) குறிப்புகளுக்கு (comments)தொடர்ச்சியாக வரும் + காற்புள்ளியை அனுமதிக்கின்றன (உதாரணமாக ஒரு அணியை (array) அடுத்துவரும் காற்புள்ளி + அல்லது ஒரு பொருளில் (object)உள்ள கடைசி உறுப்பை/சொத்தை( last property) அடுத்து வரும் காற்புள்ளி ) +எனினும் சகல இடங்களிலும் ஜேசன் பயன்படுத்த பட வேண்டும் எனில் மேற்கூறிய குறிப்புகளை தவிர்த்தல் நல்லது .\ + + +ஜேசன் 100% மிக சரியாக அமைவது மட்டும் இன்றி +இலகுவாக புரியக் கூடிய எளிய தரவு உள்மாற்றீட்டு வடிவம் ஆகும். + + +ஜேசன் அனுமதிக்கும் தரவு வகைகள் : சரம் (string),முழு (int),பூலியன் (தர்க ரீதியில் ஆன கட்டமைப்பு), +அணி (array ),கழி (null ),பொருள் (object). + +ஜேசன் அனுமதிக்கும் அல்லது பாவனைக்கு உட்படுத்த கூடிய உலாவிகள் (browsers): +Firefox(Mozilla) 3.5, Internet Explorer 8, Chrome, Opera 10, Safari 4. + +ஜேசனின் கோப்புவகை(filetype) ".json " ஆகும் . + +ஜேசன் உரைக்கான MIME வகை "application/json" ஆகும். +ஜேசன் இல் காணப்படும் பிரதான பின்னடைவு தரவு இனம் இதுவென்று வரையறுக்க +படாமை ஆகும் . + +ஒரு ஜேசன் இன் எளிய கட்டமைப்பு கீழே காட்டப்பட்டுள்ளது + +```json +{ + "key": "ஒரு சாவிக்கு ஒரு பெறுமதி உள்ளது ", + + "keys": "சாவிகள் , மற்றும் பெறுமானங்கள் மேற்கோள் குறிக்குள் இடல் வேண்டும்", + "numbers": 0, + "strings": "Hellø, wørld. எல்லாவகையான unicode உம் அனுமதிக்கப்படும், அத்துடன் \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "பெரும்பாலான கட்டமைப்புகள் objects இல் இருந்தே வருகின்றன", + + "array": [0, 1, 2, 3, "array யானது எல்லாவகையான பெறுமானங்களையும் கொண்டிருக்கும்", 5], + + "another object": { + "comment": "இவை ஒன்றுக்குள் இன்னொன்றை எழுத முடியும்" + } + }, + + "silliness": [ + { + "sources of potassium": ["வாழைபழம்"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "alternative style": { + "comment": "இதை பார்க்கவும்" + , "comma position": "doesn't matter - as long as it's before the value, then it's valid" + , "another comment": "how nice" + }, + + "that was short": "நீங்கள் ஜேசன் பற்றி யாவற்றையும் கற்றுள்ளீர்கள்" +} +``` + diff --git a/ta_in/xml-ta.html.markdown b/ta_in/xml-ta.html.markdown new file mode 100644 index 00000000..a9bfa9cd --- /dev/null +++ b/ta_in/xml-ta.html.markdown @@ -0,0 +1,145 @@ +--- +language: xml +filename: learnxml.xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Rasendran Kirushan", "https://github.com/kirushanr"] +lang:in-ta +--- + + +XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும் +தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது + + +HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது +* XML வாக்கிய அமைப்பு + + +```xml +<!-- இது ஒரு XML குறிப்பு --> + +<?xml version="1.0" encoding="UTF-8"?> +<bookstore> + <book category="COOKING"> + <title lang="en">Everyday Italian</title> + <author>Giada De Laurentiis</author> + <year>2005</year> + <price>30.00</price> + </book> + <book category="CHILDREN"> + <title lang="en">Harry Potter</title> + <author>J K. Rowling</author> + <year>2005</year> + <price>29.99</price> + </book> + <book category="WEB"> + <title lang="en">Learning XML</title> + <author>Erik T. Ray</author> + <year>2003</year> + <price>39.95</price> + </book> +</bookstore> + + + <!-- + + மேல காட்டப்பட்டுள்ளது ஒரு xml file இன் உதாரணம் ஆகும் + அது metadata உடன் ஆரம்பமாகிறது + XML ஆனது ஒரு மரத்தை போன்ற கட்டமைப்பை ஒத்தது. + இங்கு root node (கொப்பு) `bookstore` இது மூன்று கிளைகள் (child nodes) + கொண்டுள்ளது. இந்த கிளைகள் மேலும் சில கிளைகளை கொண்டு இருக்கலாம் + ஒவொரு node கட்டமைப்பும் ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும் + கிளைகள் இந்த கட்டமைப்புக்கு இடையில் நிறுவப்படும் + --> + + +<!-- +XML இரண்டு வகையான தகவல்களை கொண்டு செல்லக்கூடியது +1- Attributes -> ஒரு கணு(node) பற்றிய metadata +பொதுவாக XML Parser இந்த தகவலை பயன்படுத்தியே தகவலை +சரியான முறையில் சேமிக்க. +இது xml கட்டமைப்பின் ஆரம்பத்தில் உள்ள name="value" +தீர்மானிக்கபடுகிறது. + +2-Elements ->இவற்றில் முற்றிலும் தகவல்களே சேமிக்கபட்டு இருக்கும் +Elements ஒரு `<` ஆரம்பாமாகி `>` முடிவடையும் காணப்படும் + + +--> + +<!-- கிழே உள்ள element இரண்டு பெறுமானங்களை கொண்டுள்ளது --> +<file type="gif" id="4293">computer.gif</file> + + +``` + +* சரியான முறையில் ஒழுகுபடுத்தபட்ட X document + + +ஒரு XML document ஆனது சரியான முறையில் எழுத பட்டிருப்பின் மட்டுமே அது +சிறந்த வகையில் வடிவமைக்கபட்டுள்ளது,எனினும் மேலும் பல கட்டுபாடுகளை +நாம் ஒரு xml document உக்கு இட முடியும் உ.ம்:-DTD மற்றும் XML Schema. + + +ஒரு xml document ஆனது ஒரு வரையறுக்கபட்டிருப்பின் மட்டுமே +அது சரி என கொள்ளப்படும் + + +With this tool, you can check the XML data outside the application logic. +இந்த கருவியை உபயோகித்து xml தகவல்களை சோதிக்க முடியும் + +```xml + +<!-- கீழே bookstore html document இன் எளிமையான வடிவம் + DTD வரையறைகளுடன் +--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> + +<!-- DTD ஆனது பின்வருமாறு அமையும் :--> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + + +<!-- DTD ஆனது root node ஐ உருவாக்கிய பின் நிறுவ படுகிறது ,இது ஒன்று அல்லது +ஒன்றிக்கு மேற்பட்ட child node களை எதிர்பார்க்கிறது. + ஒவ்வொரு 'book' உம் கட்டாயமாக ஒரு 'title' , 'price','category', with "Literature" + ஆகிய பெறுமானங்களை கொண்டிருத்தல் அவசியம். +--> + +<!-- DTD ஆனது xml file ஒன்றினுள் உருவாக்கபடுகிறது--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> +``` diff --git a/tcl.html.markdown b/tcl.html.markdown new file mode 100644 index 00000000..b90bd690 --- /dev/null +++ b/tcl.html.markdown @@ -0,0 +1,454 @@ +--- +language: Tcl +contributors: + - ["Poor Yorick", "http://pooryorick.com/"] +filename: learntcl.tcl +--- + +Tcl was created by [John Ousterhout](http://wiki.tcl.tk/John Ousterout) as a +reusable scripting language for chip design tools he was creating. In 1997 he +was awarded the [ACM Software System +Award](http://en.wikipedia.org/wiki/ACM_Software_System_Award) for Tcl. Tcl +can be used both as an embeddable scripting language and as a general +programming language. It can also be used as a portable C library, even in +cases where no scripting capability is needed, as it provides data structures +such as dynamic strings, lists, and hash tables. The C library also provides +portable functionality for loading dynamic libraries, string formatting and +code conversion, filesystem operations, network operations, and more. +Various features of Tcl stand out: + +* Convenient cross-platform networking API + +* Fully virtualized filesystem + +* Stackable I/O channels + +* Asynchronous to the core + +* Full coroutines + +* A threading model recognized as robust and easy to use + + +If Lisp is a list processor, then Tcl is a string processor. All values are +strings. A list is a string format. A procedure definition is a string +format. To achieve performance, Tcl internally caches structured +representations of these values. The list commands, for example, operate on +the internal cached representation, and Tcl takes care of updating the string +representation if it is ever actually needed in the script. The copy-on-write +design of Tcl allows script authors can pass around large data values without +actually incurring additional memory overhead. Procedures are automatically +byte-compiled unless they use the more dynamic commands such as "uplevel", +"upvar", and "trace". + +Tcl is a pleasure to program in. It will appeal to hacker types who find Lisp, +Forth, or Smalltalk interesting, as well as to engineers and scientists who +just want to get down to business with a tool that bends to their will. Its +discipline of exposing all programmatic functionality as commands, including +things like loops and mathematical operations that are usually baked into the +syntax of other languages, allows it to fade into the background of whatever +domain-specific functionality a project needs. It's syntax, which is even +lighter that that of Lisp, just gets out of the way. + + + + + +```tcl +#! /bin/env tclsh + +################################################################################ +## 1. Guidelines +################################################################################ + +# Tcl is not Bash or C! This needs to be said because standard shell quoting +# habits almost work in Tcl and it is common for people to pick up Tcl and try +# to get by with syntax they know from another language. It works at first, +# but soon leads to frustration with more complex scripts. + +# Braces are just a quoting mechanism, not a code block constructor or a list +# constructor. Tcl doesn't have either of those things. Braces are used, +# though, to escape special characters in procedure bodies and in strings that +# are formatted as lists. + + +################################################################################ +## 2. Syntax +################################################################################ + +# Every line is a command. The first word is the name of the command, and +# subsequent words are arguments to the command. Words are delimited by +# whitespace. Since every word is a string, in the simple case no special +# markup such as quotes, braces, or backslash, is necessary. Even when quotes +# are used, they are not a string constructor, but just another escaping +# character. + +set greeting1 Sal +set greeting2 ut +set greeting3 ations + + +#semicolon also delimits commands +set greeting1 Sal; set greeting2 ut; set greeting3 ations + + +# Dollar sign introduces variable substitution +set greeting $greeting1$greeting2$greeting3 + + +# Bracket introduces command substitution. The result of the command is +# substituted in place of the bracketed script. When the "set" command is +# given only the name of a variable, it returns the value of that variable. +set greeting $greeting1$greeting2[set greeting3] + + +# Command substitution should really be called script substitution, because an +# entire script, not just a command, can be placed between the brackets. The +# "incr" command increments the value of a variable and returns its value. +set greeting $greeting[ + incr i + incr i + incr i +] + + +# backslash suppresses the special meaning of characters +set amount \$16.42 + + +# backslash adds special meaning to certain characters +puts lots\nof\n\n\n\n\n\nnewlines + + +# A word enclosed in braces is not subject to any special interpretation or +# substitutions, except that a backslash before a brace is not counted when +# looking for the closing brace +set somevar { + This is a literal $ sign, and this \} escaped + brace remains uninterpreted +} + + +# In a word enclosed in double quotes, whitespace characters lose their special +# meaning +set name Neo +set greeting "Hello, $name" + + +#variable names can be any string +set {first name} New + + +# The brace form of variable substitution handles more complex variable names +set greeting "Hello, ${first name}" + + +# The "set" command can always be used instead of variable substitution +set greeting "Hello, [set {first name}]" + + +# To promote the words within a word to individual words of the current +# command, use the expansion operator, "{*}". +``` + +```tcl +set {*}{name Neo} + +# is equivalent to +set name Neo + + +# An array is a special variable that is a container for other variables. +set person(name) Neo +set person(gender) male +set greeting "Hello, $person(name)" + + +# A namespace holds commands and variables +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +#The full name of a variable includes its enclosing namespace(s), delimited by two colons: +set greeting "Hello $people::person1::name" + + + +################################################################################ +## 3. A Few Notes +################################################################################ + +# All other functionality is implemented via commands. From this point on, +# there is no new syntax. Everything else there is to learn about Tcl is about +# the behaviour of individual commands, and what meaning they assign to their +# arguments. + + +# To end up with an interpreter that can do nothing, delete the global +# namespace. It's not very useful to do such a thing, but it illustrates the +# nature of Tcl. +namespace delete :: + + +# Because of name resolution behaviour, it's safer to use the "variable" command to +# declare or to assign a value to a namespace. If a variable called "name" already +# exists in the global namespace, using "set" here will assign a value to the global variable +# instead of creating a new variable in the local namespace. +namespace eval people { + namespace eval person1 { + variable name Neo + } +} + + +# The full name of a variable can always be used, if desired. +set people::person1::name Neo + + + +################################################################################ +## 4. Commands +################################################################################ + +# Math can be done with the "expr" command. +set a 3 +set b 4 +set c [expr {$a + $b}] + +# Since "expr" performs variable substitution on its own, brace the expression +# to prevent Tcl from performing variable substitution first. See +# "http://wiki.tcl.tk/Brace%20your%20#%20expr-essions" for details. + + +# The "expr" command understands variable and command substitution +set c [expr {$a + [set b]}] + + +# The "expr" command provides a set of mathematical functions +set c [expr {pow($a,$b)}] + + +# Mathematical operators are available as commands in the ::tcl::mathop +# namespace +::tcl::mathop::+ 5 3 + +# Commands can be imported from other namespaces +namespace import ::tcl::mathop::+ +set result [+ 5 3] + + +# New commands can be created via the "proc" command. +proc greet name { + return "Hello, $name!" +} + +#multiple parameters can be specified +proc greet {greeting name} { + return "$greeting, $name!" +} + + +# As noted earlier, braces do not construct a code block. Every value, even +# the third argument of the "proc" command, is a string. The previous command +# rewritten to not use braces at all: +proc greet greeting\ name return\ \"Hello,\ \$name! + + + +# When the last parameter is the literal value, "args", it collects all extra +# arguments when the command is invoked +proc fold {cmd args} { + set res 0 + foreach arg $args { + set res [$cmd $res $arg] + } +} +fold ::tcl::mathop::* 5 3 3 ;# -> 45 + + +# Conditional execution is implemented as a command +if {3 > 4} { + puts {This will never happen} +} elseif {4 > 4} { + puts {This will also never happen} +} else { + puts {This will always happen} +} + + +# Loops are implemented as commands. The first, second, and third +# arguments of the "for" command are treated as mathematical expressions +for {set i 0} {$i < 10} {incr i} { + set res [expr {$res + $i}] +} + + +# The first argument of the "while" command is also treated as a mathematical +# expression +set i 0 +while {$i < 10} { + incr i 2 +} + + +# A list is a specially-formatted string. In the simple case, whitespace is sufficient to delimit values +set amounts 10\ 33\ 18 +set amount [lindex $amounts 1] + + +# Braces and backslash can be used to format more complex values in a list. A +# list looks exactly like a script, except that the newline character and the +# semicolon character lose their special meanings. This feature makes Tcl +# homoiconic. There are three items in the following list. +set values { + + one\ two + + {three four} + + five\{six + +} + + +# Since a list is a string, string operations could be performed on it, at the +# risk of corrupting the formatting of the list. +set values {one two three four} +set values [string map {two \{} $values] ;# $values is no-longer a \ + properly-formatted listwell-formed list + + +# The sure-fire way to get a properly-formmated list is to use "list" commands +set values [list one \{ three four] +lappend values { } ;# add a single space as an item in the list + + +# Use "eval" to evaluate a value as a script +eval { + set name Neo + set greeting "Hello, $name" +} + + +# A list can always be passed to "eval" as a script composed of a single +# command. +eval {set name Neo} +eval [list set greeting "Hello, $name"] + + +# Therefore, when using "eval", use [list] to build up a desired command +set command {set name} +lappend command {Archibald Sorbisol} +eval $command + + +# A common mistake is not to use list functions when building up a command +set command {set name} +append command { Archibald Sorbisol} +eval $command ;# There is an error here, because there are too many arguments \ + to "set" in {set name Archibald Sorbisol} + + +# This mistake can easily occur with the "subst" command. +set replacement {Archibald Sorbisol} +set command {set name $replacement} +set command [subst $command] +eval $command ;# The same error as before: too many arguments to "set" in \ + {set name Archibald Sorbisol} + + +# The proper way is to format the substituted value using use the "list" +# command. +set replacement [list {Archibald Sorbisol}] +set command {set name $replacement} +set command [subst $command] +eval $command + + +# It is extremely common to see the "list" command being used to properly +# format values that are substituted into Tcl script templates. There are +# several examples of this, below. + + +# The "apply" command evaluates a string as a command. +set cmd {{greeting name} { + return "$greeting, $name!" +}} +apply $cmd Whaddup Neo + + +# The "uplevel" command evaluates a script in some enclosing scope. +proc greet {} { + uplevel {puts "$greeting, $name"} +} + +proc set_double {varname value} { + if {[string is double $value]} { + uplevel [list variable $varname $value] + } else { + error [list {not a double} $value] + } +} + + +# The "upvar" command links a variable in the current scope to a variable in +# some enclosing scope +proc set_double {varname value} { + if {[string is double $value]} { + upvar 1 $varname var + set var $value + } else { + error [list {not a double} $value] + } +} + + +#get rid of the built-in "while" command. +rename ::while {} + + +# Define a new while command with the "proc" command. More sophisticated error +# handling is left as an exercise. +proc while {condition script} { + if {[uplevel 1 [list expr $condition]]} { + uplevel 1 $script + tailcall [namespace which while] $condition $script + } +} + + +# The "coroutine" command creates a separate call stack, along with a command +# to enter that call stack. The "yield" command suspends execution in that +# stack. +proc countdown {} { + #send something back to the initial "coroutine" command + yield + + set count 3 + while {$count > 1} { + yield [incr count -1] + } + return 0 +} +coroutine countdown1 countdown +coroutine countdown2 countdown +puts [countdown 1] ;# -> 2 +puts [countdown 2] ;# -> 2 +puts [countdown 1] ;# -> 1 +puts [countdown 1] ;# -> 0 +puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 2] ;# -> 1 + + +``` + +## Reference + +[Official Tcl Documentation](http://www.tcl.tk/man/tcl/) + +[Tcl Wiki](http://wiki.tcl.tk) + +[Tcl Subreddit](http://www.reddit.com/r/Tcl) diff --git a/tmux.html.markdown b/tmux.html.markdown index 9eb96303..868302a8 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -2,13 +2,13 @@ category: tool tool: tmux contributors: - - ["wzsk", "https://github.com/wzsk"] + - ["mdln", "https://github.com/mdln"] filename: LearnTmux.txt --- -<a href="http://tmux.sourceforge.net/"> -tmux</a> is a terminal multiplexer: it enables a number of terminals +[tmux](http://tmux.sourceforge.net) +is a terminal multiplexer: it enables a number of terminals to be created, accessed, and controlled from a single screen. tmux may be detached from a screen and continue running in the background then later reattached. @@ -38,7 +38,7 @@ then later reattached. lsp # List panes -a # List all panes -s # List all panes in session - -t # List app panes in target + -t # List all panes in target kill-window # Kill current window -t "#" # Kill target window @@ -50,13 +50,15 @@ then later reattached. -a # Kill all sessions -a -t "#" # Kill all sessions but the target +``` -## Key Bindings +### Key Bindings -# The method of controlling an attached tmux session is via key -# combinations called 'Prefix' keys. +The method of controlling an attached tmux session is via key +combinations called 'Prefix' keys. +``` ---------------------------------------------------------------------- (C-b) = Ctrl + b # 'Prefix' combination required to use keybinds @@ -109,10 +111,9 @@ then later reattached. ### Configuring ~/.tmux.conf - tmux.conf can be used to set options automatically on start up, much +tmux.conf can be used to set options automatically on start up, much like how .vimrc or init.el are used. - ``` # Example tmux.conf # 2014.10 @@ -236,8 +237,19 @@ set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | ``` -<a href="http://tmux.sourceforge.net/">Tmux | Home</a><br> -<a href="http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux">Tmux Manual page</a><br> -<a href="http://wiki.gentoo.org/wiki/Tmux">Gentoo Wiki</a><br> -<a href="https://wiki.archlinux.org/index.php/Tmux">Archlinux Wiki</a><br> -<a href="https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux">Display CPU/MEM % in statusbar</a><br> + +### References + +[Tmux | Home](http://tmux.sourceforge.net) + +[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) + +[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) + +[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) + +[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) + +[tmuxinator - Manage complex tmux sessions](https://github.com/tmuxinator/tmuxinator) + + diff --git a/tr-tr/brainfuck-tr.html.markdown b/tr-tr/brainfuck-tr.html.markdown index baca4217..bd842b17 100644 --- a/tr-tr/brainfuck-tr.html.markdown +++ b/tr-tr/brainfuck-tr.html.markdown @@ -19,7 +19,7 @@ gözardı edilir. Brainfuck 30,000 hücresi olan ve ilk değerleri sıfır olarak atanmış bir dizidir. İşaretçi ilk hücreyi işaret eder. -Sekik komut vardır: +Sekiz komut vardır: + : Geçerli hücrenin değerini bir artırır. - : Geçerli hücrenin değerini bir azaltır. > : Veri işaretçisini bir sonraki hücreye hareket ettirir(sağdaki hücreye). diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 128901de..2d4240ed 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -91,9 +91,9 @@ int main() { // Örneğin, printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words) - // If the argument of the `sizeof` operator an expression, then its argument - // is not evaluated (except VLAs (see below)). - // The value it yields in this case is a compile-time constant. + // Eger arguman düzenli ifae olan sizeof operatoru ise degerlendirilmez. + // VLAs hariç asagiya bakiniz). + // Bu durumda verimliligin degeri derleme-zamani sabitidir. int a = 1; // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir @@ -101,7 +101,7 @@ int main() { 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) + // yazdirilan "sizeof(a++) = 4 where a = 1" (32-bit mimaride) // Diziler somut bir boyut ile oluşturulmalıdır. char my_char_array[20]; // Bu dizi 1 * 20 = 20 byte alan kaplar @@ -119,19 +119,19 @@ int main() { 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 + // C99'da (ve C11 istege bagli bir ozellik olarak), değidken-uzunluklu diziler (VLAs) bildirilebilirler. + // Böyle bir dizinin boyuunu derlenmesi gerekmez + // zaman sabiti: + printf("Enter the array size: "); // dizi boyutu kullaniciya soruluyor char buf[0x100]; fgets(buf, sizeof buf, stdin); - // strtoul parses a string to an unsigned integer + // strtoul isaretsiz integerlar icin string ayiricisidir. 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: + // Bu programın olası bir sonucu olabilir: // > Enter the array size: 10 // > sizeof array = 40 @@ -151,8 +151,8 @@ int main() { 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). + // Tek tirnak arasinda karakterlere sahipsek, bu karakterler degismezdir. + // Tip `int` ise, `char` *degildir* (tarihsel sebeplerle). int cha = 'a'; // fine char chb = 'a'; // fine too (implicit conversion from int to char) @@ -201,10 +201,10 @@ int main() { 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: + // Isaretli sayilari kaydirirken dikkatli olun - tanimsizlar sunlardir: + // - isaretli sayinin isaret bitinde yapilan kaydirma (int a = 1 << 32) + // - negatif sayilarda sol kaydirma (int a = -1 << 2) + // - LHS tipinde >= ile olan ofset genisletmelerde yapilan kaydirma: // int a = 1 << 32; // UB if int is 32 bits wide /////////////////////////////////////// @@ -485,4 +485,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Diğer taraftan google sizin için bir arkadaş olabilir. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member
\ No newline at end of file +[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown new file mode 100644 index 00000000..91c7c269 --- /dev/null +++ b/tr-tr/csharp-tr.html.markdown @@ -0,0 +1,825 @@ +--- +language: c# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translators: + - ["Melih Mucuk", "http://melihmucuk.com"] +lang: tr-tr +filename: LearnCSharp-tr.cs + +--- + +C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. + +[Yazım yanlışları ve öneriler için bana ulaşabilirsiniz](mailto:melihmucuk@gmail.com) + +[Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) + +```c# +// Tek satırlık yorumlar // ile başlar +/* +Birden fazla satırlı yorumlar buna benzer +*/ +/// <summary> +/// Bu bir XML dokümantasyon yorumu +/// </summary> + +// Uygulamanın kullanacağı ad alanlarını belirtin +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// Kodu düzenlemek için paketler içinde alan tanımlayın +namespace Learning +{ + // Her .cs dosyası, dosya ile aynı isimde en az bir sınıf içermeli + // bu kurala uymak zorunda değilsiniz ancak mantıklı olan yol budur. + public class LearnCSharp + { + // TEMEL SÖZ DİZİMİ - daha önce Java ya da C++ kullandıysanız İLGİNÇ ÖZELLİKLER'e geçin + public static void Syntax() + { + // Satırları yazdırmak için Console.WriteLine kullanın + Console.WriteLine("Merhaba Dünya"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Yeni satıra geçmeden yazdırmak için Console.Write kullanın + Console.Write("Merhaba "); + Console.Write("Dünya"); + + /////////////////////////////////////////////////// + // Tipler & Değişkenler + // + // Bir değişken tanımlamak için <tip> <isim> kullanın + /////////////////////////////////////////////////// + + // Sbyte - Signed 8-bit integer + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Unsigned 8-bit integer + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-bit integer + // Signed - (-32,768 <= short <= 32,767) + // Unsigned - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit integer + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit integer + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Sayılar boyutlarına göre ön tanımlı olarak int ya da uint olabilir. + // L, değişken değerinin long ya da ulong tipinde olduğunu belirtmek için kullanılır. + + // Double - Çift hassasiyetli 64-bit IEEE 754 kayan sayı + double fooDouble = 123.4; // Hassasiyet: 15-16 basamak + + // Float - Tek hassasiyetli 32-bit IEEE 754 kayan sayı + float fooFloat = 234.5f; // Hassasiyet: 7 basamak + // f, değişken değerinin float tipinde olduğunu belirtmek için kullanılır. + + // Decimal - 128-bit veri tiğinde ve diğer kayan sayı veri tiplerinden daha hassastır, + // finansal ve mali hesaplamalar için uygundur. + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // veya false + + // Char - 16-bitlik tek bir unicode karakter + char fooChar = 'A'; + + // Strings -- Önceki baz tiplerinin hepsi değer tipiyken, + // string bir referans tipidir. Null değer atayabilirsiniz + string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; + Console.WriteLine(fooString); + + // İndeks numarası kullanarak bir string'in bütün karakterlerine erişilebilirsiniz: + char charFromString = fooString[1]; // => 'e' + // String'ler değiştirilemez: fooString[1] = 'X' işlemini yapamazsınız; + + // String'leri geçerli kültür değeri ve büyük küçük harf duyarlılığı olmadan karşılaştırma + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // sprintf baz alınarak formatlama + string fooFs = string.Format("Check Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Tarihler & Formatlama + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Bir string'i iki satıra bölmek için @ sembolü kullanabilirsiniz. " işaretinden kaçmak için "" kullanın + string bazString = @"Here's some stuff +on a new line! ""Wow!"", the masses cried"; + + // Bir değişkeni değiştirilemez yapmak için const ya da read-only kullanın. + // const değerleri derleme sırasında hesaplanır + const int HOURS_I_WORK_PER_WEEK = 9001; + + /////////////////////////////////////////////////// + // Veri Yapıları + /////////////////////////////////////////////////// + + // Diziler - Sıfır indeksli + // Dizi boyutuna tanımlama sırasında karar verilmelidir. + // Dizi tanımlama formatı şöyledir: + // <veri tipi>[] <değişken ismi> = new <veri tipi>[<dizi boyutu>]; + int[] intArray = new int[10]; + + // Bir diğer dizi tanımlama formatı şöyledir: + int[] y = { 9000, 1000, 1337 }; + + // Bir diziyi indeksleme - Bir elemente erişme + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Diziler değiştirilebilir. + intArray[1] = 1; + + // Listeler + // Listeler daha esnek oldukları için dizilerden daha sık kullanılırlar. + // Bir liste tanımlama formatı şöyledir: + // List<veri tipi> <değişken ismi> = new List<veri tipi>(); + List<int> intList = new List<int>(); + List<string> stringList = new List<string>(); + List<int> z = new List<int> { 9000, 1000, 1337 }; // tanımlama + // <> işareti generic ifadeler içindir - Güzel özellikler sekmesini inceleyin + + // Listelerin varsayılan bir değeri yoktur; + // İndekse erişmeden önce değer eklenmiş olmalıdır + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Diğer veri yapıları için şunlara bakın: + // Stack/Queue (Yığın/Kuyruk) + // Dictionary (hash map'in uygulanması) (Sözlük) + // HashSet (karma seti) + // Read-only Collections (Değiştirilemez koleksiyonlar) + // Tuple (.Net 4+) (tüp) + + /////////////////////////////////////// + // Operatörler + /////////////////////////////////////// + Console.WriteLine("\n->Operators"); + + int i1 = 1, i2 = 2; // Birden çok tanımlamanın kısa yolu + + // Aritmetik basittir + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Mod + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Karşılaştırma operatörleri + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bit düzeyi operatörleri! + /* + ~ Tekli bit tamamlayıcısı + << Sola kaydırma Signed left shift + >> Sağa kaydırma Signed right shift + & Bit düzeyi AND + ^ Bit düzeyi harici OR + | Bit düzeyi kapsayan OR + */ + + // Arttırma + int i = 0; + Console.WriteLine("\n->Inc/Dec-rementation"); + Console.WriteLine(i++); //i = 1. Post-Incrementation + Console.WriteLine(++i); //i = 2. Pre-Incrementation + Console.WriteLine(i--); //i = 1. Post-Decrementation + Console.WriteLine(--i); //i = 0. Pre-Decrementation + + /////////////////////////////////////// + // Kontrol Yapıları + /////////////////////////////////////// + Console.WriteLine("\n->Control Structures"); + + // If ifadesi c benzeridir + int j = 10; + if (j == 10) + { + Console.WriteLine("I get printed"); + } + else if (j > 10) + { + Console.WriteLine("I don't"); + } + else + { + Console.WriteLine("I also don't"); + } + + // Üçlü operatörler + // Basit bir if/else ifadesi şöyle yazılabilir + // <koşul> ? <true> : <false> + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; + + // While döngüsü + int fooWhile = 0; + while (fooWhile < 100) + { + //100 kere tekrarlanır, fooWhile 0->99 + fooWhile++; + } + + // Do While Döngüsü + int fooDoWhile = 0; + do + { + //100 kere tekrarlanır, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + + //for döngüsü yapısı => for(<başlangıç ifadesi>; <koşul>; <adım>) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + //10 kere tekrarlanır, fooFor 0->9 + } + + // For Each Döngüsü + // foreach döngüsü yapısı => foreach(<yineleyici tipi> <yineleyici ismi> in <enumerable>) + // foreach döngüsü, IEnumerable ya da IEnumerable<T> e dönüştürülmüş herhangi bir obje üzerinde döngü yapabilir + // .Net framework üzerindeki bütün koleksiyon tiplerinden (Dizi, Liste, Sözlük...) + // biri ya da hepsi uygulanarak gerçekleştirilebilir. + // (ToCharArray() silindi, çünkü string'ler aynı zamanda IEnumerable'dır.) + foreach (char character in "Hello World".ToCharArray()) + { + //String içindeki bütün karakterler üzerinde döner + } + + // Switch Case + // Bir switch byte, short, char ve int veri tipleri ile çalışır. + // Aynı zamanda sıralı tipler ile de çalışabilir.(Enum Tipleri bölümünde tartışıldı), + // String sınıfı, ve bir kaç özel sınıf kaydırılır + // basit tipler: Character, Byte, Short, and Integer. + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "January"; + break; + case 2: + monthString = "February"; + break; + case 3: + monthString = "March"; + break; + // Bir aksiyon için birden fazla durum atayabilirsiniz + // Ancak, break olmadan yeni bir durum ekleyemezsiniz + // (Eğer bunu yapmak istiyorsanız, goto komutu eklemek zorundasınız) + case 6: + case 7: + case 8: + monthString = "Summer time!!"; + break; + default: + monthString = "Some other month"; + break; + } + + /////////////////////////////////////// + // Veri Tipleri Dönüştürme ve Typecasting + /////////////////////////////////////// + + // Veri Dönüştürme + + // String'i Integer'a Dönüştürme + // bu başarısız olursa hata fırlatacaktır + int.Parse("123");// "123" 'in Integer değerini döndürür + + // try parse hata durumunda değişkene varsayılan bir değer atamak için kullanılır + // bu durumda: 0 + int tryInt; + if (int.TryParse("123", out tryInt)) // Fonksiyon boolean'dır + Console.WriteLine(tryInt); // 123 + + // Integer'ı String'e Dönüştürme + // Convert sınıfı dönüştürme işlemini kolaylaştırmak için bir dizi metoda sahiptir + Convert.ToString(123); + // veya + tryInt.ToString(); + } + + /////////////////////////////////////// + // SINIFLAR - dosyanın sonunda tanımları görebilirsiniz + /////////////////////////////////////// + public static void Classes() + { + // Obje tanımlamalarını dosyanın sonunda görebilirsiniz + + // Bir sınıfı türetmek için new kullanın + Bicycle trek = new Bicycle(); + + // Obje metodlarını çağırma + trek.SpeedUp(3); // Her zaman setter ve getter metodları kullanmalısınız + trek.Cadence = 100; + + // ToString objenin değerini göstermek için kullanılır. + Console.WriteLine("trek info: " + trek.Info()); + + // Yeni bir Penny Farthing sınıfı türetmek + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("funbike info: " + funbike.Info()); + + Console.Read(); + } // Ana metodun sonu + + // KONSOLE BAŞLANGICI Bir konsol uygulaması başlangıç olarak mutlaka ana metod'a sahip olmalı + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + // + // İLGİNÇ ÖZELLİKLER + // + + // VARSAYILAN METOD TANIMLAMALARI + + public // Görünebilir + static // Sınıf üzerinden obje türetmeden çağırılabilir + int // Dönüş Tipi, + MethodSignatures( + int maxCount, // İlk değişken, int değer bekler + int count = 0, // Eğer değer gönderilmezse varsayılan olarak 0 değerini alır + int another = 3, + params string[] otherParams // Metoda gönderilen diğer bütün parametreleri alır + ) + { + return -1; + } + + // Metodlar tanımlamalar benzersiz ise aynı isimleri alabilirler + public static void MethodSignatures(string maxCount) + { + } + + // GENERIC'LER + // TKey ve TValue değerleri kullanıcı tarafından bu fonksiyon çağırılırken belirtilir. + // Bu metod Python'daki SetDefault'a benzer + public static TValue SetDefault<TKey, TValue>( + IDictionary<TKey, TValue> dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + return dictionary[key] = defaultItem; + return result; + } + + // Gönderilen objeleri daraltabilirsiniz + public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int> + { + // Eğer T IEnumerable ise tekrarlayabiliriz + foreach (var item in toPrint) + // Item bir int + Console.WriteLine(item.ToString()); + } + + public static void OtherInterestingFeatures() + { + // İSTEĞE BAĞLI PARAMETRELER + MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); + MethodSignatures(3, another: 3); // isteğe bağlı olanlar gönderilmedi + + // UZANTI METODLARI + int i = 3; + i.Print(); // Aşağıda tanımlandı + + // NULLABLE TYPES - veri tabanı işlemleri için uygun / return values + // Herhangi bir değer tipi sonuna ? eklenerek nullable yapılabilir (sınıflar hariç) + // <tip>? <değiken ismi> = <değer> + int? nullable = null; // Nullable<int> için kısa yol + Console.WriteLine("Nullable variable: " + nullable); + bool hasValue = nullable.HasValue; // eğer null değilse true döner + + // ?? varsayılan değer belirlemek için söz dizimsel güzel bir özellik + // bu durumda değişken null'dır + int notNullable = nullable ?? 0; // 0 + + // TİPİ BELİRTİLMEMİŞ DEĞİŞKENLER - compiler değişkenin tipini bilmeden çalışabilir: + var magic = "magic is a string, at compile time, so you still get type safety"; + // magic = 9; string gibi çalışmayacaktır, bu bir int değil + + // GENERIC'LER + // + var phonebook = new Dictionary<string, string>() { + {"Sarah", "212 555 5555"} // Telefon rehberine bir kaç numara ekleyelim. + }; + + // Yukarıda generic olarak tanımlanan SETDEFAULT'u çağırma + Console.WriteLine(SetDefault<string,string>(phonebook, "Shaun", "No Phone")); // Telefonu yok + // TKey ve TValue tipini belirtmek zorunda değilsiniz + Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 + + // LAMBDA IFADELERİ - satır içinde kod yazmanıza olanak sağlar + Func<int, int> square = (x) => x * x; // Son T nesnesi dönüş değeridir + Console.WriteLine(square(3)); // 9 + + // TEK KULLANIMLIK KAYNAK YÖNETİMİ - Yönetilemeyen kaynakların üstesinden kolayca gelebilirsiniz. + // Bir çok obje yönetilemeyen kaynaklara (dosya yakalama, cihaz içeriği, vb.) + // IDisposable arabirimi ile erişebilir. Using ifadesi sizin için IDisposable objeleri temizler. + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Nothing suspicious here"); + // Bu bölümün sonunda kaynaklar temilenir. + // Hata fırlatılmış olsa bile. + } + + // PARALEL FRAMEWORK + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary<string, string>(); + + // Her istek farklı bir thread de işlem görecek + // bir sonraki işleme geçmeden birleştirilecek. + Parallel.ForEach(websites, + new ParallelOptions() {MaxDegreeOfParallelism = 3}, // en fazla 3 thread kullanmak için + website => + { + // Uzun sürecek bir işlem yapın + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // Bütün istekler tamamlanmadan bu döndü çalışmayacaktır. + foreach (var key in responses.Keys) + Console.WriteLine("{0}:{1}", key, responses[key]); + + // DİNAMİK OBJELER (diğer dillerle çalışırken kullanmak için uygun) + dynamic student = new ExpandoObject(); + student.FirstName = "First Name"; // Önce yeni bir sınıf tanımlamanız gerekmez! + + // Hatta metod bile ekleyebilirsiniz (bir string döner, ve bir string alır) + student.Introduce = new Func<string, string>( + (introduceTo) => string.Format("Hey {0}, this is {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Beth")); + + // IQUERYABLE<T> - neredeyse bütün koleksiyonlar bundan türer, bu size bir çok + // kullanışlı Map / Filter / Reduce stili metod sağlar. + var bikes = new List<Bicycle>(); + bikes.Sort(); // Dizi sıralama + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // Wheels baz alınarak sıralama + var result = bikes + .Where(b => b.Wheels > 3) // Filters- chainable (bir önceki tipin IQueryable'ını döner) + .Where(b => b.IsBroken && b.HasTassles) + .Select(b => b.ToString()); // Map - sadece bunu seçiyoruz, yani sonuç bir IQueryable<string> olacak + + var sum = bikes.Sum(b => b.Wheels); // Reduce - koleksiyonda bulunan bütün wheel değerlerinin toplamı + + // Bike içindeki bazı parametreleri baz alarak bir liste oluşturmak + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Burada göstermek zor ama, compiler yukaridaki tipleri çözümleyebilirse derlenmeden önce tipi verebilir. + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + Console.WriteLine(bikeSummary.Name); + + // ASPARALLEL + // Linq ve paralel işlemlerini birleştirme + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // bu paralel bir şekilde gerçekleşecek! Threadler otomatik ve sihirli bir şekilde işleri paylaşacak! + // Birden fazla çekirdeğiniz varsa büyük veri setleri ile kullanmak için oldukça uygun bir yapı. + + // LINQ - IQueryable<T> objelerini mapler ve saklar, gecikmeli bir işlemdir + // e.g. LinqToSql - veri tabanını mapler, LinqToXml xml dökümanlarını mapler. + var db = new BikeRepository(); + + // işlem gecikmelidir, bir veri tabanı üzerinde sorgulama yaparken harikadır. + var filter = db.Bikes.Where(b => b.HasTassles); // sorgu henüz çalışmadı + if (42 > 6) // Filtreler eklemeye devam edebilirsiniz - ileri düzey arama fonksiyonları için harikadır + filter = filter.Where(b => b.IsBroken); // sorgu henüz çalışmadı + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // hala sorgu çalışmadı + + // Şimdi sorgu çalışıyor, reader'ı açar ama sadece sizin sorgunuza uyanlar foreach döngüsüne girer. + foreach (string bike in query) + Console.WriteLine(result); + + + + } + + } // LearnCSharp sınıfının sonu + + // Bir .cs dosyasına diğer sınıflarıda dahil edebilirsiniz + + public static class Extensions + { + // UZANTI FONKSİYONLARI + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Sınıf Tanımlama Sözdizimi: + // <public/private/protected/internal> class <sınıf ismi>{ + // //veri alanları, kurucular , fonksiyonlar hepsi içindedir. + // //Fonksiyonlar Java'daki gibi metod olarak çağırılır. + // } + + public class Bicycle + { + // Bicycle'ın Alanları/Değişkenleri + public int Cadence // Public: herhangi bir yerden erişilebilir + { + get // get - değeri almak için tanımlanan metod + { + return _cadence; + } + set // set - değer atamak için tanımlanan metod + { + _cadence = value; // Değer setter'a gönderilen value değeridir + } + } + private int _cadence; + + protected virtual int Gear // Protected: Sınıf ve alt sınıflar tarafından erişilebilir + { + get; // bir üye alanına ihtiyacınız yok, bu otomatik olarak bir değer oluşturacaktır + set; + } + + internal int Wheels // Internal: Assembly tarafından erişilebilir + { + get; + private set; // Nitelik belirleyicileri get/set metodlarında atayabilirsiniz + } + + int _speed; // Her şey varsayılan olarak private'dır : Sadece sınıf içinden erişilebilir. + // İsterseniz yinede private kelimesini kullanabilirsiniz. + public string Name { get; set; } + + // Enum sabitler kümesinden oluşan bir değer tipidir. + // Gerçekten sadece bir isim ile bir değeri tutmak için kullanılır. (aksi belirtilmedikçe bir int'dir). + // İzin verilen enum tipleri şunlardır byte, sbyte, short, ushort, int, uint, long, veya ulong. + // Bir enum aynı değeri birden fazla sayıda barındıramaz. + public enum BikeBrand + { + AIST, + BMC, + Electra = 42, // bir isme tam bir değer verebilirsiniz + Gitane // 43 + } + // Bu tipi Bicycle sınıfı içinde tanımladığımız için bu bir bağımlı tipdir. + // Bu sınıf dışında kullanmak için tipi Bicycle.Brand olarak kullanmamız gerekir + + public BikeBrand Brand; // Enum tipini tanımladıktan sonra alan tipini tanımlayabiliriz + + // Static üyeler belirli bir obje yerine kendi tipine aittir + // Onlara bir obje referans göstermeden erişebilirsiniz: + // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); + static public int BicyclesCreated = 0; + + // readonly değerleri çalışma zamanında atanır + // onlara sadece tanımlama yapılarak ya da kurucular içinden atama yapılabilir + readonly bool _hasCardsInSpokes = false; // read-only private + + // Kurucular sınıf oluşturmanın bir yoludur + // Bu bir varsayılan kurucudur. + public Bicycle() + { + this.Gear = 1; // bu objenin üyelerine this anahtar kelimesi ile ulaşılır + Cadence = 50; // ama her zaman buna ihtiyaç duyulmaz + _speed = 5; + Name = "Bontrager"; + Brand = BikeBrand.AIST; + BicyclesCreated++; + } + + // Bu belirlenmiş bir kurucudur. (argümanlar içerir) + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // önce base'i çağırın + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Kurucular zincirleme olabilir + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "big wheels", true, brand) + { + } + + // Fonksiyon Sözdizimi: + // <public/private/protected> <dönüş tipi> <fonksiyon ismi>(<argümanlar>) + + // sınıflar getter ve setter'ları alanları için kendisi uygular + // veya property'ler eklenebilir (C# da tercih edilen yol budur) + + // Metod parametreleri varsayılan değerlere sahip olabilir. + // Bu durumda, metodlar bu parametreler olmadan çağırılabilir. + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // property'lerin get/set değerleri + // sadece veri gerektiği zaman erişilebilir, kullanmak için bunu göz önünde bulundurun. + // property'ler sadece get ya da set'e sahip olabilir veya ikisine birden + private bool _hasTassles; // private değişken + public bool HasTassles // public accessor + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // Ayrıca tek bir satırda otomatik property tanımlayabilirsiniz. + // bu söz dizimi otomatik olarak alan oluşturacaktır. + // Erişimi kısıtlamak için nitelik belirleyiciler getter veya setter'a ya da ikisine birden atanabilir: + public bool IsBroken { get; private set; } + + // Property'ler otomatik eklenmiş olabilir + public int FrameSize + { + get; + // nitelik beliryecileri get veya set için tanımlayabilirsiniz + // bu sadece Bicycle sınıfı Framesize değerine atama yapabilir demektir + private set; + } + + // Ayrıca obje üzerinde özel indeksleyici belirlemek mümkündür. + // Tüm bunlar bu örnek için çok kullanışlı değil, + // bicycle[0] ile ilk yolcu olan "chris" i almak mümkün veya + // bicycle[1] = "lisa" ile yolcuyu atayabilirsiniz. (bariz quattrocycle) + private string[] passengers = { "chris", "phil", "darren", "regina" } + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + return passengers[i] = value; + } + } + + //Bu objenin nitelik değerlerini göstermek için bir metod. + public virtual string Info() + { + return "Gear: " + Gear + + " Cadence: " + Cadence + + " Speed: " + _speed + + " Name: " + Name + + " Cards in Spokes: " + (_hasCardsInSpokes ? "yes" : "no") + + "\n------------------------------\n" + ; + } + + // Metodlar static olabilir. Yardımcı metodlar için kullanışlı olabilir. + public static bool DidWeCreateEnoughBycles() + { + // Bir static metod içinde sadece static sınıf üyeleri referans gösterilebilir + return BicyclesCreated > 9000; + } // Eğer sınıfınızın sadece static üyelere ihtiyacı varsa, sınıfın kendisini static yapmayı düşünebilirsiniz. + + + } // Bicycle sınıfı sonu + + // PennyFarthing , Bicycle sınıfının alt sınıfıdır. + class PennyFarthing : Bicycle + { + // (Penny Farthing'ler ön jantı büyük bisikletlerdir. + // Vitesleri yoktur.) + + // Ana kurucuyu çağırmak + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "PennyFarthing", true, BikeBrand.Electra) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new ArgumentException("You can't change gears on a PennyFarthing"); + } + } + + public override string Info() + { + string result = "PennyFarthing bicycle "; + result += base.ToString(); // Metodun temel versiyonunu çağırmak + return result; + } + } + + // Arabirimler sadece üyelerin izlerini içerir, değerlerini değil. + interface IJumpable + { + void Jump(int meters); // bütün arbirim üyeleri public'tir + } + + interface IBreakable + { + bool Broken { get; } // arabirimler property'leri, metodları ve olayları içerebilir + } + + // Sınıflar sadece tek bir sınıftan miras alabilir ama sınırsız sayıda arabirime sahip olabilir + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + /// <summary> + /// LinqToSql örneği veri tabanına bağlanmak için kullanılır. + /// EntityFramework Code First harika! (Ruby'deki ActiveRecord'a benzer, ama iki yönlü) + /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// </summary> + public class BikeRepository : DbSet + { + public BikeRepository() + : base() + { + } + + public DbSet<Bicycle> Bikes { get; set; } + } +} // namespace sonu +``` + +## İşlenmeyen Konular + + * Flags + * Attributes + * Static properties + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## Daha Fazlasını Okuyun + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + + + +[C# Kodlama Adetleri](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) diff --git a/tr-tr/markdown-tr.html.markdown b/tr-tr/markdown-tr.html.markdown new file mode 100644 index 00000000..bac8f6fc --- /dev/null +++ b/tr-tr/markdown-tr.html.markdown @@ -0,0 +1,251 @@ +--- +language: markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: markdown-tr.md +--- + +Markdown, 2004 yılında John Gruber tarafından oluşturuldu. Asıl amacı kolay okuma ve yazmayı sağlamakla beraber kolayca HTML (artık bir çok diğer formatlara) dönüşüm sağlamaktır. + + +```markdown +<!-- Markdown, HTML'i kapsar, yani her HTML dosyası geçerli bir Markdown dosyasıdır, bu demektir +ki Markdown içerisinde HTML etiketleri kullanabiliriz, örneğin bu yorum elementi, ve +markdown işleyicisinde etki etmezler. Fakat, markdown dosyası içerisinde HTML elementi oluşturursanız, +bu elementin içeriğinde markdown söz dizimlerini kullanamazsınız. --> + +<!-- Markdown ayrıca işleyiciden işleyiciye farklılık gösterebilir. Bu rehberde +evrensel özelliklere uygun anlatımlar olacaktır. Bir çok işleyici bu rehberdeki +anlatımları destekler --> + +<!-- Başlıklar --> +<!-- Kolayca <h1>'den <h6>'ya HTML etiketleri oluşturabilirsiniz. +Kare (#) sayısı bu elementin numarasını belirleyecek ve devamında getirdiğiniz +yazı bu elementin içeriği olacaktır +--> +# Bu bir <h1> +## Bu bir <h2> +### Bu bir <h3> +#### Bu bir <h4> +##### Bu bir <h5> +###### Bu bir <h6> + +<!-- Markdown ayrıca h1 ve h2 için 2 alternatif yol daha taşır --> +Bu bir h1 +========= + +Bu bir h2 +--------- + +<!-- Basit yazı stilleri --> +<!-- Markdown ile yazılar kolayca italik ve kalın belirtilebilir --> +*Bu yazı italik.* +_Bu yazı da italik._ + +**Bu yazı kalın.** +__Bu yazı da kalın.__ + +***Bu yazı hem kalın hem italik.*** +**_Bu da öyle!_** +*__Hatta bu bile!__* + +<!-- Github Flavored Markdown'da ayrıca üstü çizgili karakter de desteklenir: --> +~~Bu yazı üstü çizili olarak gözükecek.~~ + +<!-- Paragraflar bir veya daha fazla boş satırla ayrılır. --> + +Bu bir paragraf. Paragrafın içeriğine devam ediyorum, eğlenceli değil mi? + +Şimdi 2. paragrafıma geçtim. +Hala 2. paragraftayım, çünkü boş bir satır bırakmadım. + +Bu da 3. paragrafım! + +<!-- HTML'de her satır için <br /> etiketi kullanmak ister misiniz, Bir +paragrafı bitirdikten sonra 2 veya daha fazla boşluk bırakın ve yeni paragrafa +başlayın, bu bir <br /> etiketi sayılacaktır --> + +Bu yazının sonunda 2 boşluk var (bu satırı seçerek kontrol edebilirsiniz). + +Bir üst satırda <br /> etiketi var! + +<!-- Blok yazılarının yapımı oldukça kolay, (>) karakteri ile yapabilirsiniz --> + +> Bu bir blok etiketi. Satırlara ayırmak için +> her satırın başında `>` karakter yerleştirmeli veya tek satırda bütün içeriği yazabilirsiniz. +> Satır `>` karakteri ile başladığı sürece sorun yok. + +> Ayrıca alt alta da blok elementi açabilirsiniz +>> iç içe yani +> düzgün değil mi ? + +<!-- Listeler --> +<!-- Numarasız listeler için yıldız, artı, veya tire kullanabilirsiniz --> + +* Nesne +* Nesne +* Bir başka nesne + +veya + ++ Nesne ++ Nesne ++ Bir başka nesne + +veya + +- Nesne +- Nesne +- Son bir nesne + +<!-- Numaralı liste için başına sıralı bir şekilde sayı eklemeniz yeterli --> + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + +<!-- İsterseniz sıralı bir şekilde yazmak zorunda değilsiniz, markdown +biçimlendirirken sizin için sıralayacaktır, fakat bunu önermiyorum. Markdown dosyasının +düzgün gözükmesi için önerilen metodu uygulamanızı tavsiye ederim --> + +1. İlk nesne +1. İkinci nesne +1. Üçüncü nesne + +<!-- (Bunun çıktısı ile, sıralı olarak yazdığımız örneğin çıktısı aynı olacaktır) --> + +<!-- Ayrıca alt alta liste oluşturabilirsiniz --> + +1. İlk nesne +2. İkinci nesne +3. Üçüncü nesne + * Alt nesne + * Alt nesne +4. Dördüncü nesne + +<!-- Ayrıca görev listeleri de bulunmakta. HTML seçim kutusu(checkbox) oluşturacaktır. --> +Kutunun içerisinde `x` yoksa eğer seçim kutusu boş olacaktır. +- [ ] Yapılacak ilk görev. +- [ ] Yapılması gereken bir başka görev +Aşağıdaki seçim kutusu ise içi dolu olacaktır. +- [x] Bu görev başarıyla yapıldı + +<!-- Kod blokları --> +<!-- Kod bloklarını(<code> elementi) belirtmek için 4 adet boşluk veya bir +tab karakterini kullanabilirsiniz --> + + Bu bir kod + öyle mi? + +<!-- Ayrıca kod içerisinde girinti kullanmak istiyorsanız tekrar `tab` veya `4 boşluk` +kullanabilirsiniz --> + + my_array.each do |item| + puts item + end + +<!-- Yazı içerisinde kod belirtmek için sorgu tırnağı (`) kullanabilirsiniz --> + +Ahmet `go_to()` fonksiyonun ne yaptığını bilmiyor! + +<!-- Github Flavored Markdown'da, kod içerisinde aydınlatma kullanabilirsiniz --> + +\`\`\`ruby <!-- buradaki ters slaş (\) işaretlerini kullanmayın, sadece ```ruby ! --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- burada da (\) işaretlerini kullanmayın, sadece ``` --> + +<!-- Yukarıdaki örnekte girinti kullanmanıza gerek yok, Github da +``` işaretinden sonra belirttiğiniz yazılım diline göre gerekli +syntax aydınlatmaları uygulanacaktır --> + +<!-- Düz çizgi (<hr />) --> +<!-- Düz çizgiler 3 veya daha fazla yıldız/çizgi ile yapılabilir. Boşluklar önemsiz. --> + +*** +--- +- - - +**************** + +<!-- Linkler --> +<!-- Markdown'daki en güzel şeylerden biri kolayca link oluşturmaktır. +Linkte göstermek istediğiniz yazıyı [] içerisine yerleştirin ve sonuna parantezler içerisinde () +gideceği adresi belirtin --> + +[Bana tıkla!](http://test.com) + +<!-- Ayrıca linke `title` özelliği eklemek için tırnakları kullanabilirsiniz --> + +[Bana tıkla!](http://test.com "Test.com'a gider") + +<!-- Bağıl yollar da çalışıyor. --> +[Müzik dinle](/muzik/). + +<!-- Markdown ayrıca referans linklerini de destekler --> + +[Bu linke tıklayarak][link1] daha detaylı bilgi alabilirsiniz! +[Ayrıca bu linki de inceleyin][foobar] tabi istiyorsanız. + +[link1]: http://test.com/ "harika!" +[foobar]: http://foobar.biz/ "okey!" + +<!--Başlık ayrıca tek tırnak veya parantez içinde olabilir, veya direk yazılabilir. +Referans döküman içerisindeki herhangi bir yer olabilir ve referans IDsi +benzersiz olduğu sürece sorunsuz çalışacaktır. --> + +<!-- Ayrıca "dolaylı adlandırma" bulunmaktadır, "dolaylı adlandırma", linkin yazısının +aynı zamanda onun idsi olmasıdır --> + +[Bu][] bir link. +[bu]: http://bubirlink.com + +<!-- Fakat bu çok tercih edilen bir yöntem değil. --> + +<!-- Resimler --> +<!-- Resimler aslında linklere çok benziyor fakat başında ünlem bulunuyor! --> +![Bu alt etiketine gelecek içerik](http://imgur.com/resmim.jpg "Bu da isteğe bağlı olan bir başlık") + +<!-- Referanslar resimler için de geçerli --> +![Bu alt etiketi.][resmim] + +[resmim]: bagil/linkler/de/calisiyor.jpg "Başlık isterseniz buraya girebilirsiniz" + +<!-- Çeşitli --> +<!-- Oto-linkler --> + +<http://testwebsite.com/> ile +[http://testwebsite.com/](http://testwebsite.com) aynı şeyler + +<!-- Oto-linkler epostaları da destekler --> + +<foo@bar.com> + +<!-- Kaçış karakterleri --> + +Bu yazının *yıldızlar arasında gözükmesini* istiyorum fakat italik olmamasını istiyorum, +bunun için, şu şekilde: \*bu yazı italik değil, yıldızlar arasında\*. + +<!-- Tablolar --> +<!-- Tablolar sadece Github Flavored Markdown'da destekleniyor ve açıkçası +performansı çok yoruyorlar, fakat illa ki kullanmak isterseniz: --> + +| Sütun1 | Sütun 2 | Sütün 3 | +| :----------- | :------: | ------------: | +| Sola dayalı | Ortalı | Sağa dayalı | +| test | test | test | + +<!-- ayrıca, bunun aynısı --> + +Sütun 1 | Sütun 2 | Sütun 3 +:-- | :-: | --: +Çok çirkin göözüküyor | değil | mi? + +<!-- Bitiş! --> + +``` + +Daha detaylı bilgi için, John Gruber'in resmi söz dizimi yazısını [buradan](http://daringfireball.net/projects/markdown/syntax) veya Adam Pritchard'ın mükemmel hatırlatma kağıdını [buradan](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) inceleyebilirsiniz. diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown index f27cbf08..727f973e 100644 --- a/tr-tr/objective-c-tr.html.markdown +++ b/tr-tr/objective-c-tr.html.markdown @@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C programlama diline Smalltalk stilinde mesajlaşma ekler. -```objective_c +```objective-c // Tek satır yorum // işaretleri ile başlar /* diff --git a/tr-tr/python3-tr.html.markdown b/tr-tr/python3-tr.html.markdown new file mode 100644 index 00000000..2477c5da --- /dev/null +++ b/tr-tr/python3-tr.html.markdown @@ -0,0 +1,635 @@ +--- +language: python3 +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Eray AYDIN", "http://erayaydin.me/"] +lang: tr-tr +filename: learnpython3-tr.py +--- + +Python,90ların başlarında Guido Van Rossum tarafından oluşturulmuştur. En popüler olan dillerden biridir. Beni Python'a aşık eden sebep onun syntax beraklığı. Çok basit bir çalıştırılabilir söz koddur. + +Not: Bu makale Python 3 içindir. Eğer Python 2.7 öğrenmek istiyorsanız [burayı](http://learnxinyminutes.com/docs/python/) kontrol edebilirsiniz. + +```python + +# Tek satırlık yorum satırı kare(#) işareti ile başlamaktadır. + +""" Çok satırlı olmasını istediğiniz yorumlar + üç adet tırnak(") işareti ile + yapılmaktadır +""" + +#################################################### +## 1. Temel Veri Türleri ve Operatörler +#################################################### + +# Sayılar +3 # => 3 + +# Tahmin edebileceğiniz gibi matematik +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 + +# Bölme işlemi varsayılan olarak onluk döndürür +35 / 5 # => 7.0 + +# Tam sayı bölmeleri, pozitif ve negatif sayılar için aşağıya yuvarlar +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # onluklar için de bu böyledir +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Onluk kullanırsanız, sonuç da onluk olur +3 * 2.0 # => 6.0 + +# Kalan operatörü +7 % 3 # => 1 + +# Üs (2 üzeri 4) +2**4 # => 16 + +# Parantez ile önceliği değiştirebilirsiniz +(1 + 3) * 2 # => 8 + +# Boolean(Doğru-Yanlış) değerleri standart +True +False + +# 'değil' ile terse çevirme +not True # => False +not False # => True + +# Boolean Operatörleri +# "and" ve "or" büyük küçük harf duyarlıdır +True and False #=> False +False or True #=> True + +# Bool operatörleri ile sayı kullanımı +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True + +# Eşitlik kontrolü == +1 == 1 # => True +2 == 1 # => False + +# Eşitsizlik Kontrolü != +1 != 1 # => False +2 != 1 # => True + +# Diğer karşılaştırmalar +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Zincirleme şeklinde karşılaştırma da yapabilirsiniz! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Yazı(Strings) " veya ' işaretleri ile oluşturulabilir +"Bu bir yazı." +'Bu da bir yazı.' + +# Yazılar da eklenebilir! Fakat bunu yapmanızı önermem. +"Merhaba " + "dünya!" # => "Merhaba dünya!" + +# Bir yazı(string) karakter listesi gibi işlenebilir +"Bu bir yazı"[0] # => 'B' + +# .format ile yazıyı biçimlendirebilirsiniz, şu şekilde: +"{} da ayrıca {}".format("yazılar", "işlenebilir") + +# Biçimlendirme işleminde aynı argümanı da birden fazla kullanabilirsiniz. +"{0} çeviktir, {0} hızlıdır, {0} , {1} üzerinden atlayabilir".format("Ahmet", "şeker çubuğu") +#=> "Ahmet çeviktir, Ahmet hızlıdır, Ahmet , şeker çubuğu üzerinden atlayabilir" + +# Argümanın sırasını saymak istemiyorsanız, anahtar kelime kullanabilirsiniz. +"{isim} yemek olarak {yemek} istiyor".format(isim="Ahmet", yemek="patates") #=> "Ahmet yemek olarak patates istiyor" + +# Eğer Python 3 kodunuz ayrıca Python 2.5 ve üstünde çalışmasını istiyorsanız, +# eski stil formatlamayı kullanabilirsiniz: +"%s bu %s yolla da %s" % ("yazılar", "eski", "biçimlendirilebilir") + + +# Hiçbir şey(none) da bir objedir +None # => None + +# Bir değerin none ile eşitlik kontrolü için "==" sembolünü kullanmayın +# Bunun yerine "is" kullanın. Obje türünün eşitliğini kontrol edecektir. +"vb" is None # => False +None is None # => True + +# None, 0, ve boş yazılar/listeler/sözlükler hepsi False değeri döndürü. +# Diğer veriler ise True değeri döndürür +bool(0) # => False +bool("") # => False +bool([]) #=> False +bool({}) #=> False + + +#################################################### +## 2. Değişkenler ve Koleksiyonlar +#################################################### + +# Python bir yazdırma fonksiyonuna sahip +print("Ben Python. Tanıştığıma memnun oldum!") + +# Değişkenlere veri atamak için önce değişkeni oluşturmanıza gerek yok. +# Düzenli bir değişken için hepsi_kucuk_ve_alt_cizgi_ile_ayirin +bir_degisken = 5 +bir_degisken # => 5 + +# Önceden tanımlanmamış değişkene erişmek hata oluşturacaktır. +# Kontrol akışları başlığından hata kontrolünü öğrenebilirsiniz. +bir_bilinmeyen_degisken # NameError hatası oluşturur + +# Listeler ile sıralamaları tutabilirsiniz +li = [] +# Önceden doldurulmuş listeler ile başlayabilirsiniz +diger_li = [4, 5, 6] + +# 'append' ile listenin sonuna ekleme yapabilirsiniz +li.append(1) # li artık [1] oldu +li.append(2) # li artık [1, 2] oldu +li.append(4) # li artık [1, 2, 4] oldu +li.append(3) # li artık [1, 2, 4, 3] oldu +# 'pop' ile listenin son elementini kaldırabilirsiniz +li.pop() # => 3 ve li artık [1, 2, 4] +# Çıkarttığımız tekrardan ekleyelim +li.append(3) # li yeniden [1, 2, 4, 3] oldu. + +# Dizi gibi listeye erişim sağlayın +li[0] # => 1 +# Son elemente bakın +li[-1] # => 3 + +# Listede olmayan bir elemente erişim sağlamaya çalışmak IndexError hatası oluşturur +li[4] # IndexError hatası oluşturur + +# Bir kısmını almak isterseniz. +li[1:3] # => [2, 4] +# Başlangıç belirtmezseniz +li[2:] # => [4, 3] +# Sonu belirtmesseniz +li[:3] # => [1, 2, 4] +# Her ikişer objeyi seçme +li[::2] # =>[1, 4] +# Listeyi tersten almak +li[::-1] # => [3, 4, 2, 1] +# Kombinasyonları kullanarak gelişmiş bir şekilde listenin bir kısmını alabilirsiniz +# li[baslangic:son:adim] + +# "del" ile isteğe bağlı, elementleri listeden kaldırabilirsiniz +del li[2] # li artık [1, 2, 3] oldu + +# Listelerde de ekleme yapabilirsiniz +# Not: değerler üzerinde değişiklik yapılmaz. +li + diger_li # => [1, 2, 3, 4, 5, 6] + +# Listeleri birbirine bağlamak için "extend()" kullanılabilir +li.extend(diger_li) # li artık [1, 2, 3, 4, 5, 6] oldu + +# Listedeki bir elementin olup olmadığı kontrolü "in" ile yapılabilir +1 in li # => True + +# Uzunluğu öğrenmek için "len()" kullanılabilir +len(li) # => 6 + + +# Tüpler listeler gibidir fakat değiştirilemez. +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # TypeError hatası oluşturur + +# Diğer liste işlemlerini tüplerde de uygulayabilirsiniz +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Tüpleri(veya listeleri) değişkenlere açabilirsiniz +a, b, c = (1, 2, 3) # 'a' artık 1, 'b' artık 2 ve 'c' artık 3 +# Eğer parantez kullanmazsanız varsayılan oalrak tüpler oluşturulur +d, e, f = 4, 5, 6 +# 2 değeri birbirine değiştirmek bu kadar kolay +e, d = d, e # 'd' artık 5 ve 'e' artık 4 + + +# Sözlükler anahtar kodlarla verileri tutar +bos_sozl = {} +# Önceden doldurulmuş sözlük oluşturma +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} + +# Değere bakmak için [] kullanalım +dolu_sozl["bir"] # => 1 + +# Bütün anahtarları almak için "keys()" kullanılabilir. +# Listelemek için list() kullanacağınız çünkü dönen değerin işlenmesi gerekiyor. Bu konuya daha sonra değineceğiz. +# Not - Sözlük anahtarlarının sıralaması kesin değildir. +# Beklediğiniz çıktı sizinkiyle tam uyuşmuyor olabilir. +list(dolu_sozl.keys()) # => ["uc", "iki", "bir"] + + +# Tüm değerleri almak için "values()" kullanacağız. Dönen değeri biçimlendirmek için de list() kullanmamız gerekiyor +# Not - Sıralama değişebilir. +list(dolu_sozl.values()) # => [3, 2, 1] + + +# Bir anahtarın sözlükte olup olmadığını "in" ile kontrol edebilirsiniz +"bir" in dolu_sozl # => True +1 in dolu_sozl # => False + +# Olmayan bir anahtardan değer elde etmek isterseniz KeyError sorunu oluşacaktır. +dolu_sozl["dort"] # KeyError hatası oluşturur + +# "get()" metodu ile değeri almaya çalışırsanız KeyError sorunundan kurtulursunuz +dolu_sozl.get("bir") # => 1 +dolu_sozl.get("dort") # => None +# "get" metoduna parametre belirterek değerin olmaması durumunda varsayılan bir değer döndürebilirsiniz. +dolu_sozl.get("bir", 4) # => 1 +dolu_sozl.get("dort", 4) # => 4 + +# "setdefault()" metodu sözlükte, belirttiğiniz anahtarın [olmaması] durumunda varsayılan bir değer atayacaktır +dolu_sozl.setdefault("bes", 5) # dolu_sozl["bes"] artık 5 değerine sahip +dolu_sozl.setdefault("bes", 6) # dolu_sozl["bes"] değişmedi, hala 5 değerine sahip + +# Sözlüğe ekleme +dolu_sozl.update({"dort":4}) #=> {"bir": 1, "iki": 2, "uc": 3, "dort": 4} +#dolu_sozl["dort"] = 4 #sözlüğe eklemenin bir diğer yolu + +# Sözlükten anahtar silmek için 'del' kullanılabilir +del dolu_sozl["bir"] # "bir" anahtarını dolu sözlükten silecektir + + +# Setler ... set işte :D +bos_set = set() +# Seti bir veri listesi ile de oluşturabilirsiniz. Evet, biraz sözlük gibi duruyor. Üzgünüm. +bir_set = {1, 1, 2, 2, 3, 4} # bir_set artık {1, 2, 3, 4} + +# Sete yeni setler ekleyebilirsiniz +dolu_set = bir_set + +# Sete bir diğer öğe ekleme +dolu_set.add(5) # dolu_set artık {1, 2, 3, 4, 5} oldu + +# Setlerin çakışan kısımlarını almak için '&' kullanabilirsiniz +diger_set = {3, 4, 5, 6} +dolu_set & diger_set # => {3, 4, 5} + +# '|' ile aynı olan elementleri almayacak şekilde setleri birleştirebilirsiniz +dolu_set | diger_set # => {1, 2, 3, 4, 5, 6} + +# Farklılıkları almak için "-" kullanabilirsiniz +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Bir değerin olup olmadığının kontrolü için "in" kullanılabilir +2 in dolu_set # => True +10 in dolu_set # => False + + +#################################################### +## 3. Kontrol Akışları ve Temel Soyutlandırma +#################################################### + +# Bir değişken oluşturalım +bir_degisken = 5 + +# Burada bir "if" ifadesi var. Girinti(boşluk,tab) python için önemlidir! +# çıktı olarak "bir_degisken 10 dan küçük" yazar +if bir_degisken > 10: + print("bir_degisken 10 dan büyük") +elif bir_degisken < 10: # Bu 'elif' ifadesi zorunlu değildir. + print("bir_degisken 10 dan küçük") +else: # Bu ifade de zorunlu değil. + print("bir_degisken değeri 10") + + +""" +Döngülerle lsiteleri döngüye alabilirsiniz +çıktı: + köpek bir memeli hayvandır + kedi bir memeli hayvandır + fare bir memeli hayvandır +""" +for hayvan in ["köpek", "kedi, "fare"]: + # format ile kolayca yazıyı biçimlendirelim + print("{} bir memeli hayvandır".format(hayvan)) + +""" +"range(sayi)" bir sayı listesi döndür +0'dan belirttiğiniz sayıyıa kadar +çıktı: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +'While' döngüleri koşul çalıştıkça işlemleri gerçekleştirir. +çıktı: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Uzun hali x = x + 1 + +# Hataları kontrol altına almak için try/except bloklarını kullanabilirsiniz +try: + # Bir hata oluşturmak için "raise" kullanabilirsiniz + raise IndexError("Bu bir index hatası") +except IndexError as e: + pass # Önemsiz, devam et. +except (TypeError, NameError): + pass # Çoklu bir şekilde hataları kontrol edebilirsiniz, tabi gerekirse. +else: # İsteğe bağlı bir kısım. Eğer hiçbir hata kontrol mekanizması desteklemiyorsa bu blok çalışacaktır + print("Her şey iyi!") # IndexError, TypeError ve NameError harici bir hatada bu blok çalıştı + +# Temel Soyutlandırma, bir objenin işlenmiş halidir. +# Aşağıdaki örnekte; Obje, range fonksiyonuna temel soyutlandırma gönderdi. + +dolu_sozl = {"bir": 1, "iki": 2, "uc": 3} +temel_soyut = dolu_sozl.keys() +print(temel_soyut) #=> range(1,10). Bu obje temel soyutlandırma arayüzü ile oluşturuldu + +# Temel Soyutlandırılmış objeyi döngüye sokabiliriz. +for i in temel_soyut: + print(i) # Çıktısı: bir, iki, uc + +# Fakat, elementin anahtarına değerine. +temel_soyut[1] # TypeError hatası! + +# 'iterable' bir objenin nasıl temel soyutlandırıldığıdır. +iterator = iter(temel_soyut) + +# 'iterator' o obje üzerinde yaptığımız değişiklikleri hatırlayacaktır +# Bir sonraki objeyi almak için __next__ fonksiyonunu kullanabilirsiniz. +iterator.__next__() #=> "bir" + +# Bir önceki __next__ fonksiyonumuzu hatırlayıp bir sonraki kullanımda bu sefer ondan bir sonraki objeyi döndürecektir +iterator.__next__() #=> "iki" +iterator.__next__() #=> "uc" + +# Bütün nesneleri aldıktan sonra bir daha __next__ kullanımınızda, StopIterator hatası oluşturacaktır. +iterator.__next__() # StopIteration hatası + +# iterator'deki tüm nesneleri almak için list() kullanabilirsiniz. +list(dolu_sozl.keys()) #=> Returns ["bir", "iki", "uc"] + + +#################################################### +## 4. Fonksiyonlar +#################################################### + +# "def" ile yeni fonksiyonlar oluşturabilirsiniz +def topla(x, y): + print("x = {} ve y = {}".format(x, y)) + return x + y # Değer döndürmek için 'return' kullanmalısınız + +# Fonksiyonu parametleri ile çağırıyoruz +topla(5, 6) # => çıktı "x = 5 ve y = 6" ve değer olarak 11 döndürür + +# Bir diğer fonksiyon çağırma yöntemi de anahtar değerleri ile belirtmek +topla(y=6, x=5) # Anahtar değeri belirttiğiniz için parametre sıralaması önemsiz. + +# Sınırsız sayıda argüman da alabilirsiniz +def argumanlar(*argumanlar): + return argumanlar + +argumanlar(1, 2, 3) # => (1, 2, 3) + +# Parametrelerin anahtar değerlerini almak isterseniz +def anahtar_par(**anahtarlar): + return anahtar + +# Çalıştırdığımızda +anahtar_par(anah1="deg1", anah2="deg2") # => {"anah1": "deg1", "anah2": "deg2"} + + +# İsterseniz, bu ikisini birden kullanabilirsiniz +def tum_argumanlar(*argumanlar, **anahtarla): + print(argumanlar) + print(anahtarla) +""" +tum_argumanlar(1, 2, a=3, b=4) çıktı: + (1, 2) + {"a": 3, "b": 4} +""" + +# Fonksiyonu çağırırken de aynısını kullanabilirsiniz +argumanlar = (1, 2, 3, 4) +anahtarla = {"a": 3, "b": 4} +tum_argumanlar(*argumanlar) # = foo(1, 2, 3, 4) +tum_argumanlar(**anahtarla) # = foo(a=3, b=4) +tum_argumanlar(*argumanlar, **anahtarla) # = foo(1, 2, 3, 4, a=3, b=4) + + +# Fonksiyonlarda kullanacağımız bir değişken oluşturalım +x = 5 + +def belirleX(sayi): + # Fonksiyon içerisindeki x ile global tanımladığımız x aynı değil + x = sayi # => 43 + print (x) # => 43 + +def globalBelirleX(sayi): + global x + print (x) # => 5 + x = sayi # global olan x değişkeni artık 6 + print (x) # => 6 + +belirleX(43) +globalBelirleX(6) + + +# Sınıf fonksiyonları oluşturma +def toplama_olustur(x): + def topla(y): + return x + y + return topla + +ekle_10 = toplama_olustur(10) +ekle_10(3) # => 13 + +# Bilinmeyen fonksiyon +(lambda x: x > 2)(3) # => True + +# TODO - Fix for iterables +# Belirli sayıdan yükseğini alma fonksiyonu +map(ekle_10, [1, 2, 3]) # => [11, 12, 13] +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Filtreleme işlemi için liste comprehensions da kullanabiliriz +[ekle_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +#################################################### +## 5. Sınıflar +#################################################### + + +# Sınıf oluşturmak için objeden alt sınıf oluşturacağız. +class Insan(obje): + + # Sınıf değeri. Sınıfın tüm nesneleri tarafından kullanılabilir + tur = "H. sapiens" + + # Basit başlatıcı, Sınıf çağrıldığında tetiklenecektir. + # Dikkat edin, iki adet alt çizgi(_) bulunmakta. Bunlar + # python tarafından tanımlanan isimlerdir. + # Kendinize ait bir fonksiyon oluştururken __fonksiyon__ kullanmayınız! + def __init__(self, isim): + # Parametreyi sınıfın değerine atayalım + self.isim = isim + + # Bir metot. Bütün metotlar ilk parametre olarak "self "alır. + def soyle(self, mesaj): + return "{isim}: {mesaj}".format(isim=self.name, mesaj=mesaj) + + # Bir sınıf metotu bütün nesnelere paylaştırılır + # İlk parametre olarak sınıf alırlar + @classmethod + def getir_tur(snf): + return snf.tur + + # Bir statik metot, sınıf ve nesnesiz çağrılır + @staticmethod + def grunt(): + return "*grunt*" + + +# Sınıfı çağıralım +i = Insan(isim="Ahmet") +print(i.soyle("merhaba")) # çıktı "Ahmet: merhaba" + +j = Insan("Ali") +print(j.soyle("selam")) # çıktı "Ali: selam" + +# Sınıf metodumuzu çağıraim +i.getir_tur() # => "H. sapiens" + +# Paylaşılan değeri değiştirelim +Insan.tur = "H. neanderthalensis" +i.getir_tur() # => "H. neanderthalensis" +j.getir_tur() # => "H. neanderthalensis" + +# Statik metodumuzu çağıralım +Insan.grunt() # => "*grunt*" + + +#################################################### +## 6. Moduller +#################################################### + +# Modülleri içe aktarabilirsiniz +import math +print(math.sqrt(16)) # => 4 + +# Modülden belirli bir fonksiyonları alabilirsiniz +from math import ceil, floor +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Modüldeki tüm fonksiyonları içe aktarabilirsiniz +# Dikkat: bunu yapmanızı önermem. +from math import * + +# Modül isimlerini değiştirebilirsiniz. +# Not: Modül ismini kısaltmanız çok daha iyi olacaktır +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modulleri aslında birer python dosyalarıdır. +# İsterseniz siz de yazabilir ve içe aktarabilirsiniz Modulün +# ismi ile dosyanın ismi aynı olacaktır. + +# Moduldeki fonksiyon ve değerleri öğrenebilirsiniz. +import math +dir(math) + + +#################################################### +## 7. Gelişmiş +#################################################### + +# Oluşturucular uzun uzun kod yazmamanızı sağlayacak ve yardımcı olacaktır +def kare_sayilar(nesne): + for i in nesne: + yield i + i + +# Bir oluşturucu(generator) değerleri anında oluşturur. +# Bir seferde tüm değerleri oluşturup göndermek yerine teker teker her oluşumdan +# sonra geri döndürür. Bu demektir ki, kare_sayilar fonksiyonumuzda 15'ten büyük +# değerler işlenmeyecektir. +# Not: range() da bir oluşturucu(generator)dur. 1-900000000 arası bir liste yapmaya çalıştığınızda +# çok fazla vakit alacaktır. +# Python tarafından belirlenen anahtar kelimelerden kaçınmak için basitçe alt çizgi(_) kullanılabilir. +range_ = range(1, 900000000) +# kare_sayilar'dan dönen değer 30'a ulaştığında durduralım +for i in kare_sayilar(range_): + print(i) + if i >= 30: + break + + +# Dekoratörler +# Bu örnekte, +# Eğer lutfen_soyle True ise dönen değer değişecektir. +from functools import wraps + + +def yalvar(hedef_fonksiyon): + @wraps(hedef_fonksiyon) + def metot(*args, **kwargs): + msj, lutfen_soyle = hedef_fonksiyon(*args, **kwargs) + if lutfen_soyle: + return "{} {}".format(msj, "Lütfen! Artık dayanamıyorum :(") + return msj + + return metot + + +@yalvar +def soyle(lutfen_soyle=False): + msj = "Bana soda alır mısın?" + return msj, lutfen_soyle + + +print(soyle()) # Bana soda alır mısın? +print(soyle(lutfen_soyle=True)) # Ban soda alır mısın? Lutfen! Artık dayanamıyorum :( +``` + +## Daha Fazlasına Hazır Mısınız? + +### Ücretsiz Online + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Ideas for Python Projects](http://pythonpracticeprojects.com) + +* [The Official Docs](http://docs.python.org/3/) +* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [Python Course](http://www.python-course.eu/index.php) + +### Kitaplar + +* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) +* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) + diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown new file mode 100644 index 00000000..c13f5ecf --- /dev/null +++ b/tr-tr/swift-tr.html.markdown @@ -0,0 +1,588 @@ +--- +language: swift +contributors: + - ["Özgür Şahin", "https://github.com/ozgurshn/"] +filename: learnswift.swift +lang: tr-tr +--- + +Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. + + +Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı. + +Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var. + + + +```swift +// modülü import etme +import UIKit + +// +// MARK: Temeller +// + + +//XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot + listesinde gruplama yapmanıza olanak sağlıyor +// MARK: Bölüm işareti +// TODO: Daha sonra yapılacak +// FIXME: Bu kodu düzelt + + +//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print + otomatik olarak yeni satır ekliyor. +print("Merhaba dünya") // println print olarak kullanılıyor. +print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar. + +// variables (var) değer atandıktan sonra değiştirilebilir. +// constants (let) değer atndıktan sonra değiştirilemez. + +var degiskenim = 42 +let øπΩ = "deger" // unicode degişken adları +let π = 3.1415926 +let convenience = "keyword" // bağlamsal değişken adı +let isim = "ahmet"; let soyad = "un" // farklı ifadeler noktalı virgül +kullanılarak ayrılabilir. +let `class` = "keyword" // rezerve edilmiş keywordler tek tırnak içerisine +alınarak değişken adı olarak kullanılabilir +let doubleOlduguBelli: Double = 70 +let intDegisken = 0007 // 7 +let largeIntDegisken = 77_000 // 77000 +let etiket = "birseyler " + String(degiskenim) // Cast etme +let piYazi = "Pi = \(π), Pi 2 = \(π * 2)" // String içerisine değiken yazdırma + + +// Builde özel değişkenler +// -D build ayarını kullanır. +#if false + print("yazılmadı") + let buildDegiskeni= 3 +#else + let buildDegiskeni = 7 +#endif +print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7 + +/* + Optionals Swift dilinde bazı değerleri veya yokluğu (None) bir değişkende + tutmanıza olanak sağlar. + + Swift'te her bir degişkeninin bir değeri olması gerektiğinden, nil değeri + bile Optional değer olarak saklanır. + + Optional<T> bir enum'dır. +*/ +var baziOptionalString: String? = "optional" // nil olabilir. +// yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay +okunabilir) +var someOptionalString2: Optional<String> = "optional" + + +if baziOptionalString != nil { + // ben nil değilim + if baziOptionalString!.hasPrefix("opt") { + print("ön eki var") + } + + let bos = baziOptionalString?.isEmpty +} +baziOptionalString = nil + +// belirgin olarak acilan(unwrap) opsiyonel (optional) değer +var acilanString: String! = "Değer bekleniliyor" +//yukarıdakiyle aynı ama ! bir postfix operatördür (kolay okunabilir) +var acilanString2: ImplicitlyUnwrappedOptional<String> = "Değer bekleniliyor." + +if let baziOpsiyonelSabitString = baziOptionalString { + // eğer bir değeri varsa, nil değilse + if ! baziOpsiyonelSabitString("tamam") { + // ön eke sahip değil + } +} + +// Swift değişkenlerde herhangi bir tip saklanabilir. +// AnyObject == id +// Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle + çalışabilir (Class, Int, struct, etc) +var herhangiBirObject: AnyObject = 7 +herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün" + +/* + Yorumlar buraya + + /* + İç içe yorum yazılması da mümkün + */ +*/ + +// +// MARK: Koleksiyonlar +// + +/* + Array ve Dictionary tipleri aslında structdırlar. Bu yüzden `let` ve `var` + ayrıca bu tipleri tanımlarken değişebilir(var) veya değişemez(let) + olduğunu belirtir. + +*/ + +// Diziler +var liste = ["balik", "su", "limon"] +liste[1] = "şişe su" +let bosDizi = [String]() // let == değiştirilemez +let bosDizi2 = Array<String>() // yukarıdakiyle aynı +var bosDegistirilebilirDizi = [String]() // var == değişebilir + + +// Dictionary +var meslekler = [ + "Kamil": "Kaptan", + "Ayse": "Analist" +] +meslekler["Cansu"] = "Halkla İlişkiler" +let bosDictionary = [String: Float]() // let == değiştirilemez +let bosDictionary2 = Dictionary<String, Float>() // yukarıdakiyle aynı +var bosDegistirilebirDictionary = [String: Float]() // var == değiştirilebilir + + +// +// MARK: Kontroller +// + +// for döngüsü (dizi) +let dizi = [1, 1, 2, 3, 5] +for deger in dizi { + if deger == 1 { + print("Bir!") + } else { + print("Bir degil!") + } +} + +// for döngüsü (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// for döngüsü (aralık) +for i in -1...liste.count { + print(i) +} +liste[1...2] = ["et", "yogurt"] +// ..< kullanarak son elemanı çıkartabilirsiniz + +// while döngüsü +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while döngüsü +do { + print("merhaba") +} while 1 == 2 + +// Switch +// Çok güçlü, `if` ifadesenin daha kolay okunabilir hali olarak düşünün +// String, object örnekleri, ve primitif tipleri (Int, Double, vs) destekler. +let sebze = "kırmızı biber" +switch sebze { +case "sogan": + let sebzeYorumu = "Biraz da domates ekle" +case "domates", "salata": + let sebzeYorumu = "İyi bir sandviç olur" +case let lokalScopeDegeri where lokalScopeDegeri.hasSuffix("biber"): + let sebzeYorumu = "Acı bir \(lokalScopeDegeri)?" +default: // zorunludur (tüm olasılıkları yakalamak icin) + let sebzeYorumu = "Corbadaki herseyin tadı güzel" +} + + +// +// MARK: Fonksiyonlar +// + +// Fonksiyonlar first-class tiplerdir, yani başka fonksiyon içine konabilir +// ve parametre olarak geçirilebilirler. + +// Swift dökümanlarıylaa birlikte Fonksiyonlar (format as reStructedText) + +/** + selamlama işlemi + + :param: isim e isim + :param: gun e A gun + :returns: isim ve gunu iceren bir String +*/ +func selam(isim: String, gun: String) -> String { + return "Merhaba \(isim), bugün \(gun)." +} +selam("Can", "Salı") + +// fonksiyon parametre davranışı hariç yukarıdakine benzer +func selam2(#gerekliIsim: String, disParametreIsmi lokalParamtreIsmi: String) -> String { + return "Merhaba \(gerekliIsim), bugün \(lokalParamtreIsmi)" +} +selam2(gerekliIsim:"Can", disParametreIsmi: "Salı") + +// Bir tuple ile birden fazla deger dönen fonksiyon +func fiyatlariGetir() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let fiyatTuple = fiyatlariGetir() +let fiyat = fiyatTuple.2 // 3.79 +// _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden +gelir +let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69 +print(fiyat1 == fiyatTuple.1) // true +print("Benzin fiyatı: \(fiyat)") + +// Çeşitli Argümanlar +func ayarla(sayilar: Int...) { + // bu bir dizidir + let sayi = sayilar[0] + let argumanSAyisi = sayilar.count +} + +// fonksiyonu parametre olarak geçirme veya döndürme +func arttirmaIslemi() -> (Int -> Int) { + func birEkle(sayi: Int) -> Int { + return 1 + sayi + } + return birEkle +} +var arttir = arttirmaIslemi() +arttir(7) + +// referans geçirme +func yerDegistir(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +yerDegistir(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closurelar +// +var sayilar = [1, 2, 6] + +// Fonksiyonlar özelleştirilmiş closurelardır. ({}) + +// Closure örneği. +// `->` parametrelerle dönüş tipini birbirinden ayırır +// `in` closure başlığını closure bodysinden ayırır. +sayilar.map({ + (sayi: Int) -> Int in + let sonuc = 3 * sayi + return sonuc +}) + +// eger tip biliniyorsa, yukarıdaki gibi, şöyle yapabiliriz +sayilar = sayilar.map({ sayi in 3 * sayi }) +// Hatta bunu +//sayilar = sayilar.map({ $0 * 3 }) + +print(sayilar) // [3, 6, 18] + +// Trailing closure +sayilar = sorted(sayilar) { $0 > $1 } + +print(sayilar) // [18, 6, 3] + +// Super kısa hali ise, < operatörü tipleri çıkartabildiği için + +sayilar = sorted(sayilar, < ) + +print(sayilar) // [3, 6, 18] + +// +// MARK: Yapılar +// + +// Structurelar ve sınıflar birçok aynı özelliğe sahiptir. +struct IsimTablosu { + let isimler = [String]() + + // Özelleştirilmiş dizi erişimi + subscript(index: Int) -> String { + return isimler[index] + } +} + +// Structurelar otomatik oluşturulmuş kurucu metoda sahiptir. +let isimTablosu = IsimTablosu(isimler: ["Ben", "Onlar"]) +let isim = isimTablosu[1] +print("İsim \(name)") // İsim Onlar + +// +// MARK: Sınıflar +// + +// Sınıflar, structurelar ve üyeleri 3 seviye erişime sahiptir. +// Bunlar: internal (default), public, private + +public class Sekil { + public func alaniGetir() -> Int { + return 0; + } +} + +// Sınıfın tüm değişkenleri ve metotları publictir. +// Eğer sadece veriyi yapılandırılmış bir objede +// saklamak istiyorsanız, `struct` kullanmalısınız. + +internal class Rect: Sekil { + var yanUzunluk: Int = 1 + + // Özelleştirilmiş getter ve setter propertyleri + private var cevre: Int { + get { + return 4 * yanUzunluk + } + set { + // `newValue ` setterlarda yeni değere erişimi sağlar + yanUzunluk = newValue / 4 + } + } + + // Bir değişkene geç atama(lazy load) yapmak + // altSekil getter cağrılana dek nil (oluşturulmamış) olarak kalır + lazy var altSekil = Rect(yanUzunluk: 4) + + // Eğer özelleştirilmiş getter ve setter a ihtiyacınız yoksa, + // ama bir değişkene get veya set yapıldıktan sonra bir işlem yapmak + // istiyorsanız, `willSet` ve `didSet` metotlarını kullanabilirsiniz + var identifier: String = "defaultID" { + // `willSet` argümanı yeni değer için değişkenin adı olacaktır. + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(yanUzunluk: Int) { + self. yanUzunluk = yanUzunluk + // super.init i her zaman özelleştirilmiş değerleri oluşturduktan sonra + çağırın + super.init() + } + + func kisalt() { + if yanUzunluk > 0 { + --yanUzunluk + } + } + + override func alaniGetir() -> Int { + return yanUzunluk * yanUzunluk + } +} + +// Basit `Kare` sınıfI `Rect` sınıfını extend ediyor. +class Kare: Rect { + convenience init() { + self.init(yanUzunluk: 5) + } +} + +var benimKarem = Kare() +print(m benimKarem.alaniGetir()) // 25 +benimKarem.kisalt() +print(benimKarem.yanUzunluk) // 4 + +// sınıf örneğini cast etme +let birSekil = benimKarem as Sekil + +// örnekleri karşılaştır, objeleri karşılaştıran == (equal to) ile aynı değil +if benimKarem === benimKarem { + print("Evet, bu benimKarem") +} + +// Opsiyonel init +class Daire: Sekil { + var yaricap: Int + override func alaniGetir() -> Int { + return 3 * yaricap * yaricap + } + + // Eğer init opsiyonelse (nil dönebilir) `init` den sonra soru işareti + // son eki ekle. + init?(yaricap: Int) { + self.yaricap = yaricap + super.init() + + if yaricap <= 0 { + return nil + } + } +} + +var benimDairem = Daire(radius: 1) +print(benimDairem?.alaniGetir()) // Optional(3) +print(benimDairem!. alaniGetir()) // 3 +var benimBosDairem = Daire(yaricap: -1) +print(benimBosDairem?. alaniGetir()) // "nil" +if let daire = benimBosDairem { + // benimBosDairem nil olduğu için çalışmayacak + print("circle is not nil") +} + + +// +// MARK: Enumlar +// + +// Enumlar opsiyonel olarak özel bir tip veya kendi tiplerinde olabilirler. +// Sınıflar gibi metotlar içerebilirler. + +enum Kart { + case Kupa, Maca, Sinek, Karo + func getIcon() -> String { + switch self { + case .Maca: return "♤" + case .Kupa: return "♡" + case .Karo: return "♢" + case .Sinek: return "♧" + } + } +} + +// Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz. +var kartTipi: Kart = .Kupa + +// Integer olmayan enumlar direk değer (rawValue) atama gerektirir. +enum KitapAdi: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(KitapAdi.John.rawValue)") + +// Değerlerle ilişkilendirilmiş Enum +enum Mobilya { + // Int ile ilişkilendirilmiş + case Masa(yukseklik: Int) + // String ve Int ile ilişkilendirilmiş + case Sandalye(String, Int) + + func aciklama() -> String { + switch self { + case .Masa(let yukseklik): + return "Masa boyu \(yukseklik) cm" + case .Sandalye(let marka, let yukseklik): + return "\(brand) marka sandalyenin boyu \(yukseklik) cm" + } + } +} + +var masa: Mobilya = .Masa(yukseklik: 80) +print(masa.aciklama()) // "Masa boyu 80 cm" +var sandalye = Mobilya.Sandalye("Foo", 40) +print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm" + + +// +// MARK: Protokoller +// + +// `protocol` onu kullanan tiplerin bazı özel değişkenleri, metotları, +// tip metotlarını,opertörleri ve alt indisleri (subscripts) içermesini +// zorunlu hale getirebilir. + +protocol SekilUretici { + var aktif: Bool { get set } + func sekilOlustur() -> Sekil +} + +// @objc ile tanımlanan protokoller, uygunluğu kontrol edebilmenizi sağlayacak +// şekilde opsiyonel fonksiyonlara izin verir +@objc protocol SekliDondur { + optional func sekillendirilmis() + optional func sekillendirilebilir() -> Bool +} + +class BenimSeklim: Rect { + var delegate: SekliDondur? + + func buyut() { + yanUzlunluk += 2 + + // Bir çalışma zamanı hatası("optional chaining") fırlatmak yerine nil + //değeri görmezden gelerek nil dönmek için opsiyonel değişken, metot veya + // altindisten sonra soru işareti koyabilirsiniz. + if let izinVeriyormu = self.delegate?.sekillendirilebilir?() { + // önce delegate i sonra metodu test edin + self.delegate?.sekillendirilmis?() + } + } +} + + +// +// MARK: Diğerleri +// + +// `extension`lar: Var olan tiplere ekstra özellikler ekleyin + +// Kare artık `Printable` protokolüne uyuyor. +extension Kare: Printable { + var description: String { + return "Alan: \(alaniGetir()) - ID: \(self.identifier)" + } +} + +print("Kare: \(benimKarem)") + +// Dahili tipleri de yeni özellikler ekleyebilirsiniz +extension Int { + var customProperty: String { + return "Bu sayı \(self)" + } + + func carp(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "Bu sayı 7" +print(14.carp(3)) // 42 + +// Genericler: Java ve C#'a benzer şekilde. `where` anahtar kelimesini +// kullanarak genericlerin özelliklerini belirleyin + +func indexiBul<T: Equatable>(dizi: [T], bulunacakDeger: T) -> Int? { + for (index, deger) in enumerate(dizi) { + if deger == bulunacakDeger { + return index + } + } + return nil +} +let bulunanIndex = indexiBul([1, 2, 3, 4], 3) +print(bulunanIndex == 2) // true + +// Operatorler: +// Özel operatorler şu karakterlerle başlayabilir: +// / = - + * % < > ! & | ^ . ~ +// veya +// Unicode math, symbol, arrow, dingbat, ve line/box karakterleri. +prefix operator !!! {} + +// Yan uzunluğu 3 katına çıkartan prefix operatörü +prefix func !!! (inout sekil: Kare) -> Kare { + sekil.YanUzunluk *= 3 + return sekil +} + +// güncel deger +print(benimKarem.YanUzunluk) // 4 + +// yan uzunluğu !!! operatorü kullanarak 3 katına çıkar +!!!benimKarem +print(benimKarem.YanUzunluk) // 12 +``` diff --git a/typescript.html.markdown b/typescript.html.markdown index 9f04169a..e9135510 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -9,105 +9,116 @@ TypeScript is a language that aims at easing development of large scale applicat TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. -This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as opposed to [JavaScript] (../javascript/). To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. ```js -//There are 3 basic types in TypeScript +// There are 3 basic types in TypeScript var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//..When it's impossible to know, there is the "Any" type +// When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean -//For collections, there are typed arrays and generic arrays +// For collections, there are typed arrays and generic arrays var list: number[] = [1, 2, 3]; -//Alternatively, using the generic array type +// Alternatively, using the generic array type var list: Array<number> = [1, 2, 3]; -//For enumerations: +// For enumerations: enum Color {Red, Green, Blue}; var c: Color = Color.Green; -//Lastly, "void" is used in the special case of a function not returning anything +// Lastly, "void" is used in the special case of a function returning nothing function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference -//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted -var f1 = function(i: number) : number { return i * i; } -var f2 = function(i: number) { return i * i; } //Return type infered -var f3 = (i : number) : number => { return i * i; } -var f4 = (i: number) => { return i * i; } //Return type infered -var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed - -//Interfaces are structural, anything that has the properties is compliant with the interface +// Functions are first class citizens, support the lambda "fat arrow" syntax and +// use type inference + +// The following are equivalent, the same signature will be infered by the +// compiler, and same JavaScript will be emitted +var f1 = function(i: number): number { return i * i; } +// Return type inferred +var f2 = function(i: number) { return i * i; } +var f3 = (i: number): number => { return i * i; } +// Return type inferred +var f4 = (i: number) => { return i * i; } +// Return type inferred, one-liner means no return keyword needed +var f5 = (i: number) => i * i; + +// Interfaces are structural, anything that has the properties is compliant with +// the interface interface Person { name: string; - //Optional properties, marked with a "?" + // Optional properties, marked with a "?" age?: number; - //And of course functions + // And of course functions move(): void; } -//..Object that implements the "Person" interface -var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties -//..Objects that have the optional property: -var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; -var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number +// Object that implements the "Person" interface +// Can be treated as a Person since it has the name and move properties +var p: Person = { name: "Bobby", move: () => {} }; +// Objects that have the optional property: +var validPerson: Person = { name: "Bobby", age: 42, move: () => {} }; +// Is not a person because age is not a number +var invalidPerson: Person = { name: "Bobby", age: true }; -//..Interfaces can also describe a function type +// Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//..Only the parameters' types are important, names are not important. +// Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -//Classes - members are public by default +// Classes - members are public by default class Point { - //Properties - x: number; - - //Constructor - the public/private keywords in this context will generate the boiler plate code - // for the property and the initialization in the constructor. - // In this example, "y" will be defined just like "x" is, but with less code - //Default values are also supported - constructor(x: number, public y: number = 0) { - this.x = x; - } - - //Functions - dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } - - //Static members - static origin = new Point(0, 0); + // Properties + x: number; + + // Constructor - the public/private keywords in this context will generate + // the boiler plate code for the property and the initialization in the + // constructor. + // In this example, "y" will be defined just like "x" is, but with less code + // Default values are also supported + + constructor(x: number, public y: number = 0) { + this.x = x; + } + + // Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + // Static members + static origin = new Point(0, 0); } var p1 = new Point(10 ,20); var p2 = new Point(25); //y will be 0 -//Inheritance +// Inheritance class Point3D extends Point { - constructor(x: number, y: number, public z: number = 0) { - super(x, y); //Explicit call to the super class constructor is mandatory - } - - //Overwrite - dist() { - var d = super.dist(); - return Math.sqrt(d * d + this.z * this.z); - } + constructor(x: number, y: number, public z: number = 0) { + super(x, y); // Explicit call to the super class constructor is mandatory + } + + // Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } } -//Modules, "." can be used as separator for sub modules +// Modules, "." can be used as separator for sub modules module Geometry { export class Square { constructor(public sideLength: number = 0) { @@ -120,32 +131,32 @@ module Geometry { var s1 = new Geometry.Square(5); -//..Local alias for referencing a module +// Local alias for referencing a module import G = Geometry; var s2 = new G.Square(10); -//Generics -//..Classes +// Generics +// Classes class Tuple<T1, T2> { constructor(public item1: T1, public item2: T2) { } } -//..Interfaces +// Interfaces interface Pair<T> { - item1: T; - item2: T; + item1: T; + item2: T; } -//..And functions +// And functions var pairToTuple = function<T>(p: Pair<T>) { - return new Tuple(p.item1, p.item2); + return new Tuple(p.item1, p.item2); }; var tuple = pairToTuple({ item1:"hello", item2:"world"}); -//Including references to a definition file: +// Including references to a definition file: /// <reference path="jquery.d.ts" /> ``` diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown new file mode 100644 index 00000000..fedbf5ac --- /dev/null +++ b/uk-ua/javascript-ua.html.markdown @@ -0,0 +1,501 @@ +--- +language: javascript +contributors: + - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +filename: javascript-ru.js +translators: + - ["Alexey Gonchar", "http://github.com/finico"] + - ["Andre Polykanine", "https://github.com/Oire"] +lang: ru-ru +--- + +JavaScript було створено в 1995 році Бренданом Айком, який працював у копаніх Netscape. +Він був задуманий як проста мова сценаріїв для веб-сайтів, який би доповнював Java +для більш складних веб-застосунків. Але тісна інтеграція з веб-сторінками і +вбудована підтримка браузерами призвела до того, що JavaScript став популярніший +за власне Java. + +Зараз JavaScript не обмежується тільки веб-браузеорм. Наприклад, Node.js, +програмна платформа, що дозволяє виконувати JavaScript код з використанням +рушія V8 від браузера Google Chrome, стає все більш і більш популярною. + +```js +// С-подібні коментарі. Однорядкові коментарі починаються з двох символів /(слеш) +/* а багаторядкові коментарі починаються з послідовності слеша та зірочки і + закінчуються символами зірочка-слеш */ + +Інструкції можуть закінчуватися крапкою з комою ; +doStuff(); + +// ... але не обов’язково, тому що крапка з комою автоматично вставляється на +// місці символу нового рядка, крім деяких випадків. +doStuff() + +// Ми завжди будемо використовувати крапку з комою в цьому посібнику, тому що ці +// винятки можуть призвести до неочікуваних результатів + +/////////////////////////////////// +// 1. Числа, Рядки і Оператори + +// В JavaScript числа зберігаються тільки в одному форматі (64-bit IEEE 754 double) +// Цей тип має 52-бітну мантису, якої достатньо для збереження чисел з +// точністю до 9✕10¹⁵. +3; // = 3 +1.5; // = 1.5 + +// Деякі прості арифметичні операції працють так, як ми очікуємо. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 (а деякі - ні) +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// В тому числі ділення з остачою +5 / 2; // = 2.5 + +// В JavaScript є побітові операції; коли ви виконуєте таку операцію, +// число з плаваючою точкою переводиться в ціле зі знаком +// довжиною *до* 32 розрядів. +1 << 2; // = 4 + +// Пріоритет у виразах можна задати явно круглими дужками +(1 + 3) * 2; // = 8 + +// Є три спеціальні значення, які не є реальними числами: +Infinity; // "нескінченність", наприклад, як результат ділення на 0 +-Infinity; // "мінус нескінченність", як результат ділення від’ємного числа на 0 +NaN; // "не число", наприклад, ділення 0/0 + +// Логічні типи +true; +false; + +// Рядки створюються за допомогою подвійних та одинарних лапок +'абв'; +"Hello, world!"; + +// Для логічного заперечення використовується знак оклику. +!true; // = false +!false; // = true + +// Строга рівність === +1 === 1; // = true +2 === 1; // = false + +// Строга нерівність !== +1 !== 1; // = false +2 !== 1; // = true + +// Інші оператори порівняння +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Рядки об’єднуються за допомогою оператор + +"hello, " + "world!"; // = "hello, world!" + +// І порівнюються за допомогою > і < +"a" < "b"; // = true + +// Перевірка на рівність з приведнням типів здійснюється оператором == +"5" == 5; // = true +null == undefined; // = true + +// ... але приведення не виконується при === +"5" === 5; // = false +null === undefined; // = false + +// ... приведення типів може призвести до дивних результатів +13 + !0; // 14 +"13" + !0; // '13true' + +// Можна отримати доступ до будь-якого символа рядка за допомгою charAt +"Это строка".charAt(0); // = 'Э' + +// ... або використати метод substring, щоб отримати більший кусок +"Hello, world".substring(0, 5); // = "Hello" + +// length - це не метод, а поле +"Hello".length; // = 5 + +// Типи null и undefined +null; // навмисна відсутність результату +undefined; // використовується для позначення відсутності присвоєного значення + +// false, null, undefined, NaN, 0 и "" — хиба; все інше - істина. +// Потрібно відмітити, що 0 — це зиба, а "0" — істина, не зважаючи на те що: +// 0 == "0". + +/////////////////////////////////// +// 2. Змінні, Масиви, Об’єкти + +// Змінні оголошуються за допомогою ключового слова var. JavaScript — мова з +// динамічною типізацією, тому не потрібно явно вказувати тип. Для присвоєння +// значення змінної використовується символ = +var someVar = 5; + +// якщо пропустити слово var, ви не отримаєте повідомлення про помилку, ... +someOtherVar = 10; + +// ... але ваша змінна буде створення в глобальному контексті, а не там, де +// ви її оголосили + +// Змінні, які оголошені без присвоєння, автоматично приймають значення undefined +var someThirdVar; // = undefined + +// У математичних операцій є скорочені форми: +someVar += 5; // як someVar = someVar + 5; +someVar *= 10; // тепер someVar = 100 + +// Інкремент і декремент +someVar++; // тепер someVar дорівнює 101 +someVar--; // а зараз 100 + +// Масиви — це нумеровані списку, які зберігають значення будь-якого типу. +var myArray = ["Hello", 45, true]; + +// Доступ до елементів можна отримати за допомогою синтаксиса з квадратними дужками +// Індексація починається з нуля +myArray[1]; // = 45 + +// Массивы можно изменять, как и их длину, +myArray.push("Мир"); +myArray.length; // = 4 + +// додавання і редагування елементів +myArray[3] = "Hello"; + +// Об’єкти в JavaScript сході на словники або асоціативні масиви в інших мовах +var myObj = {key1: "Hello", key2: "World"}; + +// Ключі - це рядки, але лапки не обов’язкі, якщо ключ задовольняє +// правилам формування назв змінних. Значення можуть бути будь-яких типів. +var myObj = {myKey: "myValue", "my other key": 4}; + +// Атрибути можна отримати використовуючи квадратні дужки +myObj["my other key"]; // = 4 + +// Або через точку, якщо ключ є правильним ідентифікатором +myObj.myKey; // = "myValue" + +// Об’єкти можна динамічно змінювати й додавати нові поля +myObj.myThirdKey = true; + +// Коли ви звертаєтесб до поля, яке не існує, ви отримуєте значення undefined +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Управляючі конструкції + +// Синтаксис для цього розділу майже такий самий, як у Java + +// Умовна конструкція +var count = 1; +if (count == 3) { + // виконується, якщо count дорівнює 3 +} else if (count == 4) { + // .. +} else { + // ... +} + +// ... цикл while. +while (true){ + // Нескінченний цикл! +} + +// Цикл do-while такий самий, як while, але завжди виконується принаймні один раз. +var input +do { + input = getInput(); +} while (!isValid(input)) + +// цикл for такий самий, кяк в C і Java: +// ініціалізація; умова; крок. +for (var i = 0; i < 5; i++) { + // виконається 5 разів +} + +// && — логічне І, || — логічне АБО +if (house.size == "big" && house.color == "blue") { + house.contains = "bear"; +} +if (color == "red" || color == "blue") { + // колір червоний або синій +} + +// && і || використовують скорочене обчислення +// тому їх можна використовувати для задання значень за замовчуванням. +var name = otherName || "default"; + +// Оператор switch виконує перевірку на рівність за допомогою === +// використовуйте break, щоб призупити виконання наступного case, +grade = 4; +switch (grade) { + case 5: + console.log("Відмінно"); + break; + case 4: + console.log("Добре"); + break; + case 3: + console.log("Можна краще"); + break; + default: + console.log("Погано!"); + break; +} + + +/////////////////////////////////// +// 4. Функції, область видимості і замикання + +// Функції в JavaScript оголошуються за допомогою ключового слова function. +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Зверність увагу, що значення яке буде повернено, повинно починатися на тому ж +// рядку, що і ключове слово return, інакше завжди буде повертатися значення undefined +// із-за автоматичної вставки крапки з комою +function myFunction() +{ + return // <- крапка з комою вставляється автоматично + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// В JavaScript функції - це об`єкти першого класу, тому вони можуть присвоюватися +// іншим змінним і передаватися іншим функціям, наприклад, щоб визначити обробник +// події. +function myFunction() { + // код буде виконано через 5 сек. +} +setTimeout(myFunction, 5000); +// setTimeout не є частиною мови, але реалізований в браузерах і Node.js + +// Функции не обязательно должны иметь имя при объявлении — вы можете написать +// анонимное определение функции непосредственно в аргументе другой функции. +// Функції не обов’язково мають мати ім’я при оголошенні — ви можете написати +// анонімну функцію прямо в якості аргумента іншої функції +setTimeout(function() { + // Цей код буде виконано через п’ять секунд +}, 5000); + +// В JavaScript реалізована концепція області видимості; функції мають свою +// область видимости, а інші блоки не мають +if (true) { + var i = 5; +} +i; // = 5, а не undefined, як це звичайно буває в інших мова + +// Така особливість призвела до шаблону "анонімних функцій, які викликають самих себе" +// що дозволяє уникнути проникнення змінних в глобальну область видимості +(function() { + var temporary = 5; + // об’єкт window зберігає глобальний контекст; таким чином ми можемо також додавати + // змінні до глобальної області + window.permanent = 10; +})(); +temporary; // повідомлення про помилку ReferenceError +permanent; // = 10 + +// Одной из самых мощных возможностей JavaScript являются замыкания. Если функция +// определена внутри другой функции, то внутренняя функция имеет доступ к +// переменным внешней функции даже после того, как контекст выполнения выйдет из +// внешней функции. +// Замикання - одна з найпотужніших інтрументів JavaScript. Якщо функція визначена +// всередині іншої функції, то внутрішня функція має доступ до змінних зовнішньої +// функції навіть після того, як код буде виконуватися поза контекстом зовнішньої функції +function sayHelloInFiveSeconds(name) { + var prompt = "Hello, " + name + "!"; + // Внутрішня функція зберігається в локальній області так, + // ніби функція була оголошена за допомогою ключового слова var + function inner() { + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout асинхронна, тому функція sayHelloInFiveSeconds зразу завершиться, + // після чого setTimeout викличе функцію inner. Але функція inner + // «замкнута» кругом sayHelloInFiveSeconds, вона все рівно має доступ до змінної prompt +} +sayHelloInFiveSeconds("Адам"); // Через 5 с відкриється вікно «Hello, Адам!» + +/////////////////////////////////// +// 5. Об’єкти: конструктори і прототипи + +// Об’єкти можуть містити функції +var myObj = { + myFunc: function() { + return "Hello, world!"; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Функції, що прикріплені до об’єктів мають доступ до поточного об’єкта за +// допомогою ключового слова this. +myObj = { + myString: "Hello, world!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // = "Hello, world!" + +// Значення this залежить від того, як функція викликається +// а не від того, де вона визначена. Таким чином наша функція не працює, якщо +// вона викликана не в контексті об’єкта +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Функція може бути присвоєна іншому об’єкту. Тоді вона матиме доступ до +// цього об’єкта через this +var myOtherFunc = function() { +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO, WORLD!" + +// Контекст виконання функції можна задати за допомогою сall або apply +var anotherFunc = function(s) { + return this.myString + s; +} +anotherFunc.call(myObj, " Hello!"); // = "Hello, world! Hello!" + +// Функцiя apply приймає в якості аргументу масив +anotherFunc.apply(myObj, [" Hello!"]); // = "Hello, world! Hello!" + +// apply можна використати, коли функція працює послідовністю аргументів, а +// ви хочете передати масив +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Ой-ой!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Але call і apply — тимчасові. Коли ми хочемо зв’язати функцію і об’єкт +// використовують bind +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" Hello!"); // = "Hello world, Hello!" + +// Bind можна використати для задання аргументів +var product = function(a, b) { return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Коли ви викликаєте функцію за допомогою ключового слова new, створюється новий об’єкт, +// доступний функції за допомогою this. Такі функції називають конструкторами. +var MyConstructor = function() { + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// У кожного об’єкта є прототип. Коли ви звертаєтесь до поля, яке не існує в цьому +// об’єктів, інтерпретатор буде шукати поле в прототипі + +// Деякі реалізації мови дозволяють отримати доступ до прототипа об’єкта через +// "магічну" властивість __proto__. Це поле не є частиною стандарта, але існують +// стандартні способи використання прототипів, які ми побачимо пізніше +var myObj = { + myString: "Hello, world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase() + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Аналогічно для функцій +myObj.myFunc(); // = "Hello, world!" + +// Якщо інтерпретатор не знайде властивість в прототипі, то він продвжить пошук +// в прототипі прототипа і так далі +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Кожег об’єкт зберігає посилання на свій прототип. Це значить, що ми можемо змінити +// наш прототип, і наші зміни будуть всюди відображені. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Ми сказали, що властивість __proto__ нестандартне, і нема ніякого стандартного способу +// змінити прототип об’єкта, що вже існує. Але є два способи створити новий об’єкт зі заданим +// прототипом + +// Перший спосіб — це Object.create, який з’явився JavaScript недавно, +// а тому в деяких реалізаціях може бути не доступним. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Другий спосіб: у конструкторів є властивість з іменем prototype. Це *не* +// прототип функції-конструктора, це прототип для нових об’єктів, які будуть створені +// цим конструктором і ключового слова new. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function() { + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 + +// У вбудованих типів(рядок, число) теж є конструктори, які створють еквівалентні +// об’єкти-обгортки +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Але вони не ідентичні +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0) { + // Этот код не выполнится, потому что 0 - это ложь. +} + +// Об’єкти-обгортки і вбудовані типи мають спільні прототипи, тому +// ви можете розширити функціонал рядків: +String.prototype.firstCharacter = function() { + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Такий прийом часто використовуються в поліфілах, які реалізують нові можливості +// JavaScript в старій реалізації мови, так що вони можуть бути використані в старих +// середовищах + +// Наприклад, Object.create доступний не у всіх реалізація, но ми можемо +// використати функції за допомогою наступного поліфіла: +if (Object.create === undefined) { // не перезаписываем метод, если он существует + Object.create = function(proto) { + // Створюємо правильний конструктор з правильним прототипом + var Constructor = function(){}; + Constructor.prototype = proto; + + return new Constructor(); + } +} +``` + +## Що почитати + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: http://www.amazon.com/gp/product/0596805527/ +[7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[8]: http://eloquentjavascript.net/ +[9]: http://jstherightway.org/ diff --git a/vi-vn/json-vi.html.markdown b/vi-vn/json-vi.html.markdown new file mode 100644 index 00000000..257216ff --- /dev/null +++ b/vi-vn/json-vi.html.markdown @@ -0,0 +1,76 @@ +--- +language: json +filename: learnjson-vi.json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] +translators: + - ["Thanh Phan", "https://github.com/thanhpd"] +lang: vi-vn +--- + +Do JSON là một ngôn ngữ trao đổi dữ liệu hết sức đơn giản, đây có thể sẽ là bài +đơn giản nhất của Học X trong Y phút (Learn X in Y Minutes) từ trước tới nay. + +JSON ở dạng thuần túy nhất không có chú thích cho câu lệnh (comment) nào, nhưng +hầu hết các trình phân tích cú pháp (parser) đều chấp nhận chú thích theo phong +cách của ngôn ngữ C (`//`, `/* */`). Một số trình phân tích cú pháp còn chấp +nhận dấu phẩy cuối cùng (vd: một dấu phẩy sau phần tử cuối cùng của một mảng +hoặc sau thuộc tính cuối cùng của một object), nhưng những trường hợp này nên +tránh để có sự tương thích tốt hơn. + +Để phục vụ cho mục đích bài học này, tất cả cú pháp JSON ở đây sẽ đều là 100% hợp lệ. +May mắn thay, chúng cũng tự trình bày cho chính mình mà không cần thêm giải thích. + +Các kiểu dữ liệu được JSON hỗ trợ bao gồm: số (*numbers*), chuỗi kí tự +(*string*), toán tử đúng/sai (*boolean*), mảng (*array*), *object* và *null*. +Các trình duyệt hỗ trợ bao gồm: Mozilla Firefox phiên bản 3.5 trở lên, +Internet Explorer 8 trở lên, Google Chrome, Opera 10 trở lên, Safari 4 trở lên. +Kiểu tệp JSON có dạng ".json". Kiểu MIME (Multipurpose Internet Mail Extensions) +cho JSON là "application/json". Điểm yếu của JSON đó là thiếu các định dạng cho +kiểu dữ liệu cũng như quy chuẩn cú pháp chặt chẽ sử dụng DTD. + +```json +{ + "khóa": "dữ liệu", + + "các khóa": "phải luôn được đặt trong dấu ngoặc kép", + "số": 0, + "chuỗi kí tự": "Xin chàø. Tất cả kí tự unicode đều được chấp nhận, sử dụng với dạng \"kí tự\"." + "có đúng không?": true, + "không có gì": null, + + "số rất lớn": 1.2e+100, + + "objects": { + "chú thích": "Hầu hết các cấu trúc dữ liệu bạn sẽ dùng sẽ sử dụng object.", + + "mảng": [0, 1, 2, 3, "Mảng có thể chứa bất kì thứ gì bên trong.", 5], + + "một object khác": { + "chú thích": "Những thứ này có thể lồng vào nhau, rất tiện." + } + }, + + "ngớ ngẩn": [ + { + "nguồn cung cấp kali": ["chuối"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "phong cách khác": { + "chú thích": "kiểm tra cái này xem!" + , "vị trí dấu phẩy": "không quan trọng - chỉ cần nó ở trước khóa tiếp theo là được" + , "chú thích khác": "tiện phải không" + }, + + "nó rất ngắn": "Và bạn đã xong rồi đấy. Bạn đã biết tất cả những thứ mà JSON có thể cung cấp." +} +``` diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index c97bb560..38e418e9 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```objective_c
+```objective-c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/vi-vn/ruby-vi.html.markdown b/vi-vn/ruby-vi.html.markdown new file mode 100644 index 00000000..73382100 --- /dev/null +++ b/vi-vn/ruby-vi.html.markdown @@ -0,0 +1,549 @@ +--- +language: ruby +filename: learnruby.rb +contributors: + - ["David Underwood", "http://theflyingdeveloper.com"] + - ["Joel Walden", "http://joelwalden.net"] + - ["Luke Holder", "http://twitter.com/lukeholder"] + - ["Tristan Hume", "http://thume.ca/"] + - ["Nick LaMuro", "https://github.com/NickLaMuro"] + - ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"] + - ["Ariel Krakowski", "http://www.learneroo.com"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Levi Bostian", "https://github.com/levibostian"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Vinh Nguyen", "http://rubydaily.net"] +lang: vi-vn + +--- + +```ruby +# Đây là một comment + +=begin +Đây là một comment nhiều dòng +Không ai dùng cách này +Bạn không nên dùng +=end + +# Đầu tiên và quan trọng nhất: Mọi thứ là đối tượng. + +# Các con số là các đối tượng. + +3.class #=> Fixnum + +3.to_s #=> "3" + + +# Một vài bài toán số học căn bản +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 +2**5 #=> 32 + +# Số học vừa là các cú pháp thân thiện cho việc gọi +# một hàm trên một đối tượng +1.+(3) #=> 4 +10.* 5 #=> 50 + +# Các giá trị đặc biệt là các đối tượng +nil # Ở đây không có gì để xem +true # luôn đúng +false # luôn sai + +nil.class #=> Lớp Nil +true.class #=> Lớp True +false.class #=> Lớp False + +# So sánh bằng +1 == 1 #=> true +2 == 1 #=> false + +# So sánh không bằng +1 != 1 #=> false +2 != 1 #=> true + +# Ngoài chính false, thì nil là một giá trị khác của false + +!nil #=> true +!false #=> true +!0 #=> false + +# Các loại so sánh khác +1 < 10 #=> true +1 > 10 #=> false +2 <= 2 #=> true +2 >= 2 #=> true + +# Các toán tử logic +true && false #=> false +true || false #=> true +!true #=> false + + +# Có các cách khác của các toán tử logic với mức thấp hơn +# Chúng được sử dụng như các cấu trúc điều khiển luồng nối các mệnh đề +# với nhau cho đến khi một trong số chúng trả về đúng hoặc sai. + +# `do_something_else` chỉ được gọi nếu như hàm `do_something` thành công. +do_something() and do_something_else() +# `log_error` chỉ được gọi nếu hàm `do_something` không thành công. +do_something() or log_error() + + +# Các chuỗi là các đối tượng + +'I am a string'.class #=> String +"I am a string too".class #=> String + +placeholder = 'use string interpolation' +"I can #{placeholder} when using double quoted strings" +#=> "I can use string interpolation when using double quoted strings" + +# Nên đưa các chuỗi vào trong dấu nháy đơn +# Ngoài ra dấu nháy kép được sử dụng trong tính toán. + +# Nối các chuỗi, nhưng không nối với các số. +'hello ' + 'world' #=> "hello world" +'hello ' + 3 #=> TypeError: can't convert Fixnum into String +'hello ' + 3.to_s #=> "hello 3" + +# Xuất ra ngoài màn hình +puts "I'm printing!" + +# Các biến +x = 25 #=> 25 +x #=> 25 + +# Chú ý về việc gán các giá trị được trả về vào biến. +# Điều này có nghĩa là bạn có thể gán nhiều biến. + +x = y = 10 #=> 10 +x #=> 10 +y #=> 10 + +# Theo quy ước, dùng snake_case cho các tên của biến. +snake_case = true + +# Dùng để mô tả tên các biến +path_to_project_root = '/good/name/' +path = '/bad/name/' + +# Ký tự (là các đối tượng) +# Các ký tự là bất biến, như các biến hằng số chỉ đến các số nguyên. +# Chúng thường xuyên được sử dụng thay cho các chuỗi để chuyển đổi các giá +# trị hiệu quả. + +:pending.class #=> Symbol + +status = :pending + +status == :pending #=> true + +status == 'pending' #=> false + +status == :approved #=> false + +# Các mảng + +# Đây là một mảng +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] + +# Các mảng có thể chứa nhiều phần tử khác nhau + +[1, 'hello', false] #=> [1, "hello", false] + +# Có thể truy cập các giá trị của mảng thông qua các chỉ mục +array[0] #=> 1 +array[12] #=> nil + +# Giống như số học, sử dụng [biến] là một cú pháp thông dụng +array.[] 0 #=> 1 +array.[] 12 #=> nil + +# Lấy phần tử cuối cùng +array[-1] #=> 5 + +# Bắt đầu từ chỉ mục và số phần tử cần lấy +array[2, 3] #=> [3, 4, 5] + +# Đảo ngược một mảng +a=[1,2,3] +a.reverse! #=> [3,2,1] + +# Lấy một khoảng +array[1..3] #=> [2, 3, 4] + +# Thêm phần tử vào mảng bằng cách này +array << 6 #=> [1, 2, 3, 4, 5, 6] +# Hoặc cách này +array.push(6) #=> [1, 2, 3, 4, 5, 6] + +# Kiểm tra phần tử có tồn tại trong mảng +array.include?(1) #=> true + +# Băm là phần chính của Ruby với các cặp khoá/giá trị +# Băm được biểu thị bằng dấu ngoặc nhọn: +hash = { 'color' => 'green', 'number' => 5 } + +hash.keys #=> ['color', 'number'] + +# Băm có thể được truy cập nhanh chóng thông qua khoá +hash['color'] #=> 'green' +hash['number'] #=> 5 + +# Khoá không tồn tại sẽ trả về nil +hash['nothing here'] #=> nil + +# Kể từ Ruby bản 1.9, đây là một cú pháp đặc biệt, sử dụng symbol như khoá + +new_hash = { defcon: 3, action: true } + +new_hash.keys #=> [:defcon, :action] + +# Kiểm tra khoá hoặc giá trị có tồn tại hay không +new_hash.has_key?(:defcon) #=> true +new_hash.has_value?(3) #=> true + +# Mẹo: Cả Mảng và Băm đều là Enumberable +# Chúng cùng chia sẻ rất nhiều phương thức hữu ích như each, map, count... + +# Cấu trúc điều khiển + +if true + 'if statement' +elsif false + 'else if, optional' +else + 'else, also optional' +end + +for counter in 1..5 + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# TUY NHIÊN, không ai sử dụng vòng lặp for. +# Thay vào đó, ban nên dùng phương thức "each" và truyền vào đó một khối. +# Một khối là một loạt các mã mà bạn có thể truyền +# cho một phương thức giống như each. +# Nó tương tự với lambda, các hàm ẩn danh hoặc closures trong các ngôn ngữ +# lập trình khác. +# +# Phương thức "each" cho một khoản sẽ chạy qua từng phần tử của khoảng đó. +# Khối được truyền vào là một số đếm như là tham số. +# Gọi một method "each" với một khối sẽ trông như thế này: + +(1..5).each do |counter| + puts "iteration #{counter}" +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +# Bạn cũng có thể bao khối trong các dấu ngoặc nhọn. +(1..5).each { |counter| puts "iteration #{counter}" } + +# Các nội dung của cấu trúc dữ liệu cũng có thể được lặp bằng each. +array.each do |element| + puts "#{element} is part of the array" +end +hash.each do |key, value| + puts "#{key} is #{value}" +end + +counter = 1 +while counter <= 5 do + puts "iteration #{counter}" + counter += 1 +end +#=> iteration 1 +#=> iteration 2 +#=> iteration 3 +#=> iteration 4 +#=> iteration 5 + +grade = 'B' + +case grade +when 'A' + puts 'Way to go kiddo' +when 'B' + puts 'Better luck next time' +when 'C' + puts 'You can do better' +when 'D' + puts 'Scraping through' +when 'F' + puts 'You failed!' +else + puts 'Alternative grading system, eh?' +end +#=> "Better luck next time" + +# Cases cũng được dùng cho các dãy +grade = 82 +case grade +when 90..100 + puts 'Hooray!' +when 80...90 + puts 'OK job' +else + puts 'You failed!' +end +#=> "OK job" + +# Xử lý ngoại lệ: +begin + # Code ở đây có thể sẽ đưa ra một ngoại lệ. + raise NoMemoryError, 'You ran out of memory.' +rescue NoMemoryError => exception_variable + puts 'NoMemoryError was raised', exception_variable +rescue RuntimeError => other_exception_variable + puts 'RuntimeError was raised now' +else + puts 'This runs if no exceptions were thrown at all' +ensure + puts 'This code always runs no matter what' +end + +# Hàm + +def double(x) + x * 2 +end + +# Hàm (và tất cả các khối) được mặc định giá trị trả về ở mệnh đề cuối. +double(2) #=> 4 + +# Dấu ngoặc là một tuỳ chọn cho một kết quả rõ ràng. +double 3 #=> 6 + +double double 3 #=> 12 + +def sum(x, y) + x + y +end + +# Các đối số được chia cắt bởi dấu phẩy. +sum 3, 4 #=> 7 + +sum sum(3, 4), 5 #=> 12 + +# yield +# Tất cả các hàm có thể có một tham số tuỳ chọn. +# Nó có thể được gọi với từ khóa "yield". +def surround + puts '{' + yield + puts '}' +end + +surround { puts 'hello world' } + +# { +# hello world +# } + + +# Bạn có thể truyền một khối đến một hàm +# Dấu "&" được đánh dấu đến một khối +def guests(&block) + block.call 'some_argument' +end + +# Bạn có thể truyền một danh sách các tham số, nó sẽ được chuyển thành mảng. +# Thông qua việc sử dụng dấu *. +def guests(*array) + array.each { |guest| puts guest } +end + +# Định nghĩ một lớp thông qua từ khoá class. +class Human + + # Một biến class. Nó được chia sẽ cho tất cả các instance của lớp này. + @@species = 'H. sapiens' + + # Các khởi tạo căn bản + def initialize(name, age = 0) + # Gán đối số đến biến instance "name" + @name = name + # Nếu không có age, sẽ lấy giá trị mặc định trong danh sách đối số. + @age = age + end + + # Hàm nhập giá trị căn bản + def name=(name) + @name = name + end + + # Hàm lấy giá trị căn bản + def name + @name + end + + # Các hàm trên có thể được gọn lại bằng cách dùng hàm attr_accessor + attr_accessor :name + + # Các hàm nhận/lấy cũng có thể được tạo riêng như sau: + attr_reader :name + attr_writer :name + + # Một hàm lớp dùng self để phân biệt với hàm instance. + # Nó chỉ có thể được gọi trên lớp. + def self.say(msg) + puts msg + end + + def species + @@species + end +end + + +# Khởi tạo một lớp +jim = Human.new('Jim Halpert') + +dwight = Human.new('Dwight K. Schrute') + +# Hãy gọi một cặp các hàm. +jim.species #=> "H. sapiens" +jim.name #=> "Jim Halpert" +jim.name = "Jim Halpert II" #=> "Jim Halpert II" +jim.name #=> "Jim Halpert II" +dwight.species #=> "H. sapiens" +dwight.name #=> "Dwight K. Schrute" + +# Gọi một hàm lớp +Human.say('Hi') #=> "Hi" + +# Phạm vi của biến được định nghĩa bởi cách chúng ta đặt tên cho chúng. +# Các biến bắt đầu với dấu $ là biến toàn cục. +$var = "I'm a global var" +defined? $var #=> "global-variable" + +# Các biến bắt đầu với dấu @ là biến phạm vi. +@var = "I'm an instance var" +defined? @var #=> "instance-variable" + +# Các biến bắt đầu với dấu @@ có pham vi là trong một lớp. +@@var = "I'm a class var" +defined? @@var #=> "class variable" + +# Các biến bắt đầu với ký tự viết hoa là biến hằng. +Var = "I'm a constant" +defined? Var #=> "constant" + +# Lớp cũng là một đối tượng trong Ruby. Bởi vậy lớp có các biến instance. +# Biến lớp được chia sẽ trong lớp và các lớp kế thừa nó. + +# Lớp cơ sở +class Human + @@foo = 0 + + def self.foo + @@foo + end + + def self.foo=(value) + @@foo = value + end +end + +# Lớp kế thừa +class Worker < Human +end + +Human.foo # 0 +Worker.foo # 0 + +Human.foo = 2 # 2 +Worker.foo # 2 + +# Các biến lớp instance không được chia sẽ trong lớp kế thừa. + +class Human + @bar = 0 + + def self.bar + @bar + end + + def self.bar=(value) + @bar = value + end +end + +class Doctor < Human +end + +Human.bar # 0 +Doctor.bar # nil + +module ModuleExample + def foo + 'foo' + end +end + +# Include một module sẽ đưa các hàm của module thành instances của lớp. +# Extend một module sẽ đưa các hàm của module thành các biến của lớp. + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Hàm hồi quy được thực hiện khi include và extend một module. + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' +``` + +## Các nguồn tham khảo thêm. + +- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges. +- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/) +- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/) +- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online. +- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide. diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index fbfa500d..0371e6f6 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -9,15 +9,15 @@ filename: learnvisualbasic.vb Module Module1 Sub Main() - ' A Quick Overview of Visual Basic Console Applications before we dive - ' in to the deep end. - ' Apostrophe starts comments. - ' To Navigate this tutorial within the Visual Basic Complier, I've put - ' together a navigation system. - ' This navigation system is explained however as we go deeper into this - ' tutorial, you'll understand what it all means. + 'A Quick Overview of Visual Basic Console Applications before we dive + 'in to the deep end. + 'Apostrophe starts comments. + 'To Navigate this tutorial within the Visual Basic Complier, I've put + 'together a navigation system. + 'This navigation system is explained however as we go deeper into this + 'tutorial, you'll understand what it all means. Console.Title = ("Learn X in Y Minutes") - Console.WriteLine("NAVIGATION") 'Display + Console.WriteLine("NAVIGATION") 'Display Console.WriteLine("") Console.ForegroundColor = ConsoleColor.Green Console.WriteLine("1. Hello World Output") @@ -32,6 +32,9 @@ Module Module1 Console.WriteLine("50. About") Console.WriteLine("Please Choose A Number From The Above List") Dim selection As String = Console.ReadLine + 'The "Case" in the Select statement is optional. + 'For example, "Select selection" instead of "Select Case selection" + 'will also work. Select Case selection Case "1" 'HelloWorld Output Console.Clear() 'Clears the application and opens the private sub @@ -39,13 +42,13 @@ Module Module1 Case "2" 'Hello Input Console.Clear() HelloWorldInput() - Case "3" 'Calculating Whole Numbers + Case "3" 'Calculating Whole Numbers Console.Clear() CalculatingWholeNumbers() - Case "4" 'Calculting Decimal Numbers + Case "4" 'Calculating Decimal Numbers Console.Clear() CalculatingDecimalNumbers() - Case "5" 'Working Calcculator + Case "5" 'Working Calculator Console.Clear() WorkingCalculator() Case "6" 'Using Do While Loops @@ -74,10 +77,10 @@ Module Module1 'One - I'm using numbers to help with the above navigation when I come back 'later to build it. - 'We use private subs to seperate different sections of the program. + 'We use private subs to separate different sections of the program. Private Sub HelloWorldOutput() 'Title of Console Application - Console.Title = "Hello World Ouput | Learn X in Y Minutes" + Console.Title = "Hello World Output | Learn X in Y Minutes" 'Use Console.Write("") or Console.WriteLine("") to print outputs. 'Followed by Console.Read() alternatively Console.Readline() 'Console.ReadLine() prints the output to the console. @@ -88,18 +91,18 @@ Module Module1 'Two Private Sub HelloWorldInput() Console.Title = "Hello World YourName | Learn X in Y Minutes" - ' Variables - ' Data entered by a user needs to be stored. - ' Variables also start with a Dim and end with an As VariableType. + 'Variables + 'Data entered by a user needs to be stored. + 'Variables also start with a Dim and end with an As VariableType. - ' In this tutorial, we want to know what your name, and make the program - ' respond to what is said. + 'In this tutorial, we want to know what your name, and make the program + 'respond to what is said. Dim username As String 'We use string as string is a text based variable. Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. username = Console.ReadLine() 'Stores the users name. Console.WriteLine("Hello " + username) 'Output is Hello 'Their name' - Console.ReadLine() 'Outsputs the above. + Console.ReadLine() 'Outputs the above. 'The above will ask you a question followed by printing your answer. 'Other variables include Integer and we use Integer for whole numbers. End Sub @@ -107,7 +110,7 @@ Module Module1 'Three Private Sub CalculatingWholeNumbers() Console.Title = "Calculating Whole Numbers | Learn X in Y Minutes" - Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104 ect + Console.Write("First number: ") 'Enter a whole number, 1, 2, 50, 104, etc Dim a As Integer = Console.ReadLine() Console.Write("Second number: ") 'Enter second whole number. Dim b As Integer = Console.ReadLine() @@ -123,10 +126,10 @@ Module Module1 'Of course we would like to be able to add up decimals. 'Therefore we could change the above from Integer to Double. - 'Enter a whole number, 1.2, 2.4, 50.1, 104.9 ect + 'Enter a floating-point number, 1.2, 2.4, 50.1, 104.9, etc Console.Write("First number: ") Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. + Console.Write("Second number: ") 'Enter second floating-point number. Dim b As Double = Console.ReadLine Dim c As Double = a + b Console.WriteLine(c) @@ -142,15 +145,15 @@ Module Module1 'Copy and paste the above again. Console.Write("First number: ") Dim a As Double = Console.ReadLine - Console.Write("Second number: ") 'Enter second whole number. - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b + Console.Write("Second number: ") 'Enter second floating-point number. + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Dim d As Double = a * b + Dim e As Double = a - b + Dim f As Double = a / b 'By adding the below lines we are able to calculate the subtract, - 'multply as well as divide the a and b values + 'multiply as well as divide the a and b values Console.Write(a.ToString() + " + " + b.ToString()) 'We want to pad the answers to the left by 3 spaces. Console.WriteLine(" = " + c.ToString.PadLeft(3)) @@ -159,7 +162,7 @@ Module Module1 Console.Write(a.ToString() + " - " + b.ToString()) Console.WriteLine(" = " + e.ToString.PadLeft(3)) Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) Console.ReadLine() End Sub @@ -172,15 +175,15 @@ Module Module1 'program more than once. Console.Title = "UsingDoWhileLoops | Learn X in Y Minutes" Dim answer As String 'We use the variable "String" as the answer is text - Do 'We start the program with + Do 'We start the program with Console.Write("First number: ") Dim a As Double = Console.ReadLine Console.Write("Second number: ") - Dim b As Integer = Console.ReadLine - Dim c As Integer = a + b - Dim d As Integer = a * b - Dim e As Integer = a - b - Dim f As Integer = a / b + Dim b As Double = Console.ReadLine + Dim c As Double = a + b + Dim d As Double = a * b + Dim e As Double = a - b + Dim f As Double = a / b Console.Write(a.ToString() + " + " + b.ToString()) Console.WriteLine(" = " + c.ToString.PadLeft(3)) @@ -189,14 +192,14 @@ Module Module1 Console.Write(a.ToString() + " - " + b.ToString()) Console.WriteLine(" = " + e.ToString.PadLeft(3)) Console.Write(a.ToString() + " / " + b.ToString()) - Console.WriteLine(" = " + e.ToString.PadLeft(3)) + Console.WriteLine(" = " + f.ToString.PadLeft(3)) Console.ReadLine() 'Ask the question, does the user wish to continue? Unfortunately it - 'is case sensitive. - Console.Write("Would you like to continue? (yes / no)") + 'is case sensitive. + Console.Write("Would you like to continue? (yes / no) ") 'The program grabs the variable and prints and starts again. answer = Console.ReadLine - 'The command for the variable to work would be in this case "yes" + 'The command for the variable to work would be in this case "yes" Loop While answer = "yes" End Sub @@ -208,8 +211,8 @@ Module Module1 Console.Title = "Using For Loops | Learn X in Y Minutes" 'Declare Variable and what number it should count down in Step -1, - 'Step -2, Step -3 ect. - For i As Integer = 10 To 0 Step -1 + 'Step -2, Step -3, etc. + For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) 'Print the value of the counter Next i 'Calculate new value Console.WriteLine("Start") 'Lets start the program baby!! @@ -219,7 +222,7 @@ Module Module1 'Eight Private Sub ConditionalStatement() Console.Title = "Conditional Statements | Learn X in Y Minutes" - Dim userName As String = Console.ReadLine + Dim userName As String Console.WriteLine("Hello, What is your name? ") 'Ask the user their name. userName = Console.ReadLine() 'Stores the users name. If userName = "Adam" Then @@ -235,36 +238,34 @@ Module Module1 'Nine Private Sub IfElseStatement() - Console.Title = "If / Else Statement | Learn X in Y Minutes" - 'Sometimes its important to consider more than two alternatives. + Console.Title = "If / Else Statement | Learn X in Y Minutes" + 'Sometimes it is important to consider more than two alternatives. 'Sometimes there are a good few others. 'When this is the case, more than one if statement would be required. 'An if statement is great for vending machines. Where the user enters a code. - 'A1, A2, A3, ect to select an item. - 'All choices can be combined into a single if statement. + 'A1, A2, A3, etc to select an item. + 'All choices can be combined into a single if block. - Dim selection As String = Console.ReadLine 'Value for selection - Console.WriteLine("A1. for 7Up") - Console.WriteLine("A2. for Fanta") - Console.WriteLine("A3. for Dr. Pepper") - Console.WriteLine("A4. for Diet Coke") - Console.ReadLine() - If selection = "A1" Then - Console.WriteLine("7up") - Console.ReadLine() - ElseIf selection = "A2" Then - Console.WriteLine("fanta") - Console.ReadLine() - ElseIf selection = "A3" Then - Console.WriteLine("dr. pepper") - Console.ReadLine() - ElseIf selection = "A4" Then - Console.WriteLine("diet coke") - Console.ReadLine() - Else - Console.WriteLine("Please select a product") - Console.ReadLine() - End If + Dim selection As String 'Declare a variable for selection + Console.WriteLine("Please select a product form our lovely vending machine.") + Console.WriteLine("A1. for 7Up") + Console.WriteLine("A2. for Fanta") + Console.WriteLine("A3. for Dr. Pepper") + Console.WriteLine("A4. for Diet Coke") + + selection = Console.ReadLine() 'Store a selection from the user + If selection = "A1" Then + Console.WriteLine("7up") + ElseIf selection = "A2" Then + Console.WriteLine("fanta") + ElseIf selection = "A3" Then + Console.WriteLine("dr. pepper") + ElseIf selection = "A4" Then + Console.WriteLine("diet coke") + Else + Console.WriteLine("Sorry, I don't have any " + selection) + End If + Console.ReadLine() End Sub @@ -274,8 +275,8 @@ End Module ## References -I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. +I learnt Visual Basic in the console application. It allowed me to understand the principles of computer programming to go on to learn other programming languages easily. -I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more. +I created a more indepth <a href="http://www.vbbootcamp.co.uk/" Title="Visual Basic Tutorial">Visual Basic tutorial</a> for those who would like to learn more. -The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program. +The entire syntax is valid. Copy the and paste in to the Visual Basic compiler and run (F5) the program. diff --git a/whip.html.markdown b/whip.html.markdown index 3faee98a..e7e5e427 100644 --- a/whip.html.markdown +++ b/whip.html.markdown @@ -2,13 +2,14 @@ language: whip contributors: - ["Tenor Biel", "http://github.com/L8D"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] author: Tenor Biel author_url: http://github.com/L8D filename: whip.lisp --- Whip is a LISP-dialect made for scripting and simplified concepts. -It has also borrowed a lot of functions and syntax from Haskell(a non-related language). +It has also borrowed a lot of functions and syntax from Haskell (a non-related language). These docs were written by the creator of the language himself. So is this line. @@ -93,13 +94,13 @@ null ; used to indicate a deliberate non-value undefined ; user to indicate a value that hasn't been set ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Vairbles, Lists, and Dicts +; 2. Variables, Lists, and Dicts ; Variables are declared with the `def` or `let` functions. ; Variables that haven't been set will be `undefined`. (def some_var 5) ; `def` will keep the variable in the global context. -; `let` will only have the variable inside its context, and has a wierder syntax. +; `let` will only have the variable inside its context, and has a weirder syntax. (let ((a_var 5)) (+ a_var 5)) ; => 10 (+ a_var 5) ; = undefined + 5 => undefined @@ -163,7 +164,7 @@ undefined ; user to indicate a value that hasn't been set (my_function 10 10) ; = (+ (+ 10 10) 10) => 30 -; Obiously, all lambdas by definition are anonymous and +; Obviously, all lambdas by definition are anonymous and ; technically always used anonymously. Redundancy. ((lambda (x) x) 10) ; => 10 @@ -171,12 +172,12 @@ undefined ; user to indicate a value that hasn't been set ; Comprehensions ; `range` or `..` generates a list of numbers for -; each number between it's two args. +; each number between its two args. (range 1 5) ; => (1 2 3 4 5) (.. 0 2) ; => (0 1 2) -; `map` applies it's first arg(which should be a lambda/function) -; to each item in the following arg(which should be a list) +; `map` applies its first arg (which should be a lambda/function) +; to each item in the following arg (which should be a list) (map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) ; Reduce @@ -191,7 +192,7 @@ undefined ; user to indicate a value that hasn't been set (slice (.. 1 5) 2) ; => (3 4 5) (\ (.. 0 100) -5) ; => (96 97 98 99 100) -; `append` or `<<` is self expanatory +; `append` or `<<` is self explanatory (append 4 (1 2 3)) ; => (1 2 3 4) (<< "bar" ("foo")) ; => ("foo" "bar") diff --git a/xml.html.markdown b/xml.html.markdown index 94fc93f4..b4b54330 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -3,18 +3,77 @@ language: xml filename: learnxml.xml contributors: - ["João Farias", "https://github.com/JoaoGFarias"] + - ["Rachel Stiyer", "https://github.com/rstiyer"] + - ["Deepanshu Utkarsh", "https://github.com/duci9y"] --- -XML is a markup language designed to store and transport data. +XML is a markup language designed to store and transport data. It is supposed to be both human readable and machine readable. -Unlike HTML, XML does not specifies how to display or to format data, just carry it. +Unlike HTML, XML does not specify how to display or to format data, it just carries it. -* XML Syntax +Distinctions are made between the **content** and the **markup**. In short, content could be anything, markup is defined. + +## Some definitions and introductions + +XML Documents are basically made up of *elements* which can have *attributes* describing them and may contain some textual content or more elements as its children. All XML documents must have a root element, which is the ancestor of all the other elements in the document. + +XML Parsers are designed to be very strict, and will stop parsing malformed documents. Therefore it must be ensured that all XML documents follow the [XML Syntax Rules](http://www.w3schools.com/xml/xml_syntax.asp). ```xml -<!-- Comments in XML are like this --> +<!-- This is a comment. It must not contain two consecutive hyphens (-). --> +<!-- Comments can span + multiple lines --> + +<!-- Elements --> +<!-- An element is a basic XML component. There are two types, empty: --> +<element1 attribute="value" /> <!-- Empty elements do not hold any content --> +<!-- and non-empty: --> +<element2 attribute="value">Content</element2> +<!-- Element names may only contain alphabets and numbers. --> + +<empty /> <!-- An element either consists an empty element tag… --> +<!-- …which does not hold any content and is pure markup. --> + +<notempty> <!-- Or, it consists of a start tag… --> + <!-- …some content… --> +</notempty> <!-- and an end tag. --> + +<!-- Element names are case sensitive. --> +<element /> +<!-- is not the same as --> +<eLEMENT /> + +<!-- Attributes --> +<!-- An attribute is a key-value pair and exists within an element. --> +<element attribute="value" another="anotherValue" many="space-separated list" /> +<!-- An attribute may appear only once in an element. It holds just one value. + Common workarounds to this involve the use of space-separated lists. --> + +<!-- Nesting elements --> +<!-- An element's content may include other elements: --> +<parent> + <child>Text</child> + <emptysibling /> +</parent> +<!-- Standard tree nomenclature is followed. Each element being called a node. + An ancestor a level up is the parent, descendants a level down are children. + Elements within the same parent element are siblings. --> + +<!-- XML preserves whitespace. --> +<child> + Text +</child> +<!-- is not the same as --> +<child>Text</child> +``` +## An XML document + +This is what makes XML versatile. It is human readable too. The following document tells us that it defines a bookstore which sells three books, one of which is Learning XML by Erik T. Ray. All this without having used an XML Parser yet. + +```xml <?xml version="1.0" encoding="UTF-8"?> +<!-- This is called an XML prolog. Optional, but recommended. --> <bookstore> <book category="COOKING"> <title lang="en">Everyday Italian</title> @@ -35,83 +94,49 @@ Unlike HTML, XML does not specifies how to display or to format data, just carry <price>39.95</price> </book> </bookstore> - -<!-- Above is a typical XML file. - It starts with a declaration, informing some metadata (optional). - - XML uses a tree structure. Above, the root node is 'bookstore', which has - three child nodes, all 'books'. Those nodes has more child nodes, and so on... - - Nodes are created using open/close tags, and childs are just nodes between - the open and close tags.--> - - -<!-- XML carries two kind of data: - 1 - Attributes -> That's metadata about a node. - Usually, the XML parser uses this information to store the data properly. - It is characterized by appearing in parenthesis within the opening tag - 2 - Elements -> That's pure data. - That's what the parser will retrieve from the XML file. - Elements appear between the open and close tags, without parenthesis. --> - - -<!-- Below, an element with two attributes --> -<file type="gif" id="4293">computer.gif</file> - - ``` -* Well-Formated Document x Validation - -A XML document is well-formated if it is syntactically correct. -However, it is possible to inject more constraints in the document, -using document definitions, such as DTD and XML Schema. +## Well-formedness and Validation -A XML document which follows a document definition is called valid, -regarding that document. - -With this tool, you can check the XML data outside the application logic. +A XML document is *well-formed* if it is syntactically correct. However, it is possible to add more constraints to the document, using Document Type Definitions (DTDs). A document whose elements are attributes are declared in a DTD and which follows the grammar specified in that DTD is called *valid* with respect to that DTD, in addition to being well-formed. ```xml - -<!-- Below, you can see an simplified version of bookstore document, - with the addition of DTD definition.--> - +<!-- Declaring a DTD externally: --> <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<!DOCTYPE bookstore SYSTEM "Bookstore.dtd"> +<!-- Declares that bookstore is our root element and 'Bookstore.dtd' is the path + to our DTD file. --> <bookstore> <book category="COOKING"> - <title >Everyday Italian</title> + <title lang="en">Everyday Italian</title> + <author>Giada De Laurentiis</author> + <year>2005</year> <price>30.00</price> </book> </bookstore> -<!-- This DTD could be something like:--> - -<!DOCTYPE note -[ +<!-- The DTD file: --> <!ELEMENT bookstore (book+)> -<!ELEMENT book (title,price)> +<!-- The bookstore element may contain one or more child book elements. --> +<!ELEMENT book (title, price)> +<!-- Each book must have a title and a price as its children. --> <!ATTLIST book category CDATA "Literature"> +<!-- A book should have a category attribute. If it doesn't, its default value + will be 'Literature'. --> <!ELEMENT title (#PCDATA)> +<!-- The element title must only contain parsed character data. That is, it may + only contain text which is read by the parser and must not contain children. + Compare with CDATA, or character data. --> <!ELEMENT price (#PCDATA)> ]> - -<!-- The DTD starts with a declaration. - Following, the root node is declared, requiring 1 or more child nodes 'book'. - Each 'book' should contain exactly one 'title' and 'price' and an attribute - called 'category', with "Literature" as its default value. - The 'title' and 'price' nodes contain a parsed character data.--> - <!-- The DTD could be declared inside the XML file itself.--> <?xml version="1.0" encoding="UTF-8"?> -<!DOCTYPE note -[ +<!DOCTYPE bookstore [ <!ELEMENT bookstore (book+)> -<!ELEMENT book (title,price)> +<!ELEMENT book (title, price)> <!ATTLIST book category CDATA "Literature"> <!ELEMENT title (#PCDATA)> <!ELEMENT price (#PCDATA)> @@ -119,8 +144,23 @@ With this tool, you can check the XML data outside the application logic. <bookstore> <book category="COOKING"> - <title >Everyday Italian</title> + <title>Everyday Italian</title> <price>30.00</price> </book> </bookstore> -```
\ No newline at end of file +``` + +## DTD Compatibility and XML Schema Definitions + +Support for DTDs is ubiquitous because they are so old. Unfortunately, modern XML features like namespaces are not supported by DTDs. XML Schema Definitions (XSDs) are meant to replace DTDs for defining XML document grammar. + +## Resources + +* [Validate your XML](http://www.xmlvalidation.com) + +## Further Reading + +* [XML Schema Definitions Tutorial](http://www.w3schools.com/schema/) +* [DTD Tutorial](http://www.w3schools.com/xml/xml_dtd_intro.asp) +* [XML Tutorial](http://www.w3schools.com/xml/default.asp) +* [Using XPath queries to parse XML](http://www.w3schools.com/xml/xml_xpath.asp) diff --git a/yaml.html.markdown b/yaml.html.markdown index 6e3e2c94..62f08fb9 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -3,6 +3,7 @@ language: yaml filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] + - ["Suhas SG", "https://github.com/jargnar"] --- YAML is a data serialisation language designed to be directly writable and @@ -66,14 +67,19 @@ a_nested_map: # Maps don't have to have string keys. 0.25: a float key -# Keys can also be multi-line objects, using ? to indicate the start of a key. +# Keys can also be complex, like multi-line objects +# We use ? followed by a space to indicate the start of a complex key. ? | This is a key that has multiple lines : and this is its value -# YAML also allows collection types in keys, but many programming languages -# will complain. +# YAML also allows mapping between sequences with the complex key syntax +# Some language parsers might complain +# An example +? - Manchester United + - Real Madrid +: [ 2001-01-01, 2002-02-02 ] # Sequences (equivalent to lists or arrays) look like this: a_sequence: @@ -101,12 +107,31 @@ json_seq: [3, 2, 1, "takeoff"] anchored_content: &anchor_name This string will appear as the value of two keys. other_anchor: *anchor_name +# Anchors can be used to duplicate/inherit properties +base: &base + name: Everyone has same name + +foo: &foo + <<: *base + age: 10 + +bar: &bar + <<: *base + age: 20 + +# foo and bar would also have name: Everyone has same name + # YAML also has tags, which you can use to explicitly declare types. explicit_string: !!str 0.5 # Some parsers implement language specific tags, like this one for Python's # complex number type. python_complex_number: !!python/complex 1+2j +# We can also use yaml complex keys with language specific tags +? !!python/tuple [5, 7] +: Fifty Seven +# Would be {(5, 7): 'Fifty Seven'} in python + #################### # EXTRA YAML TYPES # #################### diff --git a/zfs.html.markdown b/zfs.html.markdown new file mode 100644 index 00000000..74487e35 --- /dev/null +++ b/zfs.html.markdown @@ -0,0 +1,400 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] +filename: LearnZfs.txt +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) +is a rethinking of the storage stack, combining traditional file systems as well as volume +managers into one cohesive tool. ZFS has some specific teminology that sets it appart from +more traditional storage systems, however it has a great set of features with a focus on +usability for systems administrators. + + +## ZFS Concepts + +### Virtual Devices + +A VDEV is similar to a raid device presented by a RAID card, there are several different +types of VDEV's that offer various advantages, including redundancy and speed. In general +VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a +RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. + +Types of VDEV's +* stripe (a single disk, no redundancy) +* mirror (n-way mirrors supported) +* raidz + * raidz1 (1-disk parity, similar to RAID 5) + * raidz2 (2-disk parity, similar to RAID 6) + * raidz3 (3-disk parity, no RAID analog) +* disk +* file (not recommended for production due to another filesystem adding unnecessary layering) + +Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will +increase your IOPS. + +### Storage Pools + +ZFS uses Storage Pools as an abstraction over the lower level storage provider (VDEV), allow +you to separate the user visable file system from the physcal layout. + +### ZFS Dataset + +ZFS datasets are analagous to traditional filesystems but with many more features. They +provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) +snapshots, quota's, compression and deduplication. + + +### Limits + +One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool +can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A +single host can have 2^64 storage pools. The limits are huge. + + +## Commands + +### Storage Pools + +Actions: +* List +* Status +* Destroy +* Get/Set properties + +List zpools + +```bash +# Create a raidz zpool +$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# List ZPools +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# List detailed information about a specific zpool +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Status of zpools + +```bash +# Get status information about zpools +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# Scrubbing a zpool to correct any errors +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Properties of zpools + +```bash + +# Getting properties from the pool properties can be user set or system provided. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Setting a zpool property +$ zpool set comment="Storage of mah stuff" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Storage of mah stuff local +``` + +Remove zpool + +```bash +$ zpool destroy test +``` + + +### Datasets + +Actions: +* Create +* List +* Rename +* Delete +* Get/Set properties + +Create datasets + +```bash +# Create dataset +$ zfs create tank/root/data +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) + +# Create child dataset +$ zfs create tank/root/data/stuff +$ mount | grep data +tank/root/data on /data (zfs, local, nfsv4acls) +tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Create Volume +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +tank/win_vm 4.13G 17.9G 64K - +``` + +List datasets + +```bash +# List all datasets +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# List a specific dataset +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# List snapshots +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Rename datasets + +```bash +$ zfs rename tank/root/home tank/root/old_home +$ zfs rename tank/root/new_home tank/root/home +``` + +Delete dataset + +```bash +# Datasets cannot be deleted if they have any snapshots +zfs destroy tank/root/home +``` + +Get / set properties of a dataset + +```bash +# Get all properties +$ zfs get all zroot/usr/home │157 # Create Volume +NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm +zroot/home type filesystem - │159 $ zfs list zroot/win_vm +zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT +zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - +zroot/home available 94.1G - │162 ``` +zroot/home referenced 11.9G - │163 +zroot/home mounted yes - +... + +# Get property from dataset +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Set property on dataset +$ zfs set compression=gzip-9 mypool/lamb + +# Get a set of properties from all datasets +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Snapshots + +ZFS snapshots are one of the things about zfs that are a really big deal + +* The space they take up is equal to the difference in data between the filesystem and its snapshot +* Creation time is only seconds +* Recovery is as fast as you can write data. +* They are easy to automate. + +Actions: +* Create +* Delete +* Rename +* Access snapshots +* Send / Receive +* Clone + + +Create snapshots + +```bash +# Create a snapshot of a single dataset +zfs snapshot tank/home/sarlalian@now + +# Create a snapshot of a dataset and its children +$ zfs snapshot -r tank/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +tank/home@now 0 - 26K - +tank/home/sarlalian@now 0 - 259M - +tank/home/alice@now 0 - 156M - +tank/home/bob@now 0 - 156M - +... + +Destroy snapshots + +```bash +# How to destroy a snapshot +$ zfs destroy tank/home/sarlalian@now + +# Delete a snapshot on a parent dataset and its children +$ zfs destroy -r tank/home/sarlalian@now + +``` + +Renaming Snapshots + +```bash +# Rename a snapshot +$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today +$ zfs rename tank/home/sarlalian@now today + +# zfs rename -r tank/home@now @yesterday +``` + +Accessing snapshots + +```bash +# CD Into a snapshot directory +$ cd /home/.zfs/snapshot/ +``` + +Sending and Receiving + +```bash +# Backup a snapshot to a file +$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz + +# Send a snapshot to another dataset +$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Send a snapshot to a remote host +$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' + +# Send full dataset with snapshos to new host +$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +``` + +Cloneing Snapshots + +```bash +# Clone a snapshot +$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new + +# Promoting the clone so it is no longer dependent on the snapshot +$ zfs promote tank/home/sarlalian_new +``` + +### Putting it all together + +This following a script utilizing FreeBSD, jails and ZFS to automate +provisioning a clean copy of a mysql staging database from a live replication +slave. + +```bash +#!/bin/sh + +echo "==== Stopping the staging database server ====" +jail -r staging + +echo "==== Cleaning up existing staging server and snapshot ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Quiescing the slave database ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Snapshotting the slave db filesystem as zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Starting the slave database server ====" +jail -c slave + +echo "==== Cloning the slave snapshot to the staging server ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Installing the staging mysql config ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Setting up the staging rc.conf file ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Starting the staging db server ====" +jail -c staging + +echo "==== Make sthe staging database not pull from the master ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Additional Reading + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://wiki.freebsd.org/ZF://wiki.freebsd.org/ZFS) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 6afa659a..d85e5b8f 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -5,7 +5,14 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Darren Lin", "https://github.com/CogBear"] - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] translators: + - ["Jinchang Ye", "https://github.com/Alwayswithme"] - ["Chunyang Xu", "https://github.com/XuChunyang"] filename: LearnBash-cn.sh lang: zh-cn @@ -23,31 +30,45 @@ Bash 是一个为 GNU 计划编写的 Unix shell,是 Linux 和 Mac OS X 下的 # 如你所见,注释以 # 开头,shebang 也是注释。 # 显示 “Hello world!” -echo Hello, world! +echo Hello world! # 每一句指令以换行或分号隔开: echo 'This is the first line'; echo 'This is the second line' # 声明一个变量: -VARIABLE="Some string" +Variable="Some string" # 下面是错误的做法: -VARIABLE = "Some string" -# Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。 +Variable = "Some string" +# Bash 会把 Variable 当做一个指令,由于找不到该指令,因此这里会报错。 +# 也不可以这样: +Variable= 'Some string' +# Bash 会认为 'Some string' 是一条指令,由于找不到该指令,这里再次报错。 +# (这个例子中 'Variable=' 这部分会被当作仅对 'Some string' 起作用的赋值。) # 使用变量: -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' +echo $Variable +echo "$Variable" +echo '$Variable' # 当你赋值 (assign) 、导出 (export),或者以其他方式使用变量时,变量名前不加 $。 # 如果要使用变量的值, 则要加 $。 # 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。 # 在变量内部进行字符串代换 -echo ${VARIABLE/Some/A} -# 会把 VARIABLE 中首次出现的 "some" 替换成 “A”。 +echo ${Variable/Some/A} +# 会把 Variable 中首次出现的 "some" 替换成 “A”。 + +# 变量的截取 +Length=7 +echo ${Variable:0:Length} +# 这样会仅返回变量值的前7个字符 + +# 变量的默认值 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# 对 null (Foo=) 和空串 (Foo="") 起作用; 零(Foo=0)时返回0 +# 注意这仅返回默认值而不是改变变量的值 # 内置变量: # 下面的内置变量很有用 @@ -55,26 +76,37 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments separeted in different variables: $1 $2..." +echo "Scripts arguments separated in different variables: $1 $2..." # 读取输入: echo "What's your name?" -read NAME # 这里不需要声明新变量 -echo Hello, $NAME! +read Name # 这里不需要声明新变量 +echo Hello, $Name! # 通常的 if 结构看起来像这样: # 'man test' 可查看更多的信息 -if [ $NAME -ne $USER ] +if [ $Name -ne $USER ] then - echo "Your name is you username" + echo "Your name isn't your username" else - echo "Your name isn't you username" + echo "Your name is your username" fi # 根据上一个指令执行结果决定是否执行下一个指令 -echo "Always executed" || echo "Only executed if first command fail" +echo "Always executed" || echo "Only executed if first command fails" echo "Always executed" && echo "Only executed if first command does NOT fail" +# 在 if 语句中使用 && 和 || 需要多对方括号 +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + # 表达式的格式如下: echo $(( 10 + 5 )) @@ -88,18 +120,54 @@ ls -l # 列出文件和目录的详细信息 # 用下面的指令列出当前目录下所有的 txt 文件: ls -l | grep "\.txt" +# 重定向输入和输出(标准输入,标准输出,标准错误)。 +# 以 ^EOF$ 作为结束标记从标准输入读取数据并覆盖 hello.py : +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + # 重定向可以到输出,输入和错误输出。 -python2 hello.py < "input.in" -python2 hello.py > "output.out" -python2 hello.py 2> "error.err" +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 # > 会覆盖已存在的文件, >> 会以累加的方式输出文件中。 +python hello.py >> "output.out" 2>> "error.err" + +# 覆盖 output.out , 追加 error.err 并统计行数 +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# 运行指令并打印文件描述符 (比如 /dev/fd/123) +# 具体可查看: man fd +echo <(echo "#helloworld") + +# 以 "#helloworld" 覆盖 output.out: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# 清理临时文件并显示详情(增加 '-i' 选项启用交互模式) +rm -v output.out error.err output-and-error.log # 一个指令可用 $( ) 嵌套在另一个指令内部: # 以下的指令会打印当前目录下的目录和文件总数 echo "There are $(ls | wc -l) items here." +# 反引号 `` 起相同作用,但不允许嵌套 +# 优先使用 $( ). +echo "There are `ls | wc -l` items here." + # Bash 的 case 语句与 Java 和 C++ 中的 switch 语句类似: -case "$VARIABLE" in +case "$Variable" in # 列出需要匹配的字符串 0) echo "There is a zero.";; 1) echo "There is a one.";; @@ -107,11 +175,37 @@ case "$VARIABLE" in esac # 循环遍历给定的参数序列: -# 变量$VARIABLE 的值会被打印 3 次。 -# 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。 -for VARIABLE in `seq 3` +# 变量$Variable 的值会被打印 3 次。 +for Variable in {1..3} +do + echo "$Variable" +done + +# 或传统的 “for循环” : +for ((a=1; a <= 3; a++)) do - echo "$VARIABLE" + echo $a +done + +# 也可以用于文件 +# 用 cat 输出 file1 和 file2 内容 +for Variable in file1 file2 +do + cat "$Variable" +done + +# 或作用于其他命令的输出 +# 对 ls 输出的文件执行 cat 指令。 +for Output in $(ls) +do + cat "$Output" +done + +# while 循环: +while [ true ] +do + echo "loop body here..." + break done # 你也可以使用函数 @@ -132,17 +226,52 @@ bar () } # 调用函数 -foo "My name is" $NAME +foo "My name is" $Name # 有很多有用的指令需要学习: -tail -n 10 file.txt # 打印 file.txt 的最后 10 行 -head -n 10 file.txt +tail -n 10 file.txt # 打印 file.txt 的前 10 行 -sort file.txt +head -n 10 file.txt # 将 file.txt 按行排序 -uniq -d file.txt +sort file.txt # 报告或忽略重复的行,用选项 -d 打印重复的行 -cut -d ',' -f 1 file.txt +uniq -d file.txt # 打印每行中 ',' 之前内容 +cut -d ',' -f 1 file.txt +# 将 file.txt 文件所有 'okay' 替换为 'great', (兼容正则表达式) +sed -i 's/okay/great/g' file.txt +# 将 file.txt 中匹配正则的行打印到标准输出 +# 这里打印以 "foo" 开头, "bar" 结尾的行 +grep "^foo.*bar$" file.txt +# 使用选项 "-c" 统计行数 +grep -c "^foo.*bar$" file.txt +# 如果只是要按字面形式搜索字符串而不是按正则表达式,使用 fgrep (或 grep -F) +fgrep "^foo.*bar$" file.txt + + +# 以 bash 内建的 'help' 指令阅读 Bash 自带文档: +help +help help +help for +help return +help source +help . + +# 用 man 指令阅读相关的 Bash 手册 +apropos bash +man 1 bash +man bash + +# 用 info 指令查阅命令的 info 文档 (info 中按 ? 显示帮助信息) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# 阅读 Bash 的 info 文档: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash ``` diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown new file mode 100644 index 00000000..e1551e2b --- /dev/null +++ b/zh-cn/c++-cn.html.markdown @@ -0,0 +1,572 @@ +---
+language: c++
+filename: learncpp-cn.cpp
+contributors:
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Matt Kline", "https://github.com/mrkline"]
+translators:
+ - ["Arnie97", "https://github.com/Arnie97"]
+lang: zh-cn
+---
+
+C++是一种系统编程语言。用它的发明者,
+[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是:
+
+- 成为“更好的C语言”
+- 支持数据的抽象与封装
+- 支持面向对象编程
+- 支持泛型编程
+
+C++提供了对硬件的紧密控制(正如C语言一样),
+能够编译为机器语言,由处理器直接执行。
+与此同时,它也提供了泛型、异常和类等高层功能。
+虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞——
+功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。
+
+```c++
+////////////////
+// 与C语言的比较
+////////////////
+
+// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处,
+// 例如变量和函数的声明,原生数据类型等等。
+
+// 和C语言一样,在C++中,你的程序会从main()开始执行,
+// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。
+// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。
+// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息)
+int main(int argc, char** argv)
+{
+ // 和C语言一样,命令行参数通过argc和argv传递。
+ // argc代表命令行参数的数量,
+ // 而argv是一个包含“C语言风格字符串”(char *)的数组,
+ // 其中每个字符串代表一个命令行参数的内容,
+ // 首个命令行参数是调用该程序时所使用的名称。
+ // 如果你不关心命令行参数的值,argc和argv可以被忽略。
+ // 此时,你可以用int main()作为函数原型。
+
+ // 退出状态值为0时,表示程序执行成功
+ return 0;
+}
+
+// 然而,C++和C语言也有一些区别:
+
+// 在C++中,字符字面量的大小是一个字节。
+sizeof('c') == 1
+
+// 在C语言中,字符字面量的大小与int相同。
+sizeof('c') == sizeof(10)
+
+
+// C++的函数原型与函数定义是严格匹配的
+void func(); // 这个函数不能接受任何参数
+
+// 而在C语言中
+void func(); // 这个函数能接受任意数量的参数
+
+// 在C++中,用nullptr代替C语言中的NULL
+int* ip = nullptr;
+
+// C++也可以使用C语言的标准头文件,
+// 但是需要加上前缀“c”并去掉末尾的“.h”。
+#include <cstdio>
+
+int main()
+{
+ printf("Hello, world!\n");
+ return 0;
+}
+
+///////////
+// 函数重载
+///////////
+
+// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。
+
+void print(char const* myString)
+{
+ printf("String %s\n", myString);
+}
+
+void print(int myInt)
+{
+ printf("My int is %d", myInt);
+}
+
+int main()
+{
+ print("Hello"); // 解析为 void print(const char*)
+ print(15); // 解析为 void print(int)
+}
+
+///////////////////
+// 函数参数的默认值
+///////////////////
+
+// 你可以为函数的参数指定默认值,
+// 它们将会在调用者没有提供相应参数时被使用。
+
+void doSomethingWithInts(int a = 1, int b = 4)
+{
+ // 对两个参数进行一些操作
+}
+
+int main()
+{
+ doSomethingWithInts(); // a = 1, b = 4
+ doSomethingWithInts(20); // a = 20, b = 4
+ doSomethingWithInts(20, 5); // a = 20, b = 5
+}
+
+// 默认参数必须放在所有的常规参数之后。
+
+void invalidDeclaration(int a = 1, int b) // 这是错误的!
+{
+}
+
+
+///////////
+// 命名空间
+///////////
+
+// 命名空间为变量、函数和其他声明提供了分离的的作用域。
+// 命名空间可以嵌套使用。
+
+namespace First {
+ namespace Nested {
+ void foo()
+ {
+ printf("This is First::Nested::foo\n");
+ }
+ } // 结束嵌套的命名空间Nested
+} // 结束命名空间First
+
+namespace Second {
+ void foo()
+ {
+ printf("This is Second::foo\n")
+ }
+}
+
+void foo()
+{
+ printf("This is global foo\n");
+}
+
+int main()
+{
+ // 如果没有特别指定,就从“Second”中取得所需的内容。
+ using namespace Second;
+
+ foo(); // 显示“This is Second::foo”
+ First::Nested::foo(); // 显示“This is First::Nested::foo”
+ ::foo(); // 显示“This is global foo”
+}
+
+////////////
+// 输入/输出
+////////////
+
+// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。
+// cin、cout、和cerr分别代表
+// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。
+
+#include <iostream> // 引入包含输入/输出流的头文件
+
+using namespace std; // 输入输出流在std命名空间(也就是标准库)中。
+
+int main()
+{
+ int myInt;
+
+ // 在标准输出(终端/显示器)中显示
+ cout << "Enter your favorite number:\n";
+ // 从标准输入(键盘)获得一个值
+ cin >> myInt;
+
+ // cout也提供了格式化功能
+ cout << "Your favorite number is " << myInt << "\n";
+ // 显示“Your favorite number is <myInt>”
+
+ cerr << "Used for error messages";
+}
+
+/////////
+// 字符串
+/////////
+
+// C++中的字符串是对象,它们有很多成员函数
+#include <string>
+
+using namespace std; // 字符串也在std命名空间(标准库)中。
+
+string myString = "Hello";
+string myOtherString = " World";
+
+// + 可以用于连接字符串。
+cout << myString + myOtherString; // "Hello World"
+
+cout << myString + " You"; // "Hello You"
+
+// C++中的字符串是可变的,具有“值语义”。
+myString.append(" Dog");
+cout << myString; // "Hello Dog"
+
+
+/////////////
+// 引用
+/////////////
+
+// 除了支持C语言中的指针类型以外,C++还提供了_引用_。
+// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。
+// 使用引用时的语法与原变量相同:
+// 也就是说,对引用类型进行解引用时,不需要使用*;
+// 赋值时也不需要用&来取地址。
+
+using namespace std;
+
+string foo = "I am foo";
+string bar = "I am bar";
+
+
+string& fooRef = foo; // 建立了一个对foo的引用。
+fooRef += ". Hi!"; // 通过引用来修改foo的值
+cout << fooRef; // "I am foo. Hi!"
+
+// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。
+// 也就是说,在执行这条语句之后,foo == "I am bar"。
+fooRef = bar;
+
+const string& barRef = bar; // 建立指向bar的常量引用。
+// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。
+barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。
+
+///////////////////
+// 类与面向对象编程
+///////////////////
+
+// 有关类的第一个示例
+#include <iostream>
+
+// 声明一个类。
+// 类通常在头文件(.h或.hpp)中声明。
+class Dog {
+ // 成员变量和成员函数默认情况下是私有(private)的。
+ std::string name;
+ int weight;
+
+// 在这个标签之后,所有声明都是公有(public)的,
+// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止
+public:
+
+ // 默认的构造器
+ Dog();
+
+ // 这里是成员函数声明的一个例子。
+ // 可以注意到,我们在此处使用了std::string,而不是using namespace std
+ // 语句using namespace绝不应当出现在头文件当中。
+ void setName(const std::string& dogsName);
+
+ void setWeight(int dogsWeight);
+
+ // 如果一个函数不对对象的状态进行修改,
+ // 应当在声明中加上const。
+ // 这样,你就可以对一个以常量方式引用的对象执行该操作。
+ // 同时可以注意到,当父类的成员函数需要被子类重写时,
+ // 父类中的函数必须被显式声明为_虚函数(virtual)_。
+ // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。
+ virtual void print() const;
+
+ // 函数也可以在class body内部定义。
+ // 这样定义的函数会自动成为内联函数。
+ void bark() const { std::cout << name << " barks!\n" }
+
+ // 除了构造器以外,C++还提供了析构器。
+ // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。
+ // 这使得RAII这样的强大范式(参见下文)成为可能。
+ // 为了衍生出子类来,基类的析构函数必须定义为虚函数。
+ virtual ~Dog();
+
+}; // 在类的定义之后,要加一个分号
+
+// 类的成员函数通常在.cpp文件中实现。
+void Dog::Dog()
+{
+ std::cout << "A dog has been constructed\n";
+}
+
+// 对象(例如字符串)应当以引用的形式传递,
+// 对于不需要修改的对象,最好使用常量引用。
+void Dog::setName(const std::string& dogsName)
+{
+ name = dogsName;
+}
+
+void Dog::setWeight(int dogsWeight)
+{
+ weight = dogsWeight;
+}
+
+// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复
+void Dog::print() const
+{
+ std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
+}
+
+void Dog::~Dog()
+{
+ cout << "Goodbye " << name << "\n";
+}
+
+int main() {
+ Dog myDog; // 此时显示“A dog has been constructed”
+ myDog.setName("Barkley");
+ myDog.setWeight(10);
+ myDog.printDog(); // 显示“Dog is Barkley and weighs 10 kg”
+ return 0;
+} // 显示“Goodbye Barkley”
+
+// 继承:
+
+// 这个类继承了Dog类中的公有(public)和保护(protected)对象
+class OwnedDog : public Dog {
+
+ void setOwner(const std::string& dogsOwner)
+
+ // 重写OwnedDogs类的print方法。
+ // 如果你不熟悉子类多态的话,可以参考这个页面中的概述:
+ // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B
+
+ // override关键字是可选的,它确保你所重写的是基类中的方法。
+ void print() const override;
+
+private:
+ std::string owner;
+};
+
+// 与此同时,在对应的.cpp文件里:
+
+void OwnedDog::setOwner(const std::string& dogsOwner)
+{
+ owner = dogsOwner;
+}
+
+void OwnedDog::print() const
+{
+ Dog::print(); // 调用基类Dog中的print方法
+ // "Dog is <name> and weights <weight>"
+
+ std::cout << "Dog is owned by " << owner << "\n";
+ // "Dog is owned by <owner>"
+}
+
+/////////////////////
+// 初始化与运算符重载
+/////////////////////
+
+// 在C++中,通过定义一些特殊名称的函数,
+// 你可以重载+、-、*、/等运算符的行为。
+// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。
+
+#include <iostream>
+using namespace std;
+
+class Point {
+public:
+ // 可以以这样的方式为成员变量设置默认值。
+ double x = 0;
+ double y = 0;
+
+ // 定义一个默认的构造器。
+ // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。
+ Point() { };
+
+ // 下面使用的语法称为初始化列表,
+ // 这是初始化类中成员变量的正确方式。
+ Point (double a, double b) :
+ x(a),
+ y(b)
+ { /* 除了初始化成员变量外,什么都不做 */ }
+
+ // 重载 + 运算符
+ Point operator+(const Point& rhs) const;
+
+ // 重载 += 运算符
+ Point& operator+=(const Point& rhs);
+
+ // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。
+};
+
+Point Point::operator+(const Point& rhs) const
+{
+ // 创建一个新的点,
+ // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。
+ return Point(x + rhs.x, y + rhs.y);
+}
+
+Point& Point::operator+=(const Point& rhs)
+{
+ x += rhs.x;
+ y += rhs.y;
+ return *this;
+}
+
+int main () {
+ Point up (0,1);
+ Point right (1,0);
+ // 这里使用了Point类型的运算符“+”
+ // 调用up(Point类型)的“+”方法,并以right作为函数的参数
+ Point result = up + right;
+ // 显示“Result is upright (1,1)”
+ cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
+ return 0;
+}
+
+///////////
+// 异常处理
+///////////
+
+// 标准库中提供了一些基本的异常类型
+// (参见http://en.cppreference.com/w/cpp/error/exception)
+// 但是,其他任何类型也可以作为一个异常被拋出
+#include <exception>
+
+// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。
+try {
+ // 不要用 _new_关键字在堆上为异常分配空间。
+ throw std::exception("A problem occurred");
+}
+// 如果拋出的异常是一个对象,可以用常量引用来捕获它
+catch (const std::exception& ex)
+{
+ std::cout << ex.what();
+// 捕获尚未被_catch_处理的所有错误
+} catch (...)
+{
+ std::cout << "Unknown exception caught";
+ throw; // 重新拋出异常
+}
+
+///////
+// RAII
+///////
+
+// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization),
+// 它被视作C++中最强大的编程范式之一。
+// 简单说来,它指的是,用构造函数来获取一个对象的资源,
+// 相应的,借助析构函数来释放对象的资源。
+
+// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况:
+void doSomethingWithAFile(const char* filename)
+{
+ // 首先,让我们假设一切都会顺利进行。
+
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+ fclose(fh); // 关闭文件句柄
+}
+
+// 不幸的是,随着错误处理机制的引入,事情会变得复杂。
+// 假设fopen函数有可能执行失败,
+// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。
+// (虽然异常是C++中处理错误的推荐方式,
+// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。
+// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+ if (fh == nullptr) // 当执行失败是,返回的指针是nullptr
+ return false; // 向调用者汇报错误
+
+ // 假设每个函数会在执行失败时返回false
+ if (!doSomethingWithTheFile(fh)) {
+ fclose(fh); // 关闭文件句柄,避免造成内存泄漏。
+ return false; // 反馈错误
+ }
+ if (!doSomethingElseWithIt(fh)) {
+ fclose(fh); // 关闭文件句柄
+ return false; // 反馈错误
+ }
+
+ fclose(fh); // 关闭文件句柄
+ return true; // 指示函数已成功执行
+}
+
+// C语言的程序员通常会借助goto语句简化上面的代码:
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r");
+ if (fh == nullptr)
+ return false;
+
+ if (!doSomethingWithTheFile(fh))
+ goto failure;
+
+ if (!doSomethingElseWithIt(fh))
+ goto failure;
+
+ fclose(fh); // 关闭文件
+ return true; // 执行成功
+
+failure:
+ fclose(fh);
+ return false; // 反馈错误
+}
+
+// 如果用异常捕获机制来指示错误的话,
+// 代码会变得清晰一些,但是仍然有优化的余地。
+void doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // 以只读模式打开文件
+ if (fh == nullptr)
+ throw std::exception("Could not open the file.");
+
+ try {
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+ }
+ catch (...) {
+ fclose(fh); // 保证出错的时候文件被正确关闭
+ throw; // 之后,重新抛出这个异常
+ }
+
+ fclose(fh); // 关闭文件
+ // 所有工作顺利完成
+}
+
+// 相比之下,使用C++中的文件流类(fstream)时,
+// fstream会利用自己的析构器来关闭文件句柄。
+// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。
+void doSomethingWithAFile(const std::string& filename)
+{
+ // ifstream是输入文件流(input file stream)的简称
+ std::ifstream fh(filename); // 打开一个文件
+
+ // 对文件进行一些操作
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+} // 文件已经被析构器自动关闭
+
+// 与上面几种方式相比,这种方式有着_明显_的优势:
+// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。
+// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。
+// 2. 可以注意到,通过这种方式写出来的代码十分简洁。
+// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。
+// 3. 这种方式的代码具有异常安全性。
+// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。
+
+// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括:
+// - 用unique_ptr和shared_ptr管理的内存
+// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等;
+// 当它们脱离作用域时,析构器会自动释放其中储存的内容。
+// - 用lock_guard和unique_lock实现的互斥
+```
+扩展阅读:
+
+<http://cppreference.com/w/cpp> 提供了最新的语法参考。
+
+可以在 <http://cplusplus.com> 找到一些补充资料。
diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index a3cda5b3..971c1be9 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -232,7 +232,8 @@ on a new line! ""Wow!"", the masses cried"; // 三元表达式 // 简单的 if/else 语句可以写成: // <条件> ? <真> : <假> - string isTrue = (true) ? "True" : "False"; + int toCompare = 17; + string isTrue = toCompare == 17 ? "True" : "False"; // While 循环 int fooWhile = 0; diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 9f6a8c15..49224085 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -239,7 +239,7 @@ func learnConcurrency() { go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) - // 从channel中独处结果并打印。 + // 从channel中读取结果并打印。 // 打印出什么东西是不可预知的。 fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是读操作。 @@ -283,4 +283,4 @@ Go的根源在[Go官方网站](http://golang.org/)。 强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) -学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! +学习Go还要阅读Go[标准库的源代码](http://golang.org/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](http://golang.org/pkg/)中点击函数名,源代码就出来了! diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown new file mode 100644 index 00000000..562a0284 --- /dev/null +++ b/zh-cn/groovy-cn.html.markdown @@ -0,0 +1,420 @@ +--- +language: Groovy +filename: learngroovy-cn.groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +translators: + - ["Todd Gao", "http://github.com/7c00"] +lang: zh-cn +--- + +Groovy - Java平台的动态语言。[了解更多。](http://www.groovy-lang.org/) + +```groovy + +/* + 安装: + + 1) 安装 GVM - http://gvmtool.net/ + 2) 安装 Groovy: gvm install groovy + 3) 启动 groovy 控制台,键入: groovyConsole + +*/ + +// 双斜线开始的是单行注释 +/* +像这样的是多行注释 +*/ + +// Hello World +println "Hello world!" + +/* + 变量: + + 可以给变量赋值,以便稍后使用 +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + 集合和映射 +*/ + +//创建一个空的列表 +def technologies = [] + +/*** 往列表中增加一个元素 ***/ + +// 和Java一样 +technologies.add("Grails") + +// 左移添加,返回该列表 +technologies << "Groovy" + +// 增加多个元素 +technologies.addAll(["Gradle","Griffon"]) + +/*** 从列表中删除元素 ***/ + +// 和Java一样 +technologies.remove("Griffon") + +// 减号也行 +technologies = technologies - 'Grails' + +/*** 遍历列表 ***/ + +// 遍历列表中的元素 +technologies.each { println "Technology: $it"} +technologies.eachWithIndex { it, i -> println "$i: $it"} + +/*** 检查列表内容 ***/ + +//判断列表是否包含某元素,返回boolean +contained = technologies.contains( 'Groovy' ) + +// 或 +contained = 'Groovy' in technologies + +// 检查多个元素 +technologies.containsAll(['Groovy','Grails']) + +/*** 列表排序 ***/ + +// 排序列表(修改原列表) +technologies.sort() + +// 要想不修改原列表,可以这样: +sortedTechnologies = technologies.sort( false ) + +/*** 列表操作 ***/ + +//替换列表元素 +Collections.replaceAll(technologies, 'Gradle', 'gradle') + +//打乱列表 +Collections.shuffle(technologies, new Random()) + +//清空列表 +technologies.clear() + +//创建空的映射 +def devMap = [:] + +//增加值 +devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +devMap.put('lastName','Perez') + +//遍历映射元素 +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//判断映射是否包含某键 +assert devMap.containsKey('name') + +//判断映射是否包含某值 +assert devMap.containsValue('Roberto') + +//取得映射所有的键 +println devMap.keySet() + +//取得映射所有的值 +println devMap.values() + +/* + Groovy Beans + + GroovyBeans 是 JavaBeans,但使用了更简单的语法 + + Groovy 被编译为字节码时,遵循下列规则。 + + * 如果一个名字声明时带有访问修饰符(public, private, 或者 protected), + 则会生成一个字段(field)。 + + * 名字声明时没有访问修饰符,则会生成一个带有public getter和setter的 + private字段,即属性(property)。 + + * 如果一个属性声明为final,则会创建一个final的private字段,但不会生成setter。 + + * 可以声明一个属性的同时定义自己的getter和setter。 + + * 可以声明具有相同名字的属性和字段,该属性会使用该字段。 + + * 如果要定义private或protected属性,必须提供声明为private或protected的getter + 和setter。 + + * 如果使用显式或隐式的 this(例如 this.foo, 或者 foo)访问类的在编译时定义的属性, + Groovy会直接访问对应字段,而不是使用getter或者setter + + * 如果使用显式或隐式的 foo 访问一个不存在的属性,Groovy会通过元类(meta class) + 访问它,这可能导致运行时错误。 + +*/ + +class Foo { + // 只读属性 + final String name = "Roberto" + + // 只读属性,有public getter和protected setter + String language + protected void setLanguage(String language) { this.language = language } + + // 动态类型属性 + def lastName +} + +/* + 逻辑分支和循环 +*/ + +//Groovy支持常见的if - else语法 +def x = 3 + +if(x==1) { + println "One" +} else if(x==2) { + println "Two" +} else { + println "X greater than Two" +} + +//Groovy也支持三元运算符 +def y = 10 +def x = (y > 1) ? "worked" : "failed" +assert x == "worked" + +//for循环 +//使用区间(range)遍历 +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//遍历列表 +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//遍历数组 +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//遍历映射 +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + 运算符 + + 在Groovy中以下常用运算符支持重载: + http://www.groovy-lang.org/operators.html#Operator-Overloading + + 实用的groovy运算符 +*/ +//展开(spread)运算符:对聚合对象的所有元素施加操作 +def technologies = ['Groovy','Grails','Gradle'] +technologies*.toUpperCase() // 相当于 technologies.collect { it?.toUpperCase() } + +//安全导航(safe navigation)运算符:用来避免NullPointerException +def user = User.get(1) +def username = user?.username + + +/* + 闭包 + Groovy闭包好比代码块或者方法指针,它是一段代码定义,可以以后执行。 + + 更多信息见:http://www.groovy-lang.org/closures.html +*/ +//例子: +def clos = { println "Hello World!" } + +println "Executing the Closure:" +clos() + +//传参数给闭包 +def sum = { a, b -> println a+b } +sum(2,4) + +//闭包可以引用参数列表以外的变量 +def x = 5 +def multiplyBy = { num -> num * x } +println multiplyBy(10) + +// 只有一个参数的闭包可以省略参数的定义 +def clos = { print it } +clos( "hi" ) + +/* + Groovy可以记忆闭包结果 [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // 模拟费时操作 + a + b +} + +mem = cl.memoize() + +def callClosure(a, b) { + def start = System.currentTimeMillis() + mem(a, b) + println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs." +} + +callClosure(1, 2) +callClosure(1, 2) +callClosure(2, 3) +callClosure(2, 3) +callClosure(3, 4) +callClosure(3, 4) +callClosure(1, 2) +callClosure(2, 3) +callClosure(3, 4) + +/* + Expando + + Expando类是一种动态bean类,可以给它的实例添加属性和添加闭包作为方法 + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def user = new Expando(name:"Roberto") + assert 'Roberto' == user.name + + user.lastName = 'Pérez' + assert 'Pérez' == user.lastName + + user.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println user.showInfo(sw) + + +/* + 元编程(MOP) +*/ + +//使用ExpandoMetaClass增加行为 +String.metaClass.testAdd = { + println "we added this" +} + +String x = "test" +x?.testAdd() + +//拦截方法调用 +class Test implements GroovyInterceptable { + def sum(Integer x, Integer y) { x + y } + + def invokeMethod(String name, args) { + System.out.println "Invoke method $name with args: $args" + } +} + +def test = new Test() +test?.sum(2,3) +test?.multiply(2,3) + +//Groovy支持propertyMissing,来处理属性解析尝试 +class Foo { + def propertyMissing(String name) { name } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + 类型检查和静态编译 + Groovy天生是并将永远是一门动态语言,但也支持类型检查和静态编译 + + 更多: http://www.infoq.com/articles/new-groovy-20 +*/ +//类型检查 +import groovy.transform.TypeChecked + +void testMethod() {} + +@TypeChecked +void test() { + testMeethod() + + def name = "Roberto" + + println naameee + +} + +//另一例子 +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numbers = [1,2,3,4] + + Date date = numbers[1] + + return "Test" + +} + +//静态编译例子 +import groovy.transform.CompileStatic + +@CompileStatic +int sum(int x, int y) { + x + y +} + +assert sum(2,5) == 7 + + +``` + +## 进阶资源 + +[Groovy文档](http://www.groovy-lang.org/documentation.html) + +[Groovy web console](http://groovyconsole.appspot.com/) + +加入[Groovy用户组](http://www.groovy-lang.org/usergroups.html) + +## 图书 + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + + + diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index cb7ccdee..b0b1183f 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -5,24 +5,25 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Peiyong Lin", ""] + - ["chad luo", "http://yuki.rocks"] lang: zh-cn --- -Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads 及其类型系统而出名,但是我回归到它本身因为。Haskell 使得编程对于我而言是一种真正的快乐。 +Haskell 是一门实用的函数式编程语言,因其 Monads 与类型系统而闻名。而我使用它则是因为它异常优雅。用 Haskell 编程令我感到非常快乐。 ```haskell --- 单行注释以两个破折号开头 +-- 单行注释以两个减号开头 {- 多行注释像这样 - 被一个闭合的块包围 + 被一个闭合的块包围 -} ---------------------------------------------------- -- 1. 简单的数据类型和操作符 ---------------------------------------------------- --- 你有数字 +-- 数字 3 -- 3 --- 数学计算就像你所期待的那样 +-- 数学计算 1 + 1 -- 2 8 - 1 -- 7 10 * 2 -- 20 @@ -34,7 +35,7 @@ Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads -- 整除 35 `div` 4 -- 8 --- 布尔值也简单 +-- 布尔值 True False @@ -45,21 +46,22 @@ not False -- True 1 /= 1 -- False 1 < 10 -- True --- 在上述的例子中,`not` 是一个接受一个值的函数。 --- Haskell 不需要括号来调用函数。。。所有的参数 --- 都只是在函数名之后列出来。因此,通常的函数调用模式是: --- func arg1 arg2 arg3... --- 查看关于函数的章节以获得如何写你自己的函数的相关信息。 +-- 在上面的例子中,`not` 是一个接受一个参数的函数。 +-- Haskell 不需要括号来调用函数,所有的参数都只是在函数名之后列出来 +-- 因此,通常的函数调用模式是: +-- func arg1 arg2 arg3... +-- 你可以查看函数部分了解如何自行编写。 -- 字符串和字符 -"This is a string." +"This is a string." -- 字符串 'a' -- 字符 '对于字符串你不能使用单引号。' -- 错误! --- 连结字符串 +-- 连接字符串 "Hello " ++ "world!" -- "Hello world!" -- 一个字符串是一系列字符 +['H', 'e', 'l', 'l', 'o'] -- "Hello" "This is a string" !! 0 -- 'T' @@ -67,162 +69,164 @@ not False -- True -- 列表和元组 ---------------------------------------------------- --- 一个列表中的每一个元素都必须是相同的类型 --- 下面两个列表一样 +-- 一个列表中的每一个元素都必须是相同的类型。 +-- 下面两个列表等价 [1, 2, 3, 4, 5] [1..5] --- 在 Haskell 你可以拥有含有无限元素的列表 -[1..] -- 一个含有所有自然数的列表 +-- 区间也可以这样 +['A'..'F'] -- "ABCDEF" --- 因为 Haskell 有“懒惰计算”,所以无限元素的列表可以正常运作。这意味着 --- Haskell 可以只在它需要的时候计算。所以你可以请求 --- 列表中的第1000个元素,Haskell 会返回给你 +-- 你可以在区间中指定步进 +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- 这样不行,因为 Haskell 默认递增 +[5,4..1] -- [5, 4, 3, 2, 1] -[1..] !! 999 -- 1000 +-- 列表下标 +[0..] !! 5 -- 5 --- Haskell 计算了列表中 1 - 1000 个元素。。。但是 --- 这个无限元素的列表中剩下的元素还不存在! Haskell 不会 --- 真正地计算它们知道它需要。 +-- 在 Haskell 你可以使用无限列表 +[1..] -- 一个含有所有自然数的列表 -<FS>- 连接两个列表 +-- 无限列表的原理是,Haskell 有“惰性求值”。 +-- 这意味着 Haskell 只在需要时才会计算。 +-- 所以当你获取列表的第 1000 项元素时,Haskell 会返回给你: +[1..] !! 999 -- 1000 +-- Haskell 计算了列表中第 1 至 1000 项元素,但这个无限列表中剩下的元素还不存在。 +-- Haskell 只有在需要时才会计算它们。 + +-- 连接两个列表 [1..5] ++ [6..10] -- 往列表头增加元素 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- 列表中的下标 -[0..] !! 5 -- 5 - --- 更多列表操作 +-- 其它列表操作 head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] last [1..5] -- 5 --- 列表推导 +-- 列表推导 (list comprehension) [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -- 附带条件 [x*2 | x <-[1..5], x*2 > 4] -- [6, 8, 10] --- 元组中的每一个元素可以是不同类型的,但是一个元组 --- 的长度是固定的 +-- 元组中的每一个元素可以是不同类型,但是一个元组的长度是固定的 -- 一个元组 ("haskell", 1) --- 获取元组中的元素 +-- 获取元组中的元素(例如,一个含有 2 个元素的元祖) fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 ---------------------------------------------------- -- 3. 函数 ---------------------------------------------------- + -- 一个接受两个变量的简单函数 add a b = a + b --- 注意,如果你使用 ghci (Hakell 解释器) --- 你将需要使用 `let`,也就是 +-- 注意,如果你使用 ghci (Hakell 解释器),你需要使用 `let`,也就是 -- let add a b = a + b --- 使用函数 +-- 调用函数 add 1 2 -- 3 --- 你也可以把函数放置在两个参数之间 --- 附带倒引号: +-- 你也可以使用反引号中置函数名: 1 `add` 2 -- 3 --- 你也可以定义不带字符的函数!这使得 --- 你定义自己的操作符!这里有一个操作符 --- 来做整除 +-- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符。 +-- 这里有一个做整除的操作符 (//) a b = a `div` b 35 // 4 -- 8 --- 守卫:一个简单的方法在函数里做分支 +-- Guard:一个在函数中做条件判断的简单方法 fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- 模式匹配是类型的。这里有三种不同的 fib --- 定义。Haskell 将自动调用第一个 --- 匹配值的模式的函数。 +-- 模式匹配与 Guard 类似。 +-- 这里给出了三个不同的 fib 定义。 +-- Haskell 会自动调用第一个符合参数模式的声明 fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- 元组的模式匹配: +-- 元组的模式匹配 foo (x, y) = (x + 1, y + 2) --- 列表的模式匹配。这里 `x` 是列表中第一个元素, --- 并且 `xs` 是列表剩余的部分。我们可以写 --- 自己的 map 函数: +-- 列表的模式匹配 +-- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分。 +-- 我们可以实现自己的 map 函数: myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) --- 编写出来的匿名函数带有一个反斜杠,后面跟着 --- 所有的参数。 +-- 匿名函数带有一个反斜杠,后面跟着所有的参数 myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] --- 使用 fold (在一些语言称为`inject`)随着一个匿名的 --- 函数。foldl1 意味着左折叠(fold left), 并且使用列表中第一个值 --- 作为累加器的初始化值。 +-- 在 fold(在一些语言称 为`inject`)中使用匿名函数 +-- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值。 foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- --- 4. 更多的函数 +-- 4. 其它函数 ---------------------------------------------------- --- 柯里化(currying):如果你不传递函数中所有的参数, --- 它就变成“柯里化的”。这意味着,它返回一个接受剩余参数的函数。 - +-- 部分调用 +-- 如果你调用函数时没有给出所有参数,它就被“部分调用”。 +-- 它将返回一个接受余下参数的函数。 add a b = a + b foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 foo 5 -- 15 --- 另外一种方式去做同样的事 +-- 另一种等价写法 foo = (+10) foo 5 -- 15 --- 函数组合 --- (.) 函数把其它函数链接到一起 --- 举个列子,这里 foo 是一个接受一个值的函数。它对接受的值加 10, --- 并对结果乘以 5,之后返回最后的值。 +-- 函列表合 +-- (.) 函数把其它函数链接到一起。 +-- 例如,这里 foo 是一个接受一个值的函数。 +-- 它对接受的值加 10,并对结果乘以 5,之后返回最后的值。 foo = (*5) . (+10) -- (5 + 10) * 5 = 75 foo 5 -- 75 --- 修复优先级 --- Haskell 有另外一个函数称为 `$`。它改变优先级 --- 使得其左侧的每一个操作先计算然后应用到 --- 右侧的每一个操作。你可以使用 `.` 和 `$` 来除去很多 --- 括号: +-- 修正优先级 +-- Haskell 有另外一个函数 `$` 可以改变优先级。 +-- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分。 +-- 你可以使用 `$` 来移除多余的括号。 --- before -(even (fib 7)) -- true +-- 修改前 +(even (fib 7)) -- False --- after -even . fib $ 7 -- true +-- 修改后 +even . fib $ 7 -- False + +-- 等价地 +even $ fib 7 -- False ---------------------------------------------------- --- 5. 类型签名 +-- 5. 类型声明 ---------------------------------------------------- --- Haskell 有一个非常强壮的类型系统,一切都有一个类型签名。 +-- Haskell 有一个非常强大的类型系统,一切都有一个类型声明。 -- 一些基本的类型: 5 :: Integer "hello" :: String True :: Bool --- 函数也有类型。 --- `not` 接受一个布尔型返回一个布尔型: +-- 函数也有类型 +-- `not` 接受一个布尔型返回一个布尔型 -- not :: Bool -> Bool --- 这是接受两个参数的函数: +-- 这是接受两个参数的函数 -- add :: Integer -> Integer -> Integer --- 当你定义一个值,在其上写明它的类型是一个好实践: +-- 当你定义一个值,声明其类型是一个好做法 double :: Integer -> Integer double x = x * 2 @@ -230,159 +234,148 @@ double x = x * 2 -- 6. 控制流和 If 语句 ---------------------------------------------------- --- if 语句 +-- if 语句: haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- if 语句也可以有多行,缩进是很重要的 +-- if 语句也可以有多行,注意缩进: haskell = if 1 == 1 then "awesome" else "awful" --- case 语句:这里是你可以怎样去解析命令行参数 +-- case 语句 +-- 解析命令行参数: case args of "help" -> printHelp "start" -> startProgram _ -> putStrLn "bad args" --- Haskell 没有循环因为它使用递归取代之。 --- map 应用一个函数到一个数组中的每一个元素 - +-- Haskell 没有循环,它使用递归 +-- map 对一个列表中的每一个元素调用一个函数 map (*2) [1..5] -- [2, 4, 6, 8, 10] -- 你可以使用 map 来编写 for 函数 for array func = map func array --- 然后使用它 +-- 调用 for [0..5] $ \i -> show i --- 我们也可以像这样写: +-- 我们也可以像这样写 for [0..5] show -- 你可以使用 foldl 或者 foldr 来分解列表 -- foldl <fn> <initial value> <list> foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- 这和下面是一样的 +-- 等价于 (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl 是左手边的,foldr 是右手边的- +-- foldl 从左开始,foldr 从右 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- 这和下面是一样的 +-- 现在它等价于 (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- -- 7. 数据类型 ---------------------------------------------------- --- 这里展示在 Haskell 中你怎样编写自己的数据类型 - +-- 在 Haskell 中声明你自己的数据类型: data Color = Red | Blue | Green -- 现在你可以在函数中使用它: - - say :: Color -> String say Red = "You are Red!" say Blue = "You are Blue!" say Green = "You are Green!" -- 你的数据类型也可以有参数: - data Maybe a = Nothing | Just a --- 类型 Maybe 的所有 -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` +-- 这些都是 Maybe 类型: +Just "hello" -- `Maybe String` 类型 +Just 1 -- `Maybe Int` 类型 +Nothing -- 对任意 `a` 为 `Maybe a` 类型 ---------------------------------------------------- -- 8. Haskell IO ---------------------------------------------------- --- 虽然在没有解释 monads 的情况下 IO不能被完全地解释, --- 着手解释到位并不难。 - --- 当一个 Haskell 程序被执行,函数 `main` 就被调用。 --- 它必须返回一个类型 `IO ()` 的值。举个列子: +-- 虽然不解释 Monads 就无法完全解释 IO,但大致了解并不难。 +-- 当执行一个 Haskell 程序时,函数 `main` 就被调用。 +-- 它必须返回一个类型 `IO ()` 的值。例如: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) --- putStrLn has type String -> IO () +-- putStrLn 的类型是 String -> IO () --- 如果你能实现你的程序依照函数从 String 到 String,那样编写 IO 是最简单的。 +-- 如果你的程序输入 String 返回 String,那样编写 IO 是最简单的。 -- 函数 -- interact :: (String -> String) -> IO () --- 输入一些文本,在其上运行一个函数,并打印出输出 +-- 输入一些文本,对其调用一个函数,并打印输出。 countLines :: String -> String countLines = show . length . lines main' = interact countLines --- 你可以考虑一个 `IO()` 类型的值,当做一系列计算机所完成的动作的代表, --- 就像一个以命令式语言编写的计算机程序。我们可以使用 `do` 符号来把动作链接到一起。 --- 举个列子: - +-- 你可以认为一个 `IO ()` 类型的值是表示计算机做的一系列操作,类似命令式语言。 +-- 我们可以使用 `do` 声明来把动作连接到一起。 +-- 举个列子 sayHello :: IO () sayHello = do putStrLn "What is your name?" - name <- getLine -- this gets a line and gives it the name "input" + name <- getLine -- 这里接受一行输入并绑定至 "name" putStrLn $ "Hello, " ++ name -- 练习:编写只读取一行输入的 `interact` -- 然而,`sayHello` 中的代码将不会被执行。唯一被执行的动作是 `main` 的值。 --- 为了运行 `sayHello`,注释上面 `main` 的定义,并代替它: +-- 为了运行 `sayHello`,注释上面 `main` 的定义,替换为: -- main = sayHello --- 让我们来更好地理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: +-- 让我们来更进一步理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: -- getLine :: IO String --- 你可以考虑一个 `IO a` 类型的值,代表一个当被执行的时候 --- 将产生一个 `a` 类型的值的计算机程序(除了它所做的任何事之外)。我们可以保存和重用这个值通过 `<-`。 --- 我们也可以写自己的 `IO String` 类型的动作: - +-- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序。 +-- (可能伴随其它行为) +-- 我们可以通过 `<-` 保存和重用这个值。 +-- 我们也可以实现自己的 `IO String` 类型函数: action :: IO String action = do putStrLn "This is a line. Duh" input1 <- getLine input2 <- getLine - -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `do` 语句的类型是它的最后一行 + -- `return` 不是关键字,只是一个普通函数 return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- 我们可以使用这个动作就像我们使用 `getLine`: - +-- 我们可以像调用 `getLine` 一样调用它 main'' = do putStrLn "I will echo two lines!" result <- action putStrLn result putStrLn "This was all, folks!" --- `IO` 类型是一个 "monad" 的例子。Haskell 使用一个 monad 来做 IO的方式允许它是一门纯函数式语言。 --- 任何与外界交互的函数(也就是 IO) 都在它的类型签名处做一个 `IO` 标志 --- 着让我们推出 什么样的函数是“纯洁的”(不与外界交互,不修改状态) 和 什么样的函数不是 “纯洁的” - --- 这是一个强有力的特征,因为并发地运行纯函数是简单的;因此,Haskell 中并发是非常简单的。 - +-- `IO` 类型是一个 "Monad" 的例子。 +-- Haskell 通过使用 Monad 使得其本身为纯函数式语言。 +-- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO`。 +-- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) , +-- 什么样的函数不是 “纯洁的”。 +-- 这个功能非常强大,因为纯函数并发非常容易,由此在 Haskell 中做并发非常容易。 ---------------------------------------------------- --- 9. The Haskell REPL +-- 9. Haskell REPL ---------------------------------------------------- --- 键入 `ghci` 开始 repl。 +-- 键入 `ghci` 开始 REPL。 -- 现在你可以键入 Haskell 代码。 --- 任何新值都需要通过 `let` 来创建: - +-- 任何新值都需要通过 `let` 来创建 let foo = 5 --- 你可以查看任何值的类型,通过命令 `:t`: - +-- 你可以通过命令 `:t` 查看任何值的类型 >:t foo foo :: Integer -- 你也可以运行任何 `IO ()`类型的动作 - > sayHello What is your name? Friend! @@ -390,7 +383,7 @@ Hello, Friend! ``` -还有很多关于 Haskell,包括类型类和 monads。这些是使得编码 Haskell 是如此有趣的主意。我用一个最后的 Haskell 例子来结束:一个 Haskell 的快排实现: +Haskell 还有许多内容,包括类型类 (typeclasses) 与 Monads。这些都是令 Haskell 编程非常有趣的好东西。我们最后给出 Haskell 的一个例子,一个快速排序的实现: ```haskell qsort [] = [] @@ -399,9 +392,9 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater greater = filter (>= p) xs ``` -安装 Haskell 是简单的。你可以从[这里](http://www.haskell.org/platform/)获得它。 +安装 Haskell 很简单。你可以[从这里获得](http://www.haskell.org/platform/)。 你可以从优秀的 [Learn you a Haskell](http://learnyouahaskell.com/) 或者 [Real World Haskell](http://book.realworldhaskell.org/) -找到优雅不少的入门介绍。 +找到更平缓的入门介绍。 diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index f7d319e6..a8fd2a4c 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -124,7 +124,7 @@ public class LearnJava { // HashMaps /////////////////////////////////////// - // 操作符 + // 操作符 /////////////////////////////////////// System.out.println("\n->Operators"); @@ -149,7 +149,7 @@ public class LearnJava { // 位运算操作符 /* - ~ 补 + ~ 取反,求反码 << 带符号左移 >> 带符号右移 >>> 无符号右移 @@ -161,10 +161,13 @@ public class LearnJava { // 自增 int i = 0; System.out.println("\n->Inc/Dec-rementation"); - System.out.println(i++); //i = 1 后自增 - System.out.println(++i); //i = 2 前自增 - System.out.println(i--); //i = 1 后自减 - System.out.println(--i); //i = 0 前自减 + // ++ 和 -- 操作符使变量加或减1。放在变量前面或者后面的区别是整个表达 + // 式的返回值。操作符在前面时,先加减,后取值。操作符在后面时,先取值 + // 后加减。 + System.out.println(i++); // 后自增 i = 1, 输出0 + System.out.println(++i); // 前自增 i = 2, 输出2 + System.out.println(i--); // 后自减 i = 1, 输出2 + System.out.println(--i); // 前自减 i = 0, 输出0 /////////////////////////////////////// // 控制结构 @@ -192,7 +195,7 @@ public class LearnJava { } System.out.println("fooWhile Value: " + fooWhile); - // Do While循环 + // Do While循环 int fooDoWhile = 0; do { @@ -402,4 +405,4 @@ class PennyFarthing extends Bicycle { * [泛型](http://docs.oracle.com/javase/tutorial/java/generics/index.html) -* [Java代码规范](http://www.oracle.com/technetwork/java/codeconv-138413.html) +* [Java代码规范](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 7dee9cc4..bdef0099 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -5,17 +5,19 @@ name: javascript filename: javascript-zh.js contributors: - ["Adam Brenecki", "http://adam.brenecki.id.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] translators: - ["Chenbo Li", "http://binarythink.net"] + - ["Guodong Qu", "https://github.com/jasonqu"] lang: zh-cn --- Javascript于1995年由网景公司的Brendan Eich发明。 最初发明的目的是作为一个简单的网站脚本语言,来作为 -复杂网站应用java的补充。但由于javascript和网站结合度很高 -所以javascript逐渐变得比java在前端更为流行了。 +复杂网站应用java的补充。但由于它与网页结合度很高并且由浏览器内置支持, +所以javascript变得比java在前端更为流行了。 -JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环境。 +不过 JavaScript 可不仅仅只用于浏览器: Node.js,一个基于Google Chrome V8引擎的独立运行时环境,也越来越流行。 很欢迎来自您的反馈,您可以通过下列方式联系到我: [@adambrenecki](https://twitter.com/adambrenecki), 或者 @@ -29,145 +31,167 @@ JavaScript 不仅仅只可以用于浏览器, 也可用于 Node.js 等后台环 // 语句可以以分号结束 doStuff(); -// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入 +// ... 但是分号也可以省略,每当遇到一个新行时,分号会自动插入(除了一些特殊情况)。 doStuff() -// 我们在这里会去掉分号,但是否添加最后的分号取决于你个人的习惯 -// 及你所在团队的编程风格 +// 因为这些特殊情况会导致意外的结果,所以我们在这里保留分号。 /////////////////////////////////// // 1. 数字、字符串与操作符 -// Javascript 只有一种数字类型 (即 64位 IEEE 754 双精度浮点). -3 // = 3 -1.5 // = 1.5 +// Javascript 只有一种数字类型(即 64位 IEEE 754 双精度浮点 double)。 +// double 有 52 位表示尾数,足以精确存储大到 9✕10¹⁵ 的整数。 +3; // = 3 +1.5; // = 1.5 -// 所有基本的算数运算 -1 + 1 // = 2 -8 - 1 // = 7 -10 * 2 // = 20 -35 / 5 // = 7 +// 所有基本的算数运算都如你预期。 +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 -// 包括无法整除的除法 -5 / 2 // = 2.5 +// 包括无法整除的除法。 +5 / 2; // = 2.5 -// 位运算也和其他语言一样。当你对浮点数进行位运算时, -// 浮点数会转换为至多 32 位的无符号整数 -1 << 2 // = 4 +// 位运算也和其他语言一样;当你对浮点数进行位运算时, +// 浮点数会转换为*至多* 32 位的无符号整数。 +1 << 2; // = 4 -// 括号可以决定优先级 -(1 + 3) * 2 // = 8 +// 括号可以决定优先级。 +(1 + 3) * 2; // = 8 // 有三种非数字的数字类型 -Infinity // 1/0 的结果 --Infinity // -1/0 的结果 -NaN // 0/0 的结果 +Infinity; // 1/0 的结果 +-Infinity; // -1/0 的结果 +NaN; // 0/0 的结果 -// 也有布尔值 -true -false +// 也有布尔值。 +true; +false; -// 可以通过单引号或双引号来构造字符串 -'abc' -"Hello, world" +// 可以通过单引号或双引号来构造字符串。 +'abc'; +"Hello, world"; // 用!来取非 -!true // = false -!false // = true +!true; // = false +!false; // = true -// 相等 == -1 == 1 // = true -2 == 1 // = false +// 相等 === +1 === 1; // = true +2 === 1; // = false // 不等 != -1 != 1 // = false -2 != 1 // = true +1 !== 1; // = false +2 !== 1; // = true // 更多的比较操作符 -1 < 10 // = true -1 > 10 // = false -2 <= 2 // = true -2 >= 2 // = true +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true // 字符串用+连接 -"Hello " + "world!" // = "Hello world!" +"Hello " + "world!"; // = "Hello world!" // 字符串也可以用 < 、> 来比较 -"a" < "b" // = true +"a" < "b"; // = true -// 比较时会进行类型转换... -"5" == 5 // = true +// 使用“==”比较时会进行类型转换... +"5" == 5; // = true +null == undefined; // = true // ...除非你是用 === -"5" === 5 // = false +"5" === 5; // = false +null === undefined; // = false -// 你可以用charAt来得到字符串中的字符 -"This is a string".charAt(0) +// ...但会导致奇怪的行为 +13 + !0; // 14 +"13" + !0; // '13true' -// 还有两个特殊的值:null和undefined -null // 用来表示刻意设置成的空值 -undefined // 用来表示还没有设置的值 +// 你可以用`charAt`来得到字符串中的字符 +"This is a string".charAt(0); // = 'T' -// null, undefined, NaN, 0 和 "" 都是假的(false),其他的都视作逻辑真 -// 注意 0 是逻辑假而 "0"是逻辑真, 尽管 0 == "0". +// ...或使用 `substring` 来获取更大的部分。 +"Hello world".substring(0, 5); // = "Hello" + +// `length` 是一个属性,所以不要使用 (). +"Hello".length; // = 5 + +// 还有两个特殊的值:`null`和`undefined` +null; // 用来表示刻意设置的空值 +undefined; // 用来表示还没有设置的值(尽管`undefined`自身实际是一个值) + +// false, null, undefined, NaN, 0 和 "" 都是假的;其他的都视作逻辑真 +// 注意 0 是逻辑假而 "0"是逻辑真,尽管 0 == "0"。 /////////////////////////////////// // 2. 变量、数组和对象 -// 变量需要用 var 这个关键字声明. Javascript是动态类型语言 -// 所以你在声明时无需指定类型。 赋值需要用 = -var someVar = 5 +// 变量需要用`var`关键字声明。Javascript是动态类型语言, +// 所以你无需指定类型。 赋值需要用 `=` +var someVar = 5; -// 如果你在声明时没有加var关键字,你也不会得到错误 -someOtherVar = 10 +// 如果你在声明时没有加var关键字,你也不会得到错误... +someOtherVar = 10; -// ...但是此时这个变量就会拥有全局的作用域,而非当前作用域 +// ...但是此时这个变量就会在全局作用域被创建,而非你定义的当前作用域 -// 没有被赋值的变量都会返回undefined这个值 -var someThirdVar // = undefined +// 没有被赋值的变量都会被设置为undefined +var someThirdVar; // = undefined -// 对变量进行数学运算有一些简写法 -someVar += 5 // 等价于 someVar = someVar + 5; someVar 现在是 10 -someVar *= 10 // 现在 someVar 是 100 +// 对变量进行数学运算有一些简写法: +someVar += 5; // 等价于 someVar = someVar + 5; someVar 现在是 10 +someVar *= 10; // 现在 someVar 是 100 // 自增和自减也有简写 -someVar++ // someVar 是 101 -someVar-- // 回到 100 +someVar++; // someVar 是 101 +someVar--; // 回到 100 // 数组是任意类型组成的有序列表 -var myArray = ["Hello", 45, true] +var myArray = ["Hello", 45, true]; + +// 数组的元素可以用方括号下标来访问。 +// 数组的索引从0开始。 +myArray[1]; // = 45 -// 数组的元素可以用方括号下标来访问 -// 数组的索引从0开始 -myArray[1] // = 45 +// 数组是可变的,并拥有变量 length。 +myArray.push("World"); +myArray.length; // = 4 -// javascript中的对象相当于其他语言中的字典或映射:是键-值的集合 -{key1: "Hello", key2: "World"} +// 在指定下标添加/修改 +myArray[3] = "Hello"; -// 键是字符串,但是引号也并非是必须的,如果键本身是合法的js标识符 -// 而值则可以是任意类型的值 -var myObj = {myKey: "myValue", "my other key": 4} +// javascript中的对象相当于其他语言中的“字典”或“映射”:是键-值对的无序集合。 +var myObj = {key1: "Hello", key2: "World"}; -// 对象的访问可以通过下标 -myObj["my other key"] // = 4 +// 键是字符串,但如果键本身是合法的js标识符,则引号并非是必须的。 +// 值可以是任意类型。 +var myObj = {myKey: "myValue", "my other key": 4}; + +// 对象属性的访问可以通过下标 +myObj["my other key"]; // = 4 // ... 或者也可以用 . ,如果属性是合法的标识符 -myObj.myKey // = "myValue" +myObj.myKey; // = "myValue" -// 对象是可变的,键和值也可以被更改或增加 -myObj.myThirdKey = true +// 对象是可变的;值也可以被更改或增加新的键 +myObj.myThirdKey = true; -// 如果你想要访问一个还没有被定义的属性,那么会返回undefined -myObj.myFourthKey // = undefined +// 如果你想要获取一个还没有被定义的值,那么会返回undefined +myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. 逻辑与控制结构 -// if语句和其他语言中一样 -var count = 1 +// 本节介绍的语法与Java的语法几乎完全相同 + +// `if`语句和其他语言中一样。 +var count = 1; if (count == 3){ // count 是 3 时执行 -} else if (count == 4) { +} else if (count == 4){ // count 是 4 时执行 } else { // 其他情况下执行 @@ -179,219 +203,270 @@ while (true) { } // Do-while 和 While 循环很像 ,但前者会至少执行一次 -var input +var input; do { - input = getInput() + input = getInput(); } while (!isValid(input)) -// for循环和C、Java中的一样 -// 初始化; 继续执行的条件; 遍历后执行. +// `for`循环和C、Java中的一样: +// 初始化; 继续执行的条件; 迭代。 for (var i = 0; i < 5; i++){ // 遍历5次 } // && 是逻辑与, || 是逻辑或 if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear" + house.contains = "bear"; } if (colour == "red" || colour == "blue"){ // colour是red或者blue时执行 } -// && 和 || 是“短路”语句,在初始化值时会变得有用 -var name = otherName || "default" +// && 和 || 是“短路”语句,它在设定初始化值时特别有用 +var name = otherName || "default"; + +// `switch`语句使用`===`检查相等性。 +// 在每一个case结束时使用 'break' +// 否则其后的case语句也将被执行。 +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} /////////////////////////////////// // 4. 函数、作用域、闭包 -// JavaScript 函数由function关键字定义 +// JavaScript 函数由`function`关键字定义 function myFunction(thing){ - return thing.toUpperCase() + return thing.toUpperCase(); } -myFunction("foo") // = "FOO" - -// 函数也可以是匿名的: -function(thing){ - return thing.toLowerCase() +myFunction("foo"); // = "FOO" + +// 注意被返回的值必须开始于`return`关键字的那一行, +// 否则由于自动的分号补齐,你将返回`undefined`。 +// 在使用Allman风格的时候要注意. +function myFunction() +{ + return // <- 分号自动插在这里 + { + thisIsAn: 'object literal' + } } -// (我们无法调用此函数,因为我们不知道这个函数的名字) +myFunction(); // = undefined -// javascript中的函数也是对象,所以函数也能够赋给一个变量,并且被传递 -// 比如一个事件处理函数: +// javascript中函数是一等对象,所以函数也能够赋给一个变量, +// 并且被作为参数传递 —— 比如一个事件处理函数: function myFunction(){ - // this code will be called in 5 seconds' time + // 这段代码将在5秒钟后被调用 } -setTimeout(myFunction, 5000) - -// 你甚至可以直接把一个函数写到另一个函数的参数中 +setTimeout(myFunction, 5000); +// 注意:setTimeout不是js语言的一部分,而是由浏览器和Node.js提供的。 -setTimeout(function myFunction(){ - // 5秒之后会执行这里的代码 -}, 5000) +// 函数对象甚至不需要声明名称 —— 你可以直接把一个函数定义写到另一个函数的参数中 +setTimeout(function(){ + // 这段代码将在5秒钟后被调用 +}, 5000); -// JavaScript 仅有函数作用于,而其他的语句则没有作用域 +// JavaScript 有函数作用域;函数有其自己的作用域而其他的代码块则没有。 if (true){ - var i = 5 + var i = 5; } -i // = 5 - 并非我们在其他语言中所得到的undefined - -// 这就导致了人们经常用一种叫做“即使执行匿名函数”的模式 -// 这样可以避免一些临时变量扩散到外边去 -function(){ - var temporary = 5 - // 我们可以访问一个全局对象来访问全局作用域 - // 在浏览器中是 'window' 这个对象。 - // 在Node.js中这个对象的名字可能会不同。 - window.permanent = 10 - // 或者,我们也可以把var去掉就行了 - permanent2 = 15 -}() -temporary // 抛出引用异常 -permanent // = 10 -permanent2 // = 15 - -// javascript最强大的功能之一就是闭包 -// 如果一个函数在另一个函数中定义,那么这个函数就拥有外部函数的所有访问权 +i; // = 5 - 并非我们在其他语言中所期望得到的undefined + +// 这就导致了人们经常使用的“立即执行匿名函数”的模式, +// 这样可以避免一些临时变量扩散到全局作用域去。 +(function(){ + var temporary = 5; + // 我们可以访问修改全局对象("global object")来访问全局作用域, + // 在web浏览器中是`window`这个对象。 + // 在其他环境如Node.js中这个对象的名字可能会不同。 + window.permanent = 10; +})(); +temporary; // 抛出引用异常ReferenceError +permanent; // = 10 + +// javascript最强大的功能之一就是闭包。 +// 如果一个函数在另一个函数中定义,那么这个内部函数就拥有外部函数的所有变量的访问权, +// 即使在外部函数结束之后。 function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!" + var prompt = "Hello, " + name + "!"; + // 内部函数默认是放在局部作用域的, + // 就像是用`var`声明的。 function inner(){ - alert(prompt) + alert(prompt); } - setTimeout(inner, 5000) - // setTimeout 是异步的,所以这个函数会马上终止不会等待。 - // 然而,在5秒结束后,inner函数仍然会弹出prompt信息。 + setTimeout(inner, 5000); + // setTimeout是异步的,所以 sayHelloInFiveSeconds 函数会立即退出, + // 而 setTimeout 会在后面调用inner + // 然而,由于inner是由sayHelloInFiveSeconds“闭合包含”的, + // 所以inner在其最终被调用时仍然能够访问`prompt`变量。 } -sayHelloInFiveSeconds("Adam") // 会在5秒后弹出 "Hello, Adam!" +sayHelloInFiveSeconds("Adam"); // 会在5秒后弹出 "Hello, Adam!" + /////////////////////////////////// // 5. 对象、构造函数与原型 -// 对象包含方法 +// 对象可以包含方法。 var myObj = { myFunc: function(){ - return "Hello world!" + return "Hello world!"; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" -// 当对象中的函数被调用时,这个函数就可以通过this关键字访问这个对象 +// 当对象中的函数被调用时,这个函数可以通过`this`关键字访问其依附的这个对象。 myObj = { myString: "Hello world!", myFunc: function(){ - return this.myString + return this.myString; } -} -myObj.myFunc() // = "Hello world!" +}; +myObj.myFunc(); // = "Hello world!" -// 但这个函数访问的其实是其运行时环境,而非定义时环境 -// 所以如果函数所在的环境不在当前对象的环境中运行时,就运行不成功了 -var myFunc = myObj.myFunc -myFunc() // = undefined +// 但这个函数访问的其实是其运行时环境,而非定义时环境,即取决于函数是如何调用的。 +// 所以如果函数被调用时不在这个对象的上下文中,就不会运行成功了。 +var myFunc = myObj.myFunc; +myFunc(); // = undefined -// 相应的,一个函数也可以被指定为一个对象的方法,并且用过this可以访问 -// 这个对象的成员,即使在定义时并没有绑定任何值 +// 相应的,一个函数也可以被指定为一个对象的方法,并且可以通过`this`访问 +// 这个对象的成员,即使在函数被定义时并没有依附在对象上。 var myOtherFunc = function(){ - return this.myString.toUpperCase() + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// 当我们通过`call`或者`apply`调用函数的时候,也可以为其指定一个执行上下文。 +var anotherFunc = function(s){ + return this.myString + s; } -myObj.myOtherFunc = myOtherFunc -myObj.myOtherFunc() // = "HELLO WORLD!" +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// `apply`函数几乎完全一样,只是要求一个array来传递参数列表。 +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -// 当你通过new关键字调用一个函数时,就会生成一个对象 -// 而对象的成员需要通过this来定义。 -// 这样的函数就叫做构造函数 +// 当一个函数接受一系列参数,而你想传入一个array时特别有用。 +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 +// 但是`call`和`apply`只是临时的。如果我们希望函数附着在对象上,可以使用`bind`。 +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` 也可以用来部分应用一个函数(柯里化)。 +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// 当你通过`new`关键字调用一个函数时,就会创建一个对象, +// 而且可以通过this关键字访问该函数。 +// 设计为这样调用的函数就叫做构造函数。 var MyConstructor = function(){ - this.myNumber = 5 + this.myNumber = 5; } -myNewObj = new MyConstructor() // = {myNumber: 5} -myNewObj.myNumber // = 5 +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 -// 每一个js对象都有一个原型,当你要访问一个没有定义过的成员时, -// 解释器就回去找这个对象的原型 +// 每一个js对象都有一个‘原型’。当你要访问一个实际对象中没有定义的一个属性时, +// 解释器就回去找这个对象的原型。 -// 有一些JS实现会让你通过一个对象的__proto__方法访问这个原型。 -// 这虽然对理解这个对象很有用,但是这并不是标准的一部分 -// 我们之后会通过标准方式来访问原型。 +// 一些JS实现会让你通过`__proto__`属性访问一个对象的原型。 +// 这虽然对理解原型很有用,但是它并不是标准的一部分; +// 我们后面会介绍使用原型的标准方式。 var myObj = { - myString: "Hello world!", -} + myString: "Hello world!" +}; var myPrototype = { meaningOfLife: 42, myFunc: function(){ return this.myString.toLowerCase() } -} -myObj.__proto__ = myPrototype -myObj.meaningOfLife // = 42 +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 -// This works for functions, too. +// 函数也可以工作。 myObj.myFunc() // = "hello world!" -// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型。 +// 当然,如果你要访问的成员在原型当中也没有定义的话,解释器就会去找原型的原型,以此类推。 myPrototype.__proto__ = { myBoolean: true -} -myObj.myBoolean // = true - -// 这其中并没有对象的拷贝。每个对象的原型实际上是持有原型对象的引用 -// 这说明当我们改变对象的原型时,会影响到其他以这个原型为原型的对象 -myPrototype.meaningOfLife = 43 -myObj.meaningOfLife // = 43 - -// 我们知道 __proto__ 并非标准规定,实际上也没有办法更改已经指定好的原型。 -// 但是,我们有两种方式可以为新的对象指定原型。 - -// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的 -// 也因此并不是所有的JS实现都有这个放啊 -var myObj = Object.create(myPrototype) -myObj.meaningOfLife // = 43 - -// 第二种方式可以在任意版本中使用,不过需要通过构造函数。 -// 构造函数有一个属性prototype。但是这 *不是* 构造函数本身的函数 -// 而是通过构造函数和new关键字生成新对象时自动生成的。 -myConstructor.prototype = { +}; +myObj.myBoolean; // = true + +// 这其中并没有对象的拷贝;每个对象实际上是持有原型对象的引用。 +// 这意味着当我们改变对象的原型时,会影响到其他以这个原型为原型的对象。 +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// 我们知道 `__proto__` 并非标准规定,实际上也没有标准办法来修改一个已存在对象的原型。 +// 然而,我们有两种方式为指定原型创建一个新的对象。 + +// 第一种方式是 Object.create,这个方法是在最近才被添加到Js中的, +// 因此并不是所有的JS实现都有这个方法 +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// 第二种方式可以在任意版本中使用,不过必须通过构造函数。 +// 构造函数有一个属性prototype。但是它 *不是* 构造函数本身的原型;相反, +// 是通过构造函数和new关键字创建的新对象的原型。 +MyConstructor.prototype = { + myNumber: 5, getMyNumber: function(){ - return this.myNumber + return this.myNumber; } -} -var myNewObj2 = new myConstructor() -myNewObj2.getMyNumber() // = 5 +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6 +myNewObj2.getMyNumber(); // = 6 // 字符串和数字等内置类型也有通过构造函数来创建的包装类型 -var myNumber = 12 -var myNumberObj = new Number(12) -myNumber == myNumberObj // = true +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true // 但是它们并非严格等价 -typeof myNumber // = 'number' -typeof myNumberObj // = 'object' -myNumber === myNumberObj // = false +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false if (0){ // 这段代码不会执行,因为0代表假 } -if (Number(0)){ - // 这段代码会执行,因为Number(0)代表真 -} -// 但是,包装类型和内置类型共享一个原型 -// 这样你就可以给内置类型也增加一些功能 +// 不过,包装类型和内置类型共享一个原型, +// 所以你实际可以给内置类型也增加一些功能,例如对string: String.prototype.firstCharacter = function(){ - return this.charAt(0) + return this.charAt(0); } -"abc".firstCharacter() // = "a" +"abc".firstCharacter(); // = "a" -// 这个技巧可以用来用老版本的javascript子集来是实现新版本js的功能 +// 这个技巧经常用在“代码填充”中,来为老版本的javascript子集增加新版本js的特性, // 这样就可以在老的浏览器中使用新功能了。 -// 比如,我们知道Object.create并没有在所有的版本中都实现 -// 但是我们仍然可以通过这个技巧来使用 +// 比如,我们知道Object.create并没有在所有的版本中都实现, +// 但是我们仍然可以通过“代码填充”来实现兼容: if (Object.create === undefined){ // 如果存在则不覆盖 Object.create = function(proto){ // 用正确的原型来创建一个临时构造函数 - var Constructor = function(){} - Constructor.prototype = proto + var Constructor = function(){}; + Constructor.prototype = proto; // 之后用它来创建一个新的对象 - return new Constructor() + return new Constructor(); } } ``` @@ -399,19 +474,23 @@ if (Object.create === undefined){ // 如果存在则不覆盖 ## 更多阅读 [Mozilla 开发者 -网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了很好的 -Javascript文档,并且由于是wiki,所以你也可以自行编辑来分享你的知识。 +网络](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 提供了优秀的介绍 +Javascript如何在浏览器中使用的文档。而且它是wiki,所以你也可以自行编辑来分享你的知识。 MDN的 [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -覆盖了这里提到的绝大多数话题,大多数只是Javascript这个语言本身。 +覆盖了这里提到的绝大多数话题的细节。该导引的大多数内容被限定在只是Javascript这个语言本身; 如果你想了解Javascript是如何在网页中被应用的,那么可以查看 [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) +[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) 是本参考的另一个版本,并包含了挑战习题。 + [Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 -讲解所有Javascript反直觉部分的一本书 +讲解所有Javascript反直觉部分的导引。 + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) 是一个经典的指导参考书。 除了这篇文章的直接贡献者之外,这篇文章也参考了这个网站上 Louie Dinh 的 Python 教程,以及 Mozilla开发者网络上的[JS -Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)。 diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 1c577efb..b633714d 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -69,7 +69,7 @@ __此文本也是__ <!-- 如果你插入一个 HTML中的<br />标签,你可以在段末加入两个以上的空格, 然后另起一段。--> -此段落结尾有两个空格(选中以显示)。 +此段落结尾有两个空格(选中以显示)。 上文有一个 <br /> ! @@ -127,7 +127,7 @@ __此文本也是__ <!-- 代码段落 --> <!-- 代码段落(HTML中 <code>标签)可以由缩进四格(spaces) -或者一个标签页(tab)实现--> +或者一个制表符(tab)实现--> This is code So is this diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown new file mode 100644 index 00000000..77ba765a --- /dev/null +++ b/zh-cn/matlab-cn.html.markdown @@ -0,0 +1,491 @@ +---
+language: Matlab
+contributors:
+ - ["mendozao", "http://github.com/mendozao"]
+ - ["jamesscottbrown", "http://jamesscottbrown.com"]
+translators:
+ - ["sunxb10", "https://github.com/sunxb10"]
+lang: zh-cn
+---
+
+MATLAB 是 MATrix LABoratory (矩阵实验室)的缩写,它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。
+
+如果您有任何需要反馈或交流的内容,请联系本教程作者[@the_ozzinator](https://twitter.com/the_ozzinator)、[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。
+
+```matlab
+% 以百分号作为注释符
+
+%{
+多行注释
+可以
+这样
+表示
+%}
+
+% 指令可以随意跨行,但需要在跨行处用 '...' 标明:
+ a = 1 + 2 + ...
+ + 4
+
+% 可以在MATLAB中直接向操作系统发出指令
+!ping google.com
+
+who % 显示内存中的所有变量
+whos % 显示内存中的所有变量以及它们的类型
+clear % 清除内存中的所有变量
+clear('A') % 清除指定的变量
+openvar('A') % 在变量编辑器中编辑指定变量
+
+clc % 清除命令窗口中显示的所有指令
+diary % 将命令窗口中的内容写入本地文件
+ctrl-c % 终止当前计算
+
+edit('myfunction.m') % 在编辑器中打开指定函数或脚本
+type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码
+
+profile on % 打开 profile 代码分析工具
+profile of % 关闭 profile 代码分析工具
+profile viewer % 查看 profile 代码分析工具的分析结果
+
+help command % 在命令窗口中显示指定命令的帮助文档
+doc command % 在帮助窗口中显示指定命令的帮助文档
+lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令
+lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令
+
+
+% 输出格式
+format short % 浮点数保留 4 位小数
+format long % 浮点数保留 15 位小数
+format bank % 金融格式,浮点数只保留 2 位小数
+fprintf('text') % 在命令窗口中显示 "text"
+disp('text') % 在命令窗口中显示 "text"
+
+
+% 变量与表达式
+myVariable = 4 % 命令窗口中将新创建的变量
+myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+2 ^ 3 % ans = 8
+a = 2; b = 3;
+c = exp(a)*sin(pi/2) % c = 7.3891
+
+
+% 调用函数有两种方式:
+% 标准函数语法:
+load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔
+% 指令语法:
+load myFile.mat y % 不加括号,以空格分隔参数
+% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字,
+% 不能是变量的具体值,同样也不能是输出变量
+[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法
+[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写
+
+
+
+% 逻辑运算
+1 > 5 % 假,ans = 0
+10 >= 10 % 真,ans = 1
+3 ~= 4 % 不等于 -> ans = 1
+3 == 3 % 等于 -> ans = 1
+3 > 1 && 4 > 1 % 与 -> ans = 1
+3 > 1 || 4 > 1 % 或 -> ans = 1
+~1 % 非 -> ans = 0
+
+% 逻辑运算可直接应用于矩阵,运算结果也是矩阵
+A > 5
+% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1
+A( A > 5 )
+% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素
+
+% 字符串
+a = 'MyString'
+length(a) % ans = 8
+a(2) % ans = y
+[a,a] % ans = MyStringMyString
+b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字
+length(b) % ans = 3
+b(2) % ans = 符
+[b,b] % ans = 字符串字符串
+
+
+% 元组(cell 数组)
+a = {'one', 'two', 'three'}
+a(1) % ans = 'one' - 返回一个元组
+char(a(1)) % ans = one - 返回一个字符串
+
+
+% 结构体
+A.b = {'one','two'};
+A.c = [1 2];
+A.d.e = false;
+
+
+% 向量
+x = [4 32 53 7 1]
+x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0
+x(2:3) % ans = 32 53
+x(2:end) % ans = 32 53 7 1
+
+x = [4; 32; 53; 7; 1] % 列向量
+
+x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10
+
+
+% 矩阵
+A = [1 2 3; 4 5 6; 7 8 9]
+% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素
+% A =
+
+% 1 2 3
+% 4 5 6
+% 7 8 9
+
+A(2,3) % ans = 6,A(row, column)
+A(6) % ans = 8
+% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素)
+
+
+A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42
+% A =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+A(2:3,2:3) % 取原矩阵中的一块作为新矩阵
+%ans =
+
+% 5 42
+% 8 9
+
+A(:,1) % 第 1 列的所有元素
+%ans =
+
+% 1
+% 4
+% 7
+
+A(1,:) % 第 1 行的所有元素
+%ans =
+
+% 1 2 3
+
+[A ; A] % 将两个矩阵上下相接构成新矩阵
+%ans =
+
+% 1 2 3
+% 4 5 42
+% 7 8 9
+% 1 2 3
+% 4 5 42
+% 7 8 9
+
+% 等价于
+vertcat(A, A);
+
+
+[A , A] % 将两个矩阵左右相接构成新矩阵
+
+%ans =
+
+% 1 2 3 1 2 3
+% 4 5 42 4 5 42
+% 7 8 9 7 8 9
+
+% 等价于
+horzcat(A, A);
+
+
+A(:, [3 1 2]) % 重新排布原矩阵的各列
+%ans =
+
+% 3 1 2
+% 42 4 5
+% 9 7 8
+
+size(A) % 返回矩阵的行数和列数,ans = 3 3
+
+A(1, :) =[] % 删除矩阵的第 1 行
+A(:, 1) =[] % 删除矩阵的第 1 列
+
+transpose(A) % 矩阵转置,等价于 A'
+ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数)
+
+
+% 元素运算 vs. 矩阵运算
+% 单独运算符就是对矩阵整体进行矩阵运算
+% 在运算符加上英文句点就是对矩阵中的元素进行元素计算
+% 示例如下:
+A * B % 矩阵乘法,要求 A 的列数等于 B 的行数
+A .* B % 元素乘法,要求 A 和 B 形状一致(A 的行数等于 B 的行数, A 的列数等于 B 的列数)
+% 元素乘法的结果是与 A 和 B 形状一致的矩阵,其每个元素等于 A 对应位置的元素乘 B 对应位置的元素
+
+% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算:
+exp(A) % 对矩阵中每个元素做指数运算
+expm(A) % 对矩阵整体做指数运算
+sqrt(A) % 对矩阵中每个元素做开方运算
+sqrtm(A) % 对矩阵整体做开放运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵)
+
+
+% 绘图
+x = 0:.10:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi(pi 就是圆周率)
+y = sin(x);
+plot(x,y)
+xlabel('x axis')
+ylabel('y axis')
+title('Plot of y = sin(x)')
+axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1
+
+plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线
+legend('Line 1 label', 'Line 2 label') % 为图片加注图例
+% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应
+
+% 在同一张图上绘制多条曲线的另一种方法:
+% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线,
+% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。
+% 在 hold on 和 hold off 中可以放置任意多的 plot 指令,
+% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。
+plot(x, y1)
+hold on
+plot(x, y2)
+plot(x, y3)
+plot(x, y4)
+hold off
+
+loglog(x, y) % 对数—对数绘图
+semilogx(x, y) % 半对数(x 轴对数)绘图
+semilogy(x, y) % 半对数(y 轴对数)绘图
+
+fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线
+
+grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示
+axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长)
+axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长)
+
+scatter(x, y); % 散点图
+hist(x); % 直方图
+
+z = sin(x);
+plot3(x,y,z); % 绘制三维曲线
+
+pcolor(A) % 伪彩色图(热图)
+contour(A) % 等高线图
+mesh(A) % 网格曲面图
+
+h = figure % 创建新的图片对象并返回其句柄 h
+figure(h) % 将句柄 h 对应的图片作为当前图片
+close(h) % 关闭句柄 h 对应的图片
+close all % 关闭 MATLAB 中所用打开的图片
+close % 关闭当前图片
+
+shg % 显示图形窗口
+clf clear % 清除图形窗口中的图像,并重置图像属性
+
+% 图像属性可以通过图像句柄进行设定
+% 在创建图像时可以保存图像句柄以便于设置
+% 也可以用 gcf 函数返回当前图像的句柄
+h = plot(x, y); % 在创建图像时显式地保存图像句柄
+set(h, 'Color', 'r')
+% 颜色代码:'y' 黄色,'m' 洋红色,'c' 青色,'r' 红色,'g' 绿色,'b' 蓝色,'w' 白色,'k' 黑色
+set(h, 'Color', [0.5, 0.5, 0.4])
+% 也可以使用 RGB 值指定颜色
+set(h, 'LineStyle', '--')
+% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线
+get(h, 'LineStyle')
+% 获取当前句柄的线型
+
+
+% 用 gca 函数返回当前图像的坐标轴句柄
+set(gca, 'XDir', 'reverse'); % 令 x 轴反向
+
+% 用 subplot 指令创建平铺排列的多张子图
+subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图
+plot(x1); title('First Plot') % 在选中的图中绘图
+subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图
+plot(x2); title('Second Plot') % 在选中的图中绘图
+
+
+% 要调用函数或脚本,必须保证它们在你的当前工作目录中
+path % 显示当前工作目录
+addpath /path/to/dir % 将指定路径加入到当前工作目录中
+rmpath /path/to/dir % 将指定路径从当前工作目录中删除
+cd /path/to/move/into % 以制定路径作为当前工作目录
+
+
+% 变量可保存到 .mat 格式的本地文件
+save('myFileName.mat') % 保存当前工作空间中的所有变量
+load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间
+
+
+% .m 脚本文件
+% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名
+% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令
+
+
+% .m 函数文件
+% 与脚本文件类似,同样以 .m 作为后缀名
+% 但函数文件可以接受用户输入的参数并返回运算结果
+% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突
+% 函数文件的名称应当与其所定义的函数的名称一致(比如下面例子中函数文件就应命名为 double_input.m)
+% 使用 'help double_input.m' 可返回函数定义中第一行注释信息
+function output = double_input(x)
+ % double_input(x) 返回 x 的 2 倍
+ output = 2*x;
+end
+double_input(6) % ans = 12
+
+
+% 同样还可以定义子函数和内嵌函数
+% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用
+% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量
+
+
+% 使用匿名函数可以不必创建 .m 函数文件
+% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等)
+% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用:
+sqr = @(x) x.^2;
+sqr(10) % ans = 100
+doc function_handle % find out more
+
+
+% 接受用户输入
+a = input('Enter the value: ')
+
+
+% 从文件中读取数据
+fopen(filename)
+% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件)
+
+
+% 输出
+disp(a) % 在命令窗口中打印变量 a 的值
+disp('Hello World') % 在命令窗口中打印字符串
+fprintf % 按照指定格式在命令窗口中打印内容
+
+% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆)
+if (a > 15)
+ disp('Greater than 15')
+elseif (a == 23)
+ disp('a is 23')
+else
+ disp('neither condition met')
+end
+
+% 循环语句
+% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!!
+% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!!
+% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句
+for k = 1:5
+ disp(k)
+end
+
+k = 0;
+while (k < 5)
+ k = k + 1;
+end
+
+
+% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果
+tic
+A = rand(1000);
+A*A*A*A*A*A*A;
+toc
+
+
+% 链接 MySQL 数据库
+dbname = 'database_name';
+username = 'root';
+password = 'root';
+driver = 'com.mysql.jdbc.Driver';
+dburl = ['jdbc:mysql://localhost:8889/' dbname];
+javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号
+% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载
+conn = database(dbname, username, password, driver, dburl);
+sql = ['SELECT * from table_name where id = 22'] % SQL 语句
+a = fetch(conn, sql) % a 即包含所需数据
+
+
+% 常用数学函数
+sin(x)
+cos(x)
+tan(x)
+asin(x)
+acos(x)
+atan(x)
+exp(x)
+sqrt(x)
+log(x)
+log10(x)
+abs(x)
+min(x)
+max(x)
+ceil(x)
+floor(x)
+round(x)
+rem(x)
+rand % 均匀分布的伪随机浮点数
+randi % 均匀分布的伪随机整数
+randn % 正态分布的伪随机浮点数
+
+% 常用常数
+pi
+NaN
+inf
+
+% 求解矩阵方程(如果方程无解,则返回最小二乘近似解)
+% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数
+x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确
+x=b/A % 求解 xA=b
+
+inv(A) % 逆矩阵
+pinv(A) % 伪逆矩阵
+
+
+% 常用矩阵函数
+zeros(m, n) % m x n 阶矩阵,元素全为 0
+ones(m, n) % m x n 阶矩阵,元素全为 1
+diag(A) % 返回矩阵 A 的对角线元素
+diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素
+eye(m, n) % m x n 阶单位矩阵
+linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点
+inv(A) % 矩阵 A 的逆矩阵
+det(A) % 矩阵 A 的行列式
+eig(A) % 矩阵 A 的特征值和特征向量
+trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A))
+isempty(A) % 测试 A 是否为空
+all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值)
+any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值)
+isequal(A, B) % 测试 A 和 B是否相等
+numel(A) % 矩阵 A 的元素个数
+triu(x) % 返回 x 的上三角这部分
+tril(x) % 返回 x 的下三角这部分
+cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积)
+dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长
+transpose(A) % A 的转置,等价于 A'
+fliplr(A) % 将一个矩阵左右翻转
+flipud(A) % 将一个矩阵上下翻转
+
+% 矩阵分解
+[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵
+[P, D] = eig(A) % 特征值分解:AP = PD,D 是由特征值构成的对角阵,P 的各列就是对应的特征向量
+[U, S, V] = svd(X) % 奇异值分解:XV = US,U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵
+
+% 常用向量函数
+max % 最大值
+min % 最小值
+length % 元素个数
+sort % 按升序排列
+sum % 各元素之和
+prod % 各元素之积
+mode % 众数
+median % 中位数
+mean % 平均值
+std % 标准差
+perms(x) % x 元素的全排列
+
+```
+
+## 相关资料
+
+* 官方网页:[http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/)
+* 官方论坛:[http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/)
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 99250b43..14d38137 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] - ["lidashuang", "https://github.com/lidashuang"] + - ["ftwbzhao", "https://github.com/ftwbzhao"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] --- @@ -120,11 +121,11 @@ status == :approved #=> false # 数组 # 这是一个数组 -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # 数组可以包含不同类型的元素 -array = [1, "hello", false] #=> => [1, "hello", false] +[1, "hello", false] #=> [1, "hello", false] # 数组可以被索引 # 从前面开始 @@ -140,8 +141,8 @@ array.[] 12 #=> nil # 从尾部开始 array[-1] #=> 5 -# 同时指定开始的位置和结束的位置 -array[2, 4] #=> [3, 4, 5] +# 同时指定开始的位置和长度 +array[2, 3] #=> [3, 4, 5] # 或者指定一个范围 array[1..3] #=> [2, 3, 4] diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown new file mode 100644 index 00000000..17a897df --- /dev/null +++ b/zh-cn/rust-cn.html.markdown @@ -0,0 +1,296 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Guangming Mao", "http://maogm.com"] +filename: learnrust-cn.rs +lang: zh-cn +--- + +Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制与高级语言的便利性和安全保障结合在了一起。 + +而 Rust 并不需要一个垃圾回收器或者运行时即可实现这个目的,这使得 Rust 库可以成为一种 C 语言的替代品。 + +Rust 第一版(0.1 版)发布于 2012 年 1 月,3 年以来一直在紧锣密鼓地迭代。 +因为更新太频繁,一般建议使用每夜构建版而不是稳定版,直到最近 1.0 版本的发布。 + +2015 年 3 月 15 日,Rust 1.0 发布,完美向后兼容,最新的每夜构建版提供了缩短编译时间等新特性。 +Rust 采用了持续迭代模型,每 6 周一个发布版。Rust 1.1 beta 版在 1.0 发布时同时发布。 + +尽管 Rust 相对来说是一门底层语言,它提供了一些常见于高级语言的函数式编程的特性。这让 Rust 不仅高效,并且易用。 + +```rust +// 这是注释,单行注释... +/* ...这是多行注释 */ + +/////////////// +// 1. 基础 // +/////////////// + +// 函数 (Functions) +// `i32` 是有符号 32 位整数类型(32-bit signed integers) +fn add2(x: i32, y: i32) -> i32 { + // 隐式返回 (不要分号) + x + y +} + +// 主函数(Main function) +fn main() { + // 数字 (Numbers) // + + // 不可变绑定 + let x: i32 = 1; + + // 整形/浮点型数 后缀 + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // 类型推导 + // 大部分时间,Rust 编译器会推导变量类型,所以不必把类型显式写出来。 + // 这个教程里面很多地方都显式写了类型,但是只是为了示范。 + // 绝大部分时间可以交给类型推导。 + let implicit_x = 1; + let implicit_f = 1.3; + + // 算术运算 + let sum = x + y + 13; + + // 可变变量 + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // 字符串 (Strings) // + + // 字符串字面量 + let x: &str = "hello world!"; + + // 输出 + println!("{} {}", f, x); // 1.3 hello world + + // 一个 `String` – 在堆上分配空间的字符串 + let s: String = "hello world".to_string(); + + // 字符串分片(slice) - 另一个字符串的不可变视图 + // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何内容,只是一个指向某个东西的指针 + // 比如这里就是 `s` + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hello world hello world + + // 数组 (Vectors/arrays) // + + // 长度固定的数组 (array) + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // 变长数组 (vector) + let mut vector: Vec<i32> = vec![1, 2, 3, 4]; + vector.push(5); + + // 分片 - 某个数组(vector/array)的不可变视图 + // 和字符串分片基本一样,只不过是针对数组的 + let slice: &[i32] = &vector; + + // 使用 `{:?}` 按调试样式输出 + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // 元组 (Tuples) // + + // 元组是固定大小的一组值,可以是不同类型 + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // 解构 `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // 索引 + println!("{}", x.1); // hello + + ////////////// + // 2. 类型 (Type) // + ////////////// + + // 结构体(Sturct) + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // 匿名成员结构体,又叫“元组结构体”(‘tuple struct’) + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // 基础的 C 风格枚举类型(enum) + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // 有成员的枚举类型 + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // 泛型 (Generics) // + + struct Foo<T> { bar: T } + + // 这个在标准库里面有实现,叫 `Option` + enum Optional<T> { + SomeVal(T), + NoVal, + } + + // 方法 (Methods) // + + impl<T> Foo<T> { + // 方法需要一个显式的 `self` 参数 + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // 接口(Traits) (其他语言里叫 interfaces 或 typeclasses) // + + trait Frobnicate<T> { + fn frobnicate(self) -> Option<T>; + } + + impl<T> Frobnicate<T> for Foo<T> { + fn frobnicate(self) -> Option<T> { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + /////////////////////////////////// + // 3. 模式匹配 (Pattern matching) // + /////////////////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // 高级模式匹配 + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } + + /////////////////////////////// + // 4. 流程控制 (Control flow) // + /////////////////////////////// + + // `for` 循环 + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // 区间 (Ranges) + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // 输出 `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` 可以当表达式 + let value = if true { + "good" + } else { + "bad" + }; + + // `while` 循环 + while 1 == 1 { + println!("The universe is operating normally."); + } + + // 无限循环 + loop { + println!("Hello!"); + } + + //////////////////////////////////////////////// + // 5. 内存安全和指针 (Memory safety & pointers) // + //////////////////////////////////////////////// + + // 独占指针 (Owned pointer) - 同一时刻只能有一个对象能“拥有”这个指针 + // 意味着 `Box` 离开他的作用域后,会被安全地释放 + let mut mine: Box<i32> = Box::new(3); + *mine = 5; // 解引用 + // `now_its_mine` 获取了 `mine` 的所有权。换句话说,`mine` 移动 (move) 了 + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // 编译报错,因为现在 `now_its_mine` 独占那个指针 + + // 引用 (Reference) – 引用其他数据的不可变指针 + // 当引用指向某个值,我们称为“借用”这个值,因为是被不可变的借用,所以不能被修改,也不能移动 + // 借用一直持续到生命周期结束,即离开作用域 + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); //不像 `box`, `var` 还可以继续使用 + println!("{}", *ref_var); + // var = 5; // 编译报错,因为 `var` 被借用了 + // *ref_var = 6; // 编译报错,因为 `ref_var` 是不可变引用 + + // 可变引用 (Mutable reference) + // 当一个变量被可变地借用时,也不可使用 + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; + + println!("{}", *ref_var2); // 6 + // var2 = 2; // 编译报错,因为 `var2` 被借用了 +} +``` + +## 更深入的资料 + +Rust 还有很多很多其他内容 - 这只是 Rust 最基本的功能,帮助你了解 Rust 里面最重要的东西。 +如果想深入学习 Rust,可以去读 +[The Rust Programming Language](http://doc.rust-lang.org/book/index.html) +或者上 reddit [/r/rust](http://reddit.com/r/rust) 订阅。 +同时 irc.mozilla.org 的 #rust 频道上的小伙伴们也非常欢迎新来的朋友。 + +你可以在这个在线编译器 [Rust playpen](http://play.rust-lang.org) 上尝试 Rust 的一些特性 +或者上[官方网站](http://rust-lang.org). diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 58f5cd47..508dd58e 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -4,12 +4,15 @@ filename: learnscala-zh.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] translators: - ["Peiyong Lin", ""] + - ["Jinchang Ye", "http://github.com/alwayswithme"] + - ["Guodong Qu", "https://github.com/jasonqu"] lang: zh-cn --- -Scala - 一门可拓展性的语言 +Scala - 一门可拓展的语言 ```scala @@ -17,23 +20,31 @@ Scala - 一门可拓展性的语言 自行设置: 1) 下载 Scala - http://www.scala-lang.org/downloads - 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下 - 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符: + 2) unzip/untar 到您喜欢的地方,并把 bin 子目录添加到 path 环境变量 + 3) 在终端输入 scala,启动 Scala 的 REPL,您会看到提示符: scala> - 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点: + 这就是所谓的 REPL (读取-求值-输出循环,英语: Read-Eval-Print Loop), + 您可以在其中输入合法的表达式,结果会被打印。 + 在教程中我们会进一步解释 Scala 文件是怎样的,但现在先了解一点基础。 */ -println(10) // 打印整数 10 -println("Boo!") // 打印字符串 "BOO!" +///////////////////////////////////////////////// +// 1. 基础 +///////////////////////////////////////////////// +// 单行注释开始于两个斜杠 -// 一些基础 +/* + 多行注释,如您之前所见,看起来像这样 +*/ // 打印并强制换行 println("Hello world!") +println(10) + // 没有强制换行的打印 print("Hello world") @@ -41,13 +52,19 @@ print("Hello world") // val 声明是不可变的,var 声明是可修改的。不可变性是好事。 val x = 10 // x 现在是 10 x = 20 // 错误: 对 val 声明的变量重新赋值 -var x = 10 -x = 20 // x 现在是 20 +var y = 10 +y = 20 // y 现在是 20 -// 单行注释开始于两个斜杠 -/* -多行注释看起来像这样。 +/* + Scala 是静态语言,但注意上面的声明方式,我们没有指定类型。 + 这是因为类型推导的语言特性。大多数情况, Scala 编译器可以推测变量的类型, + 所以您不需要每次都输入。可以像这样明确声明变量类型: */ +val z: Int = 10 +val a: Double = 1.0 + +// 注意从 Int 到 Double 的自动转型,结果是 10.0, 不是 10 +val b: Double = 10 // 布尔值 true @@ -64,9 +81,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// 在 REPL 计算一个命令会返回给你结果的类型和值 +// 在 REPL 计算一个表达式会返回给您结果的类型和值 1 + 7 @@ -77,58 +96,190 @@ true == false // false 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 - 1+7 的结果是一样的 + 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果, + 您看到的输出可能不一样。 */ +"Scala strings are surrounded by double quotes" +'a' // Scala 的字符 +// '不存在单引号字符串' <= 这会导致错误 -// 包括函数在内,每一个事物都是对象。在 REPL 中输入: +// String 有常见的 Java 字符串方法 +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") -7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名) +// 也有一些额外的 Scala 方法,另请参见:scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) -// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数 -(x:Int) => x * x +// 字符串改写:留意前缀 "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" -// 你可以分配给函数一个标识符,像这样: -val sq = (x:Int) => x * x +// 在要改写的字符串中使用表达式也是可以的 +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -/* 上面的例子说明 - - sq: Int => Int = <function1> +// 添加 "f" 前缀对要改写的字符串进行格式化 +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" - 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数 +// 未处理的字符串,忽略特殊字符。 +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." - sq 可以像下面那样被执行: -*/ +// 一些字符需要转义,比如字符串中的双引号 +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -sq(10) // 返回给你:res33: Int = 100. +// 三个双引号可以使字符串跨越多行,并包含引号 +val html = """<form id="daform"> + <p>Press belo', Joe</p> + <input type="submit"> + </form>""" -// Scala 允许方法和函数返回或者接受其它的函数或者方法作为参数。 -val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 -List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +///////////////////////////////////////////////// +// 2. 函数 +///////////////////////////////////////////////// + +// 函数可以这样定义: +// +// def functionName(args...): ReturnType = { body... } +// +// 如果您以前学习过传统的编程语言,注意 return 关键字的省略。 +// 在 Scala 中, 函数代码块最后一条表达式就是返回值。 +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} -// 匿名函数可以被使用来代替有命名的函数: -List(1, 2, 3) map (x => x + 10) +// 如果函数体是单行表达式,{ } 可以省略: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 -List(1, 2, 3) map (_ + 10) +// 函数调用的语法是熟知的: +sumOfSquares(3, 4) // => 25 -// 如果你所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 -List("Dom", "Bob", "Natalia") foreach println +// 在多数情况下 (递归函数是需要注意的例外), 函数返回值可以省略, +// 变量所用的类型推导一样会应用到函数返回值中: +def sq(x: Int) = x * x // 编译器会推断得知返回值是 Int +// 函数可以有默认参数 +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 -// 数据结构 +// 匿名函数是这样的: +(x:Int) => x * x + +// 和 def 不同,如果语义清晰,匿名函数的参数类型也可以省略。 +// 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。 +val sq: Int => Int = x => x * x + +// 匿名函数的调用也是类似的: +sq(10) // => 100 + +// 如果您的匿名函数中每个参数仅使用一次, +// Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见, +// 在数据结构部分会明显可见。 +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// return 关键字是存在的,但它只从最里面包裹了 return 的 def 函数中返回。 +// 警告: 在 Scala 中使用 return 容易出错,应该避免使用。 +// 在匿名函数中没有效果,例如: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // 这一行令 z 成为 foo 函数的返回值! + else + z + 2 // 这一行是 anonFunc 函数的返回值 + } + anonFunc(x) // 这一行是 foo 函数的返回值 +} + +/* + * 译者注:此处是指匿名函数中的 return z 成为最后执行的语句, + * 在 anonFunc(x) 下面的表达式(假设存在)不再执行。如果 anonFunc + * 是用 def 定义的函数, return z 仅返回到 anonFunc(x) , + * 在 anonFunc(x) 下面的表达式(假设存在)会继续执行。 + */ + + +///////////////////////////////////////////////// +// 3. 控制语句 +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// 附注: Scala 对点和括号的要求想当宽松,注意其规则是不同的。 +// 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。 + +(5 to 1 by -1) foreach ( println ) + +// while 循环 +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // 没错,再执行一次,发生了什么?为什么? + +i // 显示 i 的值。注意 while 是经典的循环方式,它连续执行并改变循环中的变量。 + // while 执行很快,比 Java 的循环快,但像上面所看到的那样用组合子和推导式 + // 更易于理解和并行化。 + +// do while 循环 +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Scala 中尾递归是一种符合语言习惯的递归方式。 +// 递归函数需要清晰的返回类型,编译器不能推断得知。 +// 这是一个 Unit。 +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// 条件语句 + +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" + + +///////////////////////////////////////////////// +// 4. 数据结构 +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) -a(21) // 这会抛出一个异常 +a(21) // 抛出异常 val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // 这会抛出一个异常 +m("bottle") // 抛出异常 val safeM = m.withDefaultValue("no lo se") safeM("bottle") @@ -137,9 +288,9 @@ val s = Set(1, 3, 7) s(0) s(1) -/* 查看 map 的文档 - * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) - * 确保你可以读它 +/* 这里查看 map 的文档 - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * 并确保你会阅读 */ @@ -154,13 +305,11 @@ s(1) (a, 2, "three") // 为什么有这个? - val divideInts = (x:Int, y:Int) => (x / y, x % y) -divideInts(10,3) // 函数 divideInts 返回你结果和余数 +divideInts(10,3) // 函数 divideInts 同时返回结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 - val d = divideInts(10,3) d._1 @@ -168,234 +317,289 @@ d._1 d._2 +///////////////////////////////////////////////// +// 5. 面向对象编程 +///////////////////////////////////////////////// -// 选择器 - -s.map(sq) - -val sSquared = s. map(sq) - -sSquared.filter(_ < 10) +/* + 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。 + 这些表达式可以输入到命令行解释器中作为快速测试,但它们不能独立存在于 Scala + 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。相反 Scala 文件 + 允许的顶级结构是: -sSquared.reduce (_+_) + - objects + - classes + - case classes + - traits -// filter 函数接受一个预测(一个函数,形式为 A -> Boolean) 并选择出所有的元素满足这个预测 + 现在来解释这些是什么。 +*/ -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)) +// 类和其他语言的类相似,构造器参数在类名后声明,初始化在类结构体中完成。 +class Dog(br: String) { + // 构造器代码在此 + var breed: String = br + // 定义名为 bark 的方法,返回字符串 + def bark = "Woof, woof!" -// Scala 的 foreach 方法定义在特定的接受一个类型的集合上 -// 返回 Unit(一个 void 方法) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println + // 值和方法作用域假定为 public。"protected" 和 "private" 关键字也是可用的。 + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类必须被声明为 abstract + // abstract class Dog(...) { ... } + // def chaseAfter(what: String): String +} +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" -// For 包含 +// "object" 关键字创造一种类型和该类型的单例。 +// Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例 +// 共用的行为则放入 object 中。两者的区别和其他语言中类方法和静态方法类似。 +// 请注意 object 和 class 可以同名。 +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} -for { n <- s } yield sq(n) -val nSquared2 = for { n <- s } yield sq(n) +// Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类 +// 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值 +// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变 +// 数据。它们通常只有几个方法,且方法几乎没有副作用。 +case class Person(name: String, phoneNumber: String) -for { n <- nSquared2 if n < 10 } yield n +// 创造新实例,注意 case 类不需要使用 "new" 关键字 +val george = Person("George", "1234") +val kate = Person("Kate", "4567") -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +// 使用 case 类,您可以轻松得到一些功能,像 getters: +george.phoneNumber // => "1234" -/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'), - 然而,一个 for-包含 定义了一个两个数据结合间的关系 */ +// 每个字段的相等性比较(无需覆盖 .equals) +Person("George", "1234") == Person("Kate", "1236") // => false +// 简单的拷贝方式 +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") +// 还有很多。case 类同时可以用于模式匹配,接下来会看到。 -// 循环和迭代 -1 to 5 -val r = 1 to 5 -r.foreach( println ) +// 敬请期待 Traits ! -r foreach println -// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。 -// 这帮助你编写读起来像英语的 DSLs 和 APIs -(5 to 1 by -1) foreach ( println ) +///////////////////////////////////////////////// +// 6. 模式匹配 +///////////////////////////////////////////////// -// while 循环 -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - -while (i < 10) { println("i " + i); i+=1 } // 发生了什么?为什么? - -i // 展示 i 的值。注意到 while 是一个传统意义上的循环 - // 它顺序地执行并且改变循环变量的值。while 非常快,比 Java // 循环快, - // 但是在其上使用选择器和包含更容易理解和并行。 - -// do while 循环 -do { - println("x is still less then 10"); - x += 1 -} while (x < 10) +// 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。 +// 附注:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 +// fall-through 现象不会发生。 -// 在 Scala中,尾递归是一种惯用的执行循环的方式。 -// 递归函数需要显示的返回类型,编译器不能推断出类型。 -// 这里它是 Unit。 -def showNumbersInRange(a:Int, b:Int):Unit = { - print(a) - if (a < b) - showNumbersInRange(a + 1, b) +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } +val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则 +// 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。 +// Scala 中您可以匹配很多东西: +def matchEverything(obj: Any): String = obj match { + // 匹配值: + case "Hello world" => "Got the string Hello world" -// 条件语句 - -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") + // 匹配类型: + case x: Double => "Got a Double: " + x -println(if (x == 10) "yeah" else "nope") -val text = if (x == 10) "yeah" else "nope" + // 匹配时指定条件 + case x: Int if x > 10000 => "Got a pretty big number!" -var i = 0 -while (i < 10) { println("i " + i); i+=1 } + // 像之前一样匹配 case 类: + case Person(name, number) => s"Got contact info for $name!" + // 匹配正则表达式: + case email(name, domain) => s"Got email address $name@$domain" + // 匹配元组: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// 面向对象特性 + // 匹配数据结构: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -// 类名是 Dog -class Dog { - //bark 方法,返回字符串 - def bark: String = { - // the body of the method - "Woof, woof!" - } + // 模式可以嵌套 + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -// 类可以包含几乎其它的构造,包括其它的类, -// 函数,方法,对象,case 类,特性等等。 - - +// 事实上,你可以对任何有 "unapply" 方法的对象进行模式匹配。 +// 这个特性如此强大以致于 Scala 允许定义一个函数作为模式匹配: +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} -// Case 类 -case class Person(name:String, phoneNumber:String) +///////////////////////////////////////////////// +// 7. 函数式编程 +///////////////////////////////////////////////// -Person("George", "1234") == Person("Kate", "1236") +// Scala 允许方法和函数作为其他方法和函数的参数和返回值。 +val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +// 匿名函数可以被使用来代替有命名的函数: +List(1, 2, 3) map (x => x + 10) +// 如果匿名函数只有一个参数可以用下划线作为变量 +List(1, 2, 3) map (_ + 10) -// 模式匹配 +// 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 +List("Dom", "Bob", "Natalia") foreach println -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..." } +// 译注: val sq: Int => Int = x => x * x +s.map(sq) -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val sSquared = s. map(sq) -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +sSquared.filter(_ < 10) -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +sSquared.reduce (_+_) -val kate = Person("Kate", "1234") +// filter 函数接受一个 predicate (函数根据条件 A 返回 Boolean)并选择 +// 所有满足 predicate 的元素 +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +// Scala 的 foreach 方法定义在某些集合中,接受一个函数并返回 Unit (void 方法) +// 另请参见: +// http://www.scala-lang.org/api/current/index.html#scala.collection.IterableLike@foreach(f:A=>Unit):Unit +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println +// For 推导式 -// 正则表达式 +for { n <- s } yield sq(n) -val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式 +val nSquared2 = for { n <- s } yield sq(n) -val email(user, domain) = "henry@zkpr.com" +for { n <- nSquared2 if n < 10 } yield n -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name -} +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +/* 注意,这些不是 for 循环,for 循环的语义是‘重复’,然而 for 推导式定义 + 两个数据集合的关系。 */ -// 字符串 +///////////////////////////////////////////////// +// 8. 隐式转换 +///////////////////////////////////////////////// -"Scala 字符串被双引号包围" // -'a' // Scala 字符 -'单引号的字符串不存在' // 错误 -"字符串拥有通常的 Java 方法定义在其上".length -"字符串也有额外的 Scala 方法".reverse +/* 警告 警告: 隐式转换是 Scala 中一套强大的特性,因此容易被滥用。 + * Scala 初学者在理解它们的工作原理和最佳实践之前,应抵制使用它的诱惑。 + * 我们加入这一章节仅因为它们在 Scala 的库中太过常见,导致没有用隐式转换的库 + * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。 + */ -// 参见: scala.collection.immutable.StringOps +// 可以通过 "implicit" 声明任何值(val, 函数,对象等)为隐式值, +// 请注意这些例子中,我们用到第5部分的 Dog 类。 +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// implicit 关键字本身不改变值的行为,所以上面的值可以照常使用。 +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" -val n = 45 -println(s"We have $n apples") +// 区别在于,当另一段代码“需要”隐式值时,这些值现在有资格作为隐式值。 +// 一种情况是隐式函数参数。 +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +// 如果提供值给 “howMany”,函数正常运行 +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" -// 一些字符需要被转义,举例来说,字符串中的双引号: -val a = "They stood outside the \"Rose and Crown\"" +// 如果省略隐式参数,会传一个和参数类型相同的隐式值, +// 在这个例子中, 是 “myImplicitInt": +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" -// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义) +// 隐式的函数参数使我们可以模拟其他函数式语言的 type 类(type classes)。 +// 它经常被用到所以有特定的简写。这两行代码是一样的: +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... -val html = """<form id="daform"> - <p>Press belo', Joe</p> - | <input type="submit"> - </form>""" +// 编译器寻找隐式值另一种情况是你调用方法时 +// obj.method(...) +// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果有一个参数类型为 A +// 返回值类型为 B 的隐式转换,obj 的类型是 A,B 有一个方法叫 "method" ,这样 +// 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" +// 这里字符串先被上面的函数转换为 Dog 对象,然后调用相应的方法。 +// 这是相当强大的特性,但再次提醒,请勿轻率使用。 +// 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解 +// 你正在做什么否则不要使用。 -// 应用结果和组织 +///////////////////////////////////////////////// +// 9. 杂项 +///////////////////////////////////////////////// -// import +// 导入类 import scala.collection.immutable.List -// Import 所有的子包 +// 导入所有子包 import scala.collection.immutable._ -// 在一条语句中 Import 多个类 +// 一条语句导入多个类 import scala.collection.immutable.{List, Map} -// 使用 '=>' 来重命名一个 import +// 使用 ‘=>’ 对导入进行重命名 import scala.collection.immutable.{ List => ImmutableList } -// import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类: +// 导入所有类,排除其中一些。下面的语句排除了 Map 和 Set: import scala.collection.immutable.{Map => _, Set => _, _} -// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义: - +// 在 Scala 文件用 object 和单一的 main 方法定义程序入口: object Application { def main(args: Array[String]): Unit = { // stuff goes here. } } -// 文件可以包含多个类和对象。由 scalac 来编译 +// 文件可以包含多个 class 和 object,用 scalac 编译源文件 // 输入和输出 -// 一行一行读取文件 +// 按行读文件 import scala.io.Source -for(line <- Source.fromPath("myfile.txt").getLines()) +for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -// 使用 Java 的 PrintWriter 来写文件 - +// 用 Java 的 PrintWriter 写文件 +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() ``` diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index b9696c72..3efe4941 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -5,223 +5,610 @@ contributors: - ["Grant Timmerman", "http://github.com/grant"] translators: - ["Xavier Yao", "http://github.com/xavieryao"] + - ["Joey Huang", "http://github.com/kamidox"] + - ["CY Lim", "http://github.com/cylim"] lang: zh-cn --- -Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014年Apple WWDC (全球开发者大会)中被引入,用以与Objective-C 共存,同时对错误代码更具弹性。Swift 由Xcode 6 beta 中包含的LLVM编译器编译。 +Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。 -参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程 +Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载. + +亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程 ```swift +// 导入外部模块 +import UIKit + // -// 基础 +// MARK: 基础 // -println("Hello, world") +// XCODE 支持给注释代码作标记,这些标记会列在 XCODE 的跳转栏里,支持的标记为 +// MARK: 普通标记 +// TODO: TODO 标记 +// FIXME: FIXME 标记 + +// Swift2.0 println() 及 print() 已经整合成 print()。 +print("Hello, world") // 这是原本的 println(),会自动进入下一行 +print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false + +// 变量 (var) 的值设置后可以随意改变 +// 常量 (let) 的值设置后不能改变 var myVariable = 42 +let øπΩ = "value" // 可以支持 unicode 变量名 +let π = 3.1415926 let myConstant = 3.1415926 -let explicitDouble: Double = 70 -let label = "some text " + String(myVariable) // Casting -let piText = "Pi = \(myConstant)" // String interpolation -var optionalString: String? = "optional" // Can be nil -optionalString = nil +let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型 +let weak = "keyword"; let override = "another keyword" // 语句之间可以用分号隔开,语句未尾不需要分号 +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // 类型转换 +let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串 + +// 条件编译 +// 使用 -D 定义编译开关 +#if false + print("Not printed") + let buildValue = 3 +#else + let buildValue = 7 +#endif +print("Build value: \(buildValue)") // Build value: 7 + +/* + Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。 + 可在值名称后加个问号 (?) 来表示这个值是 Optional。 + + Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil + + Optional<T> 是个枚举类型 +*/ +var someOptionalString: String? = "optional" // 可以是 nil +// 下面的语句和上面完全等价,上面的写法更推荐,因为它更简洁,问号 (?) 是 Swift 提供的语法糖 +var someOptionalString2: Optional<String> = "optional" + +if someOptionalString != nil { + // 变量不为空 + if someOptionalString!.hasPrefix("opt") { + print("has the prefix") + } + + let empty = someOptionalString?.isEmpty +} +someOptionalString = nil + +/* + 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。 +*/ + +// 显式解包 optional 变量 +var unwrappedString: String! = "Value is expected." +// 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖 +var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected." + +if let someOptionalStringConstant = someOptionalString { + // 由于变量 someOptinalString 有值,不为空,所以 if 条件为真 + if !someOptionalStringConstant.hasPrefix("ok") { + // does not have the prefix + } +} + +// Swift 支持可保存任何数据类型的变量 +// AnyObject == id +// 和 Objective-C `id` 不一样, AnyObject 可以保存任何类型的值 (Class, Int, struct, 等) +var anyObjectVar: AnyObject = 7 +anyObjectVar = "Changed value to a string, not good practice, but possible." + +/* + 这里是注释 + + /* + 支持嵌套的注释 + */ +*/ // -// 数组与字典(关联数组) +// Mark: 数组与字典(关联数组) // -// 数组 +/* + Array 和 Dictionary 是结构体,不是类,他们作为函数参数时,是用值传递而不是指针传递。 + 可以用 `var` 和 `let` 来定义变量和常量。 +*/ + +// Array var shoppingList = ["catfish", "water", "lemons"] shoppingList[1] = "bottle of water" -let emptyArray = String[]() +let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容 +let emptyArray2 = Array<String>() // 与上一语句等价,上一语句更常用 +var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素 +var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价 // 字典 var occupations = [ - "Malcolm": "Captain", - "kaylee": "Mechanic" + "Malcolm": "Captain", + "kaylee": "Mechanic" ] -occupations["Jayne"] = "Public Relations" -let emptyDictionary = Dictionary<String, Float>() +occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存在,自动添加一个字典元素 +let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值 +let emptyDictionary2 = Dictionary<String, Float>() // 与上一语句类型等价,上一语句更常用 +var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量 +var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价 // -// 控制流 +// MARK: 控制流 // -// 用于数组的for 循环 +// 数组的 for 循环 let myArray = [1, 1, 2, 3, 5] for value in myArray { - if value == 1 { - println("One!") - } else { - println("Not one!") - } + if value == 1 { + print("One!") + } else { + print("Not one!") + } } -// 用于字典的for 循环 +// 字典的 for 循环 +var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } -// 用于区间的for 循环 -for i in -1...1 { // [-1, 0, 1] - println(i) +// 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3) +for i in -1...shoppingList.count { + print(i) } -// 使用 .. 表示的区间不包含最后一个元素 [-1,0,1) +shoppingList[1...2] = ["steak", "peacons"] +// 可以使用 `..<` 来去掉最后一个元素 // while 循环 var i = 1 while i < 1000 { - i *= 2 + i *= 2 } // do-while 循环 do { - println("hello") + print("hello") } while 1 == 2 -// Switch +// Switch 语句 +// Swift 里的 Switch 语句功能异常强大,结合枚举类型,可以实现非常简洁的代码,可以把 switch 语句想象成 `if` 的语法糖 +// 它支持字符串,类实例或原生数据类型 (Int, Double, etc) let vegetable = "red pepper" switch vegetable { case "celery": - let vegetableComment = "Add some raisins and make ants on a log." + let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": - let vegetableComment = "That would make a good tea sandwich." -case let x where x.hasSuffix("pepper"): - let vegetableComment = "Is it a spicy \(x)?" -default: // 必须 (为了覆盖所有可能的输入) - let vegetableComment = "Everything tastes good in soup." + let vegetableComment = "That would make a good tea sandwich." +case let localScopeValue where localScopeValue.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(localScopeValue)?" +default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句 + let vegetableComment = "Everything tastes good in soup." } // -// 函数 +// MARK: 函数 // -// 函数是一等类型,这意味着可以在函数中构建函数 -// 并且可以被传递 +// 函数是一个 first-class 类型,他们可以嵌套,可以作为函数参数传递 -// 函数 +// 函数文档可使用 reStructedText 格式直接写在函数的头部 +/** + A greet operation + + - A bullet in docs + - Another bullet in the docs + + :param: name A name + :param: day A day + :returns: A string containing the name and day value. +*/ func greet(name: String, day: String) -> String { - return "Hello \(name), today is \(day)." + return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday") -// 使用多元数组返回多返回值的函数 -func getGasPrices() -> (Double, Double, Double) { - return (3.59, 3.69, 3.79) +// 函数参数前带 `#` 表示外部参数名和内部参数名使用同一个名称。 +// 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName` +func greet2(#requiredName: String, externalParamName localParamName: String) -> String { + return "Hello \(requiredName), the day is \(localParamName)" } +greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值 -// 不定参数 -func setup(numbers: Int...) {} +// 函数可以通过元组 (tuple) 返回多个值 +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let pricesTuple = getGasPrices() +let price = pricesTuple.2 // 3.79 +// 通过下划线 (_) 来忽略不关心的值 +let (_, price1, _) = pricesTuple // price1 == 3.69 +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") + +// 可变参数 +func setup(numbers: Int...) { + // 可变参数是个数组 + let number = numbers[0] + let argCount = numbers.count +} -// 传递、返回函数 +// 函数变量以及函数作为返回值返回 func makeIncrementer() -> (Int -> Int) { - func addOne(number: Int) -> Int { - return 1 + number - } - return addOne + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne } var increment = makeIncrementer() increment(7) +// 强制进行指针传递 (引用传递),使用 `inout` 关键字修饰函数参数 +func swapTwoInts(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +swapTwoInts(&someIntA, &someIntB) +print(someIntB) // 7 + // -// 闭包 +// MARK: 闭包 // +var numbers = [1, 2, 6] -// 函数是特殊的闭包({}) +// 函数是闭包的一个特例 ({}) -// 闭包示例. -// `->` 分隔参数和返回类型 -// `in` 分隔闭包头和闭包体 +// 闭包实例 +// `->` 分隔了闭包的参数和返回值 +// `in` 分隔了闭包头 (包括参数及返回值) 和闭包体 +// 下面例子中,`map` 的参数是一个函数类型,它的功能是把数组里的元素作为参数,逐个调用 `map` 参数传递进来的函数。 numbers.map({ - (number: Int) -> Int in - let result = 3 * number - return result - }) + (number: Int) -> Int in + let result = 3 * number + return result +}) -// 当类型已知时,可以这样做: -var numbers = [1, 2, 6] +// 当闭包的参数类型和返回值都是己知的情况下,且只有一个语句作为其返回值时,我们可以简化闭包的写法 numbers = numbers.map({ number in 3 * number }) +// 我们也可以使用 $0, $1 来指代第 1 个,第 2 个参数,上面的语句最终可简写为如下形式 +// numbers = numbers.map({ $0 * 3 }) + +print(numbers) // [3, 6, 18] + +// 简洁的闭包 +numbers = sorted(numbers) { $0 > $1 } +// 函数的最后一个参数可以放在括号之外,上面的语句是这个语句的简写形式 +// numbers = sorted(numbers, { $0 > $1 }) + +print(numbers) // [18, 6, 3] + +// 超级简洁的闭包,因为 `<` 是个操作符函数 +numbers = sorted(numbers, < ) + print(numbers) // [3, 6, 18] // -// 类 +// MARK: 结构体 // -// 类的全部方法和属性都是public 的 -// 如果你在一个数据结构中只需储存数据, -// 应使用 `struct` +// 结构体和类非常类似,可以有属性和方法 -// 集成自`Shape` 类的简单的类`Square -class Rect: Shape { - var sideLength: Int = 1 +struct NamesTable { + let names = [String]() - // Custom getter and setter property - var perimeter: Int { - get { - return 4 * sideLength + // 自定义下标运算符 + subscript(index: Int) -> String { + return names[index] } - set { - sideLength = newValue / 4 +} + +// 结构体有一个自动生成的隐含的命名构造函数 +let namesTable = NamesTable(names: ["Me", "Them"]) +let name = namesTable[1] +print("Name is \(name)") // Name is Them + +// +// MARK: 类 +// + +// 类和结构体的有三个访问控制级别,他们分别是 internal (默认), public, private +// internal: 模块内部可以访问 +// public: 其他模块可以访问 +// private: 只有定义这个类或结构体的源文件才能访问 + +public class Shape { + public func getArea() -> Int { + return 0; + } +} + +// 类的所有方法和属性都是 public 的 +// 如果你只是需要把数据保存在一个结构化的实例里面,应该用结构体 + +internal class Rect: Shape { + // 值属性 (Stored properties) + var sideLength: Int = 1 + + // 计算属性 (Computed properties) + private var perimeter: Int { + get { + return 4 * sideLength + } + set { + // `newValue` 是个隐含的变量,它表示将要设置进来的新值 + sideLength = newValue / 4 + } + } + + // 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化 + // subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例 + lazy var subShape = Rect(sideLength: 4) + + // 监控属性值的变化。 + // 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数 + // `willSet`: 值改变之前被调用 + // `didSet`: 值改变之后被调用 + var identifier: String = "defaultID" { + // `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue` + willSet(someIdentifier) { + print(someIdentifier) + } + // `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue` + didSet { + print(oldValue) + } + } + + // 命名构造函数 (designated inits),它必须初始化所有的成员变量, + // 然后调用父类的命名构造函数继续初始化父类的所有变量。 + init(sideLength: Int) { + self.sideLength = sideLength + // 必须显式地在构造函数最后调用父类的构造函数 super.init + super.init() } - } - init(sideLength: Int) { - super.init() - self.sideLength = sideLength - } + func shrink() { + if sideLength > 0 { + --sideLength + } + } - func shrink() { - if sideLength > 0 { - --sideLength + // 函数重载使用 override 关键字 + override func getArea() -> Int { + return sideLength * sideLength } - } +} - override func getArea() -> Int { - return sideLength * sideLength - } +// 类 `Square` 从 `Rect` 继承 +class Square: Rect { + // 便捷构造函数 (convenience inits) 是调用自己的命名构造函数 (designated inits) 的构造函数 + // Square 自动继承了父类的命名构造函数 + convenience init() { + self.init(sideLength: 5) + } + // 关于构造函数的继承,有以下几个规则: + // 1. 如果你没有实现任何命名构造函数,那么你就继承了父类的所有命名构造函数 + // 2. 如果你重载了父类的所有命名构造函数,那么你就自动继承了所有的父类快捷构造函数 + // 3. 如果你没有实现任何构造函数,那么你继承了父类的所有构造函数,包括命名构造函数和便捷构造函数 } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square() print(mySquare.getArea()) // 25 mySquare.shrink() print(mySquare.sideLength) // 4 -// 如果你不需要自定义getter 和setter, -// 但仍希望在获取或设置一个属性之前或之后运行 -// 一些代码,你可以使用`willSet` 和 `didSet` +// 类型转换 +let aShape = mySquare as Shape + +// 使用三个等号来比较是不是同一个实例 +if mySquare === aShape { + print("Yep, it's mySquare") +} + +class Circle: Shape { + var radius: Int + override func getArea() -> Int { + return 3 * radius * radius + } + + // optional 构造函数,可能会返回 nil + init?(radius: Int) { + self.radius = radius + super.init() + + if radius <= 0 { + return nil + } + } +} + +// 根据 Swift 类型推断,myCircle 是 Optional<Circle> 类型的变量 +var myCircle = Circle(radius: 1) +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 +var myEmptyCircle = Circle(radius: -1) +print(myEmptyCircle?.getArea()) // "nil" +if let circle = myEmptyCircle { + // 此语句不会输出,因为 myEmptyCircle 变量值为 nil + print("circle is not nil") +} // -// 枚举类型 +// MARK: 枚举 // -// 枚举类型可以是某种指定的类型,抑或自成一种类型 -// 像类一样,枚举类型可以包含方法 +// 枚举可以像类一样,拥有方法 enum Suit { - case Spades, Hearts, Diamonds, Clubs - func getIcon() -> String { - switch self { - case .Spades: return "♤" - case .Hearts: return "♡" - case .Diamonds: return "♢" - case .Clubs: return "♧" + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + +// 当变量类型明确指定为某个枚举类型时,赋值时可以省略枚举类型 +var suitValue: Suit = .Hearts + +// 非整型的枚举类型需要在定义时赋值 +enum BookName: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(BookName.John.rawValue)") + +// 与特定数据类型关联的枚举 +enum Furniture { + // 和 Int 型数据关联的枚举记录 + case Desk(height: Int) + // 和 String, Int 关联的枚举记录 + case Chair(brand: String, height: Int) + + func description() -> String { + switch self { + case .Desk(let height): + return "Desk with \(height) cm" + case .Chair(let brand, let height): + return "Chair of \(brand) with \(height) cm" + } } - } } +var desk: Furniture = .Desk(height: 80) +print(desk.description()) // "Desk with 80 cm" +var chair = Furniture.Chair(brand: "Foo", height: 40) +print(chair.description()) // "Chair of Foo with 40 cm" + // -// 其它 +// MARK: 协议 +// 与 Java 的 interface 类似 // -// `协议(protocol)`: 与Java 的接口(Interface) 类似. -// `扩展(extension)`: 为现有类型添加额外特性 -// 泛型: 与Java 相似。使用`where` 关键字指定 -// 泛型的要求. +// 协议可以让遵循同一协议的类型实例拥有相同的属性,方法,类方法,操作符或下标运算符等 +// 下面代码定义一个协议,这个协议包含一个名为 enabled 的计算属性且包含 buildShape 方法 +protocol ShapeGenerator { + var enabled: Bool { get set } + func buildShape() -> Shape +} + +// 协议声明时可以添加 @objc 前缀,添加 @objc 前缀后, +// 可以使用 is, as, as? 等来检查协议兼容性 +// 需要注意,添加 @objc 前缀后,协议就只能被类来实现, +// 结构体和枚举不能实现加了 @objc 的前缀 +// 只有添加了 @objc 前缀的协议才能声明 optional 方法 +// 一个类实现一个带 optional 方法的协议时,可以实现或不实现这个方法 +// optional 方法可以使用 optional 规则来调用 +@objc protocol TransformShape { + optional func reshaped() + optional func canReshape() -> Bool +} + +class MyShape: Rect { + var delegate: TransformShape? + + func grow() { + sideLength += 2 + + // 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。 + // 这样就不会引起运行时错误 (runtime error) + if let allow = self.delegate?.canReshape?() { + // 注意语句中的问号 + self.delegate?.reshaped?() + } + } +} + + +// +// MARK: 其它 +// + +// 扩展: 给一个已经存在的数据类型添加功能 + +// 给 Square 类添加 `Printable` 协议的实现,现在其支持 `Printable` 协议 +extension Square: Printable { + var description: String { + return "Area: \(self.getArea()) - ID: \(self.identifier)" + } +} + +print("Square: \(mySquare)") // Area: 16 - ID: defaultID + +// 也可以给系统内置类型添加功能支持 +extension Int { + var customProperty: String { + return "This is \(self)" + } + + func multiplyBy(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 + +// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。 +// 如果只有一个类型限制,可以省略 `where` 关键字 +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { + for (index, value) in enumerate(array) { + if value == valueToFind { + return index + } + } + return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +print(foundAtIndex == 2) // true + +// 自定义运算符: +// 自定义运算符可以以下面的字符打头: +// / = - + * % < > ! & | ^ . ~ +// 甚至是 Unicode 的数学运算符等 +prefix operator !!! {} + +// 定义一个前缀运算符,使矩形的边长放大三倍 +prefix func !!! (inout shape: Square) -> Square { + shape.sideLength *= 3 + return shape +} + +// 当前值 +print(mySquare.sideLength) // 4 + +// 使用自定义的 !!! 运算符来把矩形边长放大三倍 +!!!mySquare +print(mySquare.sideLength) // 12 + +// 运算符也可以是泛型 +infix operator <-> {} +func <-><T: Equatable> (inout a: T, inout b: T) { + let c = a + a = b + b = c +} + +var foo: Float = 10 +var bar: Float = 20 + +foo <-> bar +print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0" ``` |