summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown11
-rw-r--r--c++.html.markdown349
-rw-r--r--c.html.markdown14
-rw-r--r--coffeescript.html.markdown4
-rw-r--r--common-lisp.html.markdown2
-rw-r--r--compojure.html.markdown280
-rw-r--r--de-de/coffeescript-de.html.markdown106
-rw-r--r--de-de/go-de.html.markdown2
-rw-r--r--de-de/markdown-de.html.markdown256
-rw-r--r--erlang.html.markdown14
-rw-r--r--es-es/go-es.html.markdown2
-rw-r--r--es-es/markdown-es.html.markdown2
-rw-r--r--es-es/perl-es.html.markdown120
-rw-r--r--fr-fr/javascript-fr.html.markdown525
-rw-r--r--fr-fr/objective-c-fr.html.markdown2
-rw-r--r--fr-fr/ruby-fr.html.markdown4
-rw-r--r--go.html.markdown65
-rw-r--r--ja-jp/r-jp.html.markdown4
-rw-r--r--java.html.markdown2
-rw-r--r--ko-kr/go-kr.html.markdown2
-rw-r--r--markdown.html.markdown10
-rw-r--r--matlab.html.markdown2
-rw-r--r--objective-c.html.markdown2
-rw-r--r--ocaml.html.markdown372
-rw-r--r--perl6.html.markdown145
-rw-r--r--pt-br/go-pt.html.markdown2
-rw-r--r--pt-br/markdown-pt.html.markdown2
-rw-r--r--purescript.html.markdown195
-rw-r--r--python.html.markdown14
-rw-r--r--python3.html.markdown36
-rw-r--r--r.html.markdown2
-rw-r--r--ru-ru/go-ru.html.markdown44
-rw-r--r--ru-ru/objective-c-ru.html.markdown2
-rw-r--r--ru-ru/python-ru.html.markdown266
-rw-r--r--ruby.html.markdown102
-rw-r--r--scala.html.markdown4
-rw-r--r--swift.html.markdown338
-rw-r--r--tmux.html.markdown244
-rw-r--r--tr-tr/objective-c-tr.html.markdown2
-rw-r--r--typescript.html.markdown158
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--zh-cn/common-lisp-cn.html.markdown2
-rw-r--r--zh-cn/go-cn.html.markdown2
-rw-r--r--zh-cn/lua-cn.html.markdown1
-rw-r--r--zh-cn/markdown-cn.html.markdown240
-rw-r--r--zh-cn/r-cn.html.markdown2
-rw-r--r--zh-cn/ruby-cn.html.markdown2
-rw-r--r--zh-cn/scala-cn.html.markdown2
-rw-r--r--zh-cn/swift-cn.html.markdown2
49 files changed, 3546 insertions, 417 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index 061d35b0..dc7d32b6 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -8,6 +8,7 @@ contributors:
- ["Denis Arh", "https://github.com/darh"]
- ["akirahirose", "https://twitter.com/akirahirose"]
- ["Anton Strömkvist", "http://lutic.org/"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
filename: LearnBash.sh
---
@@ -73,9 +74,9 @@ echo Hello, $NAME!
# use 'man test' for more info about conditionals
if [ $NAME -ne $USER ]
then
- echo "Your name is your username"
-else
echo "Your name isn't your username"
+else
+ echo "Your name is your username"
fi
# There is also conditional execution
@@ -140,6 +141,12 @@ do
echo "$VARIABLE"
done
+# Or write it the "traditional for loop" way:
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+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
diff --git a/c++.html.markdown b/c++.html.markdown
new file mode 100644
index 00000000..7609dd46
--- /dev/null
+++ b/c++.html.markdown
@@ -0,0 +1,349 @@
+---
+language: c++
+filename: learncpp.cpp
+contributors:
+ - ["Steven Basart", "http://github.com/xksteven"]
+lang: en
+---
+
+I am writing this to highlight the differences and
+additions that C++ has with respect to C. My
+suggestion would be to follow the C tutorial first
+then look here for the additions and differences.
+
+```c++
+///////////////////////////////////////
+// C++ differences
+///////////////////////////////////////
+
+
+//In C++
+//cannot use void main()
+int main() { //or int main(int argc, char **argv)
+ //cannot end with return;
+ return 0;
+ //Can also end without return statement
+}
+
+//In C++
+/*
+ //This could lead to compiler errors and is discouraged
+ //#if 0 #endif pairs are encouraged instead
+*/
+
+//In C++
+sizeof(10) //Typically 4
+sizeof('c') == 1
+
+//In C
+sizeof('c') == sizeof(10) //true chars are passed as ints
+
+
+//In C++ strict prototyping
+void func(); //function which accepts no arguments
+
+//In C
+void func(); //function which may accept arguments
+
+
+//In C++
+for(int i = 0; i < 10; i++) {;}
+//In C must int i must be declared before
+
+
+//C++ Supports Function overloading
+//Provided each function takes different
+//parameters
+
+void printing(char const *myString)
+{printf("String %s\n",myString);} //Hello
+
+void printing(int myInt)
+{printf("My int is %d",myInt);} //15
+
+int main ()
+{
+ printing("Hello");
+ printing(15);
+}
+
+
+
+//C++ Default Function Arguments
+void two_ints(int a = 1, int b = 4);
+
+int main()
+{
+ two_ints(); // arguments: 1, 4
+ two_ints(20); // arguments: 20, 4
+ two_ints(20, 5); // arguments: 20, 5
+}
+
+
+//C++ added the nullptr which is different from 0
+int *ip = nullptr; // OK
+int value = nullptr; // error: value is no pointer
+
+
+///////////////////////////////////////
+// C++ Additions ontop of C
+///////////////////////////////////////
+
+
+///////////////////////////////////////
+// C++ Namespace
+///////////////////////////////////////
+
+//Namespaces allow you to define your own
+//functions and variables for use
+
+// Use '::' to change variable (or function) scope
+// Putting '::' before a function or variable will
+// reference a global scope
+
+// This allows you to make normal c library calls
+// std is for standard library
+using namespace std;
+
+#include <stdio.h>
+
+int counter = 50; // global variable
+
+int main()
+{
+ for (int counter = 1; // this refers to the
+ counter < 2; // local variable
+ counter++)
+ {
+ printf("Global var %d local var %d\n",
+ ::counter, // global variable
+ counter); // local variable
+ // => Global var 50 local var 1
+ }
+}
+
+// Namespaces can be nested
+
+
+namespace myFirstNameSpace
+{
+ namespace myInnerSoul
+ {
+ cos(int x)
+ {
+ printf("My inner soul was made to program.");
+ }
+ }
+}
+
+namespace anotherNameSpace
+{
+ cos(int x) {;} //does nothing
+}
+
+int main()
+{
+ //Specify the full path because main is outside of both namespaces.
+ //Will print out My inner soul was made to program.
+ myFirstNameSpace::myInnerSoul::cos(60);
+}
+
+
+///////////////////////////////////////
+// C++ Strings
+///////////////////////////////////////
+
+//Strings in C++ are Objects and have many functions
+myString = "Hello";
+myOtherString = " World";
+
+myString + myOtherString; // => "Hello World"
+
+myString + ' You'; // => "Hello You"
+
+myString != myOtherString; //True
+
+//An example of a string method
+myString.append(" Dog"); // => "Hello Dog"
+
+
+///////////////////////////////////////
+// C++ Input Output
+///////////////////////////////////////
+
+//C++ input and output streams
+//cin, cout, cerr, << is insertion and >> is extraction operator
+#include <iostream>
+
+using namespace std;
+
+int main()
+{
+
+ int myInt;
+
+ //Prints to stdout (or terminal/screen)
+ cout << "Enter your fav number:\n";
+ //Takes in input
+ cin >> myInt;
+
+ //cout can also be formatted
+ cout << "Your fav number is " << myInt << "\n";
+ //Your fav number is ##
+
+ cerr << "Used for error messages";
+}
+
+
+///////////////////////////////////////
+// C++ Classes
+///////////////////////////////////////
+
+
+//First example of classes
+#include <iostream>
+
+//define a class
+class Doggie
+{
+ std::string name;
+ int weight;
+
+ // These are only the declarations
+ //Can also have private and protected
+ public:
+ //The public methods (can also include variables)
+
+ // Default constructor
+ Doggie();
+
+ void setName(std::string dogsName);
+ void setWeight(int dogsWeight);
+ void printDog();
+
+ //Can define functions within class declaration too
+ void dogBark() {std::cout << "Bark Bark\n"}
+
+ //Destructors are methods that free the allocated space
+ ~doggieDestructor();
+ //if no destructor compiler defines the trivial destructor
+
+//Classes are similar to structs and must close the } with ;
+};
+
+// This is the implementation of the class methods
+// Also called the definition
+void Doggie::Doggie () {
+ std::cout << "A doggie is born. Woof!\n";
+}
+
+void Doggie::setName (std::string doggie_name) {
+ name = doggie_name;
+}
+
+void Doggie::setWeight (int doggie_weight) {
+ weight = doggie_weight;
+}
+
+void Doggie::printDog () {
+ std::cout << "Dog is " << name << " weighs" << weight << "\n";
+}
+
+void Doggie::~doggieDestructor () {
+ delete[] name;
+ delete weight;
+}
+
+int main () {
+ Doggie deedee; // prints out a doggie is born. Woof!
+ deedee.setName ("Barkley");
+ deedee.setWeight(1000000);
+ deedee.printDog;
+ //prints => Dog is Barkley weighs 1000000
+ return 0;
+}
+
+
+//C++ Class inheritance
+
+class German_Sheperd
+{
+ //This class now inherits everything public and protected from Doggie class
+ Doggie d_dog;
+
+ //Good practice to put d_ in front of datatypes in classes
+ std::string d_type;
+
+ public:
+ void dogType() {d_type = "German Sheperd";}
+};
+
+
+
+///////////////////////////////////////
+// C++ Exception Handling
+///////////////////////////////////////
+
+try {
+ throw 12.25; // throws a double no handler declared
+} catch (int errorNum)
+{
+ std::cout << "I caught an int " << errorNum << "\n";
+//default catcher
+} catch (...)
+{
+ std::cout << "I got an error. Not sure what but I can pass it up.";
+ throw;
+}
+
+
+///////////////////////////////////////
+// C++ Operator Overloading
+///////////////////////////////////////
+
+// In C++ you can overload operators such as +, -, new, etc.
+
+#include <iostream>
+using namespace std;
+
+class Vector {
+ public:
+ double x,y;
+ Vector () {};
+ Vector (double a, double b) : x(a), y(b) {}
+ Vector operator + (const CVector&);
+ Vector operator += (const CVector&);
+};
+
+Vector Vector::operator+ (const Vector& rhs)
+{
+ Vector temp;
+ temp.x = x + rhs.x;
+ temp.y = y + rhs.y;
+ return temp;
+}
+
+Vector Vector::operator+= (const Vector& rhs)
+{
+ x += rhs.x;
+ y += rhs.y;
+ return *this;
+}
+
+int main () {
+ Vector up (0,1);
+ Vector right (1,0);
+ Vector result;
+ // This calls the Vector + operator
+ // Vector up calls the + (function) with right as its paramater
+ result = up + right;
+ // prints out => Result is upright (1,1)
+ cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
+ return 0;
+}
+
+```
+Futher Reading
+
+for more resources see: http://www.icce.rug.nl/documents/cplusplus/
+for other reference material: http://www.cplusplus.com/doc/tutorial/
diff --git a/c.html.markdown b/c.html.markdown
index 8e170300..cbb6d289 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -4,6 +4,7 @@ filename: learnc.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
+ - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
---
@@ -175,6 +176,9 @@ int main() {
i2 * i1; // => 2
i1 / i2; // => 0 (0.5, but truncated towards 0)
+ // You need to cast at least one integer to float to get a floating-point result
+ (float)i1 / i2 // => 0.5f
+ i1 / (double)i2 // => 0.5 // Same with double
f1 / f2; // => 0.5, plus or minus epsilon
// Floating-point numbers and calculations are not exact
@@ -194,9 +198,11 @@ int main() {
2 >= 2; // => 1
// C is not Python - comparisons don't chain.
- // WRONG:
- //int between_0_and_2 = 0 < a < 2;
- // Correct:
+ // Warning: The line below will compile, but it means `(0 < a) < 2`.
+ // This expression is always true, because (0 < a) could be either 1 or 0.
+ // In this case it's 1, because (0 < 1).
+ int between_0_and_2 = 0 < a < 2;
+ // Instead use:
int between_0_and_2 = 0 < a && a < 2;
// Logic works on ints
@@ -573,7 +579,7 @@ typedef void (*my_fnp_type)(char *);
'\''; // single quote
'\"'; // double quote
'\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character
-'\ooo'; // octal number. Example: '\013' = vertical tab character
+'\0oo'; // octal number. Example: '\013' = vertical tab character
//print formatting:
"%d"; // integer
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown
index d96eed39..4c080bc6 100644
--- a/coffeescript.html.markdown
+++ b/coffeescript.html.markdown
@@ -11,7 +11,7 @@ As one of the succeeders of JavaScript, CoffeeScript tries its best to output re
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
-``` coffeescript
+```coffeescript
# CoffeeScript is a hipster language.
# It goes with the trends of many modern languages.
# So comments are like Ruby and Python, they use number symbols.
@@ -20,7 +20,7 @@ See also [the CoffeeScript website](http://coffeescript.org/), which has a compl
Block comments are like these, and they translate directly to '/ *'s and '* /'s
for the resulting JavaScript code.
-You should understand most of JavaScript semantices
+You should understand most of JavaScript semantics
before continuing.
###
diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown
index 8de81549..08134e35 100644
--- a/common-lisp.html.markdown
+++ b/common-lisp.html.markdown
@@ -17,7 +17,7 @@ Another popular and recent book is
-```scheme
+```common_lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 0. Syntax
diff --git a/compojure.html.markdown b/compojure.html.markdown
new file mode 100644
index 00000000..36a8d123
--- /dev/null
+++ b/compojure.html.markdown
@@ -0,0 +1,280 @@
+---
+category: tool
+tool: compojure
+contributors:
+ - ["Adam Bard", "http://adambard.com/"]
+filename: learncompojure.clj
+---
+
+## Getting Started with Compojure
+
+Compojure is a DSL for *quickly* creating *performant* web applications
+in Clojure with minimal effort:
+
+```clojure
+(ns myapp.core
+ (:require [compojure.core :refer :all]
+ [org.httpkit.server :refer [run-server]])) ; httpkit is a server
+
+(defroutes myapp
+ (GET "/" [] "Hello World"))
+
+(defn -main []
+ (run-server myapp {:port 5000}))
+```
+
+**Step 1:** Create a project with [Leiningen](http://leiningen.org/):
+
+```
+lein new myapp
+```
+
+**Step 2:** Put the above code in `src/myapp/core.clj`
+
+**Step 3:** Add some dependencies to `project.clj`:
+
+```
+[compojure "1.1.8"]
+[http-kit "2.1.16"]
+```
+
+**Step 4:** Run:
+
+```
+lein run -m myapp.core
+```
+
+View at: <http://localhost:5000/>
+
+Compojure apps will run on any ring-compatible server, but we recommend
+[http-kit](http://http-kit.org/) for its performance and
+[massive concurrency](http://http-kit.org/600k-concurrent-connection-http-kit.html).
+
+### Routes
+
+In compojure, each route is an HTTP method paired with a URL-matching pattern,
+an argument list, and a body.
+
+```clojure
+(defroutes myapp
+ (GET "/" [] "Show something")
+ (POST "/" [] "Create something")
+ (PUT "/" [] "Replace something")
+ (PATCH "/" [] "Modify Something")
+ (DELETE "/" [] "Annihilate something")
+ (OPTIONS "/" [] "Appease something")
+ (HEAD "/" [] "Preview something"))
+```
+
+Compojure route definitions are just functions which
+[accept request maps and return response maps](https://github.com/mmcgrana/ring/blob/master/SPEC):
+
+```clojure
+(myapp {:uri "/" :request-method :post})
+; => {:status 200
+; :headers {"Content-Type" "text/html; charset=utf-8}
+; :body "Create Something"}
+```
+
+The body may be a function, which must accept the request as a parameter:
+
+```clojure
+(defroutes myapp
+ (GET "/" [] (fn [req] "Do something with req")))
+```
+
+Or, you can just use the request directly:
+
+```clojure
+(defroutes myapp
+ (GET "/" req "Do something with req"))
+```
+
+Route patterns may include named parameters:
+
+```clojure
+(defroutes myapp
+ (GET "/hello/:name" [name] (str "Hello " name)))
+```
+
+You can adjust what each parameter matches by supplying a regex:
+
+```clojure
+(defroutes myapp
+ (GET ["/file/:name.:ext" :name #".*", :ext #".*"] [name ext]
+ (str "File: " name ext)))
+```
+
+### Middleware
+
+Clojure uses [Ring](https://github.com/ring-clojure/ring) for routing.
+Handlers are just functions that accept a request map and return a
+response map (Compojure will turn strings into 200 responses for you).
+
+You can easily write middleware that wraps all or part of your
+application to modify requests or responses:
+
+```clojure
+(defroutes myapp
+ (GET "/" req (str "Hello World v" (:app-version req))))
+
+(defn wrap-version [handler]
+ (fn [request]
+ (handler (assoc request :app-version "1.0.1"))))
+
+(defn -main []
+ (run-server (wrap-version myapp) {:port 5000}))
+```
+
+[Ring-Defaults](https://github.com/ring-clojure/ring-defaults) provides some handy
+middlewares for sites and apis, so add it to your dependencies:
+
+```
+[ring/ring-defaults "0.1.1"]
+```
+
+Then, you can import it in your ns:
+
+```
+(ns myapp.core
+ (:require [compojure.core :refer :all]
+ [ring.middleware.defaults :refer :all]
+ [org.httpkit.server :refer [run-server]]))
+```
+
+And use `wrap-defaults` to add the `site-defaults` middleware to your
+app:
+
+```
+(defn -main []
+ (run-server (wrap-defaults myapp site-defaults) {:port 5000}))
+```
+
+Now, your handlers may utilize query parameters:
+
+```clojure
+(defroutes myapp
+ (GET "/posts" req
+ (let [title (get (:params req) "title")
+ author (get (:params req) "author")]
+ (str "Title: " title ", Author: " author))))
+```
+
+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")]
+ (str "Title: " title ", Author: " author))))
+```
+
+
+### Return values
+
+The return value of a route block determines the response body
+passed on to the HTTP client, or at least the next middleware in the
+ring stack. Most commonly, this is a string, as in the above examples.
+But, you may also return a [response map](https://github.com/mmcgrana/ring/blob/master/SPEC):
+
+```clojure
+(defroutes myapp
+ (GET "/" []
+ {:status 200 :body "Hello World"})
+ (GET "/is-403" []
+ {:status 403 :body ""})
+ (GET "/is-json" []
+ {:status 200 :headers {"Content-Type" "application/json"} :body "{}"}))
+```
+
+### Static Files
+
+To serve up static files, use `compojure.route.resources`.
+Resources will be served from your project's `resources/` folder.
+
+```clojure
+(require '[compojure.route :as route])
+
+(defroutes myapp
+ (GET "/")
+ (route/resources "/")) ; Serve static resources at the root path
+
+(myapp {:uri "/js/script.js" :request-method :get})
+; => Contents of resources/public/js/script.js
+```
+
+### Views / Templates
+
+To use templating with Compojure, you'll need a template library. Here are a few:
+
+#### [Stencil](https://github.com/davidsantiago/stencil)
+
+[Stencil](https://github.com/davidsantiago/stencil) is a [Mustache](http://mustache.github.com/) template library:
+
+```clojure
+(require '[stencil.core :refer [render-string]])
+
+(defroutes myapp
+ (GET "/hello/:name" [name]
+ (render-string "Hello {{name}}" {:name name})))
+```
+
+You can easily read in templates from your resources directory. Here's a helper function
+
+```clojure
+(require 'clojure.java.io)
+
+(defn read-template [filename]
+ (slurp (clojure.java.io/resource filename)))
+
+(defroutes myapp
+ (GET "/hello/:name" [name]
+ (render-string (read-template "templates/hello.html") {:name name})))
+```
+
+#### [Selmer](https://github.com/yogthos/Selmer)
+
+[Selmer](https://github.com/yogthos/Selmer) is a Django and Jinja2-inspired templating language:
+
+```clojure
+(require '[selmer.parser :refer [render-file]])
+
+(defroutes myapp
+ (GET "/hello/:name" [name]
+ (render-file "templates/hello.html" {:name name})))
+```
+
+#### [Hiccup](https://github.com/weavejester/hiccup)
+
+[Hiccup](https://github.com/weavejester/hiccup) is a library for representing HTML as Clojure code
+
+```clojure
+(require '[hiccup.core :as hiccup])
+
+(defroutes myapp
+ (GET "/hello/:name" [name]
+ (hiccup/html
+ [:html
+ [:body
+ [:h1 {:class "title"}
+ (str "Hello " name)]]])))
+```
+
+#### [Markdown](https://github.com/yogthos/markdown-clj)
+
+[Markdown-clj](https://github.com/yogthos/markdown-clj) is a Markdown implementation.
+
+```clojure
+(require '[markdown.core :refer [md-to-html-string]])
+
+(defroutes myapp
+ (GET "/hello/:name" [name]
+ (md-to-html-string "## Hello, world")))
+```
+
+Further reading:
+
+* [Official Compojure Documentation](https://github.com/weavejester/compojure/wiki)
+
+* [Clojure for the Brave and True](http://www.braveclojure.com/)
diff --git a/de-de/coffeescript-de.html.markdown b/de-de/coffeescript-de.html.markdown
new file mode 100644
index 00000000..98a452ba
--- /dev/null
+++ b/de-de/coffeescript-de.html.markdown
@@ -0,0 +1,106 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["Frederik Ring", "https://github.com/m90"]
+ - ["Philipp Fischbeck", "https://github.com/PFischbeck"]
+filename: coffeescript-de.coffee
+lang: de-de
+---
+
+CoffeeScript ist eine kleine Sprache, die eins zu eins nach JavaScript übersetzt wird - es findet keine Interpretation zur Laufzeit statt.
+Als Nachfolger von JavaScript konzipiert, gibt CoffeeScript sein Bestes, lesbaren, gut formatierten und sauber laufenden JavaScript-Code zu erzeugen, der in jeder JavaScript-Laufzeit einwandfrei funktioniert.
+
+Auf [der CoffeeScript Website](http://coffeescript.org/) gibt es ein ausführliches Tutorial.
+
+``` coffeescript
+# CoffeeScript ist eine dieser Sprachen für "Hipster"
+# und folgt daher vielen Trends und Einflüssen aus modernen Sprachen.
+# Kommentare werden daher wie in Ruby und Python mit Hashes gekennzeichnet
+
+###
+Kommentarblöcke sehen aus wie diese und werden direkt nach '/ *'s und '* /'s
+im erzeugten JavaScript umgewandelt.
+
+Vorweg: bevor du mit CoffeeScript anfängst, solltest du bereits einen guten
+Überblick über die Sprache JavaScript haben.
+###
+
+# Zuweisung:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Bedingungen:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Funktionen:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "Kaffee") ->
+ "#{container} wird mit #{liquid} gefüllt..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "Kaffee";
+# }
+# return container + " wird mit " + liquid + " gefüllt...";
+#};
+
+# "Ranges":
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Objekte:
+math =
+ root: Math.sqrt
+ square: square
+ cube: (x) -> x * square x
+#=> var math = {
+# "root": Math.sqrt,
+# "square": square,
+# "cube": function(x) { return x * square(x); }
+#}
+
+# "Splats":
+race = (winner, runners...) ->
+ print winner, runners
+#=>race = function() {
+# var runners, winner;
+# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winner, runners);
+#};
+
+# Existenz-Operator:
+alert "Hab ich's nicht gesagt?" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Hab ich's nicht gesagt?"); }
+
+# Listen-Abstraktion:
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['Brokkoli', 'Spinat', 'Schokolade']
+eat food for food in foods when food isnt 'Schokolade'
+#=>foods = ['Brokkoli', 'Spinat', 'Schokolade'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'Schokolade') {
+# eat(food);
+# }
+#}
+```
+
+## Weiterführende Links
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown
index 8c2f58dd..ca27fdc7 100644
--- a/de-de/go-de.html.markdown
+++ b/de-de/go-de.html.markdown
@@ -79,7 +79,7 @@ func learnTypes() {
Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ
// nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel.
- g := 'Σ' // Ein Runen-Typ, alias uint32, gebraucht für unicode code points.
+ g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points.
f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl
c := 3 + 4i // complex128, besteht intern aus zwei float64-er
diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown
new file mode 100644
index 00000000..6a90980b
--- /dev/null
+++ b/de-de/markdown-de.html.markdown
@@ -0,0 +1,256 @@
+---
+language: markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators :
+ - ["Frederik Ring", "https://github.com/m90"]
+ - ["Philipp Fischbeck", "https://github.com/PFischbeck"]
+filename: markdown-de.md
+lang: de-de
+---
+
+Markdown wurde im Jahr 2004 von John Gruber kreiert. Ziel ist und war eine
+Syntax, in der sich Dokumente leicht schreiben *und* lesen lassen. Außerdem
+sollte Markdown sich leicht nach HTML (und in andere Formate) konvertieren
+lassen.
+
+```markdown
+<!-- Markdown ist eine Obermenge von HTML - jede valide HTML-Datei ist also
+automatisch valides Markdown - was heisst dass wir jedes HTML-Element (also auch
+Kommentare) in Markdown benutzen können, ohne dass der Parser sie verändert.
+Jedoch kann man innerhalb eines solchen HTML-Elements dann kein Markdown
+mehr verwenden. -->
+
+<!-- Es existieren unterschiedliche Markdown-Parser und -Dialekte, die sich in
+manchen Punkten unterscheiden. Diese Einführung wird versuchen, zu erläutern,
+welche Features überall verfügbar sind, und welche davon parser-spezifisch sind -->
+
+<!-- Überschriften -->
+<!-- HTML-Überschriften <h1> bis <h6> lassen sich einfach durch ein Voranstellen
+der entsprechenden Anzahl an Hashes (#) auszeichnen -->
+# Das ist eine <h1>
+## Das ist eine <h2>
+### Das ist eine <h3>
+#### Das ist eine <h4>
+##### Das ist eine <h5>
+###### Das ist eine <h6>
+
+<!-- Für die Elemente <h1> und <h2> gibt es in Markdown noch Sonderformen -->
+Das ist eine h1
+=============
+
+Das ist eine h2
+-------------
+
+<!-- Einfaches Textstyling -->
+<!-- Jeglicher Text lässt sich mit Markdown leicht als kursiv oder
+auch als fett auszeichnen -->
+
+*Dieser Text ist kursiv.*
+_Genau wie dieser._
+
+**Dieser Text ist fett.**
+__Genau wie dieser.__
+
+***Dieser Text ist beides***
+**_Dieser auch!_**
+*__Und dieser genau so!__*
+
+<!-- In "Github Flavored Markdown", dem von Github verwendeten Dialekt / Parser,
+gibt es auch noch durchgestrichenen Text: -->
+
+~~Dieser Text wird durchgestrichen dargestellt.~~
+
+<!-- Absätze sind eine oder mehrere zusammenhängende Zeilen Text, und werden
+durch eine oder mehrere Leerzeilen voneinander abgesetzt. -->
+
+Das ist ein Absatz. Ich kann immer noch nicht glauben, wie viel Spaß das macht !?!
+
+Jetzt bin ich schon bei Absatz 2.
+Hier ist dann immer noch Absatz 2!
+
+
+Jetzt ist das dann Nummer drei!
+
+<!-- Sollte man jemals ein <br />-Tag einfügen wollen, kann man einen Absatz
+mit zwei oder mehr Leerzeichen beenden, und danach einen neuen Absatz beginnen. -->
+
+Ich höre mit zwei Leerzeichen auf (markiere mich, und du siehst es).
+
+Über mir ist wohl ein <br />!
+
+<!-- Zitate werden ganz einfach mit einem > ausgezeichnet. -->
+
+> Das ist ein Zitat. Du kannst Zeilenumbrüche
+> entweder manuell hinzufügen und ein `>` vor jeder Zeile einfügen, oder du kannst deine Zeilen einfach immer länger und länger werden lassen, die Umbrüche werden dann automatisch erzeugt.
+> Solange sie mit einem `>` beginnen, macht das keinen Unterschied.
+
+> Auch möglich ist es, den Text
+>> mehrstufig einzurücken.
+> Nicht schlecht, oder?
+
+<!-- Listen -->
+<!-- <ul>s können mit Sternen, Pluszeichen oder Minuszeichen erzeugt werden -->
+
+* Punkt auf der Liste
+* Punkt auf der Liste
+* Anderer Punkt auf der Liste
+
+oder
+
++ Punkt auf der Liste
++ Punkt auf der Liste
++ Noch ein Punkt auf der Liste
+
+oder
+
+- Punkt auf der Liste
+- Punkt auf der Liste
+- Ein letzter Punkt auf der Liste
+
+<!-- <ol>s werden mit einer Zahl gefolgt von einem Punkt erzeugt -->
+
+1. Punkt eins
+2. Punkt zwei
+3. Punkt drei
+
+<!-- Auch wenn es keine gute Idee sein mag: du müsstest die einzelnen Punkte
+nicht mal korrekt numerieren -->
+
+1. Punkt eins
+1. Punkt zwei
+1. Punkt drei
+<!-- (Das sieht genau so aus wie das Beispiel eins weiter oben) -->
+
+<!-- Man kann Listen auch verschachteln -->
+
+1. Punkt eins
+2. Punkt zwei
+3. Punkt drei
+ * Unterpunkt
+ * Unterpunkt
+4. Punkt vier
+
+<!-- Code-Blöcke -->
+<!-- Blöcke von Programmcode (also ein <code>-Element) kannst du auszeichnen,
+indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst -->
+
+ Das ist Quellcode
+ Das hier auch
+
+<!-- Der Code kann natürlich auch wiederum eingerückt sein -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Innerhalb normalen Texts kannst du Code mit Backticks ` auszeichnen -->
+
+Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte!
+
+<!-- In "Github Flavored Markdown" gibt es für Code nocheinmal eine
+besondere Syntax -->
+
+\`\`\`ruby <!-- in "echt" musst du die Backslashes entfernen: ```ruby ! -->
+def foobar
+ puts "Hallo Welt!"
+end
+\`\`\` <!-- hier auch keine Backslashes, nur ``` -->
+
+<-- der obige Block muss nicht extra eingerückt werden, außerdem fügt Github
+Syntax-Highlighting für die nach dem ``` angegebene Sprache hinzu -->
+
+<!-- Horizontale Linie (<hr />) -->
+<!-- Trenner lassen sich einfach mit drei (oder mehr) Sternen oder Bindestrichen
+erzeugen (egal ob mit oder ohne Leerzeichen dazwischen)-->
+
+***
+---
+- - -
+****************
+
+<!-- Hyperlinks -->
+<!-- Eines der besten Features von Markdown ist das kinderleichte Erzeugen von
+Hyperlinks: Einfach den Linktext in eckige Klammern [] setzen, gefolgt von
+einer mit runden Klammern () umschlossenen URL. -->
+
+[Klick mich!](http://test.de/)
+
+<!-- Man kann dem Link auch noch ein title-Attribut geben -->
+
+[Klick mich!](http://test.at/ "Link zu Test.at")
+
+<!-- Relative Pfade funktionieren natürlich auch -->
+
+[Zu meiner Musiksammlung](/music/).
+
+<!-- URLs lassen sich auch über Referenzen festlegen -->
+
+[Klick mich][link1], um mehr über mich herauszufinden!
+[Hier kannst du auch mal draufklicken][foobar], wenn es dich interessiert.
+
+[link1]: http://test.de/ "Wahnsinn!"
+[foobar]: http://foobar.ch/ "Erstaunlich!"
+
+<!-- Das title-Attribut wird entweder mit Anführungszeichen oder Klammern
+umschlossen (oder gleich ganz weggelassen). Die Referenzen können an jeder
+Stelle im gesamtem Dokument vorkommen, als ID kann alles verwendet werden, solange
+es dokumentweit eindeutig ist. -->
+
+<!-- Man kann den Linktext auch als implizite Referenz benutzen -->
+
+[Das][] ist ein Link.
+
+[das]: http://dasisteinlink.at/
+
+<!-- Das ist aber eher unüblich. -->
+
+<!-- Bilder -->
+<!-- Bilder funktionieren genau wie Links, nur dass man noch ein Ausrufezeichen
+voranstellt! -->
+
+![Das ist das alt-Attribut für mein Bild](http://imgur.com/myimage.jpg "Hier noch ein title-Attribut")
+
+<!-- Referenzen funktionieren auch hier genau wie erwartet -->
+
+![Das ist das alt-Attribut][meinbild]
+
+[meinbild]: relative/urls/gehen/auch.jpg "hier wäre noch Platz für einen title"
+
+<!-- Bonusfeatures -->
+<!-- Auto-Links -->
+
+<http://testwebseite.de/> ist das selbe wie
+[http://testwebseite.de/](http://testwebseite.de/)
+
+<!-- Automatische Links für E-Mail-Addressen -->
+
+<foo@bar.com>
+
+<!-- Maskieren -->
+
+Ich würde *diesen Teil gerne mit Sternen umschließen*, doch ohne dass er kursiv
+wird. Also mache ich folgendes: \*Ich umschließe diesen Text mit Sternen\*!
+
+<!-- Tabellen -->
+<!-- Tabellen gibt es bis jetzt nur in "Github Flavored Markdown".
+Zudem sind sie ziemlich mühselig, aber wenn du es wirklich wissen willst: -->
+
+| Spalte1 | Spalte2 | Spalte3 |
+| :----------- | :------: | ------------: |
+| linksbündig | mittig | rechtsbündig |
+| blah | blah | blah |
+
+<!-- oder das selbe in grün: -->
+
+Spalte1 | Spalte2 | Spalte3
+:-- | :-: | --:
+Ganz schön hässlich | vielleicht doch lieber | wieder aufhören
+
+<!-- Das war's! -->
+
+```
+
+Mehr Informationen gibt es in [John Gruber's offiziellem Blog-Post](http://daringfireball.net/projects/markdown/syntax)
+und bei Adam Pritchards [grandiosem Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
+Infos zu Github Flavored Markdown [gibt es hier](https://help.github.com/articles/github-flavored-markdown). \ No newline at end of file
diff --git a/erlang.html.markdown b/erlang.html.markdown
index 64b62f05..04086aeb 100644
--- a/erlang.html.markdown
+++ b/erlang.html.markdown
@@ -260,22 +260,22 @@ spawn(F). % <0.44.0>
% For all of this to be useful we need to be able to receive messages. This is
% achieved with the `receive` mechanism:
--module(caculateGeometry).
+-module(calculateGeometry).
-compile(export_all).
-caculateAera() ->
+calculateArea() ->
receive
{rectangle, W, H} ->
W * H;
{circle, R} ->
3.14 * R * R;
_ ->
- io:format("We can only caculate area of rectangles or circles.")
+ io:format("We can only calculate area of rectangles or circles.")
end.
-% Compile the module and create a process that evaluates `caculateAera` in the shell
-c(caculateGeometry).
-CaculateAera = spawn(caculateGeometry, caculateAera, []).
-CaculateAera ! {circle, 2}. % 12.56000000000000049738
+% 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
self(). % <0.41.0>
diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown
index e788e810..86de33ec 100644
--- a/es-es/go-es.html.markdown
+++ b/es-es/go-es.html.markdown
@@ -77,7 +77,7 @@ func learnTypes() {
saltos de línea.` // mismo tipo cadena
// Literal no ASCII. Los fuentes de Go son UTF-8.
- g := 'Σ' // Tipo rune, un alias de uint32, alberga un punto unicode.
+ g := 'Σ' // Tipo rune, un alias de int32, alberga un punto unicode.
f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit.
c := 3 + 4i // complex128, representado internamente por dos float64.
// Sintaxis Var con inicializadores.
diff --git a/es-es/markdown-es.html.markdown b/es-es/markdown-es.html.markdown
index 3865126c..d90e3eb5 100644
--- a/es-es/markdown-es.html.markdown
+++ b/es-es/markdown-es.html.markdown
@@ -14,7 +14,7 @@ fácilmente a HTML (y, actualmente, otros formatos también).
¡Denme todo la retroalimentación que quieran! / ¡Sientanse en la libertad de hacer forks o pull requests!
-```
+```markdown
<!-- Markdown está basado en HTML, así que cualquier archivo HTML es Markdown
válido, eso significa que podemos usar elementos HTML en Markdown como, por
ejemplo, el comentario y no serán afectados por un parseador Markdown. Aún
diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown
index 4f0c26c1..644182ff 100644
--- a/es-es/perl-es.html.markdown
+++ b/es-es/perl-es.html.markdown
@@ -7,23 +7,24 @@ contributors:
- ["Korjavin Ivan", "http://github.com/korjavin"]
translators:
- ["Francisco Gomez", "http://github.com/frncscgmz"]
+ - ["Joaquín Ferrero", "http://github.com/joaquinferrero"]
lang: es-es
---
-Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo.
+Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo.
-Perl 5 corre en mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala.
+Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala.
```perl
-# Comentarios de una sola linea con un carácter hash.
+# Comentarios de una sola línea con un carácter hash
#### Tipos de variables en Perl
-# Las variables comienzan con el símbolo $.
-# Un nombre de variable valido empieza con una letra o un guión bajo,
-# seguido por cualquier numero de letras, números o guiones bajos.
+# Las variables comienzan con el símbolo $
+# Un nombre de variable válido empieza con una letra o un guión bajo,
+# seguido por cualquier número de letras, números o guiones bajos
-### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes.
+### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes
## Escalares
# Un escalar representa un solo valor:
@@ -31,99 +32,98 @@ my $animal = "camello";
my $respuesta = 42;
# Los valores escalares pueden ser cadenas de caracteres, números enteros o
-# de punto flotante, Perl automáticamente los convertirá como sea requerido.
+# de punto flotante; Perl automáticamente los convertirá como sea requerido
## Arreglos
# Un arreglo representa una lista de valores:
-my @animales = {"camello","llama","buho"};
-my @numeros = {23,42,69};
-my @mixto = {"camello",42,1.23};
-
-
+my @animales = ("camello","llama","buho"};
+my @numeros = (23, 42, 69);
+my @mixto = ("camello", 42, 1.23);
## Hashes
-# Un hash representa un conjunto de pares llave/valor:
-
-my %color_fruta = {"manzana","rojo","banana","amarillo"};
-
-# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas
-# fácilmente.
+# Un hash representa un conjunto de pares llave/valor:
+my %color_fruta = ("manzana","rojo","banana","amarillo");
+# Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente
my %color_fruta = (
manzana => "rojo",
banana => "amarillo",
- );
-# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata).
+);
-# Los tipos de datos mas complejos pueden ser construidos utilizando
-# referencias, las cuales te permiten construir listas y hashes dentro
-# de listas y hashes.
+# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata)
-#### Estructuras condicionales y de ciclos
+# Los tipos de datos más complejos se pueden construir utilizando
+# referencias, las cuales le permiten construir listas y hashes dentro
+# de listas y hashes
-# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes.
+#### Estructuras condicionales y de ciclos
+# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes
if ( $var ) {
- ...
+ ...;
} elsif ( $var eq 'bar' ) {
- ...
+ ...;
} else {
- ...
+ ...;
}
unless ( condicion ) {
- ...
- }
-# Esto es proporcionado como una version mas fácil de leer que "if (!condición)"
+ ...;
+}
-# La post condición al modo Perl
+# Esto se ofrece como una versión más fácil de leer que "if (!condición)"
+
+# La postcondición al modo Perl:
print "Yow!" if $zippy;
print "No tenemos bananas" unless $bananas;
# while
- while ( condicion ) {
- ...
- }
-
+while ( condicion ) {
+ ...;
+}
# for y foreach
for ($i = 0; $i <= $max; $i++) {
- ...
- }
+ ...;
+}
+
+for $i (0 .. $max) {
+ ...;
+}
foreach (@array) {
- print "Este elemento es $_\n";
- }
+ print "Este elemento es $_\n";
+}
#### Expresiones regulares
-# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es
-# sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
+# El soporte de expresiones regulares en Perl es muy amplio y profundo, y
+# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros.
# Sin embargo, resumiendo:
-# Pareo simple
+# Coincidencia simple
if (/foo/) { ... } # verdadero si $_ contiene "foo"
if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo"
# Substitución simple
-$a =~ s/foo/bar/; # remplaza foo con bar en $a
-$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a
+$a =~ s/foo/bar/; # remplaza "foo" con "bar" en $a
+$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en $a
-#### Archivos e I/O
+#### Archivos y E/S
-# Puedes abrir un archivo para obtener datos o escribirlos utilizando la
-# función "open()".
+# Puede abrir un archivo para obtener datos o escribirlos utilizando la
+# función "open()"
open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!";
open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!";
open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!";
-# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>"
-# operador. En contexto escalar leer una sola linea desde el gestor de
-# archivo, y en contexto de lista leer el archivo completo en donde, asigna
-# cada linea a un elemento de la lista.
+# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>".
+# En contexto escalar, leer una sola línea desde el gestor de archivo, y
+# en contexto de lista, leer el archivo completo en donde asigna
+# cada línea a un elemento de la lista
my $linea = <$entrada>;
my @lineas = <$entrada>;
@@ -131,30 +131,26 @@ my @lineas = <$entrada>;
#### Escribiendo subrutinas
# Escribir subrutinas es fácil:
-
sub logger {
my $mensajelog = shift;
open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!";
print $archivolog $mensajelog;
}
-# Ahora podemos utilizar la subrutina al igual que cualquier otra función
-# incorporada:
-
+# Ahora podemos utilizar la subrutina al igual que cualquier otra función incorporada:
logger("Tenemos una subrutina logger!");
-
```
#### Utilizando módulos Perl
-Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl.
+Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl.
-perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar.
+perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar.
#### Material de Lectura
- [perl-tutorial](http://perl-tutorial.org/)
- - [Aprende en www.perl.com](http://www.perl.org/learn.html)
+ - [Learn Perl](http://www.perl.org/learn.html)
- [perldoc](http://perldoc.perl.org/)
- - y perl incorporado: `perldoc perlintro`
+ - y en su propio perl: `perldoc perlintro`
diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown
new file mode 100644
index 00000000..2e18d0be
--- /dev/null
+++ b/fr-fr/javascript-fr.html.markdown
@@ -0,0 +1,525 @@
+---
+language: javascript
+contributors:
+ - ['Adam Brenecki', 'http://adam.brenecki.id.au']
+ - ['Ariel Krakowski', 'http://www.learneroo.com']
+filename: javascript-fr.js
+translators:
+ - ['@nbrugneaux', 'https://nicolasbrugneaux.me']
+lang: fr-fr
+---
+
+JavaScript a été créé par Brendan Eich, travaillant alors a Netscape, en 1995.
+Le langage avait à l'origine pour but d'être un langage de scripting simple
+pour les sites web, complétant le Java (à ne pas confondre avec JavaScript)
+pour des applications web complexes. Mais son intégration très proche et
+simple des pages web, ainsi que le support natif des navigateurs a rendu
+le JavaScript incontournable aujourd'hui tant bien dans le front-end que
+dans le back-end.
+
+En effet, le JavaScript n'est plus uniquement limité aux navigateurs, grâce à
+Node.JS, un projet qui offre un environnement indépendant dans lequel un
+interpréteur Javascript, basé sur le célèbre moteur V8 de Google Chrome,
+peut être utilisé directement côté serveur pour exécuter des programmes écrits
+en JavaScript.
+
+```js
+// Les commentaires sont comme en C. Les commentaires mono-ligne commencent par 2 slashs,
+/* et les commentaires sur plusieurs lignes commencent avec slash-étoile
+ et finissent avec étoile-slash */
+
+// Toutes les expressions peuvent finir par ;
+doStuff();
+
+// ... mais n'en n'ont pas forcément besoin, les point-virgules sont ajoutés
+// lors de l’interprétation aux sauts de ligne, sauf exceptions
+doStuff()
+
+// Parce que ces cas peuvent produire des effets inattendus, nous utiliserons
+// des point-virgules dans ce guide.
+
+
+///////////////////////////////////
+// 1. Nombres, Chaines de caractères et Opérateurs
+
+// JavaScript a un seul type de nombre (qui est un 64-bit IEEE 754 double (décimaux))
+// Comme avec le Lua, ne paniquez pas à cause du manque d'int (entiers) : les
+// doubles ont un mantisse de 52 bits, ce qui est assez pour stocker des int jusqu'à
+// 9 x 10¹⁵ exactement.
+3; // = 3
+1.5; // = 1.5
+
+// L'arithmétique de base fonctionne comme vous vous y attendriez
+1 + 1; // = 2
+8 - 1; // = 7
+10 * 2; // = 20
+35 / 5; // = 7
+
+// Ainsi que les divisions non-entières
+5 / 2; // = 2.5
+
+// Les opérations bits à bits fonctionnent aussi, quand vous effectuez une opération
+// bits à bits, votre nombre décimal est converti en entier *jusqu'à* 32 bits.
+1 << 2; // = 4
+
+// Comme en mathématiques, la priorité est donnée aux parenthèses.
+(1 + 3) * 2; // = 8
+
+// Il existe 3 valeurs spéciales pour les nombres:
+Infinity; // le résultat de 1/0 par exemple
+-Infinity; // le résultat de -1/0 par exemple
+NaN; // le résultat de 0/0 par exemple
+
+// Il existe également le type booléen.
+true; // vrai
+false; // faux
+
+// Les chaines de caractères (strings) sont créees avec " ou ' indifféremment, la seule
+// raison de choisir l'un ou l'autre est la cohérence dans votre code.
+"abc";
+'Hello, world';
+
+// La négation utilise le symbole !
+!true; // = false
+!false; // = true
+
+// L'égalité est === ou ==
+// === compare la valeur exacte 2 === '2' // = false
+// == convertit la valeur pour comparer 2 === '2' // = true
+// En général, il vaut mieux utiliser === pour ne pas faire d'erreur.
+1 === 1; // = true
+2 === 1; // = false
+
+// L'inégalité est !== ou !=, basé sur le même principe qu'avant.
+1 !== 1; // = false
+2 !== 1; // = true
+
+// Plus de comparaisons :
+1 < 10; // = true
+1 > 10; // = false
+2 <= 2; // = true
+2 >= 2; // = true
+
+// Les chaines de caractères se concatènent avec +
+'Hello ' + 'world!'; // = 'Hello world!'
+
+// et peuvent être comparées alphabétiquement avec < et >
+'a' < 'b'; // = true
+
+// Vous pouvez accéder les caractères dans une string avec charAt
+'This is a string'.charAt(0); // = 'T'
+
+// ... ou utiliser substring pour avoir un plus gros morceau
+'Hello world'.substring(0, 5); // = 'Hello'
+
+// la longueur, length, est une propriété, donc n'utilisez pas de ()
+'Hello'.length; // = 5
+
+// Il y a également null et undefined
+null; // utilisé pour une non-valeur
+undefined; // utilisé pour une valeur actuellement non présente (cependant,
+ // undefined est aussi une valeur valide)
+
+// false, null, undefined, NaN, 0 and '' sont 'presque-faux' (falsy), tout le reste
+// est 'presque-vrai' (truthy)
+// Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0')
+
+
+///////////////////////////////////
+// 2. Variables, Tableaux et Objets
+
+// Les variables sont déclarées avec le mot clé var. Le typage en JavaScript est
+// dynamique, donc pas besoin de spécifier le type. L'assignement utilise un seul =.
+var someVar = 5;
+
+// si vous oubliez le mot clé var, vous n'aurez pas d'erreur (sauf en mode strict)
+someOtherVar = 10;
+
+// ... mais la variable aura une portée globale (plus communément trouvé en tant
+// que "global scope" en anglais), et non pas une portée limitée à la fonction
+// dans laquelle vous l'aviez définie.
+
+// Les variables déclarées et non assignées sont undefined par défaut
+var someThirdVar;
+var someThirdVar = undefined;
+
+// ... sont deux déclarations identiques.
+
+// Il y a des raccourcis pour les opérations mathématiques:
+someVar += 5; // équivalent pour someVar = someVar + 5;
+someVar *= 10; // de même, someVar = someVar * 100;
+someVar++; // = someVar += 1;
+someVar--; // = someVar -= 1;
+
+// Les tableaux (Arrays) sont des listes ordonnées de valeurs, de tous types.
+var myArray = ['Hello', 45, true];
+
+// Leurs membres peuvent être accédés en utilisant les crochets
+// Les indices commencent à 0.
+myArray[1]; // = 45
+
+// Les tableaux sont modifiables, ainsi que leurs longueurs
+myArray.push( 'World' );
+myArray.length; // = 4
+
+// Ajout/Modification à un index spécifique
+myArray[3] = 'Hello';
+
+// Les objets JavaScript sont appelés 'dictionnaires' ou 'maps' dans certains autres
+// langages : ils sont une liste non-ordonnée de paires clé-valeur.
+var myObj = {key1: 'Hello', key2: 'World'};
+
+// Les clés sont des strings, mais les ' ou " sont optionels si elles sont des
+// noms valides en JavaScript. Les valeurs peuvent être de n'importe quel type.
+var myObj = {myKey: 'myValue', 'my other key': 4};
+
+// Les attributs d'objets peuvent être accédés avec les crochets
+myObj['my other key']; // = 4
+
+// .. ou avec un point si la clé est un identifiant valide.
+myObj.myKey; // = 'myValue'
+
+// Les objets sont eux aussi modifiables.
+myObj.myThirdKey = true;
+
+// Si vous essayez d'accéder à une valeur non-définie, vous obtiendrez undefined
+myObj.myFourthKey; // = undefined
+
+
+///////////////////////////////////
+// 3. Logique et structures de contrôle
+
+// Les si (if) fonctionnent comme vous vous y attendez.
+var count = 1;
+if (count === 3) {
+ // seulement quand count est 3
+}
+else if (count === 4) {
+ // uniquement quand count est 4
+}
+else {
+ // le reste du temps, si ni 3, ni 4.
+}
+
+// De même pour while.
+while (true) {
+ // Une boucle infinie !
+}
+
+// Les boucles do-while sont pareilles, mais sont exécutées au moins une fois.
+var input
+do {
+ input = getInput();
+} while (!isValid(input))
+
+// La boucle for est la même qu'en C ou en Java:
+// initialisation; condition pour continuer; itération
+for (var i = 0; i < 5; i++){
+ // sera exécutée 5 fois
+}
+
+// && est le "et" logique, || est le "ou" logique
+if (house.size === 'big' && house.colour === 'blue'){
+ house.contains = 'bear';
+}
+if (colour === 'red' || colour === 'blue'){
+ // colour est soit 'red' soit 'blue'
+}
+
+// Les raccourcis && et || sont pratiques pour instancier des valeurs par defaut.
+var name = otherName || 'default';
+
+// Ceci est l'équivalent de
+var name = otherName;
+if (!name){
+ name = 'default';
+}
+
+// Le switch vérifie les égalités avec ===
+// utilisez un "break" à la fin de chaque cas
+// ou les cas suivants seront eux aussi exécutés
+grade = 'B';
+switch (grade) {
+ case 'A':
+ console.log('Great job');
+ break;
+ case 'B':
+ console.log('OK job');
+ break;
+ case 'C':
+ console.log('You can do better');
+ break;
+ default:
+ console.log('Oy vey');
+ break;
+}
+
+
+///////////////////////////////////
+// 4. Fonctions, Scope (Environnement) et Closures
+
+// Les fonctions sont déclarées avec le mot clé function
+function myFunction(thing){
+ return thing.toUpperCase();
+}
+myFunction('foo'); // = 'FOO'
+
+// Les fonctions JavaScript sont des objets de première classe, donc peuvent
+// être réassignées à d'autres variables et passées en tant que paramètres pour
+// d'autres fonctions
+function myFunction(){
+ // ce code s'exécutera dans 5 secondes
+}
+setTimeout(myFunction, 5000);
+// Note: setTimeout ne fait pas parti du langage, mais les navigateurs ainsi
+// que Node.js le rendent disponible
+
+// Les fonctions n'ont pas nécessairement besoin d'un nom, elles peuvent être
+// anonymes
+setTimeout(function(){
+ // ce code s'exécutera dans 5 secondes
+}, 5000);
+
+// Le Javascript crée uniquement un scope, une portée d'action limitée, pour
+// les fonctions, et pas dans les autres blocs.
+if (true){
+ var i = 5;
+}
+i; // = 5 - et non undefined comme vous pourriez vous y attendre
+
+// Cela a mené à un style commun de fonctions anonymes immédiatement exécutée;
+// ou "immediately-executing anonymous functions"
+(function(){
+ var temporary = 5;
+ // Nous pouvons accéder au scope global en assignant à l'objet global,
+ // qui dans les navigateurs est "window". Il est différent dans Node.js,
+ // le scope global sera en fait local au module dans lequel vous
+ // vous trouvez. http://nodejs.org/api/globals.html
+ window.permanent = 10;
+})();
+// Cela permet de ne pas avoir de fuites de variables qui polluent
+// l’environnement global.
+temporary; // raises ReferenceError
+permanent; // = 10
+
+// Une des fonctionnalités les plus puissantes de Javascript est le système de
+// closures. Si une fonction est définie dans une autre fonction, alors la
+// fonction interne aura accès aux variables de la fonction parente, même si
+// celle-ci a déjà finie son exécution.
+function sayHelloInFiveSeconds(name){
+ var prompt = 'Hello, ' + name + '!';
+ // Fonction interne
+ function inner(){
+ alert(prompt);
+ }
+ setTimeout(inner, 5000);
+ // setTimeout is asynchrone, donc la fonction sayHelloInFiveSeconds quittera
+ // immédiatement, et setTimeout appelera inner après.
+}
+sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec
+
+
+///////////////////////////////////
+// 5. Encore plus à propos des Objets; Constructeurs and Prototypes
+
+// Les objets peuvent contenir des fonctions.
+var myObj = {
+ myFunc: function(){
+ return 'Hello world!';
+ }
+};
+myObj.myFunc(); // = 'Hello world!'
+
+// Lorsqu'une fonction attachée à un objet est appelée, elle peut accéder à
+// l'objet avec le mot clé this.
+myObj = {
+ myString: 'Hello world!',
+ myFunc: function(){
+ return this.myString;
+ }
+};
+myObj.myFunc(); // = 'Hello world!'
+
+// La valeur de "this" change de par l'endroit où la fonction est appelée, et
+// non de l'endroit où elle est définie. Donc elle ne fonctionnera pas si elle
+// est appelée hors du contexte l'objet.
+var myFunc = myObj.myFunc;
+myFunc(); // = undefined
+
+// A l'inverse, une fonction peut être attachée à un objet et y gagner l'accès
+// au travers de "this"
+var myOtherFunc = function(){
+ return this.myString.toUpperCase();
+}
+
+myObj.myOtherFunc = myOtherFunc;
+myObj.myOtherFunc(); // = 'HELLO WORLD!'
+
+// Le contexte correspond à la valeur de "this".
+// Nous pouvons aussi spécifier un contexte, forcer la valeur de "this,
+// pour une fonction quand elle est appelée grâce à "call" ou "apply".
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, ' And Hello Moon!'); // = 'Hello World! And Hello Moon!'
+
+// 'apply' est presque identique, mais prend un tableau comme liste d’arguments.
+
+anotherFunc.apply(myObj, [' And Hello Sun!']); // = 'Hello World! And Hello Sun!'
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// Mais, "call" and "apply" fonctionnenent uniquement au moment de l'appel de la
+// fonction. Pour lier le contexte de façon permanente, nous pouvons utiliser
+// "bind" pour garder une référence à la fonction avec ce "this".
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(' And Hello Saturn!'); // = 'Hello World! And Hello Saturn!'
+
+// "bind" peut aussi être utilisé pour créer une application partielle de la
+// fonction (curry)
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
+// Lorsque vous appelez une fonction avec le mot clé "new", un nouvel objet est
+// crée et mis à disposition de la fonction via "this". Ces fonctions sont
+// communément appelées constructeurs.
+var MyConstructor = function(){
+ this.myNumber = 5;
+}
+myNewObj = new MyConstructor(); // = {myNumber: 5}
+myNewObj.myNumber; // = 5
+
+// Chaque objet en Javascript a un "prototype". Quand vous essayez d'accéder à
+// une propriété que l'objet n'a pas, l'interpréteur va regarder son prototype.
+
+// Quelques implémentations de JS vous laissent accéder au prototype avec la
+// propriété "magique" __proto__. Ceci peut être utile, mais n'est pas standard
+// et ne fonctionne pas dans certains des navigateurs actuels.
+var myObj = {
+ myString: 'Hello world!'
+};
+var myPrototype = {
+ meaningOfLife: 42,
+ myFunc: function(){
+ return this.myString.toLowerCase()
+ }
+};
+
+myObj.__proto__ = myPrototype;
+myObj.meaningOfLife; // = 42
+myObj.myFunc(); // = 'hello world!'
+
+myPrototype.__proto__ = {
+ myBoolean: true
+};
+myObj.myBoolean; // = true
+
+
+// Pour obtenir le prototype il existe également Object.getPrototypeOf
+Object.getPrototypeOf( myObj ) // = {meaningOfLife: 42, myFunc: function}
+
+// Il n'y a pas de copie ici. Chacun des objets stocke une référence à son
+// prototype. Cela veut dire que l'on peut le modifier et cela se répercutera
+// partout.
+myPrototype.meaningOfLife = 43;
+myObj.meaningOfLife; // = 43
+
+// L'inverse n'est cependant pas vrai. Changer la propriété d'un objet ne change
+// pas la chaine prototypale.
+myObj.meaningOfLife = 42;
+myPrototype.meaningOfLife; // = 43
+
+// Comme précédemment dit, __proto__ n'est pas standard et ne devrait pas être
+// utilisé. Il y a deux autres moyen de créer un nouvel objet avec un prototype
+// donné.
+
+// Le premier est Object.create, mais c'est assez récent et risque de ne pas
+// fonctionner dans tous les navigateurs.
+var myObj = Object.create(myPrototype);
+myObj.meaningOfLife; // = 43
+
+// Le deuxième moyen, qui marche partout, fonctionne avec les constructeurs.
+// Les constructeurs ont un propriété appelée prototype. Ce n'est *pas* le
+// prototype du constructeur de la fonction elle-même, c'est le prototype que
+// les nouveaux objets crées grâce à ce constructeur avec "new" auront.
+MyConstructor.prototype = {
+ myNumber: 5,
+ getMyNumber: function(){
+ return this.myNumber;
+ }
+};
+var myNewObj2 = new MyConstructor();
+myNewObj2.getMyNumber(); // = 5
+myNewObj2.myNumber = 6
+myNewObj2.getMyNumber(); // = 6
+
+// Les types pré-définis tels que les strings ou nombres ont aussi des
+// constructeurs
+var myNumber = 12;
+var myNumberObj = new Number(12);
+myNumber == myNumberObj; // = true
+
+// ... mais ils ne sont pas exactement équivalent.
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
+myNumber === myNumberObj; // = false
+if (0){
+ // 0 est falsy, le code ne fonctionnera pas.
+}
+if (Number(0)){
+ // Parce que Number(0) est truthy, le code fonctionnera
+}
+
+// Cependant, vous pouvez ajouter des fonctionnalités aux types de bases grâce à
+// cette particularité.
+String.prototype.firstCharacter = function(){
+ return this.charAt(0);
+}
+'abc'.firstCharacter(); // = 'a'
+
+// C'est très souvent utilisé pour le "polyfilling", qui implémente des nouvelles
+// fonctionnalités de JavaScript dans de plus anciens environnements, tels que
+// les vieux navigateurs.
+
+//Par exemple, Object.create est assez récent, mais peut être implémenté grâce à
+// ce polyfill
+if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe déjà
+ Object.create = function(proto){
+ // on crée un constructeur temporaire avec le bon prototype
+ var Constructor = function(){};
+ Constructor.prototype = proto;
+ // puis on utilise "new" pour créer un object avec ce même prototype
+ return new Constructor();
+ }
+}
+```
+
+## Pour aller plus loin (en anglais)
+
+The [Mozilla Developer
+Network](https://developer.mozilla.org/fr-FR/docs/Web/JavaScript) expose une
+excellente documentation pour le Javascript dans les navigateurs. Et contient
+également un wiki pour s'entraider.
+
+MDN's [A re-introduction to
+JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+recouvre les principaux sujets vus ici. Le guide est délibérément uniquement
+à propos du JavaScript, et ne parle pas des navigateurs; pour cela, dirigez vous
+plutôt ici :
+[Document Object
+Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)
+
+[Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges.
+
+[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth
+un guide pour vous éviter les faux-amis dans le JavaScript.
+
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire.
+
+En addition aux contributeurs de cet article, du contenu provient du
+"Python tutorial" de Louie Dinh, et de [JS
+Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)
+sur le réseau Mozilla.
diff --git a/fr-fr/objective-c-fr.html.markdown b/fr-fr/objective-c-fr.html.markdown
index b98d161e..69f4d8f9 100644
--- a/fr-fr/objective-c-fr.html.markdown
+++ b/fr-fr/objective-c-fr.html.markdown
@@ -14,7 +14,7 @@ lang: fr-fr
L'Objective-C est un langage de programmation orienté objet réflexif principalement utilisé par Apple pour les systèmes d'exploitations Mac OS X et iOS et leurs frameworks respectifs, Cocoa et Cocoa Touch.
-```cpp
+```objective_c
// Les commentaires sur une seule ligne commencent par //
/*
diff --git a/fr-fr/ruby-fr.html.markdown b/fr-fr/ruby-fr.html.markdown
index 3060bd75..75c8d0d3 100644
--- a/fr-fr/ruby-fr.html.markdown
+++ b/fr-fr/ruby-fr.html.markdown
@@ -336,8 +336,8 @@ class Humain
puts "#{msg}"
end
- def species
- @@species
+ def espece
+ @@espece
end
end
diff --git a/go.html.markdown b/go.html.markdown
index 656b1051..b4c6afff 100644
--- a/go.html.markdown
+++ b/go.html.markdown
@@ -12,7 +12,7 @@ contributors:
- ["Alexej Friesen", "https://github.com/heyalexej"]
---
-Go was created out of the need to get work done. It's not the latest trend
+Go was created out of the need to get work done. It's not the latest trend
in computer science, but it is the newest fastest way to solve real-world
problems.
@@ -26,7 +26,7 @@ Go comes with a great standard library and an enthusiastic community.
```go
// Single line comment
/* Multi-
- line comment */
+ line comment */
// A package clause starts every source file.
// Main is a special name declaring an executable rather than a library.
@@ -41,8 +41,8 @@ import (
"strconv" // String conversions.
)
-// A function definition. Main is special. It is the entry point for the
-// executable program. Love it or hate it, Go uses brace brackets.
+// A function definition. Main is special. It is the entry point for the
+// executable program. Love it or hate it, Go uses brace brackets.
func main() {
// Println outputs a line to stdout.
// Qualify it with the package name, fmt.
@@ -77,8 +77,8 @@ func learnTypes() {
s2 := `A "raw" string literal
can include line breaks.` // Same string type.
- // Non-ASCII literal. Go source is UTF-8.
- g := 'Σ' // rune type, an alias for uint32, holds a unicode code point.
+ // Non-ASCII literal. Go source is UTF-8.
+ g := 'Σ' // rune type, an alias for int32, holds a unicode code point.
f := 3.14195 // float64, an IEEE-754 64-bit floating point number.
c := 3 + 4i // complex128, represented internally with two float64's.
@@ -92,17 +92,32 @@ can include line breaks.` // Same string type.
// Arrays have size fixed at compile time.
var a4 [4]int // An array of 4 ints, initialized to all 0.
- a3 := [...]int{3, 1, 5} // An array of 3 ints, initialized as shown.
+ a3 := [...]int{3, 1, 5} // An array initialized with a fixed size of three
+ // elements, with values 3, 1, and 5.
- // Slices have dynamic size. Arrays and slices each have advantages
+ // Slices have dynamic size. Arrays and slices each have advantages
// but use cases for slices are much more common.
- s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here.
+ s3 := []int{4, 5, 9} // Compare to a3. No ellipsis here.
s4 := make([]int, 4) // Allocates slice of 4 ints, initialized to all 0.
var d2 [][]float64 // Declaration only, nothing allocated here.
bs := []byte("a slice") // Type conversion syntax.
+ // Because they are dynamic, slices can be appended to on-demand.
+ // To append elements to a slice, built-in append() function is used.
+ // First argument is a slice to which we are appending. Commonly,
+ // the array variable is updated in place, as in example below.
+ s := []int{1, 2, 3} // Result is a slice of length 3.
+ s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6.
+ fmt.Println(s) // Updated slice is now [1 2 3 4 5 6]
+ // To append another slice, instead of list of atomic elements we can
+ // pass a reference to a slice or a slice literal like this, with a
+ // trailing elipsis, meaning take a slice and unpack its elements,
+ // appending them to slice s.
+ s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal.
+ fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9]
+
p, q := learnMemory() // Declares p, q to be type pointer to int.
- fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
+ fmt.Println(*p, *q) // * follows a pointer. This prints two ints.
// Maps are a dynamically growable associative array type, like the
// hash or dictionary types of some other languages.
@@ -128,7 +143,7 @@ func learnNamedReturns(x, y int) (z int) {
return // z is implicit here, because we named it earlier.
}
-// Go is fully garbage collected. It has pointers but no pointer arithmetic.
+// Go is fully garbage collected. It has pointers but no pointer arithmetic.
// You can make a mistake with a nil pointer, but not by incrementing a pointer.
func learnMemory() (p, q *int) {
// Named return values p and q have type pointer to int.
@@ -206,7 +221,7 @@ func learnFlowControl() {
func(a, b int) int {
return (a + b) * 2
}(10, 2)) // Called with args 10 and 2
- // => Add + double two numbers: 24
+ // => Add + double two numbers: 24
// When you need it, you'll love it.
goto love
@@ -253,7 +268,7 @@ type pair struct {
x, y int
}
-// Define a method on type pair. Pair now implements Stringer.
+// Define a method on type pair. Pair now implements Stringer.
func (p pair) String() string { // p is called the "receiver"
// Sprintf is another public function in package fmt.
// Dot syntax references fields of p.
@@ -261,13 +276,13 @@ func (p pair) String() string { // p is called the "receiver"
}
func learnInterfaces() {
- // Brace syntax is a "struct literal." It evaluates to an initialized
- // struct. The := syntax declares and initializes p to this struct.
+ // Brace syntax is a "struct literal". It evaluates to an initialized
+ // struct. The := syntax declares and initializes p to this struct.
p := pair{3, 4}
fmt.Println(p.String()) // Call String method of p, of type pair.
var i Stringer // Declare i of interface type Stringer.
i = p // Valid because pair implements Stringer
- // Call String method of i, of type Stringer. Output same as above.
+ // Call String method of i, of type Stringer. Output same as above.
fmt.Println(i.String())
// Functions in the fmt package call the String method to ask an object
@@ -305,7 +320,7 @@ func learnErrorHandling() {
// prints 'strconv.ParseInt: parsing "non-int": invalid syntax'
fmt.Println(err)
}
- // We'll revisit interfaces a little later. Meanwhile,
+ // We'll revisit interfaces a little later. Meanwhile,
learnConcurrency()
}
@@ -316,12 +331,12 @@ func inc(i int, c chan int) {
// We'll use inc to increment some numbers concurrently.
func learnConcurrency() {
- // Same make function used earlier to make a slice. Make allocates and
+ // Same make function used earlier to make a slice. Make allocates and
// initializes slices, maps, and channels.
c := make(chan int)
- // Start three concurrent goroutines. Numbers will be incremented
+ // Start three concurrent goroutines. Numbers will be incremented
// concurrently, perhaps in parallel if the machine is capable and
- // properly configured. All three send to the same channel.
+ // properly configured. All three send to the same channel.
go inc(0, c) // go is a statement that starts a new goroutine.
go inc(10, c)
go inc(-805, c)
@@ -334,7 +349,7 @@ func learnConcurrency() {
go func() { c <- 84 }() // Start a new goroutine just to send a value.
go func() { cs <- "wordy" }() // Again, for cs this time.
// Select has syntax like a switch statement but each case involves
- // a channel operation. It selects a case at random out of the cases
+ // a channel operation. It selects a case at random out of the cases
// that are ready to communicate.
select {
case i := <-c: // The value received can be assigned to a variable,
@@ -344,7 +359,7 @@ func learnConcurrency() {
case <-ccs: // Empty channel, not ready for communication.
fmt.Println("didn't happen.")
}
- // At this point a value was taken from either c or cs. One of the two
+ // At this point a value was taken from either c or cs. One of the two
// goroutines started above has completed, the other will remain blocked.
learnWebProgramming() // Go does it. You want to do it too.
@@ -383,15 +398,15 @@ func requestServer() {
The root of all things Go is the [official Go web site](http://golang.org/).
There you can follow the tutorial, play interactively, and read lots.
-The language definition itself is highly recommended. It's easy to read
+The language definition itself is highly recommended. It's easy to read
and amazingly short (as language definitions go these days.)
You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go.
On the reading list for students of Go is the [source code to the standard
-library](http://golang.org/src/pkg/). Comprehensively documented, it
+library](http://golang.org/src/pkg/). Comprehensively documented, it
demonstrates the best of readable and understandable Go, Go style, and Go
-idioms. Or you can click on a function name in [the
+idioms. Or you can click on a function name in [the
documentation](http://golang.org/pkg/) and the source code comes up!
Another great resource to learn Go is [Go by example](https://gobyexample.com/).
diff --git a/ja-jp/r-jp.html.markdown b/ja-jp/r-jp.html.markdown
index 3e6621f5..a8dd7c9c 100644
--- a/ja-jp/r-jp.html.markdown
+++ b/ja-jp/r-jp.html.markdown
@@ -14,7 +14,7 @@ R は統計計算用の言語です。
データの取得やクリーニング、統計処理やグラフ作成をするために便利な、たくさんのライブラリがあります。また、LaTeX文書からRコマンドを呼び出すこともできます
-```python
+```r
# コメント行は、#で開始します
@@ -772,4 +772,4 @@ pp + geom_point()
* RとR GUIはこちら [http://www.r-project.org/](http://www.r-project.org/)
-* [RStudio](http://www.rstudio.com/ide/) 別のGUI \ No newline at end of file
+* [RStudio](http://www.rstudio.com/ide/) 別のGUI
diff --git a/java.html.markdown b/java.html.markdown
index 3484aee5..dffc3828 100644
--- a/java.html.markdown
+++ b/java.html.markdown
@@ -101,7 +101,7 @@ public class LearnJava {
// Arrays
//The array size must be decided upon instantiation
- //The following formats work for declaring an arrow
+ //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];
diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown
index e4eaee56..3012c04f 100644
--- a/ko-kr/go-kr.html.markdown
+++ b/ko-kr/go-kr.html.markdown
@@ -79,7 +79,7 @@ func learnTypes() {
개행을 포함할 수 있다.` // 같은 string 타입
// non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다.
- g := 'Σ' // 유니코드 코드 포인트를 담고 있고, uint32 타입의 가칭(alias)인 rune 타입
+ g := 'Σ' // 유니코드 코드 포인트를 담고 있고, int32 타입의 가칭(alias)인 rune 타입
f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입
c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 9a863bac..3d4d0af6 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -10,7 +10,7 @@ Markdown was created by John Gruber in 2004. It's meant to be an easy to read an
Give me as much feedback as you want! / Feel free to fork and pull request!
-```
+```markdown
<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown, that
means we can use HTML elements in Markdown, such as the comment element, and
they won't be affected by a markdown parser. However, if you create an HTML
@@ -39,7 +39,7 @@ This is an h2
-------------
<!-- Simple text styles -->
-<!-- Text can be easily styled as italic, bold, or strikethrough using markdown -->
+<!-- Text can be easily styled as italic or bold using markdown -->
*This text is in italics.*
_And so is this text._
@@ -52,7 +52,7 @@ __And so is this text.__
*__And this!__*
<!-- In Github Flavored Markdown, which is used to render markdown files on
-Github, we also have: -->
+Github, we also have strikethrough: -->
~~This text is rendered with strikethrough.~~
@@ -201,11 +201,11 @@ can be anything so long as they are unique. -->
<!-- Images -->
<!-- Images are done the same way as links but with an exclamation point in front! -->
-![This is hover-text (alt text) for my image](http://imgur.com/myimage.jpg "An optional title")
+![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
<!-- And reference style works as expected -->
-![This is the hover-text.][myimage]
+![This is the alt-attribute.][myimage]
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
diff --git a/matlab.html.markdown b/matlab.html.markdown
index d9a82890..9dae8ef2 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas
% Logicals can be applied to matrices:
A > 5
% for each element, if condition is true, that element is 1 in returned matrix
-A[ A > 5 ]
+A( A > 5 )
% returns a vector containing the elements in A for which condition is true
% Strings
diff --git a/objective-c.html.markdown b/objective-c.html.markdown
index 772e72ca..caad49a5 100644
--- a/objective-c.html.markdown
+++ b/objective-c.html.markdown
@@ -12,7 +12,7 @@ filename: LearnObjectiveC.m
Objective-C is the main programming language used by Apple for the OS X and iOS operating systems and their respective frameworks, Cocoa and Cocoa Touch.
It is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language.
-```cpp
+```objective_c
// Single-line comments start with //
/*
diff --git a/ocaml.html.markdown b/ocaml.html.markdown
new file mode 100644
index 00000000..b9505f13
--- /dev/null
+++ b/ocaml.html.markdown
@@ -0,0 +1,372 @@
+---
+language: OCaml
+contributors:
+ - ["Daniil Baturin", "http://baturin.org/"]
+---
+
+OCaml is a strictly evaluated functional language with some imperative
+features.
+
+Along with StandardML and its dialects it belongs to ML language family.
+F# is also heavily influenced by OCaml.
+
+Just like StandardML, OCaml features both an interpreter, that can be
+used interactively, and a compiler.
+The interpreter binary is normally called "ocaml" and the compiler is "ocamlopt".
+There is also a bytecode compiler, "ocamlc", but there are few reasons to use it.
+
+It is strongly and statically typed, but instead of using manually written
+type annotations, it infers types of expressions using Hindley-Milner algorithm.
+It makes type annotations unnecessary in most cases, but can be a major
+source of confusion for beginners.
+
+When you are in the top level loop, OCaml will print the inferred type
+after you enter an expression.
+
+```
+# let inc x = x + 1 ;;
+val inc : int -> int = <fun>
+# let a = 99 ;;
+val a : int = 99
+```
+
+For a source file you can use "ocamlc -i /path/to/file.ml" command
+to print all names and type signatures.
+
+```
+$ cat sigtest.ml
+let inc x = x + 1
+let add x y = x + y
+
+let a = 1
+
+$ ocamlc -i ./sigtest.ml
+val inc : int -> int
+val add : int -> int -> int
+val a : int
+```
+
+Note that type signatures of functions of multiple arguments are
+written in curried form. A function that takes multiple arguments can be
+represented as a composition of functions that take only one argument.
+The "f(x,y) = x + y" function from the example above applied to
+arguments 2 and 3 is equivalent to the "f0(y) = 2 + y" function applied to 3.
+Hence the "int -> int -> int" signature.
+
+
+```ocaml
+(*** Comments ***)
+
+(* Comments are enclosed in (* and *). It's fine to nest comments. *)
+
+(* There are no single-line comments. *)
+
+
+(*** Variables and functions ***)
+
+(* Expressions can be separated by a double semicolon symbol, ";;".
+ In many cases it's redundant, but in this tutorial we use it after
+ every expression for easy pasting into the interpreter shell.
+ Unnecessary use of expression separators in source code files
+ is often considered to be a bad style. *)
+
+(* Variable and function declarations use "let" keyword. *)
+let x = 10 ;;
+
+(* OCaml allows single quote characters in identifiers.
+ Single quote doesn't have a special meaning in this case, it's often used
+ in cases when in other languages one would use names like "foo_tmp". *)
+let foo = 1 ;;
+let foo' = foo * 2 ;;
+
+(* Since OCaml compiler infers types automatically, you normally don't need to
+ specify argument types explicitly. However, you can do it if
+ you want or need to. *)
+let inc_int (x: int) : int = x + 1 ;;
+
+(* One of the cases when explicit type annotations may be needed is
+ resolving ambiguity between two record types that have fields with
+ the same name. The alternative is to encapsulate those types in
+ modules, but both topics are a bit out of scope of this
+ tutorial. *)
+
+(* You need to mark recursive function definitions as such with "rec" keyword. *)
+let rec factorial n =
+ if n = 0 then 1
+ else factorial n * factorial (n-1)
+;;
+
+(* Function application usually doesn't need parentheses around arguments *)
+let fact_5 = factorial 5 ;;
+
+(* ...unless the argument is an expression. *)
+let fact_4 = factorial (5-1) ;;
+let sqr2 = sqr (-2) ;;
+
+(* Every function must have at least one argument.
+ Since some funcions naturally don't take any arguments, there's
+ "unit" type for it that has the only one value written as "()" *)
+let print_hello () = print_endline "hello world" ;;
+
+(* Note that you must specify "()" as argument when calling it. *)
+print_hello () ;;
+
+(* Calling a function with insufficient number of arguments
+ does not cause an error, it produces a new function. *)
+let make_inc x y = x + y ;; (* make_inc is int -> int -> int *)
+let inc_2 = make_inc 2 ;; (* inc_2 is int -> int *)
+inc_2 3 ;; (* Evaluates to 5 *)
+
+(* You can use multiple expressions in function body.
+ The last expression becomes the return value. All other
+ expressions must be of the "unit" type.
+ This is useful when writing in imperative style, the simplest
+ form of it is inserting a debug print. *)
+let print_and_return x =
+ print_endline (string_of_int x);
+ x
+;;
+
+(* Since OCaml is a functional language, it lacks "procedures".
+ Every function must return something. So functions that
+ do not really return anything and are called solely for their
+ side effects, like print_endline, return value of "unit" type. *)
+
+
+(* Definitions can be chained with "let ... in" construct.
+ This is roughly the same to assigning values to multiple
+ variables before using them in expressions in imperative
+ languages. *)
+let x = 10 in
+let y = 20 in
+x + y ;;
+
+(* Alternatively you can use "let ... and ... in" construct.
+ This is especially useful for mutually recursive functions,
+ with ordinary "let .. in" the compiler will complain about
+ unbound values.
+ It's hard to come up with a meaningful but self-contained
+ example of mutually recursive functions, but that syntax
+ works for non-recursive definitions too. *)
+let a = 3 and b = 4 in a * b ;;
+
+(* Anonymous functions use the following syntax: *)
+let my_lambda = fun x -> x * x ;;
+
+(*** Operators ***)
+
+(* There is little distintion between operators and functions.
+ Every operator can be called as a function. *)
+
+(+) 3 4 (* Same as 3 + 4 *)
+
+(* There's a number of built-in operators. One unusual feature is
+ that OCaml doesn't just refrain from any implicit conversions
+ between integers and floats, it also uses different operators
+ for floats. *)
+12 + 3 ;; (* Integer addition. *)
+12.0 +. 3.0 ;; (* Floating point addition. *)
+
+12 / 3 ;; (* Integer division. *)
+12.0 /. 3.0 ;; (* Floating point division. *)
+5 mod 2 ;; (* Remainder. *)
+
+(* Unary minus is a notable exception, it's polymorphic.
+ However, it also has "pure" integer and float forms. *)
+- 3 ;; (* Polymorphic, integer *)
+- 4.5 ;; (* Polymorphic, float *)
+~- 3 (* Integer only *)
+~- 3.4 (* Type error *)
+~-. 3.4 (* Float only *)
+
+(* You can define your own operators or redefine existing ones.
+ Unlike SML or Haskell, only selected symbols can be used
+ for operator names and first symbol defines associativity
+ and precedence rules. *)
+let (+) a b = a - b ;; (* Surprise maintenance programmers. *)
+
+(* More useful: a reciprocal operator for floats.
+ Unary operators must start with "~". *)
+let (~/) x = 1.0 /. x ;;
+~/4.0 (* = 0.25 *)
+
+
+(*** Built-in datastructures ***)
+
+(* Lists are enclosed in square brackets, items are separated by
+ semicolons. *)
+let my_list = [1; 2; 3] ;;
+
+(* Tuples are (optionally) enclosed in parentheses, items are separated
+ by commas. *)
+let first_tuple = 3, 4 ;; (* Has type "int * int". *)
+let second_tuple = (4, 5) ;;
+
+(* Corollary: if you try to separate list items by commas, you get a list
+ with a tuple inside, probably not what you want. *)
+let bad_list = [1, 2] ;; (* Becomes [(1, 2)] *)
+
+(* You can access individual list items with the List.nth function. *)
+List.nth my_list 1 ;;
+
+(* There are higher-order functions for lists such as map and filter. *)
+List.map (fun x -> x * 2) [1; 2; 3] ;;
+List.filter (fun x -> if x mod 2 = 0 then true else false) [1; 2; 3; 4] ;;
+
+(* You can add an item to the beginning of a list with the "::" constructor
+ often referred to as "cons". *)
+1 :: [2; 3] ;; (* Gives [1; 2; 3] *)
+
+(* Arrays are enclosed in [| |] *)
+let my_array = [| 1; 2; 3 |] ;;
+
+(* You can access array items like this: *)
+my_array.(0) ;;
+
+
+(*** Strings and characters ***)
+
+(* Use double quotes for string literals. *)
+let my_str = "Hello world" ;;
+
+(* Use single quotes for character literals. *)
+let my_char = 'a' ;;
+
+(* Single and double quotes are not interchangeable. *)
+let bad_str = 'syntax error' ;; (* Syntax error. *)
+
+(* This will give you a single character string, not a character. *)
+let single_char_str = "w" ;;
+
+(* Strings can be concatenated with the "^" operator. *)
+let some_str = "hello" ^ "world" ;;
+
+(* Strings are not arrays of characters.
+ You can't mix characters and strings in expressions.
+ You can convert a character to a string with "String.make 1 my_char".
+ There are more convenient functions for this purpose in additional
+ libraries such as Core.Std that may not be installed and/or loaded
+ by default. *)
+let ocaml = (String.make 1 'O') ^ "Caml" ;;
+
+(* There is a printf function. *)
+Printf.printf "%d %s" 99 "bottles of beer" ;;
+
+(* Unformatted read and write functions are there too. *)
+print_string "hello world\n" ;;
+print_endline "hello world" ;;
+let line = read_line () ;;
+
+
+(*** User-defined data types ***)
+
+(* You can define types with the "type some_type =" construct. Like in this
+ useless type alias: *)
+type my_int = int ;;
+
+(* More interesting types include so called type constructors.
+ Constructors must start with a capital letter. *)
+type ml = OCaml | StandardML ;;
+let lang = OCaml ;; (* Has type "ml". *)
+
+(* Type constructors don't need to be empty. *)
+type my_number = PlusInfinity | MinusInfinity | Real of float ;;
+let r0 = Real (-3.4) ;; (* Has type "my_number". *)
+
+(* Can be used to implement polymorphic arithmetics. *)
+type number = Int of int | Float of float ;;
+
+(* Point on a plane, essentially a type-constrained tuple *)
+type point2d = Point of float * float ;;
+let my_point = Point (2.0, 3.0) ;;
+
+(* Types can be parameterized, like in this type for "list of lists
+ of anything". 'a can be substituted with any type. *)
+type 'a list_of_lists = 'a list list ;;
+type int_list_list = int list_of_lists ;;
+
+(* Types can also be recursive. Like in this type analogous to
+ built-in list of integers. *)
+type my_int_list = EmptyList | IntList of int * my_int_list ;;
+let l = Cons (1, EmptyList) ;;
+
+
+(*** Pattern matching ***)
+
+(* Pattern matching is somewhat similar to switch statement in imperative
+ languages, but offers a lot more expressive power.
+
+ Even though it may look complicated, it really boils down to matching
+ an argument against an exact value, a predicate, or a type constructor.
+ The type system is what makes it so powerful. *)
+
+(** Matching exact values. **)
+
+let is_zero x =
+ match x with
+ | 0 -> true
+ | _ -> false (* The "_" pattern means "anything else". *)
+;;
+
+(* Alternatively, you can use the "function" keyword. *)
+let is_one = function
+| 1 -> true
+| _ -> false
+;;
+
+(* Matching predicates, aka "guarded pattern matching". *)
+let abs x =
+ match x with
+ | x when x < 0 -> -x
+ | _ -> x
+;;
+
+abs 5 ;; (* 5 *)
+abs (-5) (* 5 again *)
+
+(** Matching type constructors **)
+
+type animal = Dog of string | Cat of string ;;
+
+let say x =
+ match x with
+ | Dog x -> x ^ " says woof"
+ | Cat x -> x ^ " says meow"
+;;
+
+say (Cat "Fluffy") ;; (* "Fluffy says meow". *)
+
+(** Traversing datastructures with pattern matching **)
+
+(* Recursive types can be traversed with pattern matching easily.
+ Let's see how we can traverse a datastructure of the built-in list type.
+ Even though the built-in cons ("::") looks like an infix operator,
+ it's actually a type constructor and can be matched like any other. *)
+let rec sum_list l =
+ match l with
+ | [] -> 0
+ | head :: tail -> head + (sum_list tail)
+;;
+
+sum_list [1; 2; 3] ;; (* Evaluates to 6 *)
+
+(* Built-in syntax for cons obscures the structure a bit, so we'll make
+ our own list for demonstration. *)
+
+type int_list = Nil | Cons of int * int_list ;;
+let rec sum_int_list l =
+ match l with
+ | Nil -> 0
+ | Cons (head, tail) -> head + (sum_int_list tail)
+;;
+
+let t = Cons (1, Cons (2, Cons (3, Nil))) ;;
+sum_int_list t ;;
+
+```
+
+## Further reading
+
+* Visit the official website to get the compiler and read the docs: <http://ocaml.org/>
+* Try interactive tutorials and a web-based interpreter by OCaml Pro: <http://try.ocamlpro.com/>
+* Read "OCaml for the skeptical" course: <http://www2.lib.uchicago.edu/keith/ocaml-class/home.html>
diff --git a/perl6.html.markdown b/perl6.html.markdown
index fca863af..4e7d8c6e 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -30,7 +30,7 @@ double paragraphs, and single notes.
# In Perl 6, you declare a lexical variable using `my`
my $variable;
-# Perl 6 has 4 variable types :
+# Perl 6 has 4 kinds of variables:
## * Scalars. They represent a single value. They start with a `$`
@@ -56,7 +56,8 @@ my @array = <a b c>; # array of words, delimited by space.
say @array[2]; # Array indices start at 0 -- This is the third element
-say "Interpolate an array using [] : @array[]"; #=> Interpolate an array using [] : a b c
+say "Interpolate an array using [] : @array[]";
+#=> Interpolate an array using [] : a b c
## * Hashes. Key-Value Pairs.
# Hashes are actually arrays of Pairs (`Key => Value`),
@@ -99,7 +100,7 @@ my &s = &say-hello;
my &other-s = sub { say "Anonymous function !" }
# A sub can have a "slurpy" parameter, or "doesn't-matter-how-many"
-sub as-many($head, *@rest) { # The `*@` slurpy will basically "take everything else".
+sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else".
# Note: you can have parameters *before* (like here)
# a slurpy one, but not *after*.
say @rest.join(' / ') ~ " !";
@@ -191,7 +192,7 @@ named-def(def => 15); #=> 15
# its right. When passed around, containers are marked as immutable.
# Which means that, in a function, you'll get an error if you try to
# mutate one of your arguments.
-# If you really need to, you can ask for a mutable container using `is rw` :
+# If you really need to, you can ask for a mutable container using `is rw`:
sub mutate($n is rw) {
$n++;
say "\$n is now $n !";
@@ -199,7 +200,7 @@ sub mutate($n is rw) {
# If what you want is a copy instead, use `is copy`.
-# A sub itself returns a container, which means it can be marked as rw :
+# A sub itself returns a container, which means it can be marked as rw:
my $x = 42;
sub mod() is rw { $x }
mod() = 52; # in this case, the parentheses are mandatory
@@ -210,7 +211,7 @@ say $x; #=> 52
### Control Flow Structures
# You don't need to put parenthesis around the condition,
-# but that also means you always have to use brackets (`{ }`) for their body :
+# but that also means you always have to use brackets (`{ }`) for their body:
## Conditionals
@@ -246,7 +247,7 @@ my $a = $condition ?? $value-if-true !! $value-if-false;
# blocks, etc), this means the powerful `when` is not only applicable along with
# a `given`, but instead anywhere a `$_` exists.
given "foo bar" {
- when /foo/ { # You'll read about the smart-matching operator below -- just know `when` uses it.
+ when /foo/ { # Don't worry about smart matching -- just know `when` uses it.
# This is equivalent to `if $_ ~~ /foo/`.
say "Yay !";
}
@@ -262,7 +263,7 @@ given "foo bar" {
## Looping constructs
# - `loop` is an infinite loop if you don't pass it arguments,
-# but can also be a c-style `for` :
+# but can also be a c-style `for`:
loop {
say "This is an infinite loop !";
last; # last breaks out of the loop, like the `break` keyword in other languages
@@ -270,8 +271,8 @@ loop {
loop (my $i = 0; $i < 5; $i++) {
next if $i == 3; # `next` skips to the next iteration, like `continue`
- # in other languages. Note that you can also use postfix conditionals,
- # loops, etc.
+ # in other languages. Note that you can also use postfix
+ # conditionals, loops, etc.
say "This is a C-style for loop !";
}
@@ -292,12 +293,12 @@ for @array {
for @array {
# You can...
- next if $_ == 3; # Skip to the next iteration (like `continue` in C-like languages).
+ next if $_ == 3; # Skip to the next iteration (`continue` in C-like languages).
redo if $_ == 4; # Re-do the iteration, keeping the same topic variable (`$_`).
last if $_ == 5; # Or break out of a loop (like `break` in C-like languages).
}
-# Note - the "lambda" `->` syntax isn't reserved to `for` :
+# Note - the "lambda" `->` syntax isn't reserved to `for`:
if long-computation() -> $result {
say "The result is $result";
}
@@ -308,12 +309,12 @@ if long-computation() -> $result {
## Perl 6 operators are actually just funny-looking subroutines, in syntactic
## categories, like infix:<+> (addition) or prefix:<!> (bool not).
-## The categories are :
-# - "prefix" : before (like `!` in `!True`).
-# - "postfix" : after (like `++` in `$a++`).
-# - "infix" : in between (like `*` in `4 * 3`).
-# - "circumfix" : around (like `[`-`]` in `[1, 2]`).
-# - "post-circumfix" : around, after another term (like `{`-`}` in `%hash{'key'}`)
+## The categories are:
+# - "prefix": before (like `!` in `!True`).
+# - "postfix": after (like `++` in `$a++`).
+# - "infix": in between (like `*` in `4 * 3`).
+# - "circumfix": around (like `[`-`]` in `[1, 2]`).
+# - "post-circumfix": around, after another term (like `{`-`}` in `%hash{'key'}`)
## The associativity and precedence list are explained below.
@@ -334,7 +335,8 @@ if long-computation() -> $result {
(1, 2) eqv (1, 3);
# - `~~` is smart matching
-# For a complete list of combinations, use this table : http://perlcabal.org/syn/S03.html#Smart_matching
+# For a complete list of combinations, use this table:
+# http://perlcabal.org/syn/S03.html#Smart_matching
'a' ~~ /a/; # true if matches regexp
'key' ~~ %hash; # true if key exists in hash
$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg`
@@ -415,7 +417,7 @@ first-of-array(@tail); # Throws an error "Too many positional parameters passed"
# (which means the array is too big).
# You can also use a slurp ...
-sub slurp-in-array(@ [$fst, *@rest]) { # you could decide to keep `*@rest` anonymous
+sub slurp-in-array(@ [$fst, *@rest]) { # You could keep `*@rest` anonymous
say $fst + @rest.elems; # `.elems` returns a list's length.
# Here, `@rest` is `(3,)`, since `$fst` holds the `2`.
}
@@ -485,7 +487,8 @@ sub truthy-array(@array) {
# You can also use the "whatever star" to create an anonymous function
# (it'll stop at the furthest operator in the current expression)
my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }`
-my @arrayplus3 = map(*+*+3, @array); # also works. Same as `-> $a, $b { $a + $b + 3 }`
+my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }`
+ # also `sub ($a, $b) { $a + $b + 3 }`
say (*/2)(4); #=> 2
# Immediatly execute the function Whatever created.
say ((*+3)/5)(5); #=> 1.6
@@ -494,7 +497,8 @@ say ((*+3)/5)(5); #=> 1.6
# But if you need to have more than one argument (`$_`)
# in a block (without wanting to resort to `-> {}`),
# you can also use the implicit argument syntax, `$^` :
-map({ $^a + $^b + 3 }, @array); # same as the above
+map({ $^a + $^b + 3 }, @array); # equivalent to following:
+map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`)
# Note : those are sorted lexicographically.
# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }`
@@ -576,7 +580,7 @@ sub foo {
bar(); # call `bar` in-place
}
sub bar {
- say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`,
+ say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s,
# even though the blocks aren't nested (they're call-nested).
#=> 1
}
@@ -589,8 +593,9 @@ sub bar {
# but you have `$.` to get a public (immutable) accessor along with it.
# (using `$.` is like using `$!` plus a `method` with the same name)
-# (Perl 6's object model ("SixModel") is very flexible, and allows you to dynamically add methods,
-# change semantics, etc -- This will not be covered here, and you should refer to the Synopsis)
+# (Perl 6's object model ("SixModel") is very flexible,
+# and allows you to dynamically add methods, change semantics, etc ...
+# (this will not be covered here, and you should refer to the Synopsis).
class A {
has $.field; # `$.field` is immutable.
@@ -685,7 +690,7 @@ class Item does PrintableVal {
}
### Exceptions
-# Exceptions are built on top of classes, usually in the package `X` (like `X::IO`).
+# Exceptions are built on top of classes, in the package `X` (like `X::IO`).
# Unlike many other languages, in Perl 6, you put the `CATCH` block *within* the
# block to `try`. By default, a `try` has a `CATCH` block that catches
# any exception (`CATCH { default {} }`).
@@ -709,7 +714,7 @@ die X::AdHoc.new(payload => 'Error !');
# Packages are a way to reuse code. Packages are like "namespaces", and any
# element of the six model (`module`, `role`, `class`, `grammar`, `subset`
# and `enum`) are actually packages. (Packages are the lowest common denomitor)
-# Packages play a big part in a language, especially as Perl is well-known for CPAN,
+# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
# You usually don't use packages directly: you use `class Package::Name::Here;`,
# or if you only want to export variables/subs, you can use `module`:
@@ -719,7 +724,7 @@ module Hello::World { # Bracketed form
# ... declarations here ...
}
module Parse::Text; # file-scoped form
-grammar Parse::Text::Grammar { # A grammar is a fine package, which you could `use`
+grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
# NOTE for Perl 5 users: even though the `package` keyword exists,
@@ -841,7 +846,7 @@ say "This code took " ~ (time - CHECK time) ~ "s to run";
# ... or clever organization:
sub do-db-stuff {
- ENTER $db.start-transaction; # create a new transaction everytime we enter the sub
+ ENTER $db.start-transaction; # New transaction everytime we enter the sub
KEEP $db.commit; # commit the transaction if all went well
UNDO $db.rollback; # or rollback if all hell broke loose
}
@@ -951,7 +956,7 @@ say 5!; #=> 120
sub infix:<times>(Int $n, Block $r) { # infix in the middle
for ^$n {
$r(); # You need the explicit parentheses to call the function in `$r`,
- # else you'd be referring at the variable itself, kind of like with `&r`.
+ # else you'd be referring at the variable itself, like with `&r`.
}
}
3 times -> { say "hello" }; #=> hello
@@ -1004,8 +1009,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)
# of the element of the list to be passed to the operator),
# or `Any` if there's none (examples below).
#
-# Otherwise, it pops an element from the list(s) one at a time, and applies the binary function
-# to the last result (or the list's first element) and the popped element.
+# Otherwise, it pops an element from the list(s) one at a time, and applies
+# the binary function to the last result (or the list's first element)
+# and the popped element.
#
# To sum a list, you could use the reduce meta-operator with `+`, i.e.:
say [+] 1, 2, 3; #=> 6
@@ -1068,6 +1074,11 @@ my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above)
my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers,
# computed using a closure!
my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above)
+my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above)
+# $a and $b will always take the previous values, meaning here
+# they'll start with $a = 1 and $b = 1 (values we set by hand).
+# then $a = 1 and $b = 2 (result from previous $a+$b), and so on.
+
say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55
# (using a range as the index)
# Note : as for ranges, once reified, elements aren't re-calculated.
@@ -1127,15 +1138,15 @@ for <well met young hero we shall meet later> {
.say if 'B' ff 'B' for <A B C B A>; #=> B B
# because the right-hand-side was tested
# directly (and returned `True`).
- # "B"s are still printed since it matched that time
+ # "B"s are printed since it matched that time
# (it just went back to `False` right away).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
- # because the right-hand-side wasn't tested until
+ # The right-hand-side wasn't tested until
# `$_` became "C"
# (and thus did not match instantly).
# A flip-flop can change state as many times as needed:
-for <test start print this stop you stopped printing start printing again stop not anymore> {
+for <test start print it stop not printing start print again stop not anymore> {
.say if $_ eq 'start' ^ff^ $_ eq 'stop'; # exclude both "start" and "stop",
#=> "print this printing again"
}
@@ -1190,8 +1201,8 @@ say so 'a' ~~ / a /; # More readable with some spaces!
# a regexp. We're converting the result using `so`, but in fact, it's
# returning a `Match` object. They know how to respond to list indexing,
# hash indexing, and return the matched string.
-# The results of the match are also available as `$/` (implicitly lexically-scoped).
-# You can also use the capture variables (`$0`, `$1`, ... - starting at 0, not 1 !).
+# The results of the match are available as `$/` (implicitly lexically-scoped).
+# You can also use the capture variables (`$0`, `$1`, ... starting at 0, not 1 !).
#
# You can also note that `~~` does not perform start/end checking
# (meaning the regexp can be matched with just one char of the string),
@@ -1233,9 +1244,9 @@ so 'abbbbc' ~~ / a b+ c /; # `True`, matched 4 "b"s
so 'ac' ~~ / a b* c /; # `True`, they're all optional.
so 'abc' ~~ / a b* c /; # `True`
so 'abbbbc' ~~ / a b* c /; # `True`
-so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, but can't be something else.
+so 'aec' ~~ / a b* c /; # `False`. "b"(s) are optional, not replaceable.
-# - `**` - "Quantify It Yourself".
+# - `**` - (Unbound) Quantifier
# If you squint hard enough, you might understand
# why exponentation is used for quantity.
so 'abc' ~~ / a b ** 1 c /; # `True` (exactly one time)
@@ -1244,6 +1255,27 @@ so 'abbbc' ~~ / a b ** 1..3 c /; # `True`
so 'abbbbbbc' ~~ / a b ** 1..3 c /; # `False` (too much)
so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay)
+# - `<[]>` - Character classes
+# Character classes are the equivalent of PCRE's `[]` classes, but
+# they use a more perl6-ish syntax:
+say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa'
+# You can use ranges:
+say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou'
+# Just like in normal regexes, if you want to use a special character, escape it
+# (the last one is escaping a space)
+say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !'
+# You'll get a warning if you put duplicate names
+# (which has the nice effect of catching the wrote quoting:)
+'he he' ~~ / <[ h e ' ' ]> /; # Warns "Repeated characters found in characters class"
+
+# You can also negate them ... (equivalent to `[^]` in PCRE)
+so 'foo' ~~ / <-[ f o ]> + /; # False
+
+# ... and compose them: :
+so 'foo' ~~ / <[ a..z ] - [ f o ]> + /; # False (any letter except f and o)
+so 'foo' ~~ / <-[ a..z ] + [ f o ]> + /; # True (no letter except f and o)
+so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left part)
+
## Grouping and capturing
# Group: you can group parts of your regexp with `[]`.
# These groups are *not* captured (like PCRE's `(?:)`).
@@ -1255,7 +1287,7 @@ so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
# But this does not go far enough, because we can't actually get back what
# we matched.
# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (we keep `so` here and use `$/` below)
+so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
# So, starting with the grouping explanations.
# As we said before, our `Match` object is available as `$/`:
@@ -1286,7 +1318,7 @@ say $0.WHAT; #=> (Array)
# may it be a range or a specific value (even 1).
# If you're wondering how the captures are numbered, here's an explanation:
-TODO use graphs from s05
+# (TODO use graphs from s05)
## Alternatives - the `or` of regexps
@@ -1294,6 +1326,31 @@ TODO use graphs from s05
so 'abc' ~~ / a [ b | y ] c /; # `True`. Either "b" or "y".
so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ...
+# The difference between this `|` and the one you're probably used to is LTM.
+# LTM means "Longest Token Matching". This means that the engine will always
+# try to match as much as possible in the strng
+'foo' ~~ / fo | foo /; # `foo`, because it's longer.
+# To decide which part is the "longest", it first splits the regex in two parts:
+# The "declarative prefix" (the part that can be statically analyzed)
+# and the procedural parts.
+# Declarative prefixes include alternations (`|`), conjuctions (`&`),
+# sub-rule calls (not yet introduced), literals, characters classes and quantifiers.
+# The latter include everything else: back-references, code assertions,
+# and other things that can't traditionnaly be represented by normal regexps.
+#
+# Then, all the alternatives are tried at once, and the longest wins.
+# Exemples:
+# DECLARATIVE | PROCEDURAL
+/ 'foo' \d+ [ <subrule1> || <subrule2> ] /;
+# DECLARATIVE (nested groups are not a problem)
+/ \s* [ \w & b ] [ c | d ] /;
+# However, closures and recursion (of named regexps) are procedural.
+# ... There are also more complicated rules, like specificity
+# (literals win over character classes)
+
+# Note: the first-matching `or` still exists, but is now spelled `||`
+'foo' ~~ / fo || foo /; # `fo` now.
+
### Extra: the MAIN subroutime
# The `MAIN` subroutine is called when you run a Perl 6 file directly.
# It's very powerful, because Perl 6 actually parses the argument
@@ -1306,9 +1363,9 @@ sub MAIN($name) { say "Hello, you !" }
# t.pl <name>
# And since it's a regular Perl 6 sub, you can haz multi-dispatch:
-# (using a "Bool" for the named argument so that we get `--replace`
+# (using a "Bool" for the named argument so that we can do `--replace`
# instead of `--replace=1`)
-subset File of Str where *.IO.d; # convert to IO object, then check the file exists
+subset File of Str where *.IO.d; # convert to IO object to check the file exists
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
@@ -1325,7 +1382,9 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
```
If you want to go further, you can:
+
- Read the [Perl 6 Advent Calendar](http://perl6advent.wordpress.com/). This is probably the greatest source of Perl 6 information, snippets and such.
- Come along on `#perl6` at `irc.freenode.net`. The folks here are always helpful.
- Check the [source of Perl 6's functions and classes](https://github.com/rakudo/rakudo/tree/nom/src/core). Rakudo is mainly written in Perl 6 (with a lot of NQP, "Not Quite Perl", a Perl 6 subset easier to implement and optimize).
- Read the [Synopses](perlcabal.org/syn). They explain it from an implementor point-of-view, but it's still very interesting.
+
diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown
index 32c8fbdd..c7339831 100644
--- a/pt-br/go-pt.html.markdown
+++ b/pt-br/go-pt.html.markdown
@@ -75,7 +75,7 @@ func learnTypes() {
pode incluir quebras de linha.` // mesmo tipo string
// literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8.
- g := 'Σ' // tipo rune, um alias para uint32, que contém um código unicode
+ g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode
f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754)
c := 3 + 4i // complex128, representado internamente com dois float64s
diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown
index cac4a13e..4030ce3c 100644
--- a/pt-br/markdown-pt.html.markdown
+++ b/pt-br/markdown-pt.html.markdown
@@ -14,7 +14,7 @@ escrever sintaxe que converte facilmente em HTML (hoje, suporta outros formatos
Dê-me feedback tanto quanto você quiser! / Sinta-se livre para a garfar (fork) e
puxar o projeto (pull request)
-```
+```markdown
<!-- Markdown é um superconjunto do HTML, de modo que qualquer arvquivo HTML é
um arquivo Markdown válido, isso significa que nós podemos usar elementos HTML
em Markdown, como o elemento de comentário, e eles não serão afetados pelo analisador
diff --git a/purescript.html.markdown b/purescript.html.markdown
new file mode 100644
index 00000000..6bff7545
--- /dev/null
+++ b/purescript.html.markdown
@@ -0,0 +1,195 @@
+---
+language: purescript
+contributors:
+ - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"]
+---
+
+PureScript is a small strongly, statically typed language compiling to Javascript.
+
+* Learn more at [http://www.purescript.org/](http://www.purescript.org/)
+* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/)
+* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/)
+
+```haskell
+
+--
+-- 1. Primitive datatypes that corresponds to their Javascript
+-- equivalents at runtime.
+
+-- Numbers
+1 + 7*5 :: Number -- 36
+-- Types are inferred, so the following works fine
+9 / 2.5 + 4.4 -- 8
+-- Hexadecimal literals
+0xff + 1 -- 256
+-- Unary negation
+6 * -3 -- -18
+6 * negate 3 -- -18
+-- Modulus
+3 % 2 -- 1
+4 % 2 -- 0
+-- Inspect the type of an expression in psci
+:t 9 / 2.5 + 4.4 -- Prim.Number
+
+-- Booleans
+true :: Boolean -- true
+false :: Boolean -- false
+-- Negation
+not true --false
+23 == 23 -- true
+1 /= 4 -- true
+1 >= 4 -- false
+-- Comparisions < <= > >=
+-- are defined in terms of compare
+compare 1 2 -- LT
+compare 2 2 -- EQ
+compare 3 2 -- GT
+-- Conjunction and Disjunction
+true && (9 >= 19 || 1 < 2) -- true
+
+-- Strings
+"Hellow" :: String -- "Hellow"
+-- Multiline string
+"Hellow\
+\orld" -- "Helloworld"
+-- Concatenate
+"such " ++ "amaze" -- "such amaze"
+
+--
+-- 2. Arrays are Javascript arrays, but must be homogeneous
+
+[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8]
+[true, true, false] :: [Boolean] -- [true,true,false]
+-- [1,2, true, "false"] won't work
+-- `Cannot unify Prim.Number with Prim.Boolean`
+-- Cons (prepend)
+1 : [2,4,3] -- [1,2,4,3]
+
+-- Requires purescript-arrays (Data.Array)
+-- and purescript-maybe (Data.Maybe)
+
+-- Safe access return Maybe a
+head [1,2,3] -- Just (1)
+tail [3,2,1] -- Just ([2,1])
+init [1,2,3] -- Just ([1,2])
+last [3,2,1] -- Just (1)
+-- Random access - indexing
+[3,4,5,6,7] !! 2 -- Just (5)
+-- Range
+1..5 -- [1,2,3,4,5]
+length [2,2,2] -- 3
+drop 3 [5,4,3,2,1] -- [2,1]
+take 3 [5,4,3,2,1] -- [5,4,3]
+append [1,2,3] [4,5,6] -- [1,2,3,4,5,6]
+
+--
+-- 3. Records are Javascript objects, with zero or more fields, which
+-- can have different types
+let book = {title: "Foucault's pendulum", author: "Umberto Eco"}
+-- Access properties
+book.title -- "Foucault's pendulum"
+
+getTitle b = b.title
+-- Works on all records with a title (but doesn't require any other field)
+getTitle book -- "Foucault's pendulum"
+getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco"
+-- Update a record
+changeTitle b t = b {title = t}
+changeTitle book "Ill nome della rosa" -- {title: "Ill nome della
+ -- rosa", author: "Umberto Eco"}
+
+--
+-- 4. Functions
+sumOfSquares x y = x*x+y*y
+sumOfSquares 3 4 -- 25
+-- In psci you have to write `let` in front of the function to get a
+-- top level binding
+mod x y = x % y
+mod 3 2 -- 1
+-- Infix application of function
+3 `mod` 2 -- 1
+
+-- function application have higher precedence than all other
+-- operators
+sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025
+
+-- Conditional
+abs' n = if n>=0 then n else -n
+abs' (-3) -- 3
+
+-- Guarded equations
+abs n | n >= 0 = n
+ | otherwise = -n
+
+-- Pattern matching
+
+-- Note the type signature, input is an array of numbers The pattern
+-- matching destructures and binds the array into parts
+first :: [Number] -> Number
+first (x:_) = x
+first [3,4,5] -- 3
+second :: [Number] -> Number
+second (_:y:_) = y
+second [3,4,5] -- 4
+sumTwo :: [Number] -> [Number]
+sumTwo (x:y:rest) = (x+y) : rest
+sumTwo [2,3,4,5,6] -- [5,4,5,6]
+
+-- sumTwo doesn't handle when the array is empty or just have one
+-- element in which case you get an error
+sumTwo [1] -- Failed pattern match
+
+-- Complementing patterns to match
+-- Good ol' Fibonacci
+fib 1 = 1
+fib 2 = 2
+fib x = fib (x-1) + fib (x-2)
+fib 10 -- 89
+
+-- Use underscore to match any, where you don't care about the binding name
+isZero 0 = true
+isZero _ = false
+
+-- Pattern matching on records
+ecoTitle {author = "Umberto Eco", title = t} = Just t
+ecoTitle _ = Nothing
+
+ecoTitle book -- Just ("Foucault's pendulum")
+ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing
+-- ecoTitle requires both field to type check:
+ecoTitle {title: "The Quantum Thief"} -- Object does not have property author
+
+-- Lambda expressions
+(\x -> x*x) 3 -- 9
+(\x y -> x*x + y*y) 4 5 -- 41
+sqr = \x -> x*x
+
+-- Currying
+add x y = x + y -- is equivalent with
+add = \x -> (\y -> x+y)
+add3 = add 3
+:t add3 -- Prim.Number -> Prim.Number
+
+-- Forward and backward function composition
+-- drop 3 followed by taking 5
+(drop 3 >>> take 5) (1..20) -- [4,5,6,7,8]
+-- take 5 followed by dropping 3
+(drop 3 <<< take 5) (1..20) -- [4,5]
+
+-- Operations using higher order functions
+even x = x % 2 == 0
+filter even (1..10) -- [2,4,6,8,10]
+map (\x -> x+11) (1..5) -- [12,13,14,15,16]
+
+-- Requires purescript-foldable-traversabe (Data.Foldable)
+
+foldr (+) 0 (1..10) -- 55
+sum (1..10) -- 55
+product (1..10) -- 3628800
+
+-- Testing with predicate
+any even [1,2,3] -- true
+all even [1,2,3] -- false
+
+```
+
diff --git a/python.html.markdown b/python.html.markdown
index 9057dde2..390c7b76 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -57,9 +57,17 @@ to Python 2.x. Look for another tour of Python 3 soon!
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
-# Boolean values are primitives
-True
-False
+# Boolean Operators
++# Note "and" and "or" are case-sensitive
++True and False #=> False
++False or True #=> True
++
++# Note using Bool operators with ints
++0 and 2 #=> 0
++-5 or 0 #=> -5
++0 == False #=> True
++2 == True #=> False
+1 == True #=> True
# negate with not
not True # => False
diff --git a/python3.html.markdown b/python3.html.markdown
index b494dc1e..a94f4eae 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -61,6 +61,18 @@ False
not True # => False
not False # => True
+# Boolean Operators
+# Note "and" and "or" are case-sensitive
+True and False #=> False
+False or True #=> True
+
+# Note using Bool operators with ints
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
# Equality is ==
1 == 1 # => True
2 == 1 # => False
@@ -93,7 +105,9 @@ not False # => True
"{} can be {}".format("strings", "interpolated")
# You can repeat the formatting arguments to save some typing.
-"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") #=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+"{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick")
+#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick"
+
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
@@ -125,7 +139,8 @@ bool({}) #=> False
# Python has a print function
print("I'm Python. Nice to meet you!")
-# No need to declare variables before assigning to them. Convention is to use lower_case_with_underscores
+# No need to declare variables before assigning to them.
+# Convention is to use lower_case_with_underscores
some_var = 5
some_var # => 5
@@ -174,7 +189,8 @@ li[::-1] # => [3, 4, 2, 1]
del li[2] # li is now [1, 2, 3]
# You can add lists
-li + other_li # => [1, 2, 3, 4, 5, 6] - Note: values for li and for other_li are not modified.
+# Note: values for li and for other_li are not modified.
+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]
@@ -213,14 +229,17 @@ 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.
-list(filled_dict.keys()) # => ["three", "two", "one"]
+# Get all keys as a list with "keys()".
+# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later.
# Note - Dictionary key ordering is not guaranteed.
# Your results might not match this exactly.
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable.
-list(filled_dict.values()) # => [3, 2, 1]
# Note - Same as above regarding key ordering.
+list(filled_dict.values()) # => [3, 2, 1]
+
# Check for existence of keys in a dictionary with "in"
"one" in filled_dict # => True
@@ -240,6 +259,10 @@ filled_dict.get("four", 4) # => 4
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
+# Adding to a dictionary
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+#filled_dict["four"] = 4 #another way to add to dict
+
# Remove keys from a dictionary with del
del filled_dict["one"] # Removes the key "one" from filled dict
@@ -456,6 +479,7 @@ map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# We can use list comprehensions for nice maps and filters
+# List comprehension stores the output as a list which can itself be a nested list
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
diff --git a/r.html.markdown b/r.html.markdown
index b59fc29c..7cb56fd7 100644
--- a/r.html.markdown
+++ b/r.html.markdown
@@ -8,7 +8,7 @@ filename: learnr.r
R is a statistical computing language. It has lots of libraries for uploading and cleaning data sets, running statistical procedures, and making graphs. You can also run `R` commands within a LaTeX document.
-```python
+```r
# Comments start with number symbols.
diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown
index ffda01b7..44a22b45 100644
--- a/ru-ru/go-ru.html.markdown
+++ b/ru-ru/go-ru.html.markdown
@@ -13,11 +13,11 @@ lang: ru-ru
---
Go - это язык общего назначения, целью которого является удобство, простота,
-конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый
+конкурентность. Это не тренд в компьютерных науках, а новейший и быстрый
способ решать насущные проблемы.
Концепции Go схожи с другими императивными статически типизированными языками.
-Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции
+Быстро компилируется и быстро исполняется, имеет лёгкие в понимании конструкции
для создания масштабируемых и многопоточных программ.
Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным
@@ -57,7 +57,7 @@ func main() {
func beyondHello() {
var x int // Переменные должны быть объявлены до их использования.
x = 3 // Присвоение значения переменной.
- // Краткое определение := позволяет объявить перменную с автоматической
+ // Краткое определение := позволяет объявить переменную с автоматической
// подстановкой типа из значения.
y := 4
sum, prod := learnMultiple(x, y) // Функция возвращает два значения.
@@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) {
return x + y, x * y // Возврат двух значений.
}
-// Некотрые встроенные типы и литералы.
+// Некоторые встроенные типы и литералы.
func learnTypes() {
// Краткое определение переменной говорит само за себя.
s := "Learn Go!" // Тип string.
@@ -79,7 +79,7 @@ func learnTypes() {
может содержать переносы строк` // Тоже тип данных string
// Символ не из ASCII. Исходный код Go в кодировке UTF-8.
- g := 'Σ' // тип rune, это алиас для типа uint32, содержит символ юникода.
+ g := 'Σ' // тип rune, это алиас для типа int32, содержит символ юникода.
f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754).
c := 3 + 4i // complex128, внутри себя содержит два float64.
@@ -97,7 +97,7 @@ func learnTypes() {
// Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои
// преимущества, но слайсы используются гораздо чаще.
- s3 := []int{4, 5, 9} // Сравните с a3. Тут нет троеточия.
+ s3 := []int{4, 5, 9} // Сравните с a3, тут нет троеточия.
s4 := make([]int, 4) // Выделение памяти для слайса из 4-х int (нули).
var d2 [][]float64 // Только объявление, память не выделяется.
bs := []byte("a slice") // Синтаксис приведения типов.
@@ -113,7 +113,7 @@ func learnTypes() {
delete(m, "three") // Встроенная функция, удаляет элемент из map-а.
// Неиспользуемые переменные в Go являются ошибкой.
- // Нижнее подчеркивание позволяет игнорировать такие переменные.
+ // Нижнее подчёркивание позволяет игнорировать такие переменные.
_, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
// Вывод считается использованием переменной.
fmt.Println(s, c, a4, s3, d2, m)
@@ -121,16 +121,16 @@ func learnTypes() {
learnFlowControl() // Идем дальше.
}
-// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики
+// У Go есть полноценный сборщик мусора. В нем есть указатели, но нет арифметики
// указателей. Вы можете допустить ошибку с указателем на nil, но не с
// инкрементацией указателя.
func learnMemory() (p, q *int) {
// Именованные возвращаемые значения p и q являются указателями на int.
p = new(int) // Встроенная функция new выделяет память.
- // Выделенный int проинициализирован нулем, p больше не содержит nil.
+ // Выделенный int проинициализирован нулём, p больше не содержит nil.
s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов.
s[3] = 7 // Присвоить значение одному из них.
- r := -2 // Определить еще одну локальную переменную.
+ r := -2 // Определить ещё одну локальную переменную.
return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной.
}
@@ -139,7 +139,7 @@ func expensiveComputation() float64 {
}
func learnFlowControl() {
- // If-ы всегда требуют наличине фигурных скобок, но не круглых.
+ // If-ы всегда требуют наличие фигурных скобок, но не круглых.
if true {
fmt.Println("told ya")
}
@@ -178,7 +178,7 @@ func learnFlowControl() {
}
// Функции являются замыканиями.
xBig := func() bool {
- return x > 10000 // Ссылается на x, объявленый выше switch.
+ return x > 10000 // Ссылается на x, объявленный выше switch.
}
fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10).
x = 1.3e3 // Тут х == 1300
@@ -189,7 +189,7 @@ func learnFlowControl() {
love:
learnDefer() // Быстрый обзор важного ключевого слова.
- learnInterfaces() // О! Интерфейсы, идем далее.
+ learnInterfaces() // О! Интерфейсы, идём далее.
}
func learnDefer() (ok bool) {
@@ -214,7 +214,7 @@ type pair struct {
// Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer.
func (p pair) String() string { // p в данном случае называют receiver-ом.
- // Sprintf – еще одна функция из пакета fmt.
+ // Sprintf – ещё одна функция из пакета fmt.
// Обращение к полям p через точку.
return fmt.Sprintf("(%d, %d)", p.x, p.y)
}
@@ -234,7 +234,7 @@ func learnInterfaces() {
fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String.
fmt.Println(i) // Вывод такой же, что и выше.
- learnVariadicParams("Учиться", "учиться", "и еще раз учиться!")
+ learnVariadicParams("Учиться", "учиться", "и ещё раз учиться!")
}
// Функции могут иметь варьируемое количество параметров.
@@ -263,22 +263,22 @@ func learnErrorHandling() {
// выведет "strconv.ParseInt: parsing "non-int": invalid syntax"
fmt.Println(err)
}
- // Мы еще обратимся к интерфейсам чуть позже, а пока...
+ // Мы ещё обратимся к интерфейсам чуть позже, а пока...
learnConcurrency()
}
-// c – это тип данных channel (канал), объект для конкуррентного взаимодействия.
+// c – это тип данных channel (канал), объект для конкурентного взаимодействия.
func inc(i int, c chan int) {
c <- i + 1 // когда channel слева, <- являтся оператором "отправки".
}
-// Будем использовать функцию inc для конкуррентной инкрементации чисел.
+// Будем использовать функцию inc для конкурентной инкрементации чисел.
func learnConcurrency() {
// Тот же make, что и в случае со slice. Он предназначен для выделения
// памяти и инициализации типов slice, map и channel.
c := make(chan int)
- // Старт трех конкуррентных goroutine. Числа будут инкрементированы
- // конкуррентно и, может быть параллельно, если машина правильно
+ // Старт трех конкурентных goroutine. Числа будут инкрементированы
+ // конкурентно и, может быть параллельно, если машина правильно
// сконфигурирована и позволяет это делать. Все они будут отправлены в один
// и тот же канал.
go inc(0, c) // go начинает новую горутину.
@@ -291,7 +291,7 @@ func learnConcurrency() {
cs := make(chan string) // другой канал, содержит строки.
cc := make(chan chan string) // канал каналов со строками.
go func() { c <- 84 }() // пуск новой горутины для отправки значения
- go func() { cs <- "wordy" }() // еще раз, теперь для cs
+ go func() { cs <- "wordy" }() // ещё раз, теперь для cs
// Select тоже что и switch, но работает с каналами. Он случайно выбирает
// готовый для взаимодействия канал.
select {
@@ -327,7 +327,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Основа всех основ в Go это [официальный веб сайт](http://golang.org/).
Там можно пройти туториал, поиграться с интерактивной средой Go и почитать
-объемную документацию.
+объёмную документацию.
Для живого ознакомления рекомендуется почитать исходные коды [стандартной
библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она
diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown
index 72e3b9e0..3246de82 100644
--- a/ru-ru/objective-c-ru.html.markdown
+++ b/ru-ru/objective-c-ru.html.markdown
@@ -13,7 +13,7 @@ Objective-C — компилируемый объектно-ориентиров
построенный на основе языка Си и парадигм Smalltalk.
В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения.
-```cpp
+```objective_c
// Однострочный комментарий
/*
diff --git a/ru-ru/python-ru.html.markdown b/ru-ru/python-ru.html.markdown
index 204eb357..d59d3e21 100644
--- a/ru-ru/python-ru.html.markdown
+++ b/ru-ru/python-ru.html.markdown
@@ -5,25 +5,29 @@ contributors:
- ["Louie Dinh", "http://ldinh.ca"]
translators:
- ["Yury Timofeev", "http://twitter.com/gagar1n"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython-ru.py
---
-Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из самых популярных
-языков. Я люблю его за его понятный и доходчивый синтаксис - это почти что исполняемый псевдокод.
+Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из
+самых популярных языков. Я люблю его за понятный и доходчивый синтаксис — это
+почти что исполняемый псевдокод.
-С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh) или louiedinh [at] [google's email service]
+С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh)
+или louiedinh [at] [почтовый сервис Google]
-Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x. Скоро будет версия и для Python 3!
+Замечание: Эта статья относится к Python 2.7, но должно работать и в Python 2.x.
+Скоро будет версия и для Python 3!
```python
-# Однострочные комментарии начинаются с hash-символа.
+# Однострочные комментарии начинаются с символа решётки.
""" Многострочный текст может быть
записан, используя 3 знака " и обычно используется
в качестве комментария
"""
####################################################
-## 1. Примитивные типы данных и операторов
+## 1. Примитивные типы данных и операторы
####################################################
# У вас есть числа
@@ -36,17 +40,31 @@ filename: learnpython-ru.py
35 / 5 #=> 7
# А вот деление немного сложнее. В этом случае происходит деление
-# целых чисел и результат автоматически округляется в меньшую сторону.
+# целых чисел, и результат автоматически округляется в меньшую сторону.
5 / 2 #=> 2
-# Чтобы научиться делить, сначала нужно немного узнать о дробных числах.
-2.0 # Это дробное число
+# Чтобы научиться делить, сначала нужно немного узнать о числах
+# с плавающей запятой.
+2.0 # Это число с плавающей запятой
11.0 / 4.0 #=> 2.75 Вооот... Так гораздо лучше
+# Результат целочисленного деления округляется в меньшую сторону
+# как для положительных, так и для отрицательных чисел.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Остаток от деления
+7 % 3 # => 1
+
+# Возведение в степень
+2 ** 4 # => 16
+
# Приоритет операций указывается скобками
(1 + 3) * 2 #=> 8
-# Логические значения являются примитивами
+# Логические (булевы) значения являются примитивами
True
False
@@ -54,15 +72,15 @@ False
not True #=> False
not False #=> True
-# Равенство это ==
+# Равенство — это ==
1 == 1 #=> True
2 == 1 #=> False
-# Неравенство это !=
+# Неравенство — это !=
1 != 1 #=> False
2 != 1 #=> True
-# Еще немного сравнений
+# Ещё немного сравнений
1 < 10 #=> True
1 > 10 #=> False
2 <= 2 #=> True
@@ -85,9 +103,10 @@ not False #=> True
# Символ % используется для форматирования строк, например:
"%s могут быть %s" % ("строки", "интерполированы")
-# Новый метод форматирования строк - использование метода format.
+# Новый способ форматирования строк — использование метода format.
# Это предпочитаемый способ.
"{0} могут быть {1}".format("строки", "форматированы")
+
# Если вы не хотите считать, можете использовать ключевые слова.
"{name} хочет есть {food}".format(name="Боб", food="лазанью")
@@ -95,7 +114,7 @@ not False #=> True
None #=> None
# Не используйте оператор равенства '=='' для сравнения
-# объектов с None. Используйте для этого 'is'
+# объектов с None. Используйте для этого «is»
"etc" is None #=> False
None is None #=> True
@@ -113,17 +132,18 @@ None is None #=> True
## 2. Переменные и коллекции
####################################################
-# Печатать довольно просто
-print "Я Python. Приятно познакомиться!"
-
+# У Python есть функция Print, доступная в версиях 2.7 и 3,
+print("Я Python. Приятно познакомиться!")
+# ...и старый оператор print, доступный в версиях 2.x, но удалённый в версии 3.
+print "И я тоже Python!"
# Необязательно объявлять переменные перед их инициализацией.
-some_var = 5 # По соглашению используется нижний_регистр_с_подчеркиваниями
+some_var = 5 # По соглашению используется нижний_регистр_с_подчёркиваниями
some_var #=> 5
-# При попытке доступа к неинициализированной переменной,
+# При попытке доступа к неинициализированной переменной
# выбрасывается исключение.
-# См. раздел "Поток управления" для информации об исключениях.
+# См. раздел «Поток управления» для информации об исключениях.
some_other_var # Выбрасывает ошибку именования
# if может быть использован как выражение
@@ -149,24 +169,30 @@ li[0] #=> 1
# Обратимся к последнему элементу
li[-1] #=> 3
-# Попытка выйти за границы массива приведет к IndexError
-li[4] # Выдает IndexError
+# Попытка выйти за границы массива приведёт к ошибке индекса
+li[4] # Выдаёт IndexError
# Можно обращаться к диапазону, используя "кусочный синтаксис" (slice syntax)
-# (Для тех, кто любит математику, это называется замкнуто/открытый интервал.)
+# (Для тех, кто любит математику, это называется замкнуто-открытый интервал).
li[1:3] #=> [2, 4]
# Опускаем начало
li[2:] #=> [4, 3]
# Опускаем конец
li[:3] #=> [1, 2, 4]
+# Выбираем каждый второй элемент
+li[::2] # =>[1, 4]
+# Переворачиваем список
+li[::-1] # => [3, 4, 2, 1]
+# Используйте сочетания всего вышеназванного для выделения более сложных кусков
+# li[начало:конец:шаг]
# Удаляем произвольные элементы из списка оператором del
del li[2] # [1, 2, 3]
# Вы можете складывать списки
-li + other_li #=> [1, 2, 3, 4, 5, 6] - Замечание: li и other_li остаются нетронутыми
+li + other_li #=> [1, 2, 3, 4, 5, 6] — Замечание: li и other_li не изменяются
-# Конкатенировать списки можно методом extend
+# Объединять списки можно методом extend
li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
# Проверить элемент на вхождение в список можно оператором in
@@ -176,12 +202,12 @@ li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
len(li) #=> 6
-# Кортежи - это такие списки, только неизменяемые
+# Кортежи — это такие списки, только неизменяемые
tup = (1, 2, 3)
tup[0] #=> 1
-tup[0] = 3 # Выдает TypeError
+tup[0] = 3 # Выдаёт TypeError
-# Все то же самое можно делать и с кортежами
+# Всё то же самое можно делать и с кортежами
len(tup) #=> 3
tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
tup[:2] #=> (1, 2)
@@ -203,33 +229,33 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Значения ищутся по ключу с помощью оператора []
filled_dict["one"] #=> 1
-# Можно получить все ключи в виде списка
+# Можно получить все ключи в виде списка с помощью метода keys
filled_dict.keys() #=> ["three", "two", "one"]
-# Замечание - сохранение порядка ключей в словаре не гарантируется
+# Замечание: сохранение порядка ключей в словаре не гарантируется
# Ваши результаты могут не совпадать с этими.
-# Можно получить и все значения в виде списка
+# Можно получить и все значения в виде списка, используйте метод values
filled_dict.values() #=> [3, 2, 1]
-# То же самое замечание насчет порядка ключей справедливо и здесь
+# То же самое замечание насчёт порядка ключей справедливо и здесь
# При помощи оператора in можно проверять ключи на вхождение в словарь
"one" in filled_dict #=> True
1 in filled_dict #=> False
-# Попытка получить значение по несуществующему ключу выбросит KeyError
+# Попытка получить значение по несуществующему ключу выбросит ошибку ключа
filled_dict["four"] # KeyError
# Чтобы избежать этого, используйте метод get
filled_dict.get("one") #=> 1
filled_dict.get("four") #=> None
-# Метод get также принимает аргумент default, значение которого будет
+# Метод get также принимает аргумент по умолчанию, значение которого будет
# возвращено при отсутствии указанного ключа
filled_dict.get("one", 4) #=> 1
filled_dict.get("four", 4) #=> 4
-# Метод setdefault - это безопасный способ добавить новую пару ключ-значение в словарь
+# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
-filled_dict.setdefault("five", 6) #filled_dict["five"] по прежнему возвращает 5
+filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
# Множества содержат... ну, в общем, множества
@@ -237,8 +263,8 @@ empty_set = set()
# Инициализация множества набором значений
some_set = set([1,2,2,3,4]) # some_set теперь равно set([1, 2, 3, 4])
-# Начиная с Python 2.7, вы можете использовать {} чтобы обьявить множество
-filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
+# Начиная с Python 2.7, вы можете использовать {}, чтобы объявить множество
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
# Добавление новых элементов в множество
filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5}
@@ -262,33 +288,33 @@ filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
## 3. Поток управления
####################################################
-# Для начала заведем переменную
+# Для начала заведём переменную
some_var = 5
# Так выглядит выражение if. Отступы в python очень важны!
-# результат: "some_var меньше, чем 10"
+# результат: «some_var меньше, чем 10»
if some_var > 10:
- print "some_var намного больше, чем 10."
+ print("some_var намного больше, чем 10.")
elif some_var < 10: # Выражение elif необязательно.
- print "some_var меньше, чем 10."
+ print("some_var меньше, чем 10.")
else: # Это тоже необязательно.
- print "some_var равно 10."
+ print("some_var равно 10.")
"""
Циклы For проходят по спискам
Результат:
- собака это млекопитающее
- кошка это млекопитающее
- мышь это млекопитающее
+ собака — это млекопитающее
+ кошка — это млекопитающее
+ мышь — это млекопитающее
"""
for animal in ["собака", "кошка", "мышь"]:
# Можете использовать оператор % для интерполяции форматированных строк
- print "%s это млекопитающее" % animal
+ print("%s — это млекопитающее" % animal)
"""
-`range(number)` возвращает список чисел
+«range(число)» возвращает список чисел
от нуля до заданного числа
Результат:
0
@@ -297,7 +323,7 @@ for animal in ["собака", "кошка", "мышь"]:
3
"""
for i in range(4):
- print i
+ print(i)
"""
Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
@@ -309,19 +335,24 @@ for i in range(4):
"""
x = 0
while x < 4:
- print x
- x += 1 # То же самое, что x = x + 1
+ print(x)
+ x += 1 # Краткая запись для x = x + 1
-# Обрабывайте исключения блоками try/except
+# Обрабатывайте исключения блоками try/except
# Работает в Python 2.6 и выше:
try:
- # Для выбора ошибки используется raise
- raise IndexError("Это IndexError")
+ # Чтобы выбросить ошибку, используется raise
+ raise IndexError("Это ошибка индекса")
except IndexError as e:
# pass это просто отсутствие оператора. Обычно здесь происходит
- # восстановление от ошибки.
+ # восстановление после ошибки.
pass
+except (TypeError, NameError):
+ pass # Несколько исключений можно обработать вместе, если нужно.
+else: # Необязательное выражение. Должно следовать за последним блоком except
+ print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+
####################################################
@@ -330,23 +361,23 @@ except IndexError as e:
# Используйте def для создания новых функций
def add(x, y):
- print "x равен %s, а y равен %s" % (x, y)
+ print("x равен %s, а y равен %s" % (x, y))
return x + y # Возвращайте результат выражением return
# Вызов функции с аргументами
-add(5, 6) #=> prints out "x равен 5, а y равен 6" и возвращает 11
+add(5, 6) #=> выводит «x равен 5, а y равен 6» и возвращает 11
-# Другой способ вызова функции с аргументами
+# Другой способ вызова функции — вызов с именованными аргументами
add(y=6, x=5) # Именованные аргументы можно указывать в любом порядке.
-# Вы можете определить функцию, принимающую неизвестное количество аргументов
+# Вы можете определить функцию, принимающую изменяемое число аргументов
def varargs(*args):
return args
varargs(1, 2, 3) #=> (1,2,3)
-# А также можете определить функцию, принимающую изменяющееся количество
+# А также можете определить функцию, принимающую изменяемое число
# именованных аргументов
def keyword_args(**kwargs):
return kwargs
@@ -356,8 +387,8 @@ keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
# Если хотите, можете использовать оба способа одновременно
def all_the_args(*args, **kwargs):
- print args
- print kwargs
+ print(args)
+ print(kwargs)
"""
all_the_args(1, 2, a=3, b=4) выводит:
(1, 2)
@@ -368,11 +399,28 @@ all_the_args(1, 2, a=3, b=4) выводит:
# Используйте символ * для передачи кортежей и ** для передачи словарей
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
-all_the_args(*args) # эквивалент foo(1, 2, 3, 4)
-all_the_args(**kwargs) # эквивалент foo(a=3, b=4)
-all_the_args(*args, **kwargs) # эквивалент foo(1, 2, 3, 4, a=3, b=4)
+all_the_args(*args) # эквивалентно foo(1, 2, 3, 4)
+all_the_args(**kwargs) # эквивалентно foo(a=3, b=4)
+all_the_args(*args, **kwargs) # эквивалентно foo(1, 2, 3, 4, a=3, b=4)
-# Python имеет функции первого класса
+# Область определения функций
+x = 5
+
+def setX(num):
+ # Локальная переменная x — это не то же самое, что глобальная переменная x
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # Глобальная переменная x теперь равна 6
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+# В Python есть функции первого класса
def create_adder(x):
def adder(y):
return x + y
@@ -388,7 +436,7 @@ add_10(3) #=> 13
map(add_10, [1,2,3]) #=> [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
-# Мы можем использовать списки для удобного отображения и фильтрации
+# Для удобного отображения и фильтрации можно использовать списочные включения
[add_10(i) for i in [1, 2, 3]] #=> [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
@@ -402,7 +450,11 @@ class Human(object):
# Атрибут класса. Он разделяется всеми экземплярами этого класса
species = "H. sapiens"
- # Обычный конструктор
+ # Обычный конструктор, вызывается при инициализации экземпляра класса
+ # Обратите внимание, что двойное подчёркивание в начале и в конце имени
+ # означает объекты и атрибуты, которые используются Python, но находятся
+ # в пространствах имён, управляемых пользователем.
+ # Не придумывайте им имена самостоятельно.
def __init__(self, name):
# Присваивание значения аргумента атрибуту класса name
self.name = name
@@ -423,17 +475,17 @@ class Human(object):
return "*grunt*"
-# Инстанцирование класса
+# Инициализация экземпляра класса
i = Human(name="Иван")
-print i.say("привет") # "Иван: привет"
+print(i.say("привет")) # Выводит: «Иван: привет»
-j = Human("Петр")
-print j.say("Привет") # "Петр: привет"
+j = Human("Пётр")
+print(j.say("Привет")) # Выводит: «Пётр: привет»
# Вызов метода класса
i.get_species() #=> "H. sapiens"
-# Присвоение разделяемому атрибуту
+# Изменение разделяемого атрибута
Human.species = "H. neanderthalensis"
i.get_species() #=> "H. neanderthalensis"
j.get_species() #=> "H. neanderthalensis"
@@ -448,12 +500,12 @@ Human.grunt() #=> "*grunt*"
# Вы можете импортировать модули
import math
-print math.sqrt(16) #=> 4
+print(math.sqrt(16)) #=> 4
# Вы можете импортировать отдельные функции модуля
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
# Можете импортировать все функции модуля.
# (Хотя это и не рекомендуется)
@@ -463,7 +515,7 @@ from math import *
import math as m
math.sqrt(16) == m.sqrt(16) #=> True
-# Модули в Python это обычные файлы с кодом python. Вы
+# Модули в Python — это обычные Python-файлы. Вы
# можете писать свои модули и импортировать их. Название
# модуля совпадает с названием файла.
@@ -472,18 +524,72 @@ math.sqrt(16) == m.sqrt(16) #=> True
import math
dir(math)
+####################################################
+## 7. Дополнительно
+####################################################
+
+# Генераторы помогут выполнить ленивые вычисления
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Генератор создаёт значения на лету.
+# Он не возвращает все значения разом, а создаёт каждое из них при каждой
+# итерации. Это значит, что значения больше 15 в double_numbers
+# обработаны не будут.
+# Обратите внимание: xrange — это генератор, который делает то же, что и range.
+# Создание списка чисел от 1 до 900000000 требует много места и времени.
+# xrange создаёт объект генератора, а не список сразу, как это делает range.
+# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
+# мы используем подчёркивание в конце
+xrange_ = xrange(1, 900000000)
+
+# Будет удваивать все числа, пока результат не будет >= 30
+for i in double_numbers(xrange_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# Декораторы
+# В этом примере beg оборачивает say
+# Метод beg вызовет say. Если say_please равно True,
+# он изменит возвращаемое сообщение
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, " Пожалуйста! У меня нет денег :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Вы не купите мне пива?"
+ return msg, say_please
+
+
+print(say()) # Вы не купите мне пива?
+print(say(say_please=True)) # Вы не купите мне пива? Пожалуйста! У меня нет денег :(
```
-## Хотите еще?
+## Хотите ещё?
### Бесплатные онлайн-материалы
* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
* [Dive Into Python](http://www.diveintopython.net/)
-* [The Official Docs](http://docs.python.org/2.6/)
+* [Официальная документация](http://docs.python.org/2.6/)
* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
* [Python Module of the Week](http://pymotw.com/2/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
### Платные
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 962853a2..3c67de2e 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -9,6 +9,7 @@ contributors:
- ["Nick LaMuro", "https://github.com/NickLaMuro"]
- ["Marcos Brizeno", "http://www.about.me/marcosbrizeno"]
- ["Ariel Krakowski", "http://www.learneroo.com"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
---
@@ -35,7 +36,7 @@ You shouldn't either
8 - 1 #=> 7
10 * 2 #=> 20
35 / 5 #=> 7
-2 ** 5 #=> 32
+2**5 #=> 32
# Arithmetic is just syntactic sugar
# for calling a method on an object
@@ -78,14 +79,17 @@ false.class #=> FalseClass
'I am a string'.class #=> String
"I am a string too".class #=> String
-placeholder = "use string interpolation"
+placeholder = 'use string interpolation'
"I can #{placeholder} when using double quoted strings"
#=> "I can use string interpolation when using double quoted strings"
+# Prefer single quoted strings to double quoted ones where possible
+# Double quoted strings perform additional inner calculations
+
# Combine strings, but not with numbers
-"hello " + "world" #=> "hello world"
-"hello " + 3 #=> TypeError: can't convert Fixnum into String
-"hello " + 3.to_s #=> "hello 3"
+'hello ' + 'world' #=> "hello world"
+'hello ' + 3 #=> TypeError: can't convert Fixnum into String
+'hello ' + 3.to_s #=> "hello 3"
# print to the output
puts "I'm printing!"
@@ -130,7 +134,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5]
# Arrays can contain different types of items
-[1, "hello", false] #=> [1, "hello", false]
+[1, 'hello', false] #=> [1, "hello", false]
# Arrays can be indexed
# From the front
@@ -157,7 +161,7 @@ array << 6 #=> [1, 2, 3, 4, 5, 6]
# Hashes are Ruby's primary dictionary with keys/value pairs.
# Hashes are denoted with curly braces:
-hash = {'color' => 'green', 'number' => 5}
+hash = { 'color' => 'green', 'number' => 5 }
hash.keys #=> ['color', 'number']
@@ -170,7 +174,7 @@ hash['nothing here'] #=> nil
# Since Ruby 1.9, there's a special syntax when using symbols as keys:
-new_hash = { defcon: 3, action: true}
+new_hash = { defcon: 3, action: true }
new_hash.keys #=> [:defcon, :action]
@@ -180,11 +184,11 @@ new_hash.keys #=> [:defcon, :action]
# Control structures
if true
- "if statement"
+ 'if statement'
elsif false
- "else if, optional"
+ 'else if, optional'
else
- "else, also optional"
+ 'else, also optional'
end
for counter in 1..5
@@ -216,7 +220,7 @@ end
#=> iteration 5
# You can also surround blocks in curly brackets:
-(1..5).each {|counter| puts "iteration #{counter}"}
+(1..5).each { |counter| puts "iteration #{counter}" }
# The contents of data structures can also be iterated using each.
array.each do |element|
@@ -241,32 +245,30 @@ grade = 'B'
case grade
when 'A'
- puts "Way to go kiddo"
+ puts 'Way to go kiddo'
when 'B'
- puts "Better luck next time"
+ puts 'Better luck next time'
when 'C'
- puts "You can do better"
+ puts 'You can do better'
when 'D'
- puts "Scraping through"
+ puts 'Scraping through'
when 'F'
- puts "You failed!"
+ puts 'You failed!'
else
- puts "Alternative grading system, eh?"
+ puts 'Alternative grading system, eh?'
end
-
#=> "Better luck next time"
# cases can also use ranges
grade = 82
case grade
- when 90..100
- puts "Hooray!"
- when 80...90
- puts "OK job"
- else
- puts "You failed!"
+when 90..100
+ puts 'Hooray!'
+when 80...90
+ puts 'OK job'
+else
+ puts 'You failed!'
end
-
#=> "OK job"
@@ -284,23 +286,23 @@ double 3 #=> 6
double double 3 #=> 12
-def sum(x,y)
+def sum(x, y)
x + y
end
# Method arguments are separated by a comma
sum 3, 4 #=> 7
-sum sum(3,4), 5 #=> 12
+sum sum(3, 4), 5 #=> 12
# yield
# All methods have an implicit, optional block parameter
# it can be called with the 'yield' keyword
def surround
- puts "{"
+ puts '{'
yield
- puts "}"
+ puts '}'
end
surround { puts 'hello world' }
@@ -311,25 +313,25 @@ surround { puts 'hello world' }
# You can pass a block to a function
-# "&" marks a reference to a passed block
+# "&" marks a reference to a passed block
def guests(&block)
- block.call "some_argument"
+ block.call 'some_argument'
end
-
+
# You can pass a list of arguments, which will be converted into an array
-# That's what splat operator ("*") is for
+# That's what splat operator ("*") is for
def guests(*array)
- array.each { |guest| puts "#{guest}" }
+ array.each { |guest| puts guest }
end
# Define a class with the class keyword
class Human
# A class variable. It is shared by all instances of this class.
- @@species = "H. sapiens"
+ @@species = 'H. sapiens'
# Basic initializer
- def initialize(name, age=0)
+ def initialize(name, age = 0)
# Assign the argument to the "name" instance variable for the instance
@name = name
# If no age given, we will fall back to the default in the arguments list.
@@ -356,20 +358,19 @@ class Human
# A class method uses self to distinguish from instance methods.
# It can only be called on the class, not an instance.
def self.say(msg)
- puts "#{msg}"
+ puts msg
end
def species
@@species
end
-
end
# Instantiate a class
-jim = Human.new("Jim Halpert")
+jim = Human.new('Jim Halpert')
-dwight = Human.new("Dwight K. Schrute")
+dwight = Human.new('Dwight K. Schrute')
# Let's call a couple of methods
jim.species #=> "H. sapiens"
@@ -380,7 +381,7 @@ dwight.species #=> "H. sapiens"
dwight.name #=> "Dwight K. Schrute"
# Call the class method
-Human.say("Hi") #=> "Hi"
+Human.say('Hi') #=> "Hi"
# Variable's scopes are defined by the way we name them.
# Variables that start with $ have global scope
@@ -399,7 +400,7 @@ defined? @@var #=> "class variable"
Var = "I'm a constant"
defined? Var #=> "constant"
-# Class also is object in ruby. So class can have instance variables.
+# Class is also an object in ruby. So class can have instance variables.
# Class variable is shared among the class and all of its descendants.
# base class
@@ -415,7 +416,7 @@ class Human
end
end
-# derived class
+# derived class
class Worker < Human
end
@@ -451,8 +452,8 @@ module ModuleExample
end
end
-# Including modules binds the methods to the object instance
-# Extending modules binds the methods to the class instance
+# Including modules binds their methods to the class instances
+# Extending modules binds their methods to the class itself
class Person
include ModuleExample
@@ -467,7 +468,7 @@ Person.new.foo # => 'foo'
Book.foo # => 'foo'
Book.new.foo # => NoMethodError: undefined method `foo'
-# Callbacks when including and extending a module are executed
+# Callbacks are executed when including and extending a module
module ConcernExample
def self.included(base)
@@ -500,9 +501,8 @@ Something.new.qux # => 'qux'
## Additional resources
-- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
+- [Learn Ruby by Example with Challenges](http://www.learneroo.com/modules/61/nodes/338) - A variant of this reference with in-browser challenges.
- [Official Documentation](http://www.ruby-doc.org/core-2.1.1/)
- [Ruby from other languages](https://www.ruby-lang.org/en/documentation/ruby-from-other-languages/)
-- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
-
-
+- [Programming Ruby](http://www.amazon.com/Programming-Ruby-1-9-2-0-Programmers/dp/1937785491/) - An older [free addition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
diff --git a/scala.html.markdown b/scala.html.markdown
index 6b398b4b..5a0cc0ff 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -9,7 +9,7 @@ filename: learn.scala
Scala - the scalable language
-```cpp
+```scala
/*
Set yourself up:
@@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense -
// A do while loop
do {
- println("x is still less then 10");
+ println("x is still less than 10");
x += 1
} while (x < 10)
diff --git a/swift.html.markdown b/swift.html.markdown
index a47b085a..77047355 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -2,30 +2,51 @@
language: swift
contributors:
- ["Grant Timmerman", "http://github.com/grant"]
+ - ["Christopher Bess", "http://github.com/cbess"]
filename: learnswift.swift
---
Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta.
+The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks.
+
See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift.
-```js
+```swift
//
-// Basics
+// MARK: Basics
//
+// Xcode supports landmarks to annotate your code and lists them in the jump bar
+// MARK: Section mark
+// TODO: Do something soon
+// FIXME Fix this code
+
println("Hello, world")
+
var myVariable = 42
+let øπΩ = "value" // unicode variable names
let myConstant = 3.1415926
+let convenience = "keyword" // contextual variable name
+let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon
+let `class` = "keyword" // backticks allow keywords to be used as variable names
let explicitDouble: Double = 70
-let label = "some text " + String(myVariable) // Casting
-let piText = "Pi = \(myConstant)" // String interpolation
-var optionalString: String? = "optional" // Can be nil
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Casting
+let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation
+var optionalString: String? = "optional" // Can be nil
optionalString = nil
+/*
+Comment here
+ /*
+ Nested comments are also supported
+ */
+*/
//
-// Arrays and Dictionaries
+// MARK: Collections
//
// Array
@@ -35,97 +56,108 @@ let emptyArray = [String]()
// Dictionary
var occupations = [
- "Malcolm": "Captain",
- "kaylee": "Mechanic"
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
]
occupations["Jayne"] = "Public Relations"
-let emptyDictionary = Dictionary<String, Float>()
+let emptyDictionary = [String: Float]()
//
-// Control Flow
+// MARK: Control Flow
//
// for loop (array)
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
- if value == 1 {
- println("One!")
- } else {
- println("Not one!")
- }
+ if value == 1 {
+ println("One!")
+ } else {
+ println("Not one!")
+ }
}
// for loop (dictionary)
+var dict = ["one": 1, "two": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ println("\(key): \(value)")
}
// for loop (range)
for i in -1...1 { // [-1, 0, 1]
- println(i)
+ println(i)
}
// use ..< to exclude the last number
// while loop
var i = 1
while i < 1000 {
- i *= 2
+ i *= 2
}
// do-while loop
do {
- println("hello")
+ println("hello")
} while 1 == 2
// Switch
let vegetable = "red pepper"
switch vegetable {
case "celery":
- let vegetableComment = "Add some raisins and make ants on a log."
+ let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
- let vegetableComment = "That would make a good tea sandwich."
+ let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
- let vegetableComment = "Is it a spicy \(x)?"
+ let vegetableComment = "Is it a spicy \(x)?"
default: // required (in order to cover all possible input)
- let vegetableComment = "Everything tastes good in soup."
+ let vegetableComment = "Everything tastes good in soup."
}
//
-// Functions
+// MARK: Functions
//
// Functions are a first-class type, meaning they can be nested
// in functions and can be passed around
-// Function
+// Function with Swift header docs (format as reStructedText)
+/**
+ A greet operation
+
+ - A bullet in docs
+ - Another bullet in the docs
+
+ :param: name A name
+ :param: day A day
+ :returns: A string containing the name and day value.
+*/
func greet(name: String, day: String) -> String {
- return "Hello \(name), today is \(day)."
+ return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
// Function that returns multiple items in a tuple
func getGasPrices() -> (Double, Double, Double) {
- return (3.59, 3.69, 3.79)
+ return (3.59, 3.69, 3.79)
}
-// Args
+// Variadic Args
func setup(numbers: Int...) {}
// Passing and returning functions
func makeIncrementer() -> (Int -> Int) {
- func addOne(number: Int) -> Int {
- return 1 + number
- }
- return addOne
+ func addOne(number: Int) -> Int {
+ return 1 + number
+ }
+ return addOne
}
var increment = makeIncrementer()
increment(7)
//
-// Closures
+// MARK: Closures
//
var numbers = [1, 2, 6]
@@ -135,93 +167,243 @@ var numbers = [1, 2, 6]
// `->` separates the arguments and return type
// `in` separates the closure header from the closure body
numbers.map({
- (number: Int) -> Int in
- let result = 3 * number
- return result
- })
+ (number: Int) -> Int in
+ let result = 3 * number
+ return result
+})
// When the type is known, like above, we can do this
numbers = numbers.map({ number in 3 * number })
-//Or even this
+// Or even this
//numbers = numbers.map({ $0 * 3 })
print(numbers) // [3, 6, 18]
+// Trailing closure
+numbers = sorted(numbers) { $0 > $1 }
+
+print(numbers) // [18, 6, 3]
+
+// Super shorthand, since the < operator infers the types
+
+numbers = sorted(numbers, < )
+
+print(numbers) // [3, 6, 18]
//
-// Classes
+// MARK: Structures
//
+// Structures and classes have very similar capabilites
+struct NamesTable {
+ let names: [String]
+
+ // Custom subscript
+ subscript(index: Int) -> String {
+ return names[index]
+ }
+}
+
+// Structures have an auto-generated (implicit) designated initializer
+let namesTable = NamesTable(names: ["Me", "Them"])
+//let name = namesTable[2]
+//println("Name is \(name)") // Name is Them
+
+//
+// MARK: Classes
+//
+
+// Classes, structures and its members have three levels of access control
+// They are: internal (default), public, private
+
+public class Shape {
+ public func getArea() -> Int {
+ return 0;
+ }
+}
+
// All methods and properties of a class are public.
// If you just need to store data in a
// structured object, you should use a `struct`
-// A simple class `Square` extends `Shape`
-class Rect: Shape {
- var sideLength: Int = 1
+internal class Rect: Shape {
+ var sideLength: Int = 1
+
+ // Custom getter and setter property
+ private var perimeter: Int {
+ get {
+ return 4 * sideLength
+ }
+ set {
+ // `newValue` is an implicit variable available to setters
+ sideLength = newValue / 4
+ }
+ }
- // Custom getter and setter property
- var perimeter: Int {
- get {
- return 4 * sideLength
+ // Lazily load a property
+ // subShape remains nil (uninitialized) until getter called
+ lazy var subShape = Rect(sideLength: 4)
+
+ // If you don't need a custom getter and setter,
+ // but still want to run code before and after getting or setting
+ // a property, you can use `willSet` and `didSet`
+ var identifier: String = "defaultID" {
+ // the `willSet` arg will be the variable name for the new value
+ willSet(someIdentifier) {
+ print(someIdentifier)
+ }
}
- set {
- sideLength = newValue / 4
+
+ init(sideLength: Int) {
+ super.init()
+ self.sideLength = sideLength
}
- }
-
- init(sideLength: Int) {
- super.init()
- self.sideLength = sideLength
- }
-
- func shrink() {
- if sideLength > 0 {
- --sideLength
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
}
- }
+}
- override func getArea() -> Int {
- return sideLength * sideLength
- }
+// A simple class `Square` extends `Rect`
+class Square: Rect {
+ convenience init() {
+ self.init(sideLength: 5)
+ }
}
-var mySquare = new Square(sideLength: 5)
+
+var mySquare = Square()
print(mySquare.getArea()) // 25
mySquare.shrink()
print(mySquare.sideLength) // 4
-// If you don't need a custom getter and setter,
-// but still want to run code before and after getting or setting
-// a property, you can use `willSet` and `didSet`
+// compare instances, not the same as == which compares objects (equal to)
+if mySquare === mySquare {
+ println("Yep, it's mySquare")
+}
//
-// Enums
+// MARK: Enums
//
// Enums can optionally be of a specific type or on their own.
// They can contain methods like classes.
enum Suit {
- case Spades, Hearts, Diamonds, Clubs
- func getIcon() -> String {
- switch self {
- case .Spades: return "♤"
- case .Hearts: return "♡"
- case .Diamonds: return "♢"
- case .Clubs: return "♧"
+ case Spades, Hearts, Diamonds, Clubs
+ func getIcon() -> String {
+ switch self {
+ case .Spades: return "♤"
+ case .Hearts: return "♡"
+ case .Diamonds: return "♢"
+ case .Clubs: return "♧"
+ }
}
- }
}
//
-// Other
+// MARK: Protocols
+//
+
+// `protocol`s can require that conforming types have specific
+// instance properties, instance methods, type methods,
+// operators, and subscripts.
+
+protocol ShapeGenerator {
+ var enabled: Bool { get set }
+ func buildShape() -> Shape
+}
+
+/*
+// Protocols declared with @objc allow optional functions,
+// which allow you to check for conformance
+@objc protocol TransformShape {
+ optional func reshaped()
+ optional func canReshape() -> Bool
+}
+
+class MyShape: Rect {
+ var delegate: TransformShape?
+
+ func grow() {
+ sideLength += 2
+
+ if let allow = self.delegate?.canReshape?() {
+ // test for delegate then for method
+ self.delegate?.reshaped?()
+ }
+ }
+}
+*/
+
+//
+// MARK: Other
//
-// `protocol`: Similar to Java interfaces.
-// `extension`s: Add extra functionality to an already created type
+// `extension`s: Add extra functionality to an already existing type
+
+// Square now "conforms" to the `Printable` protocol
+extension Square: Printable {
+ var description: String {
+ return "Area: \(self.getArea()) - ID: \(self.identifier)"
+ }
+}
+
+println("Square: \(mySquare)")
+
+// You can also extend built-in types
+extension Int {
+ var customProperty: String {
+ return "This is \(self)"
+ }
+
+ func multiplyBy(num: Int) -> Int {
+ return num * self
+ }
+}
+
+println(7.customProperty) // "This is 7"
+println(14.multiplyBy(2)) // 42
+
// Generics: Similar to Java. Use the `where` keyword to specify the
// requirements of the generics.
+func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
+ for (index, value) in enumerate(array) {
+ if value == valueToFind {
+ return index
+ }
+ }
+ return nil
+}
+let foundAtIndex = findIndex([1, 2, 3, 4], 3)
+println(foundAtIndex == 2) // true
+
+// Operators:
+// Custom operators can start with the characters:
+// / = - + * % < > ! & | ^ . ~
+// or
+// Unicode math, symbol, arrow, dingbat, and line/box drawing characters.
+prefix operator !!! {}
+
+// A prefix operator that triples the side length when used
+prefix func !!! (inout shape: Square) -> Square {
+ shape.sideLength *= 3
+ return shape
+}
+
+// current value
+println(mySquare.sideLength) // 4
+
+// change side length using custom !!! operator, increases size by 3
+!!!mySquare
+println(mySquare.sideLength) // 12
+
```
diff --git a/tmux.html.markdown b/tmux.html.markdown
new file mode 100644
index 00000000..8d7aa752
--- /dev/null
+++ b/tmux.html.markdown
@@ -0,0 +1,244 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["kaernyk", "http://github.com/kaernyk"]
+filename: LearnTmux.txt
+---
+
+
+<a href="http://tmux.sourceforge.net/">
+tmux</a> 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.
+
+
+```
+ tmux [command] # Run a command
+ # 'tmux' with no commands will create a new
+ session
+
+ new # Create a new session
+ -s "Session" # Create named session
+ -n "Window" # Create named Window
+ -c "/dir" # Start in target directory
+
+ attach # Attach last/available session
+ -t "#" # Attach target session
+ -d # Detach the session from other instances
+
+ ls # List open sessions
+ -a # List all open sessions
+
+ lsw # List windows
+ -a # List all windows
+ -s # List all windows in session
+
+ lsp # List panes
+ -a # List all panes
+ -s # List all panes in session
+ -t # List app panes in target
+
+ kill-window # Kill current window
+ -t "#" # Kill target window
+ -a # Kill all windows
+ -a -t "#" # Kill all windows but the target
+
+ kill-session # Kill current session
+ -t "#" # Kill target session
+ -a # Kill all sessions
+ -a -t "#" # Kill all sessions but the target
+
+
+
+## Key Bindings
+
+# 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
+
+ (M-1) = Meta + 1 -or- Alt + 1
+----------------------------------------------------------------------
+
+ ? # List all key bindings
+ : # Enter the tmux command prompt
+ r # Force redraw of the attached client
+ c # Create a new window
+
+ ! # Break the current pane out of the window.
+ % # Split the current pane into two, left and right
+ " # Split the current pane into two, top and bottom
+
+ n # Change to the next window
+ p # Change to the previous window
+ { # Swap the current pane with the previous pane
+ } # Swap the current pane with the next pane
+
+ s # Select a new session for the attached client
+ interactively
+ w # Choose the current window interactively
+ 0 to 9 # Select windows 0 to 9
+
+ d # Detach the current client
+ D # Choose a client to detach
+
+ & # Kill the current window
+ x # Kill the current pane
+
+ Up, Down # Change to the pane above, below, left, or right
+ Left, Right
+
+ M-1 to M-5 # Arrange panes:
+ # 1) even-horizontal
+ # 2) even-vertical
+ # 3) main-horizontal
+ # 4) main-vertical
+ # 5) tiled
+
+ C-Up, C-Down # Resize the current pane in steps of one cell
+ C-Left, C-Right
+
+ M-Up, M-Down # Resize the current pane in steps of five cells
+ M-Left, M-Right
+
+
+
+### Configuring ~/.tmux.conf
+
+ 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.9
+
+
+### Keybinds
+######################################################################
+
+# Unbind C-b as the default prefix
+unbind-key C-befix C-a
+
+# Return to previous window when prefix is pressed twice
+bind-key C-a last-window
+bind-key ` last-window
+
+# Allow swapping C-a and ` using F11/F12
+bind-key F11 set-option -g prefix C-a
+bind-key F12 set-option -g prefix `
+
+# Activate inner-most session (when nesting tmux)
+# to send commands
+bind-key a send-prefix
+
+# Index Start
+set -g base-index 1
+
+# Window Cycle/Swap
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# easy-to-remember split pane commands
+bind | split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# moving between panes with vim movement keys
+bind h select-pane -L
+bind j select-pane -D
+bind k select-pane -U
+bind l select-pane -R
+
+
+### Theme
+#####################################################################
+
+# Statusbar Color Palette
+set-option -g status-justify left
+set-option -g status-bg black
+set-option -g status-fg white
+set-option -g status-left-length 40
+set-option -g status-right-length 80
+
+# Pane Border Color Palette
+set-option -g pane-active-border-fg green
+set-option -g pane-active-border-bg black
+set-option -g pane-border-fg white
+set-option -g pane-border-bg black
+
+# Message Color Palette
+set-option -g message-fg black
+set-option -g message-bg green
+
+# Window Status Color Palette
+setw -g window-status-bg black
+setw -g window-status-current-fg green
+setw -g window-status-bell-attr default
+setw -g window-status-bell-fg red
+setw -g window-status-content-attr default
+setw -g window-status-content-fg yellow
+setw -g window-status-activity-attr default
+setw -g window-status-activity-fg yellow
+
+
+### UI
+######################################################################
+
+# Statusbar
+set-option -g status-utf8 on
+
+# Keybind preference
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# Notification
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Mouse
+setw -g mode-mouse on
+set-option -g mouse-select-pane on
+set -g mouse-resize-pane on
+set -g mouse-select-window on
+
+# Automatically set window titles
+set-option -g set-titles on
+
+# window number,program name,active (or not)
+set-option -g set-titles-string '#H:#S.#I.#P #W #T'
+
+# Statusbar Adjustments
+set -g status-left '#[fg=red]#H#[fg=green]:#[fg=white]#S #[fg=green]][#[default]'
+set -g status-interval 3
+
+# Statusbar with right-aligned Date / Time
+#set -g status-right '#[fg=green]][#[fg=white] #T #[fg=green]][ #[fg=blue]%Y-%m-%d #[fg=white]%H:%M#[default]'
+
+# Show performance counters in statusbar
+# Requires https://github.com/thewtex/tmux-mem-cpu-load/
+#set -g status-right '#[fg=green]][#[fg=white] #(tmux-mem-cpu-load 5 4) #[fg=green]][ #[fg=yellow]%H:%M#[default]'
+
+
+### Misc
+######################################################################
+
+# Scrollback/History limit
+set -g history-limit 4096
+
+bind r source-file ~/.tmux.conf
+```
+
+### External Resources
+
+<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">Archlinux Wiki</a><br>
+<a href="https://wiki.archlinux.org/index.php/Tmux">Gentoo 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>
diff --git a/tr-tr/objective-c-tr.html.markdown b/tr-tr/objective-c-tr.html.markdown
index 854d70f6..f27cbf08 100644
--- a/tr-tr/objective-c-tr.html.markdown
+++ b/tr-tr/objective-c-tr.html.markdown
@@ -14,7 +14,7 @@ kendi çatıları olan Cocoa ve Cocoa Touch için kullanılan bir programlama di
Genel açamlı, object-oriented bir yapıya sahip programlama dilidir. C
programlama diline Smalltalk stilinde mesajlaşma ekler.
-```cpp
+```objective_c
// Tek satır yorum // işaretleri ile başlar
/*
diff --git a/typescript.html.markdown b/typescript.html.markdown
new file mode 100644
index 00000000..9f04169a
--- /dev/null
+++ b/typescript.html.markdown
@@ -0,0 +1,158 @@
+---
+language: TypeScript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+filename: learntypescript.ts
+---
+
+TypeScript is a language that aims at easing development of large scale applications written in JavaScript.
+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/).
+
+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
+var isDone: boolean = false;
+var lines: number = 42;
+var name: string = "Anders";
+
+//..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
+var list: number[] = [1, 2, 3];
+//Alternatively, using the generic array type
+var list: Array<number> = [1, 2, 3];
+
+//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
+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
+interface Person {
+ name: string;
+ //Optional properties, marked with a "?"
+ age?: number;
+ //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
+
+//..Interfaces can also describe a function type
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+//..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
+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);
+}
+
+var p1 = new Point(10 ,20);
+var p2 = new Point(25); //y will be 0
+
+//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);
+ }
+}
+
+//Modules, "." can be used as separator for sub modules
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+var s1 = new Geometry.Square(5);
+
+//..Local alias for referencing a module
+import G = Geometry;
+
+var s2 = new G.Square(10);
+
+//Generics
+//..Classes
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+//..Interfaces
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+//..And functions
+var pairToTuple = function<T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+var tuple = pairToTuple({ item1:"hello", item2:"world"});
+
+//Including references to a definition file:
+/// <reference path="jquery.d.ts" />
+
+```
+
+## Further Reading
+ * [TypeScript Official website] (http://www.typescriptlang.org/)
+ * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown
index 6d19ca02..c97bb560 100644
--- a/vi-vn/objective-c-vi.html.markdown
+++ b/vi-vn/objective-c-vi.html.markdown
@@ -12,7 +12,7 @@ filename: LearnObjectiveC-vi.m
Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành OS X, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch.
Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C.
-```cpp
+```objective_c
// Chú thích dòng đơn bắt đầu với //
/*
diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown
index c4dc3274..b82829a9 100644
--- a/zh-cn/common-lisp-cn.html.markdown
+++ b/zh-cn/common-lisp-cn.html.markdown
@@ -17,7 +17,7 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范
另外还有一本热门的近期出版的
[Land of Lisp](http://landoflisp.com/).
-```scheme
+```common-lisp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; 0. 语法
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown
index 4a87dc21..9f6a8c15 100644
--- a/zh-cn/go-cn.html.markdown
+++ b/zh-cn/go-cn.html.markdown
@@ -68,7 +68,7 @@ func learnTypes() {
can include line breaks.` // 同样是String类型
// 非ascii字符。Go使用UTF-8编码。
- g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码
+ g := 'Σ' // rune类型,int32的别名,使用UTF-8编码
f := 3.14195 // float64类型,IEEE-754 64位浮点数
c := 3 + 4i // complex128类型,内部使用两个float64表示
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
index 95a94c76..3ba098ec 100644
--- a/zh-cn/lua-cn.html.markdown
+++ b/zh-cn/lua-cn.html.markdown
@@ -9,6 +9,7 @@ contributors:
- ["Amr Tamimi", "https://amrtamimi.com"]
translators:
- ["Jakukyo Friel", "http://weakish.github.io"]
+filename: lua-cn.lua
---
```lua
diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown
new file mode 100644
index 00000000..eecb8c5b
--- /dev/null
+++ b/zh-cn/markdown-cn.html.markdown
@@ -0,0 +1,240 @@
+---
+language: Markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+translators:
+ - ["Fangzhou Chen","https://github.com/FZSS"]
+filename: learnmarkdown-cn.md
+lang: zh-cn
+---
+
+Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。
+
+欢迎您多多反馈以及分支和请求合并。
+
+
+```markdown
+<!-- Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。
+这意味着我们可以在 Markdown 里使用任何 HTML 元素,比如注释元素,
+且不会被 Markdown 解析器所影响。不过如果你在 Markdown 文件内创建了 HTML 元素,
+你将无法在 HTML 元素的内容中使用 Markdown 语法。-->
+
+<!-- 在不同的解析器中,Markdown 的实现方法有所不同。
+此教程会指出当某功能是否通用及是否只对某一解析器有效。 -->
+
+<!-- 标头 -->
+<!-- 通过在文本前加上不同数量的hash(#), 你可以创建相对应的 <h1>
+到 <h6> HTML元素。-->
+
+# 这是一个 <h1>
+## 这是一个 <h2>
+### 这是一个 <h3>
+#### 这是一个 <h4>
+##### 这是一个 <h5>
+###### 这是一个 <h6>
+
+<!-- 对于 <h1> 和 <h2> 元素,Markdown 额外提供了两种添加方式。 -->
+这是一个 h1
+=============
+
+这是一个 h2
+-------------
+
+<!-- 简易文本样式 -->
+<!-- 文本的斜体,粗体,和删除线在 Markdown 中可以轻易地被实现。-->
+
+*此文本为斜体。*
+_此文本也是。_
+
+**此文本为粗体。**
+__此文本也是__
+
+***此文本是斜体加粗体。***
+**_或者这样。_**
+*__这个也是!__*
+
+<!-- 在 Github 采用的 Markdown 中 -->
+
+~~此文本为删除线效果。~~
+
+<!-- 单个段落由一句或多句邻近的句子组成,这些句子由一个或多个空格分隔。-->
+
+这是第一段落. 这句话在同一个段落里,好玩么?
+
+现在我是第二段落。
+这句话也在第二段落!
+
+这句话在第三段落!
+
+<!-- 如果你插入一个 HTML中的<br />标签,你可以在段末加入两个以上的空格,
+然后另起一段。-->
+
+此段落结尾有两个空格(选中以显示)。
+
+上文有一个 <br /> !
+
+<!-- 段落引用可由 > 字符轻松实现。-->
+
+> 这是一个段落引用. 你可以
+> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。
+> 只要你的文字以“>” 字符开头,两种方式无异。
+
+> 你也对文本进行
+>> 多层引用
+> 这多机智啊!
+
+<!-- 序列 -->
+<!-- 无序序列可由星号,加号或者减号来建立 -->
+
+* 项目
+* 项目
+* 另一个项目
+
+或者
+
++ 项目
++ 项目
++ 另一个项目
+
+或者
+
+- 项目
+- 项目
+- 最后一个项目
+
+<!-- 有序序列可由数字加点来实现 -->
+
+1. 项目一
+2. 项目二
+3. 项目三
+
+<!-- 即使你的标签数字有误,Markdown 依旧会呈现出正确的序号,
+不过这并不是一个好主意-->
+
+1. 项目一
+1. 项目二
+1. 项目三
+<!-- (此段与前例一模一样) -->
+
+<!-- 你也可以使用子序列 -->
+
+1. 项目一
+2. 项目二
+3. 项目三
+ * 子项目
+ * 子项目
+4. 项目四
+
+<!-- 代码段落 -->
+<!-- 代码段落(HTML中 <code>标签)可以由缩进四格(spaces)
+或者一个标签页(tab)实现-->
+
+ This is code
+ So is this
+
+<!-- 在你的代码中,你仍然使用tab可以进行缩进操作 -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- 内联代码可由反引号 ` 实现 -->
+
+John 甚至不知道 `go_to()` 方程是干嘛的!
+
+<!-- 在Github的 Markdown中,对于代码你可以使用特殊的语法 -->
+
+\`\`\`ruby <!-- 插入时记得移除反斜线, 仅留```ruby ! -->
+def foobar
+ puts "Hello world!"
+end
+\`\`\` <!-- 这里也是,移除反斜线,仅留 ``` -->
+
+<!-- 以上代码不需要缩进,而且 Github 会根据```后表明的语言来进行语法高亮 -->
+
+<!-- 水平线 (<hr />) -->
+<!-- 水平线可由三个或以上的星号或者减号创建,可带可不带空格。 -->
+
+***
+---
+- - -
+****************
+
+<!-- 链接 -->
+<!-- Markdown 最棒的地方就是简易的链接制作。链接文字放在中括号[]内,
+在随后的括弧()内加入url。-->
+
+[点我点我!](http://test.com/)
+
+<!-- 你也可以为链接加入一个标题:在括弧内使用引号 -->
+
+[点我点我!](http://test.com/ "连接到Test.com")
+
+<!-- 相对路径也可以有 -->
+
+[去 music](/music/).
+
+<!-- Markdown同样支持引用样式的链接 -->
+
+[点此链接][link1]以获取更多信息!
+[看一看这个链接][foobar] 如果你愿意的话.
+
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+
+<!-- 链接的标题可以处于单引号中,括弧中或是被忽略。引用名可以在文档的任意何处,
+并且可以随意命名,只要名称不重复。-->
+
+<!-- “隐含式命名” 的功能可以让链接文字作为引用名 -->
+
+[This][] is a link.
+
+[this]: http://thisisalink.com/
+
+<!-- 但这并不常用 -->
+
+<!-- 图像 -->
+<!-- 图像与链接相似,只需在前添加一个感叹号 -->
+
+![这是我图像的悬停文本(alt text)](http://imgur.com/myimage.jpg "可选命名")
+
+<!-- 引用样式也同样起作用 -->
+
+![这是我的悬停文本.][myimage]
+
+[myimage]: relative/urls/cool/image.jpg "在此输入标题"
+
+<!-- 杂项 -->
+<!-- 自动链接 -->
+
+<http://testwebsite.com/> 与
+[http://testwebsite.com/](http://testwebsite.com/) 等同
+
+<!-- 电子邮件的自动链接 -->
+
+<foo@bar.com>
+
+<!-- 转义字符 -->
+
+我希望 *将这段文字置于星号之间* 但是我不希望它被
+斜体化, 所以我就: \*这段置文字于星号之间\*。
+
+<!-- 表格 -->
+<!-- 表格只被 Github 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: -->
+
+| 第一列 | 第二列 | 第三列 |
+| :---------- | :------: | ----------: |
+| 左对齐 | 居个中 | 右对齐 |
+| 某某某 | 某某某 | 某某某 |
+
+<!-- 或者, 同样的 -->
+
+第一列 | 第二列 | 第三列
+:-- | :-: | --:
+这太丑了 | 药不能 | 停
+
+<!-- 结束! -->
+
+```
+
+更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。
diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown
index 19c5f25d..0c46bc22 100644
--- a/zh-cn/r-cn.html.markdown
+++ b/zh-cn/r-cn.html.markdown
@@ -13,7 +13,7 @@ lang: zh-cn
R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。
你也可以在 LaTeX 文档中运行 `R` 命令。
-```python
+```r
# 评论以 # 开始
# R 语言原生不支持 多行注释
diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown
index 3c47f3f9..99250b43 100644
--- a/zh-cn/ruby-cn.html.markdown
+++ b/zh-cn/ruby-cn.html.markdown
@@ -40,7 +40,7 @@ translators:
1.+(3) #=> 4
10.* 5 #=> 50
-# 特殊的只也是对象
+# 特殊的值也是对象
nil # 空
true # 真
false # 假
diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown
index 28af8ddc..58f5cd47 100644
--- a/zh-cn/scala-cn.html.markdown
+++ b/zh-cn/scala-cn.html.markdown
@@ -11,7 +11,7 @@ lang: zh-cn
Scala - 一门可拓展性的语言
-```cpp
+```scala
/*
自行设置:
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index c87f9d10..b9696c72 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -12,7 +12,7 @@ Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014
参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程
-```js
+```swift
//
// 基础
//