diff options
54 files changed, 5952 insertions, 1024 deletions
diff --git a/bash.html.markdown b/bash.html.markdown index 3b163638..08182c2c 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,32 +32,41 @@ 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 $. # 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 @@ -64,16 +74,16 @@ echo "Last program return value: $?" echo "Script's PID: $$" echo "Number of arguments: $#" echo "Scripts arguments: $@" -echo "Scripts arguments seperated in different variables: $1 $2..." +echo "Scripts arguments separated in 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 @@ -85,14 +95,14 @@ 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: @@ -134,7 +144,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 +152,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 +171,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 +179,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 +193,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 +230,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,11 +245,13 @@ 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) +# if you literally want to search for the string, +# and not the regex, use fgrep (or grep -F) fgrep "^foo.*bar$" file.txt 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 67fa054c..ff2a98fd 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -30,10 +30,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,6 +50,8 @@ int main(int argc, char** argv) return 0; } +// However, C++ varies in some of the following ways: + // In C++, character literals are one byte. sizeof('c') == 1 @@ -287,7 +288,7 @@ 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. @@ -299,7 +300,7 @@ public: }; // 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 +323,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,7 +332,7 @@ 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" @@ -340,7 +341,7 @@ int main() { // This class inherits everything public and protected from the Dog class 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 +425,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 +433,85 @@ int main () { } ///////////////////// +// Templates +///////////////////// + +// Templates in C++ are mostly used for generic programming, though they are +// much more powerful than generics constructs in other languages. It also +// supports explicit and partial specialization, functional-style type classes, +// and also it's Turing-complete. + +// 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, and 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); + +// Up until C++11, you must place a space between the two '>'s, otherwise '>>' +// will be parsed as the right shift operator. + +// You will sometimes see +// template<typename T> +// instead. The 'class' keyword and 'typename' keyword are _mostly_ +// interchangeable in this case. For 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,12 +519,13 @@ 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) @@ -535,7 +616,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 +634,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 +665,56 @@ 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 + + +///////////////////// +// 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. + +// But somehow 'bool' type is an exception (this is to make `if (ptr)` compile). +*pt = nullptr; // This still compiles, even though '*pt' is a bool! + + +// '=' != '=' != '='! +// Calls Foo::Foo(const Foo&) or some variant 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; + ``` -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 1696d28f..d3f20eda 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -234,7 +234,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 +242,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 diff --git a/clojure-macros.html.markdown b/clojure-macros.html.markdown index 8e671936..9e907a7f 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) diff --git a/clojure.html.markdown b/clojure.html.markdown index 7917ab08..a125d18f 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 diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index c4ecb5e8..f9f64d68 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -573,13 +573,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/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index ca27fdc7..83d59c8b 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -5,34 +5,34 @@ contributors: - ["Joseph Adams", "https://github.com/jcla1"] 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 Pkaetname, 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 ) @@ -42,10 +42,10 @@ import ( // 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,7 +54,7 @@ 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 + // Kurze Deklaration: Benutzen Sie ":=", um die Typisierung automatisch zu // folgern, die Variable zu deklarieren und ihr einen Wert zu zuweisen. y := 4 @@ -70,7 +70,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 +111,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,7 +142,7 @@ 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 { @@ -170,7 +170,7 @@ func learnFlowControl() { 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 +217,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,18 +244,18 @@ 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) @@ -269,16 +269,16 @@ func learnConcurrency() { // 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. @@ -287,16 +287,16 @@ func learnConcurrency() { 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 @@ -313,6 +313,6 @@ 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/). +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/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/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/erlang.html.markdown b/erlang.html.markdown index 04086aeb..a3b571d1 100644 --- a/erlang.html.markdown +++ b/erlang.html.markdown @@ -18,7 +18,7 @@ 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. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% @@ -27,20 +27,20 @@ filename: learnerlang.erl 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. `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 +53,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 +117,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 +142,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 +158,24 @@ 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. +% 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 +198,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 +216,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 +228,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 +237,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 +251,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). @@ -272,12 +283,13 @@ 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> ``` 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/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/r-fr.html.markdown b/fr-fr/r-fr.html.markdown new file mode 100644 index 00000000..3f225a0f --- /dev/null +++ b/fr-fr/r-fr.html.markdown @@ -0,0 +1,746 @@ +--- +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 +--- + +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/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/go.html.markdown b/go.html.markdown index 17f10bd9..34b855e3 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -64,7 +64,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 +87,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 @@ -177,8 +181,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. diff --git a/groovy.html.markdown b/groovy.html.markdown index 8fb1b346..629b6d18 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -405,7 +405,7 @@ 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/) diff --git a/haskell.html.markdown b/haskell.html.markdown index 79fbf09f..6a64442f 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -148,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) @@ -181,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 @@ -202,19 +202,20 @@ foo = (*5) . (+10) foo 5 -- 75 -- 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 +(even (fib 7)) -- false -- after -even . fib $ 7 -- true +even . fib $ 7 -- false -- equivalently -even $ fib 7 -- true +even $ fib 7 -- false ---------------------------------------------------- -- 5. Type signatures @@ -281,7 +282,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 @@ -319,13 +320,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 @@ -339,43 +340,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 8599de8d..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"; @@ -487,8 +495,10 @@ class LearnHaxe3{ // 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/it-it/bash-it.html.markdown b/it-it/bash-it.html.markdown new file mode 100644 index 00000000..f892845f --- /dev/null +++ b/it-it/bash-it.html.markdown @@ -0,0 +1,275 @@ +--- +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/"] +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 piu'.](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 +echo ${VARIABILE:0:7} +# Questo ritornerà solamente i primi 7 caratteri + +# Valore di default per la variabile +echo ${FOO:-"ValoreDiDefaultSeFOOMancaOÈ Vuoto"} +# Questo funziona per null (FOO=), stringa vuota (FOO=""), zero (FOO=0) ritorna 0 + +# 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 + +# 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 $NAME è 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.txt, 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.txt 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/c++-it.html.markdown b/it-it/c++-it.html.markdown new file mode 100644 index 00000000..4f5ac8a2 --- /dev/null +++ b/it-it/c++-it.html.markdown @@ -0,0 +1,720 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +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 da un byte. +sizeof('c') == 1 + +// In C, i caratteri come letterali sono della stessa dimensione degli interi. +sizeof('c') == sizeof(10) + + +// 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() +{ + // Assume che tutto venga dal namespace "Secondo" + // a meno che non venga dichiarato altrimenti. + using namespace 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. +fooRef = bar; + +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. + +////////////////////////////////////////////////// +// 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. + virtual ~Dog(); + +}; // Un punto e virgola deve seguire la definizione della funzione + +// Le funzioni membro di una classe sono generalmente implementate in files .cpp . +void 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"; +} + +void 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 +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 { + // 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> + +// 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::exception("È avvenuto 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::exception("Non è stato possibile aprire il 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. + +// Ma in qualche modo il tipo 'bool' è una eccezione (questo è per rendere compilabile `if (ptr)`. +*pt = nullptr; // Questo compila, anche se '*pt' è un bool! + + +// '=' != '=' != '='! +// Chiama Foo::Foo(const Foo&) o qualche variante 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; + +``` +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/json-it.html.markdown b/it-it/json-it.html.markdown new file mode 100644 index 00000000..0c401753 --- /dev/null +++ b/it-it/json-it.html.markdown @@ -0,0 +1,62 @@ +--- + +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] + - ["Marco Scannadinari", "https://github.com/marcoms"] +translators: + - ["Robert Margelli", "http://github.com/sinkswim/"] +lang: it-it + +--- + +Dato che JSON è un formato per lo scambio di dati estremamente semplice, 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è. + +```json +{ + "chiave": "valore", + + "chiavi": "devono sempre essere racchiuse tra doppi apici", + "numeri": 0, + "stringhe": "Ciaø, møndø. Tutti gli unicode sono permessi, assieme con l \"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 quà!" + , "posizione della virgola": "non conta - fintantochè è prima del valore, 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/java.html.markdown b/java.html.markdown index ebe11bd3..928eb39f 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1,16 +1,16 @@ --- - language: java contributors: - ["Jake Prather", "http://github.com/JakeHP"] - - ["Madison Dickson", "http://github.com/mix3d"] - ["Jakukyo Friel", "http://weakish.github.io"] + - ["Madison Dickson", "http://github.com/mix3d"] + - ["Simon Morgan", "http://sjm.io/"] 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 // @@ -31,17 +31,17 @@ import java.security.*; // the file. public class LearnJava { - // A program must have a main method as an entry point + // A program 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"); @@ -69,7 +69,7 @@ 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 float fooFloat = 234.5f; @@ -86,7 +86,7 @@ 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; // Strings @@ -101,17 +101,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 @@ -122,17 +122,17 @@ 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 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. /////////////////////////////////////// // Operators @@ -160,13 +160,13 @@ public class LearnJava { // 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 right shift + >>> Unsigned right shift + & Bitwise AND + ^ Bitwise exclusive OR + | Bitwise inclusive OR */ // Incrementations @@ -175,10 +175,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 @@ -197,73 +197,69 @@ 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 (fooFor = 0; fooFor < 10; fooFor++) { + System.out.println(fooFor); + // Iterated 10 times, fooFor 0->9 } System.out.println("fooFor Value: " + fooFor); // 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"; - break; - case 2: - monthString = "February"; + switch (month) { + case 1: monthString = "January"; break; - case 3: - monthString = "March"; + case 2: monthString = "February"; break; - default: - monthString = "Some other month"; + case 3: monthString = "March"; break; + default: monthString = "Some other month"; + break; } System.out.println("Switch Case Result: " + monthString); // 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 @@ -287,9 +283,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 @@ -319,9 +314,9 @@ public class LearnJava { // 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 { @@ -342,7 +337,8 @@ 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; @@ -388,10 +384,8 @@ class Bicycle { //Method to display the attribute values of this Object. @Override public String toString() { - return "gear: " + gear + - " cadence: " + cadence + - " speed: " + speed + - " name: " + name; + return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + + " name: " + name; } } // end class Bicycle @@ -405,26 +399,26 @@ 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 { @@ -432,33 +426,31 @@ public interface Digestible { } -//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 { @Override public void eat() { - //... + // ... } @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 { +// 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() { - } @Override public void InterfaceTwoMethod() { - } } - ``` ## Further Reading @@ -500,5 +492,3 @@ The links provided here below are just to get an understanding of the topic, fee * [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/json.html.markdown b/json.html.markdown index f5287138..f57b82b8 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -10,7 +10,7 @@ As JSON is an extremely simple data-interchange format, this is most likely goin 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 +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 diff --git a/julia.html.markdown b/julia.html.markdown index 3a52018c..5ccd6484 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -8,7 +8,7 @@ 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 @@ -91,7 +91,7 @@ false # $ 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 @@ -190,7 +190,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 +264,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 diff --git a/nim.html.markdown b/nim.html.markdown index aa15e591..c9548a1c 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -155,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 @@ -174,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 @@ -263,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 Library](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/perl6.html.markdown b/perl6.html.markdown index 85ab1d79..3bb87916 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -10,8 +10,7 @@ contributors: Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +Perl 6 runs on [the MoarVM](http://moarvm.com) and the JVM. Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. @@ -211,7 +210,7 @@ say $x; #=> 52 # - `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 { @@ -253,7 +252,9 @@ given "foo bar" { 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) ~~ True {...} + # if $_ ~~ ($_.chars > 50) {...} + # Which means: + # if $_.chars > 50 {...} say "Quite a long string !"; } default { # same as `when *` (using the Whatever Star) @@ -305,37 +306,9 @@ if long-computation() -> $result { say "The result is $result"; } -# 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. -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. - -# You need to be aware of when flattening happens exactly. -# The general guideline is that argument lists flatten, but not method calls. -# Also note that `.list` and array assignment flatten (`@ary = ...`) flatten. -((1,2), 3, (4,5)).map({...}); # iterates over three elements (method call) -map {...}, ((1,2),3,(4,5)); # iterates over five elements (argument list is flattened) - -(@a, @b, @c).pick(1); # picks one of three arrays (method call) -pick 1, @a, @b, @c; # flattens argument list and pick one element - ### 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,17 +367,21 @@ 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. - -# 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 - +# 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 }]); + +# You can use that in most places you'd expect, even assigning to an array +my @numbers = ^20; +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`. @@ -416,7 +393,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 @@ -426,7 +403,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 @@ -560,7 +537,7 @@ subset VeryBigInteger of Int where * > 500; multi sub sayit(Int $n) { # note the `multi` keyword here say "Number: $n"; } -multi sayit(Str $s) } # a multi is a `sub` by default +multi sayit(Str $s) { # a multi is a `sub` by default say "String: $s"; } sayit("foo"); # prints "String: foo" @@ -963,7 +940,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 !! diff --git a/php.html.markdown b/php.html.markdown index 039288a0..2d4565e0 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -60,7 +60,7 @@ $float = 1.2e3; $float = 7E-10; // Delete variable -unset($int1) +unset($int1); // Arithmetic $sum = 1 + 1; // 2 diff --git a/pt-br/brainfuck-pt.html.markdown b/pt-br/brainfuck-pt.html.markdown new file mode 100644 index 00000000..c7ce55ee --- /dev/null +++ b/pt-br/brainfuck-pt.html.markdown @@ -0,0 +1,84 @@ +--- +language: brainfuck +contributors: + - ["Prajit Ramachandran", "http://prajitr.github.io/"] + - ["Mathias Bynens", "http://mathiasbynens.be/"] +translators: + - ["Suzane Sant Ana", "http://github.com/suuuzi"] +lang: pt-br +--- + +Brainfuck (em letras minúsculas, eceto 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 vaor 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/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-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/python.html.markdown b/python.html.markdown index da04d381..ace3f794 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -14,7 +14,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 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. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). ```python @@ -46,7 +46,7 @@ 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 @@ -101,6 +101,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" @@ -139,12 +141,8 @@ bool("") # => False ## 2. Variables and Collections #################################################### -# Python has a print statement, in all 2.x versions but removed from 3. +# Python has a print statement 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! ") # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores @@ -193,14 +191,14 @@ 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] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] - +r # You can add lists li + other_li # => [1, 2, 3, 4, 5, 6] # Note: values for li and for other_li are not modified. @@ -314,11 +312,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." """ @@ -330,7 +328,7 @@ prints: """ for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings - print("%s is a mammal" % animal) + print "%s is a mammal" % animal """ "range(number)" returns a list of numbers @@ -342,7 +340,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 +364,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 @@ -377,7 +387,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 %s and y is %s" % (x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -406,8 +416,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,14 +439,14 @@ def pass_all_the_args(*args, **kwargs): print varargs(*args) print keyword_args(**kwargs) -# Function Scope +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 - + def setGlobalX(num): global x print x # => 5 @@ -503,10 +513,10 @@ class Human(object): # 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" @@ -526,12 +536,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 +587,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,8 +616,8 @@ 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? diff --git a/python3.html.markdown b/python3.html.markdown index 6b1d3156..a112912f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -13,7 +13,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 @@ -39,7 +39,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria # Except division which returns floats by default 35 / 5 # => 7.0 -# 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 @@ -73,8 +73,8 @@ False or True #=> True # Note using Bool operators with ints 0 and 2 #=> 0 -5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False +0 == False #=> True +2 == True #=> False 1 == True #=> True # Equality is == @@ -101,6 +101,8 @@ False or True #=> True # 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' @@ -143,7 +145,7 @@ bool({}) #=> False # Python has a print function print("I'm Python. Nice to meet you!") -# 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 @@ -184,7 +186,7 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list +# 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] @@ -194,7 +196,7 @@ del li[2] # li is now [1, 2, 3] # 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] @@ -211,7 +213,7 @@ tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError -# You can do all those list thingies on tuples too +# 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) @@ -233,15 +235,15 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] 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. +# 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. +# 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] @@ -276,10 +278,10 @@ 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} -#Can set new variables to a set +# Can set new variables to a set filled_set = some_set -# Add one more item to the set +# Add one more item to the set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & @@ -326,7 +328,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 +340,18 @@ 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) + +""" While loops go until a condition is no longer met. prints: 0 @@ -394,7 +408,6 @@ our_iterator.__next__() # Raises StopIteration list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - #################################################### ## 4. Functions #################################################### @@ -410,7 +423,6 @@ 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. - # You can define functions that take a variable number of # positional arguments def varargs(*args): @@ -418,7 +430,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword arguments, as well def keyword_args(**kwargs): @@ -447,14 +458,14 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) -# Function Scope +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 print (x) # => 43 - + def setGlobalX(num): global x print (x) # => 5 @@ -501,7 +512,9 @@ 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 @@ -587,7 +600,7 @@ def double_numbers(iterable): # 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 @@ -636,6 +649,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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) ### Dead Tree diff --git a/racket.html.markdown b/racket.html.markdown index 6abc8759..e345db8b 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/ru-ru/bash-ru.html.markdown b/ru-ru/bash-ru.html.markdown new file mode 100644 index 00000000..e6741b1b --- /dev/null +++ b/ru-ru/bash-ru.html.markdown @@ -0,0 +1,283 @@ +--- +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"] +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/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index e7398c88..79844565 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -22,8 +22,8 @@ Google Chrome, становится все более популярной. ```js // Си-подобные комментарии. Однострочные комментарии начинаются с двух символов слэш, -/* а многострочные комментарии начинаются с звёздочка-слэш - и заканчиваются символами слэш-звёздочка */ +/* а многострочные комментарии начинаются с последовательности слэш-звёздочка + и заканчиваются символами звёздочка-слэш */ // Инструкции могут заканчиваться точкой с запятой ; doStuff(); diff --git a/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown index fd95c876..2a7b3f7b 100644 --- a/ru-ru/python3-ru.html.markdown +++ b/ru-ru/python3-ru.html.markdown @@ -593,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/ruby.html.markdown b/ruby.html.markdown index 1883d1ad..792c9c95 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -11,6 +11,7 @@ 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"] --- @@ -169,6 +170,9 @@ array[1..3] #=> [2, 3, 4] # Add to an array like this array << 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: hash = { 'color' => 'green', 'number' => 5 } @@ -188,6 +192,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 diff --git a/rust.html.markdown b/rust.html.markdown index dcb54733..17f7dc90 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -6,14 +6,21 @@ 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* without resorting to garbage collection. Rust’s first -release, 0.1, 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. On January 9 2015, Rust 1.0 Alpha was released, and the rate of -changes to the Rust compiler that break existing code has dropped significantly -since. However, a complete guarantee of backward compatibility will not exist -until the final 1.0 release. +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 advise 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 diff --git a/scala.html.markdown b/scala.html.markdown index ed1ddabb..e6638121 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -186,7 +186,7 @@ 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. @@ -465,6 +465,7 @@ val patternFunc: Person => String = { // 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: 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/tmux.html.markdown b/tmux.html.markdown index 2ccb067a..c11da5fc 100644 --- a/tmux.html.markdown +++ b/tmux.html.markdown @@ -7,8 +7,8 @@ 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. @@ -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,15 @@ 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) 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/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/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/visualbasic.html.markdown b/visualbasic.html.markdown index fbfa500d..00d61843 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -159,7 +159,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 @@ -189,7 +189,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() 'Ask the question, does the user wish to continue? Unfortunately it 'is case sensitive. diff --git a/xml.html.markdown b/xml.html.markdown index 94fc93f4..fce1a3a4 100644 --- a/xml.html.markdown +++ b/xml.html.markdown @@ -7,7 +7,7 @@ contributors: XML is a markup language designed to store and transport data. -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, just carry it. * XML Syntax @@ -123,4 +123,4 @@ With this tool, you can check the XML data outside the application logic. <price>30.00</price> </book> </bookstore> -```
\ No newline at end of file +``` diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 6afa659a..558d9110 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 . + +# 用 mam 指令阅读相关的 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/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index cb7ccdee..8904970f 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 --- after +-- 修改后 even . fib $ 7 -- true +-- 等价地 +even $ fib 7 -- true + ---------------------------------------------------- --- 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/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 64b0aadc..b450ab84 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -341,7 +341,7 @@ var myFunc = myObj.myFunc; myFunc(); // = undefined // 相应的,一个函数也可以被指定为一个对象的方法,并且可以通过`this`访问 -// 这个对象的成员,即使在行数被定义时并没有依附在对象上。 +// 这个对象的成员,即使在函数被定义时并没有依附在对象上。 var myOtherFunc = function(){ return this.myString.toUpperCase(); } diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 1c577efb..b1143dac 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -127,7 +127,7 @@ __此文本也是__ <!-- 代码段落 --> <!-- 代码段落(HTML中 <code>标签)可以由缩进四格(spaces) -或者一个标签页(tab)实现--> +或者一个制表符(tab)实现--> This is code So is this 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() ``` |