summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--README.markdown22
-rw-r--r--amd.html.markdown212
-rw-r--r--bash.html.markdown109
-rw-r--r--c++.html.markdown593
-rw-r--r--c.html.markdown29
-rw-r--r--coffeescript.html.markdown4
-rw-r--r--common-lisp.html.markdown4
-rw-r--r--compojure.html.markdown280
-rw-r--r--csharp.html.markdown6
-rw-r--r--css.html.markdown91
-rw-r--r--de-de/coffeescript-de.html.markdown106
-rw-r--r--de-de/csharp-de.html.markdown889
-rw-r--r--de-de/css-de.html.markdown179
-rw-r--r--de-de/go-de.html.markdown2
-rw-r--r--de-de/haskell-de.html.markdown2
-rw-r--r--de-de/javascript-de.html.markdown122
-rw-r--r--de-de/markdown-de.html.markdown256
-rw-r--r--elixir.html.markdown37
-rw-r--r--erlang.html.markdown14
-rw-r--r--es-es/bash-es.html.markdown196
-rw-r--r--es-es/brainfuck-es.html.markdown87
-rw-r--r--es-es/go-es.html.markdown2
-rw-r--r--es-es/javascript-es.html.markdown4
-rw-r--r--es-es/julia-es.html.markdown5
-rw-r--r--es-es/markdown-es.html.markdown2
-rw-r--r--es-es/perl-es.html.markdown120
-rw-r--r--es-es/whip-es.html.markdown255
-rw-r--r--es-es/xml-es.html.markdown131
-rw-r--r--es-es/yaml-es.html.markdown151
-rw-r--r--fa-ir/javascript.html.markdown4
-rw-r--r--forth.html.markdown225
-rw-r--r--fr-fr/bash-fr.html.markdown230
-rw-r--r--fr-fr/brainfuck-fr.html.markdown87
-rw-r--r--fr-fr/css-fr.html.markdown221
-rw-r--r--fr-fr/haskell.html.markdown2
-rw-r--r--fr-fr/javascript-fr.html.markdown525
-rw-r--r--fr-fr/lua-fr.html.markdown2
-rw-r--r--fr-fr/markdown.html.markdown289
-rw-r--r--fr-fr/objective-c-fr.html.markdown2
-rw-r--r--fr-fr/ruby-fr.html.markdown4
-rw-r--r--fr-fr/scala.html.markdown5
-rw-r--r--fr-fr/xml-fr.html.markdown128
-rw-r--r--fr-fr/yaml-fr.html.markdown157
-rw-r--r--git.html.markdown64
-rw-r--r--go.html.markdown79
-rw-r--r--haml.html.markdown155
-rw-r--r--haskell.html.markdown25
-rw-r--r--ja-jp/r-jp.html.markdown4
-rw-r--r--java.html.markdown14
-rw-r--r--javascript.html.markdown31
-rw-r--r--json.html.markdown2
-rw-r--r--julia.html.markdown9
-rw-r--r--ko-kr/go-kr.html.markdown2
-rw-r--r--ko-kr/javascript-kr.html.markdown4
-rw-r--r--ko-kr/lua-kr.html.markdown2
-rw-r--r--ko-kr/php-kr.html.markdown2
-rw-r--r--lua.html.markdown2
-rw-r--r--markdown.html.markdown18
-rw-r--r--matlab.html.markdown58
-rw-r--r--nim.html.markdown265
-rw-r--r--nl-nl/brainfuck-nl.html.markdown86
-rw-r--r--nl-nl/coffeescript-nl.html.markdown110
-rw-r--r--objective-c.html.markdown2
-rw-r--r--ocaml.html.markdown372
-rw-r--r--perl6.html.markdown770
-rw-r--r--php.html.markdown2
-rw-r--r--pl-pl/perl-pl.html.markdown169
-rw-r--r--pt-br/go-pt.html.markdown2
-rw-r--r--pt-br/groovy-pt.html.markdown435
-rw-r--r--pt-br/haskell-pt.html.markdown2
-rw-r--r--pt-br/markdown-pt.html.markdown2
-rw-r--r--pt-br/php-pt.html.markdown2
-rw-r--r--pt-br/ruby-pt.html.markdown12
-rw-r--r--purescript.html.markdown195
-rw-r--r--python.html.markdown84
-rw-r--r--python3.html.markdown44
-rw-r--r--r.html.markdown13
-rw-r--r--ru-ru/coffeescript-ru.html.markdown104
-rw-r--r--ru-ru/go-ru.html.markdown44
-rw-r--r--ru-ru/haskell-ru.html.markdown2
-rw-r--r--ru-ru/java-ru.html.markdown506
-rw-r--r--ru-ru/julia-ru.html.markdown2
-rw-r--r--ru-ru/markdown-ru.html.markdown279
-rw-r--r--ru-ru/objective-c-ru.html.markdown2
-rw-r--r--ru-ru/php-ru.html.markdown2
-rw-r--r--ru-ru/python-ru.html.markdown266
-rw-r--r--ru-ru/python3-ru.html.markdown630
-rw-r--r--ruby.html.markdown116
-rw-r--r--rust.html.markdown4
-rw-r--r--scala.html.markdown557
-rw-r--r--self.html.markdown161
-rw-r--r--swift.html.markdown439
-rw-r--r--tmux.html.markdown243
-rw-r--r--tr-tr/objective-c-tr.html.markdown2
-rw-r--r--tr-tr/php-tr.html.markdown2
-rw-r--r--typescript.html.markdown158
-rw-r--r--vi-vn/git-vi.html.markdown66
-rw-r--r--vi-vn/objective-c-vi.html.markdown2
-rw-r--r--whip.html.markdown16
-rw-r--r--zh-cn/c-cn.html.markdown4
-rw-r--r--zh-cn/common-lisp-cn.html.markdown2
-rw-r--r--zh-cn/go-cn.html.markdown2
-rw-r--r--zh-cn/haskell-cn.html.markdown2
-rw-r--r--zh-cn/javascript-cn.html.markdown4
-rw-r--r--zh-cn/julia-cn.html.markdown2
-rw-r--r--zh-cn/livescript-cn.html.markdown322
-rw-r--r--zh-cn/lua-cn.html.markdown3
-rw-r--r--zh-cn/markdown-cn.html.markdown240
-rw-r--r--zh-cn/php-cn.html.markdown2
-rw-r--r--zh-cn/python3-cn.html.markdown629
-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
114 files changed, 12486 insertions, 1166 deletions
diff --git a/README.markdown b/README.markdown
index dc379a9b..4e24bbe6 100644
--- a/README.markdown
+++ b/README.markdown
@@ -14,12 +14,12 @@ properly!
## Contributing
-All contributions welcome, from the tiniest typo to a brand new article. Translations
+All contributions are welcome, from the tiniest typo to a brand new article. Translations
in all languages are welcome (or, for that matter, original articles in any language).
Send a pull request or open an issue any time of day or night.
**Please tag your issues pull requests with [language/lang-code] at the beginning**
-**(e.g. [python/en] for english python).** This will help everyone pick out things they
+**(e.g. [python/en] for English Python).** This will help everyone pick out things they
care about.
### Style Guidelines
@@ -27,7 +27,7 @@ care about.
* **Keep lines under 80 chars**
* **Prefer example to exposition**
* **Eschew surplusage**
-* **Use utf-8**
+* **Use UTF-8**
Long version:
@@ -38,28 +38,28 @@ Long version:
* We welcome newcomers, but the target audience for this site is programmers with some experience.
So, try to avoid explaining basic concepts except for those specific to the language in question,
- to keep articles succinct and scannable. We all know how to use google here.
+ to keep articles succinct and scannable. We all know how to use Google here.
-* For translations (or english articles with non-ASCII characters), please make sure your file is
- utf-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in vim)
+* For translations (or English articles with non-ASCII characters), please make sure your file is
+ UTF-8 encoded, and try to leave out the byte-order-mark at the start of the file. (`:set nobomb` in Vim)
### Header configuration
-The actual site uses Middleman to generate HTML files from these markdown ones. Middleman, or at least
+The actual site uses Middleman to generate HTML files from these Markdown ones. Middleman, or at least
the custom scripts underpinning the site, required that some key information be defined in the header.
-The following fields are necessary for english articles about programming languages:
+The following fields are necessary for English articles about programming languages:
* **language** The *programming language* in question
-* **contributors** A list of [author, url] lists to credit
+* **contributors** A list of [author, URL] lists to credit
Other fields:
* **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable.
- For non-english articles, *filename* should have a language-specific suffix.
+ For non-English articles, *filename* should have a language-specific suffix.
* **lang**: For translations, the human language this article is in. For categorization, mostly.
-Here's an example header for an esperanto translation of Ruby:
+Here's an example header for an Esperanto translation of Ruby:
```yaml
---
diff --git a/amd.html.markdown b/amd.html.markdown
new file mode 100644
index 00000000..b3237dc7
--- /dev/null
+++ b/amd.html.markdown
@@ -0,0 +1,212 @@
+---
+category: tool
+tool: amd
+contributors:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: learnamd.js
+---
+
+## Getting Started with AMD
+
+The **Asynchronous Module Definition** API specifies a mechanism for defining
+JavaScript modules such that the module and its dependencies can be asynchronously
+loaded. This is particularly well suited for the browser environment where
+synchronous loading of modules incurs performance, usability, debugging, and
+cross-domain access problems.
+
+### Basic concept
+```javascript
+// The basic AMD API consists of nothing but two methods: `define` and `require`
+// and is all about module definition and consumption:
+// `define(id?, dependencies?, factory)` defines a module
+// `require(dependencies, callback)` imports a set of dependencies and
+// consumes them in the passed callback
+
+// Let's start by using define to define a new named module
+// that has no dependencies. We'll do so by passing a name
+// and a factory function to define:
+define('awesomeAMD', function(){
+ var isAMDAwesome = function(){
+ return true;
+ };
+ // The return value of a module's factory function is
+ // what other modules or require calls will receive when
+ // requiring our `awesomeAMD` module.
+ // The exported value can be anything, (constructor) functions,
+ // objects, primitives, even undefined (although that won't help too much).
+ return isAMDAwesome;
+});
+
+// Now, let's define another module that depends upon our `awesomeAMD` module.
+// Notice that there's an additional argument defining our
+// module's dependencies now:
+define('loudmouth', ['awesomeAMD'], function(awesomeAMD){
+ // dependencies will be passed to the factory's arguments
+ // in the order they are specified
+ var tellEveryone = function(){
+ if (awesomeAMD()){
+ alert('This is sOoOo rad!');
+ } else {
+ alert('Pretty dull, isn\'t it?');
+ }
+ };
+ return tellEveryone;
+});
+
+// As we do know how to use define now, let's use `require` to
+// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`.
+require(['loudmouth'], function(loudmouth){
+ loudmouth();
+});
+
+// To make this tutorial run code, let's implement a very basic
+// (non-asynchronous) version of AMD right here on the spot:
+function define(name, deps, factory){
+ // notice how modules without dependencies are handled
+ define[name] = require(factory ? deps : [], factory || deps);
+}
+
+function require(deps, callback){
+ var args = [];
+ // first let's retrieve all the dependencies needed
+ // by the require call
+ for (var i = 0; i < deps.length; i++){
+ args[i] = define[deps[i]];
+ }
+ // satisfy all the callback's dependencies
+ return callback.apply(null, args);
+}
+// you can see this code in action here: http://jsfiddle.net/qap949pd/
+```
+
+### Real-world usage with require.js
+
+In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR:
+
+```javascript
+/* file: app/main.js */
+require(['modules/someClass'], function(SomeClass){
+ // the callback is deferred until the dependency is loaded
+ var thing = new SomeClass();
+});
+console.log('So here we are, waiting!'); // this will run first
+```
+
+By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`:
+
+* app/
+ * main.js
+ * modules/
+ * someClass.js
+ * someHelpers.js
+ * ...
+ * daos/
+ * things.js
+ * ...
+
+This means we can define `someClass` without specifying a module id:
+
+```javascript
+/* file: app/modules/someClass.js */
+define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){
+ // module definition, of course, will also happen asynchronously
+ function SomeClass(){
+ this.method = function(){/**/};
+ // ...
+ }
+ return SomeClass;
+});
+```
+To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`:
+
+```javascript
+/* file: main.js */
+requirejs.config({
+ baseUrl : 'app',
+ paths : {
+ // you can also load modules from other locations
+ jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+});
+require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){
+ // a `main` file needs to call require at least once,
+ // otherwise no code will ever run
+ coolLib.doFancyStuffWith(helpers.transform($('#foo')));
+});
+```
+`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload:
+
+```html
+<!DOCTYPE html>
+<html>
+<head>
+ <title>A hundred script tags? Never again!</title>
+</head>
+<body>
+ <script src="require.js" data-main="app/main"></script>
+</body>
+</html>
+```
+
+### Optimizing a whole project using r.js
+
+Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load.
+
+`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption.
+
+Install it using `npm`:
+```shell
+$ npm install requirejs -g
+```
+
+Now you can feed it with a configuration file:
+```shell
+$ r.js -o app.build.js
+```
+
+For our above example the configuration might look like:
+```javascript
+/* file : app.build.js */
+({
+ name : 'main', // name of the entry point
+ out : 'main-built.js', // name of the file to write the output to
+ baseUrl : 'app',
+ paths : {
+ // `empty:` tells r.js that this should still be loaded from the CDN, using
+ // the location specified in `main.js`
+ jquery : 'empty:',
+ coolLibFromBower : '../bower_components/cool-lib/coollib'
+ }
+})
+```
+
+To use the built file in production, simply swap `data-main`:
+```html
+<script src="require.js" data-main="app/main-built"></script>
+```
+
+An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo.
+
+### Topics not covered in this tutorial
+* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html)
+* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html)
+* [Advanced configuration](http://requirejs.org/docs/api.html#config)
+* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim)
+* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss)
+* [Using almond.js for builds](https://github.com/jrburke/almond)
+
+### Further reading:
+
+* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD)
+* [Why AMD?](http://requirejs.org/docs/whyamd.html)
+* [Universal Module Definition](https://github.com/umdjs/umd)
+
+### Implementations:
+
+* [require.js](http://requirejs.org)
+* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/)
+* [cujo.js](http://cujojs.com/)
+* [curl.js](https://github.com/cujojs/curl)
+* [lsjs](https://github.com/zazl/lsjs)
+* [mmd](https://github.com/alexlawrence/mmd)
diff --git a/bash.html.markdown b/bash.html.markdown
index 845ebead..3b163638 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -8,6 +8,8 @@ contributors:
- ["Denis Arh", "https://github.com/darh"]
- ["akirahirose", "https://twitter.com/akirahirose"]
- ["Anton Strömkvist", "http://lutic.org/"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gregrory Kielian", "https://github.com/gskielian"]
filename: LearnBash.sh
---
@@ -73,9 +75,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
@@ -109,12 +111,45 @@ ls -l # Lists every file and directory on a separate line
# .txt files in the current directory:
ls -l | grep "\.txt"
-# You can also redirect a command, input and error output.
-python2 hello.py < "input.in"
-python2 hello.py > "output.out"
-python2 hello.py 2> "error.err"
-# The output error will overwrite the file if it exists, if you want to
-# concatenate them, use ">>" instead.
+# You can redirect command input and output (stdin, stdout, and stderr).
+# Read from stdin until ^EOF$ and overwrite hello.py with the lines
+# between "EOF":
+cat > hello.py << EOF
+#!/usr/bin/env python
+from __future__ import print_function
+import sys
+print("#stdout", file=sys.stdout)
+print("#stderr", file=sys.stderr)
+for line in sys.stdin:
+ print(line, file=sys.stdout)
+EOF
+
+# Run hello.py with various stdin, stdout, and stderr redirections:
+python hello.py < "input.in"
+python hello.py > "output.out"
+python hello.py 2> "error.err"
+python hello.py > "output-and-error.log" 2>&1
+python hello.py > /dev/null 2>&1
+# The output error will overwrite the file if it exists,
+# if you want to append instead, use ">>":
+python hello.py >> "output.out" 2>> "error.err"
+
+# Overwrite output.txt, append to error.err, and count lines:
+info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err
+wc -l output.out error.err
+
+# Run a command and print its file descriptor (e.g. /dev/fd/123)
+# see: man fd
+echo <(echo "#helloworld")
+
+# Overwrite output.txt with "#helloworld":
+cat > output.out <(echo "#helloworld")
+echo "#helloworld" > output.out
+echo "#helloworld" | cat > output.out
+echo "#helloworld" | tee output.out >/dev/null
+
+# Cleanup temporary files verbosely (add '-i' for interactive)
+rm -v output.out error.err output-and-error.log
# Commands can be substituted within other commands using $( ):
# The following command displays the number of files and directories in the
@@ -134,14 +169,34 @@ case "$VARIABLE" in
esac
# for loops iterate for as many arguments given:
-# The contents of var $VARIABLE is printed three times.
+# The contents of $VARIABLE is printed three times.
for VARIABLE in {1..3}
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
+do
+ cat "$VARIABLE"
+done
+
+# ..or the output from a command
+# This will cat the output from ls.
+for OUTPUT in $(ls)
+do
+ cat "$OUTPUT"
+done
+
# while loop:
-while [true]
+while [ true ]
do
echo "loop body here..."
break
@@ -178,4 +233,38 @@ sort file.txt
uniq -d file.txt
# prints only the first column before the ',' character
cut -d ',' -f 1 file.txt
+# replaces every occurrence of 'okay' with 'great' in file.txt, (regex compatible)
+sed -i 's/okay/great/g' file.txt
+# print to stdout all lines of file.txt which match some regex, the example prints lines which begin with "foo" and end in "bar"
+grep "^foo.*bar$" file.txt
+# pass the option "-c" to instead print the number of lines matching the regex
+grep -c "^foo.*bar$" file.txt
+# if you literally want to search for the string, and not the regex, use fgrep (or grep -F)
+fgrep "^foo.*bar$" file.txt
+
+
+# Read Bash shell builtins documentation with the bash 'help' builtin:
+help
+help help
+help for
+help return
+help source
+help .
+
+# Read Bash manpage documentation with man
+apropos bash
+man 1 bash
+man bash
+
+# Read info documentation with info (? for help)
+apropos info | grep '^info.*('
+man info
+info info
+info 5 info
+
+# Read bash info documentation:
+info bash
+info bash 'Bash Features'
+info bash 6
+info --apropos bash
```
diff --git a/c++.html.markdown b/c++.html.markdown
new file mode 100644
index 00000000..5f80f26f
--- /dev/null
+++ b/c++.html.markdown
@@ -0,0 +1,593 @@
+---
+language: c++
+filename: learncpp.cpp
+contributors:
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Matt Kline", "https://github.com/mrkline"]
+lang: en
+---
+
+C++ is a systems programming language that,
+[according to its inventor Bjarne Stroustrup](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote),
+was designed to
+
+- be a "better C"
+- support data abstraction
+- support object-oriented programming
+- support generic programming
+
+Though its syntax can be more difficult or complex than newer languages,
+it is widely used because it compiles to native instructions that can be
+directly run by the processor and offers tight control over hardware (like C)
+while offering high-level features such as generics, exceptions, and classes.
+This combination of speed and functionality makes C++
+one of the most widely-used programming languages.
+
+```c++
+//////////////////
+// Comparison to C
+//////////////////
+
+// C++ is _almost_ a superset of C and shares its basic syntax for
+// variable declarations, primitive types, and functions.
+// However, C++ varies in some of the following ways:
+
+// A main() function in C++ should return an int,
+// though void main() is accepted by most compilers (gcc, clang, etc.)
+// This value serves as the program's exit status.
+// See http://en.wikipedia.org/wiki/Exit_status for more information.
+int main(int argc, char** argv)
+{
+ // Command line arguments are passed in by argc and argv in the same way
+ // they are in C.
+ // argc indicates the number of arguments,
+ // and argv is an array of C-style strings (char*)
+ // representing the arguments.
+ // The first argument is the name by which the program was called.
+ // argc and argv can be omitted if you do not care about arguments,
+ // giving the function signature of int main()
+
+ // An exit status of 0 indicates success.
+ return 0;
+}
+
+// In C++, character literals are one byte.
+sizeof('c') == 1
+
+// In C, character literals are the same size as ints.
+sizeof('c') == sizeof(10)
+
+
+// C++ has strict prototyping
+void func(); // function which accepts no arguments
+
+// In C
+void func(); // function which may accept any number of arguments
+
+// Use nullptr instead of NULL in C++
+int* ip = nullptr;
+
+// C standard headers are available in C++,
+// but are prefixed with "c" and have no .h suffix.
+#include <cstdio>
+
+int main()
+{
+ printf("Hello, world!\n");
+ return 0;
+}
+
+///////////////////////
+// Function overloading
+///////////////////////
+
+// C++ supports function overloading
+// provided each function takes different parameters.
+
+void print(char const* myString)
+{
+ printf("String %s\n", myString);
+}
+
+void print(int myInt)
+{
+ printf("My int is %d", myInt);
+}
+
+int main()
+{
+ print("Hello"); // Resolves to void print(const char*)
+ print(15); // Resolves to void print(int)
+}
+
+/////////////////////////////
+// Default function arguments
+/////////////////////////////
+
+// You can provide default arguments for a function
+// if they are not provided by the caller.
+
+void doSomethingWithInts(int a = 1, int b = 4)
+{
+ // Do something with the ints here
+}
+
+int main()
+{
+ doSomethingWithInts(); // a = 1, b = 4
+ doSomethingWithInts(20); // a = 20, b = 4
+ doSomethingWithInts(20, 5); // a = 20, b = 5
+}
+
+// Default arguments must be at the end of the arguments list.
+
+void invalidDeclaration(int a = 1, int b) // Error!
+{
+}
+
+
+/////////////
+// Namespaces
+/////////////
+
+// Namespaces provide separate scopes for variable, function,
+// and other declarations.
+// Namespaces can be nested.
+
+namespace First {
+ namespace Nested {
+ void foo()
+ {
+ printf("This is First::Nested::foo\n");
+ }
+ } // end namespace Nested
+} // end namespace First
+
+namespace Second {
+ void foo()
+ {
+ printf("This is Second::foo\n")
+ }
+}
+
+void foo()
+{
+ printf("This is global foo\n");
+}
+
+int main()
+{
+ // Assume everything is from the namespace "Second"
+ // unless otherwise specified.
+ using namespace Second;
+
+ foo(); // prints "This is Second::foo"
+ First::Nested::foo(); // prints "This is First::Nested::foo"
+ ::foo(); // prints "This is global foo"
+}
+
+///////////////
+// Input/Output
+///////////////
+
+// C++ input and output uses streams
+// cin, cout, and cerr represent stdin, stdout, and stderr.
+// << is the insertion operator and >> is the extraction operator.
+
+#include <iostream> // Include for I/O streams
+
+using namespace std; // Streams are in the std namespace (standard library)
+
+int main()
+{
+ int myInt;
+
+ // Prints to stdout (or terminal/screen)
+ cout << "Enter your favorite number:\n";
+ // Takes in input
+ cin >> myInt;
+
+ // cout can also be formatted
+ cout << "Your favorite number is " << myInt << "\n";
+ // prints "Your favorite number is <myInt>"
+
+ cerr << "Used for error messages";
+}
+
+//////////
+// Strings
+//////////
+
+// Strings in C++ are objects and have many member functions
+#include <string>
+
+using namespace std; // Strings are also in the namespace std (standard library)
+
+string myString = "Hello";
+string myOtherString = " World";
+
+// + is used for concatenation.
+cout << myString + myOtherString; // "Hello World"
+
+cout << myString + " You"; // "Hello You"
+
+// C++ strings are mutable and have value semantics.
+myString.append(" Dog");
+cout << myString; // "Hello Dog"
+
+
+/////////////
+// References
+/////////////
+
+// In addition to pointers like the ones in C,
+// C++ has _references_.
+// These are pointer types that cannot be reassigned once set
+// and cannot be null.
+// They also have the same syntax as the variable itself:
+// No * is needed for dereferencing and
+// & (address of) is not used for assignment.
+
+using namespace std;
+
+string foo = "I am foo";
+string bar = "I am bar";
+
+
+string& fooRef = foo; // This creates a reference to foo.
+fooRef += ". Hi!"; // Modifies foo through the reference
+cout << fooRef; // Prints "I am foo. Hi!"
+
+// Doesn't reassign "fooRef". This is the same as "foo = bar", and
+// foo == "I am bar"
+// after this line.
+fooRef = bar;
+
+const string& barRef = bar; // Create a const reference to bar.
+// Like C, const values (and pointers and references) cannot be modified.
+barRef += ". Hi!"; // Error, const references cannot be modified.
+
+//////////////////////////////////////////
+// Classes and object-oriented programming
+//////////////////////////////////////////
+
+// First example of classes
+#include <iostream>
+
+// Declare a class.
+// Classes are usually declared in header (.h or .hpp) files.
+class Dog {
+ // Member variables and functions are private by default.
+ std::string name;
+ int weight;
+
+// All members following this are public
+// until "private:" or "protected:" is found.
+public:
+
+ // Default constructor
+ Dog();
+
+ // Member function declarations (implementations to follow)
+ // Note that we use std::string here instead of placing
+ // using namespace std;
+ // above.
+ // Never put a "using namespace" statement in a header.
+ void setName(const std::string& dogsName);
+
+ void setWeight(int dogsWeight);
+
+ // Functions that do not modify the state of the object
+ // should be marked as const.
+ // This allows you to call them if given a const reference to the object.
+ // Also note the functions must be explicitly declared as _virtual_
+ // in order to be overridden in derived classes.
+ // Functions are not virtual by default for performance reasons.
+ virtual void print() const;
+
+ // Functions can also be defined inside the class body.
+ // Functions defined as such are automatically inlined.
+ void bark() const { std::cout << name << " barks!\n" }
+
+ // Along with constructors, C++ provides destructors.
+ // These are called when an object is deleted or falls out of scope.
+ // This enables powerful paradigms such as RAII
+ // (see below)
+ // Destructors must be virtual to allow classes to be derived from this one.
+ virtual ~Dog();
+
+}; // A semicolon must follow the class definition.
+
+// Class member functions are usually implemented in .cpp files.
+void Dog::Dog()
+{
+ std::cout << "A dog has been constructed\n";
+}
+
+// Objects (such as strings) should be passed by reference
+// if you are modifying them or const reference if you are not.
+void Dog::setName(const std::string& dogsName)
+{
+ name = dogsName;
+}
+
+void Dog::setWeight(int dogsWeight)
+{
+ weight = dogsWeight;
+}
+
+// Notice that "virtual" is only needed in the declaration, not the definition.
+void Dog::print() const
+{
+ std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
+}
+
+void Dog::~Dog()
+{
+ cout << "Goodbye " << name << "\n";
+}
+
+int main() {
+ Dog myDog; // prints "A dog has been constructed"
+ myDog.setName("Barkley");
+ myDog.setWeight(10);
+ myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg"
+ return 0;
+} // prints "Goodbye Barkley"
+
+// Inheritance:
+
+// This class inherits everything public and protected from the Dog class
+class OwnedDog : public Dog {
+
+ void setOwner(const std::string& dogsOwner)
+
+ // Override the behavior of the print function for all OwnedDogs. See
+ // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
+ // for a more general introduction if you are unfamiliar with
+ // subtype polymorphism.
+ // The override keyword is optional but makes sure you are actually
+ // overriding the method in a base class.
+ void print() const override;
+
+private:
+ std::string owner;
+};
+
+// Meanwhile, in the corresponding .cpp file:
+
+void OwnedDog::setOwner(const std::string& dogsOwner)
+{
+ owner = dogsOwner;
+}
+
+void OwnedDog::print() const
+{
+ Dog::print(); // Call the print function in the base Dog class
+ std::cout << "Dog is owned by " << owner << "\n";
+ // Prints "Dog is <name> and weights <weight>"
+ // "Dog is owned by <owner>"
+}
+
+//////////////////////////////////////////
+// Initialization and Operator Overloading
+//////////////////////////////////////////
+
+// In C++ you can overload the behavior of operators such as +, -, *, /, etc.
+// This is done by defining a function which is called
+// whenever the operator is used.
+
+#include <iostream>
+using namespace std;
+
+class Point {
+public:
+ // Member variables can be given default values in this manner.
+ double x = 0;
+ double y = 0;
+
+ // Define a default constructor which does nothing
+ // but initialize the Point to the default value (0, 0)
+ Point() { };
+
+ // The following syntax is known as an initialization list
+ // and is the proper way to initialize class member values
+ Point (double a, double b) :
+ x(a),
+ y(b)
+ { /* Do nothing except initialize the values */ }
+
+ // Overload the + operator.
+ Point operator+(const Point& rhs) const;
+
+ // Overload the += operator
+ Point& operator+=(const Point& rhs);
+
+ // It would also make sense to add the - and -= operators,
+ // but we will skip those for brevity.
+};
+
+Point Point::operator+(const Point& rhs) const
+{
+ // Create a new point that is the sum of this one and rhs.
+ return Point(x + rhs.x, y + rhs.y);
+}
+
+Point& Point::operator+=(const Point& rhs)
+{
+ x += rhs.x;
+ y += rhs.y;
+ return *this;
+}
+
+int main () {
+ Point up (0,1);
+ Point right (1,0);
+ // This calls the Point + operator
+ // Point up calls the + (function) with right as its paramater
+ Point result = up + right;
+ // Prints "Result is upright (1,1)"
+ cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
+ return 0;
+}
+
+/////////////////////
+// Exception Handling
+/////////////////////
+
+// The standard library provides a few exception types
+// (see http://en.cppreference.com/w/cpp/error/exception)
+// but any type can be thrown an as exception
+#include <exception>
+
+// All exceptions thrown inside the _try_ block can be caught by subsequent
+// _catch_ handlers.
+try {
+ // Do not allocate exceptions on the heap using _new_.
+ throw std::exception("A problem occurred");
+}
+// Catch exceptions by const reference if they are objects
+catch (const std::exception& ex)
+{
+ std::cout << ex.what();
+// Catches any exception not caught by previous _catch_ blocks
+} catch (...)
+{
+ std::cout << "Unknown exception caught";
+ throw; // Re-throws the exception
+}
+
+///////
+// RAII
+///////
+
+// RAII stands for Resource Allocation Is Initialization.
+// It is often considered the most powerful paradigm in C++,
+// and is the simple concept that a constructor for an object
+// acquires that object's resources and the destructor releases them.
+
+// To understand how this is useful,
+// consider a function that uses a C file handle:
+void doSomethingWithAFile(const char* filename)
+{
+ // To begin with, assume nothing can fail.
+
+ FILE* fh = fopen(filename, "r"); // Open the file in read mode.
+
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+ fclose(fh); // Close the file handle.
+}
+
+// Unfortunately, things are quickly complicated by error handling.
+// Suppose fopen can fail, and that doSomethingWithTheFile and
+// doSomethingElseWithIt return error codes if they fail.
+// (Exceptions are the preferred way of handling failure,
+// but some programmers, especially those with a C background,
+// disagree on the utility of exceptions).
+// We now have to check each call for failure and close the file handle
+// if a problem occurred.
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // Open the file in read mode
+ if (fh == nullptr) // The returned pointer is null on failure.
+ reuturn false; // Report that failure to the caller.
+
+ // Assume each function returns false if it failed
+ if (!doSomethingWithTheFile(fh)) {
+ fclose(fh); // Close the file handle so it doesn't leak.
+ return false; // Propagate the error.
+ }
+ if (!doSomethingElseWithIt(fh)) {
+ fclose(fh); // Close the file handle so it doesn't leak.
+ return false; // Propagate the error.
+ }
+
+ fclose(fh); // Close the file handle so it doesn't leak.
+ return true; // Indicate success
+}
+
+// C programmers often clean this up a little bit using goto:
+bool doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r");
+ if (fh == nullptr)
+ reuturn false;
+
+ if (!doSomethingWithTheFile(fh))
+ goto failure;
+
+ if (!doSomethingElseWithIt(fh))
+ goto failure;
+
+ fclose(fh); // Close the file
+ return true; // Indicate success
+
+failure:
+ fclose(fh);
+ return false; // Propagate the error
+}
+
+// If the functions indicate errors using exceptions,
+// things are a little cleaner, but still sub-optimal.
+void doSomethingWithAFile(const char* filename)
+{
+ FILE* fh = fopen(filename, "r"); // Open the file in read mode
+ if (fh == nullptr)
+ throw std::exception("Could not open the file.");
+
+ try {
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+ }
+ catch (...) {
+ fclose(fh); // Be sure to close the file if an error occurs.
+ throw; // Then re-throw the exception.
+ }
+
+ fclose(fh); // Close the file
+ // Everything succeeded
+}
+
+// Compare this to the use of C++'s file stream class (fstream)
+// fstream uses its destructor to close the file.
+// Recall from above that destructors are automatically called
+// whenver an object falls out of scope.
+void doSomethingWithAFile(const std::string& filename)
+{
+ // ifstream is short for input file stream
+ std::ifstream fh(filename); // Open the file
+
+ // Do things with the file
+ doSomethingWithTheFile(fh);
+ doSomethingElseWithIt(fh);
+
+} // The file is automatically closed here by the destructor
+
+// This has _massive_ advantages:
+// 1. No matter what happens,
+// the resource (in this case the file handle) will be cleaned up.
+// Once you write the destructor correctly,
+// It is _impossible_ to forget to close the handle and leak the resource.
+// 2. Note that the code is much cleaner.
+// The destructor handles closing the file behind the scenes
+// without you having to worry about it.
+// 3. The code is exception safe.
+// An exception can be thrown anywhere in the function and cleanup
+// will still occur.
+
+// All idiomatic C++ code uses RAII extensively for all resources.
+// Additional examples include
+// - Memory using unique_ptr and shared_ptr
+// - Containers - the standard library linked list,
+// vector (i.e. self-resizing array), hash maps, and so on
+// all automatically destroy their contents when they fall out of scope.
+// - Mutexes using lock_guard and unique_lock
+```
+Futher Reading:
+
+An up-to-date language reference can be found at
+<http://cppreference.com/w/cpp>
+
+Additional resources may be found at <http://cplusplus.com>
diff --git a/c.html.markdown b/c.html.markdown
index 8e170300..f44da38e 100644
--- a/c.html.markdown
+++ b/c.html.markdown
@@ -4,6 +4,8 @@ filename: learnc.c
contributors:
- ["Adam Bard", "http://adambard.com/"]
- ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"]
+ - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"]
+ - ["Marco Scannadinari", "https://marcoms.github.io"]
---
@@ -20,6 +22,10 @@ memory management and C will take you as far as you need to go.
Multi-line comments look like this. They work in C89 as well.
*/
+/*
+Multi-line comments don't nest /* Be careful */ // comment ends on this line...
+*/ // ...not this one!
+
// Constants: #define <keyword>
#define DAYS_IN_YEAR 365
@@ -73,12 +79,12 @@ int main() {
long long x_long_long = 0;
// floats are usually 32-bit floating point numbers
- float x_float = 0.0;
+ float x_float = 0.0f; // 'f' suffix here denotes floating point literal
// doubles are usually 64-bit floating-point numbers
- double x_double = 0.0;
+ double x_double = 0.0; // real numbers without any suffix are doubles
- // Integral types may be unsigned.
+ // integer types may be unsigned (only positive)
unsigned short ux_short;
unsigned int ux_int;
unsigned long long ux_long_long;
@@ -175,6 +181,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 +203,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
@@ -211,7 +222,7 @@ int main() {
int e = 5;
int f = 10;
int z;
- z = (a > b) ? a : b; // => 10 "if a > b return a, else return b."
+ z = (e > f) ? e : f; // => 10 "if e > f return e, else return f."
//Increment and decrement operators:
char *s = "iLoveC";
@@ -573,7 +584,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
@@ -618,7 +629,7 @@ typedef void (*my_fnp_type)(char *);
## Further Reading
Best to find yourself a copy of [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language)
-It is *the* book about C, written by the creators of C. Be careful, though - it's ancient and it contains some
+It is *the* book about C, written by Dennis Ritchie, the creator of C, and Brian Kernighan. Be careful, though - it's ancient and it contains some
inaccuracies (well, ideas that are not considered good anymore) or now-changed practices.
Another good resource is [Learn C the hard way](http://c.learncodethehardway.org/book/).
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..c4ecb5e8 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
@@ -431,7 +431,7 @@ nil ; for false - and the empty list
:walked
(walker (1- n))))
-(walker) ; => :walked
+(walker 5) ; => :walked
;; Most of the time, we use DOLIST or LOOP
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/csharp.html.markdown b/csharp.html.markdown
index 136f6c50..f6708590 100644
--- a/csharp.html.markdown
+++ b/csharp.html.markdown
@@ -508,7 +508,7 @@ on a new line! ""Wow!"", the masses cried";
// LINQ - maps a store to IQueryable<T> objects, with delayed execution
// e.g. LinqToSql - maps to a database, LinqToXml maps to an xml document
- var db = new BikeRespository();
+ var db = new BikeRepository();
// execution is delayed, which is great when querying a database
var filter = db.Bikes.Where(b => b.HasTassles); // no query run
@@ -767,9 +767,9 @@ on a new line! ""Wow!"", the masses cried";
/// EntityFramework Code First is awesome (similar to Ruby's ActiveRecord, but bidirectional)
/// http://msdn.microsoft.com/en-us/data/jj193542.aspx
/// </summary>
- public class BikeRespository : DbSet
+ public class BikeRepository : DbSet
{
- public BikeRespository()
+ public BikeRepository()
: base()
{
}
diff --git a/css.html.markdown b/css.html.markdown
index cdef50cc..e058d691 100644
--- a/css.html.markdown
+++ b/css.html.markdown
@@ -3,6 +3,7 @@ language: css
contributors:
- ["Mohammad Valipour", "https://github.com/mvalipour"]
- ["Marco Scannadinari", "https://github.com/marcoms"]
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
filename: learncss.css
---
@@ -24,18 +25,19 @@ The main focus of this article is on the syntax and some general tips.
```css
-/* comments appear inside slash-asterisk, just like this line! */
+/* comments appear inside slash-asterisk, just like this line!
+ there are no "one-line comments"; this is the only comment style */
/* ####################
## SELECTORS
- ####################*/
+ #################### */
/* Generally, the primary statement in CSS is very simple */
selector { property: value; /* more properties...*/ }
/* the selector is used to target an element on page.
-You can target all elments on the page! */
+You can target all elments on the page using asterisk! */
* { color:red; }
/*
@@ -62,61 +64,61 @@ div { }
/* or that the attribute has a specific value */
[attr='value'] { font-size:smaller; }
-/* start with a value*/
+/* start with a value (CSS3) */
[attr^='val'] { font-size:smaller; }
-/* or ends with */
+/* or ends with (CSS3) */
[attr$='ue'] { font-size:smaller; }
-/* or even contains a value */
+/* or even contains a value (CSS3) */
[attr~='lu'] { font-size:smaller; }
/* and more importantly you can combine these together -- there shouldn't be
-any spaaace between different parts because that makes it to have another
-meaning.*/
+any space between different parts because that makes it to have another
+meaning. */
div.some-class[attr$='ue'] { }
-/* you can also select an element based on its parent.*/
+/* you can also select an element based on its parent. */
-/*an element which is direct child of an element (selected the same way) */
+/* an element which is direct child of an element (selected the same way) */
div.some-parent > .class-name {}
-/* or any of its parents in the tree */
-/* the following basically means any element that has class "class-name"
-and is child of a div with class name "some-parent" IN ANY DEPTH */
+/* or any of its parents in the tree
+ the following basically means any element that has class "class-name"
+ and is child of a div with class name "some-parent" IN ANY DEPTH */
div.some-parent .class-name {}
/* warning: the same selector wihout spaaace has another meaning.
-can you say what? */
+ can you say what? */
div.some-parent.class-name {}
/* you also might choose to select an element based on its direct
-previous sibling */
+ previous sibling */
.i-am-before + .this-element { }
-/*or any sibling before this */
+/* or any sibling before this */
.i-am-any-before ~ .this-element {}
/* There are some pseudo classes that allows you to select an element
-based on its page behaviour (rather than page structure) */
+ based on its page behaviour (rather than page structure) */
/* for example for when an element is hovered */
-:hover {}
+selector:hover {}
-/* or a visited link*/
-:visited {}
+/* or a visited link */
+selected:visited {}
-/* or not visited link*/
-:link {}
+/* or not visited link */
+selected:link {}
/* or an input element which is focused */
-:focus {}
+selected:focus {}
/* ####################
## PROPERTIES
- ####################*/
+ #################### */
selector {
@@ -126,8 +128,12 @@ selector {
width: 200px; /* in pixels */
font-size: 20pt; /* in points */
width: 5cm; /* in centimeters */
- width: 50mm; /* in millimeters */
- width: 5in; /* in inches */
+ min-width: 50mm; /* in millimeters */
+ max-width: 5in; /* in inches. max-(width|height) */
+ height: 0.2vh; /* times vertical height of browser viewport (CSS3) */
+ width: 0.4vw; /* times horizontal width of browser viewport (CSS3) */
+ min-height: 0.1vmin; /* the lesser of vertical, horizontal dimensions of browser viewport (CSS3) */
+ max-width: 0.3vmax; /* same as above, except the greater of the dimensions (CSS3) */
/* Colors */
background-color: #F6E; /* in short hex */
@@ -135,16 +141,20 @@ selector {
background-color: tomato; /* can be a named color */
background-color: rgb(255, 255, 255); /* in rgb */
background-color: rgb(10%, 20%, 50%); /* in rgb percent */
- background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb */
+ background-color: rgba(255, 0, 0, 0.3); /* in semi-transparent rgb (CSS3) */
+ background-color: transparent; /* see thru */
+ background-color: hsl(0, 100%, 50%); /* hsl format (CSS3). */
+ background-color: hsla(0, 100%, 50%, 0.3); /* Similar to RGBA, specify opacity at end (CSS3) */
+
/* Images */
- background-image: url(/path-to-image/image.jpg);
+ background-image: url(/path-to-image/image.jpg); /* quotes inside url() optional */
/* Fonts */
font-family: Arial;
- font-family: "Courier New"; /* if name has spaaace it appears in double-quote */
- font-family: "Courier New", Trebuchet, Arial; /* if first one was not found
- browser uses the second font, and so forth */
+ font-family: "Courier New"; /* if name has spaaace it appears in single or double quotes */
+ font-family: "Courier New", Trebuchet, Arial, sans-serif; /* if first one was not found
+ browser uses the second font, and so forth */
}
```
@@ -155,17 +165,17 @@ Save any CSS you want in a file with extension `.css`.
```xml
<!-- you need to include the css file in your page's <head>: -->
-<link rel='stylesheet' type='text/css' href='filepath/filename.css' />
+<link rel='stylesheet' type='text/css' href='path/to/style.css' />
<!-- you can also include some CSS inline in your markup. However it is highly
recommended to avoid this. -->
<style>
- selector { property:value; }
+ a { color: purple; }
</style>
<!-- or directly set CSS properties on the element.
This has to be avoided as much as you can. -->
-<div style='property:value;'>
+<div style="border: 1px solid red;">
</div>
```
@@ -207,27 +217,28 @@ The precedence of style is as followed:
Remember, the precedence is for each **property**, not for the entire block.
* `E` has the highest precedence because of the keyword `!important`.
- It is recommended to avoid this unless it is strictly necessary to use.
+ It is recommended to avoid this unless it is strictly necessary to use.
* `F` is next, because it is inline style.
* `A` is next, because it is more "specific" than anything else.
- more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
- class name `class1` + 1 attribute `attr='value'`
+ more specific = more specifiers. here 3 specifiers: 1 tagname `p` +
+ class name `class1` + 1 attribute `attr='value'`
* `C` is next. although it has the same specificness as `B`
- but it appears last.
+ but it appears last.
* Then is `B`
* and lastly is `D`.
## Compatibility
Most of the features in CSS2 (and gradually in CSS3) are compatible across
-all browsers and devices. But it's always vital to have in mind the compatiblity
+all browsers and devices. But it's always vital to have in mind the compatiblity
of what you use in CSS with your target browsers.
[QuirksMode CSS](http://www.quirksmode.org/css/) is one of the best sources for this.
+To run a quick compatibility check, [CanIUse](http://caniuse.com) is a great resource.
+
## Further Reading
* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
* [QuirksMode CSS](http://www.quirksmode.org/css/)
* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
-
diff --git a/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/csharp-de.html.markdown b/de-de/csharp-de.html.markdown
new file mode 100644
index 00000000..dc77dda0
--- /dev/null
+++ b/de-de/csharp-de.html.markdown
@@ -0,0 +1,889 @@
+---
+language: c#
+contributors:
+ - ["Irfan Charania", "https://github.com/irfancharania"]
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Melvyn Laïly", "http://x2a.yt"]
+ - ["Shaun McCarthy", "http://www.shaunmccarthy.com"]
+translators:
+ - ["Frederik Ring", "https://github.com/m90"]
+filename: LearnCSharp-de.cs
+lang: de-de
+---
+C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden.
+
+[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx)
+
+```c#
+// Einzeilige Kommentare starten mit zwei Schrägstrichen: //
+/*
+Mehrzeile Kommentare wie in C Schrägstrich / Stern
+*/
+/// <summary>
+/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden
+/// </summary>
+
+// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt
+using System;
+using System.Collections.Generic;
+using System.Data.Entity;
+using System.Dynamic;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Net;
+using System.Threading.Tasks;
+using System.IO;
+
+// definiert einen Namespace um Code in "packages" zu organisieren
+namespace Learning
+{
+ // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei
+ // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu
+ // handhaben führt aber unweigerlich ins Chaos (wirklich)!
+ public class LearnCSharp
+ {
+ // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen,
+ // wenn du bereits Java oder C++ programmieren kannst:
+ // lies bei "Interessante Features" weiter!
+ public static void Syntax()
+ {
+ // Mit Console.WriteLine kannst du einfachen Text ausgeben:
+ Console.WriteLine("Hallo Welt");
+ Console.WriteLine(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Console.Write erzeugt keinen Zeilenumbruch
+ Console.Write("Hallo ");
+ Console.Write("Welt");
+
+ ///////////////////////////////////////////////////
+ // Typen & Variablen
+ ///////////////////////////////////////////////////
+
+ // Deklariere eine Variable mit <Typ> <Name>
+
+ // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl
+ // (-128 <= sbyte <= 127)
+ sbyte fooSbyte = 100;
+
+ // Byte - Vorzeichenlose 8-Bit Ganzzahl
+ // (0 <= byte <= 255)
+ byte fooByte = 100;
+
+ // Short - 16-Bit Ganzzahl
+ // Vorzeichenbehaftet - (-32,768 <= short <= 32,767)
+ // Vorzeichenlos - (0 <= ushort <= 65,535)
+ short fooShort = 10000;
+ ushort fooUshort = 10000;
+
+ // Integer - 32-bit Ganzzahl
+ int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647)
+ uint fooUint = 1; // (0 <= uint <= 4,294,967,295)
+
+ // Long - 64-bit Ganzzahl
+ long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615)
+ // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder
+ // uint behandelt. Ein nachgestelltes L markiert den Wert als long
+ // oder ulong.
+
+ // Double - Double-precision 64-bit IEEE 754 Fließkommazahl
+ double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen
+
+ // Float - Single-precision 32-bit IEEE 754 Fließkommazahl
+ float fooFloat = 234.5f; // Genauigkeit: 7 Stellen
+ // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ
+ // float handelt
+
+ // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als
+ // andere Fließkommatypen, und somit bestens geeignet für
+ // die Berechnung von Geld- und Finanzwerten
+ decimal fooDecimal = 150.3m;
+
+ // Boolean - true & false
+ bool fooBoolean = true; // oder false
+
+ // Char - Ein einzelnes 16-Bit Unicode Zeichen
+ char fooChar = 'A';
+
+ // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die
+ // alle Werttypen sind, ist String ein Referenztyp. Strings sind
+ // somit nullable, Werttypen sind dies nicht.
+ string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu";
+ Console.WriteLine(fooString);
+
+ // Jeder Buchstabe eines Strings kann über seinen Index
+ // referenziert werden:
+ char charFromString = fooString[1]; // => 'e'
+ // Strings sind unveränderlich:
+ // `fooString[1] = 'X';` funktioniert nicht
+
+ // Ein Vergleich zweier Strings, unter Berücksichtigung der
+ // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c
+ // in deutschsprachigen Umgebungen), und ohne Beachtung von
+ // Groß- und Kleinschreibung:
+ string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase);
+
+ // Formatierung, genau wie "sprintf"
+ string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2);
+
+ // Datumsangaben und Formatierung
+ DateTime fooDate = DateTime.Now;
+ Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy"));
+
+ // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String
+ // schreiben. Um " zu maskieren benutzt man ""
+ string bazString = @"Hier geht es
+zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen";
+
+ // Die Keywords const oder readonly kennzeichnen eine
+ // unveränderliche Variable/Konstante. Die Werte von Konstanten
+ // werden übrigens bereits zur Compile-Zeit berechnet.
+ const int HOURS_I_WORK_PER_WEEK = 9001;
+
+ ///////////////////////////////////////////////////
+ // Datenstrukturen
+ ///////////////////////////////////////////////////
+
+ // Arrays - Index beginnt bei Null
+ // Die Größe des Arrays wird bei der Deklaration festgelegt.
+ // Die syntaktische Struktur um ein neues Array zu erzeugen sieht
+ // folgendermaßen aus:
+ // <datatype>[] <varname> = new <datatype>[<array size>];
+ int[] intArray = new int[10];
+
+ // Arrays können auch über ein Array-Literal deklariert werden:
+ int[] y = { 9000, 1000, 1337 };
+
+ // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element
+ Console.WriteLine("intArray @ 0: " + intArray[0]);
+ // Arrays sind veränderbar
+ intArray[1] = 1;
+
+ // Listen
+ // Durch ihre größere Flexibilität kommen Listen in C# weit
+ // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert:
+ // List<datatype> <varname> = new List<datatype>();
+ List<int> intList = new List<int>();
+ List<string> stringList = new List<string>();
+ List<int> z = new List<int> { 9000, 1000, 1337 };
+ // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen"
+
+ // Listen haben keinen Default-Wert.
+ // Bevor auf einen Index zugegriffen werden kann, muss dieser
+ // auch gesetzt worden sein:
+ intList.Add(1);
+ Console.WriteLine("intList @ 0: " + intList[0]);
+
+ // Andere interessante Datenstrukturen sind:
+ // Stack/Queue
+ // Dictionary (entspricht einer Hash Map)
+ // HashSet
+ // Read-only Collections
+ // Tuple (.Net 4+)
+
+ ///////////////////////////////////////
+ // Operatoren
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Operatoren");
+
+ // kurze Schreibweise um mehrere Deklarationen zusammenzufassen:
+ // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!)
+ int i1 = 1, i2 = 2;
+
+ // Arithmetik funktioniert wie erwartet:
+ Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3
+
+ // Modulo
+ Console.WriteLine("11%3 = " + (11 % 3)); // => 2
+
+ // Vergleiche
+ Console.WriteLine("3 == 2? " + (3 == 2)); // => false
+ Console.WriteLine("3 != 2? " + (3 != 2)); // => true
+ Console.WriteLine("3 > 2? " + (3 > 2)); // => true
+ Console.WriteLine("3 < 2? " + (3 < 2)); // => false
+ Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true
+ Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true
+
+ // Bitweise Operatoren
+ /*
+ ~ Unäres bitweises NICHT
+ << Verschieben nach links
+ >> Verschieben nach rechts
+ & Bitweises UND
+ ^ Bitweises exklusives ODER
+ | Bitweises inklusives ODER
+ */
+
+ // Inkremente
+ int i = 0;
+ Console.WriteLine("\n->Inkrement / Dekrement");
+ Console.WriteLine(i++); //i = 1. Post-Inkrement
+ Console.WriteLine(++i); //i = 2. Pre-Inkrement
+ Console.WriteLine(i--); //i = 1. Post-Dekrement
+ Console.WriteLine(--i); //i = 0. Pre-Dekrement
+
+ ///////////////////////////////////////
+ // Kontrollstrukturen
+ ///////////////////////////////////////
+ Console.WriteLine("\n->Kontrollstrukturen");
+
+ // If-Statements funktionieren wie in C
+ int j = 10;
+ if (j == 10)
+ {
+ Console.WriteLine("Ich werde ausgegeben");
+ }
+ else if (j > 10)
+ {
+ Console.WriteLine("Ich nicht");
+ }
+ else
+ {
+ Console.WriteLine("Ich leider auch nicht");
+ }
+
+ // Ternärer Operator
+ // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben:
+ // <condition> ? <true> : <false>
+ string isTrue = true ? "Ja" : "Nein";
+
+ // while-Schleife
+ int fooWhile = 0;
+ while (fooWhile < 100)
+ {
+ // Wird 100mal wiederholt, fooWhile 0->99
+ fooWhile++;
+ }
+
+ // do-while-Schleife
+ int fooDoWhile = 0;
+ do
+ {
+ // Wird 100mal wiederholt, fooDoWhile 0->99
+ fooDoWhile++;
+ } while (fooDoWhile < 100);
+
+ //for-Schleifen => for(<start_statement>; <conditional>; <step>)
+ for (int fooFor = 0; fooFor < 10; fooFor++)
+ {
+ // Wird 10mal wiederholt, fooFor 0->9
+ }
+
+ // foreach-Schleife
+ // Die normale Syntax für eine foreach-Schleife lautet:
+ // foreach(<iteratorType> <iteratorName> in <enumerable>)
+ // foreach kann mit jedem Objekt verwendet werden das IEnumerable
+ // oder IEnumerable<T> implementiert. Alle Auflistungs-Typen
+ // (Array, List, Dictionary...) im .NET Framework implementieren
+ // eines dieser beiden Interfaces.
+
+ foreach (char character in "Hallo Welt".ToCharArray())
+ {
+ // Ein Durchgang für jedes Zeichen im String
+ }
+ // (ToCharArray() könnte man hier übrigens auch weglassen,
+ // da String IEnumerable bereits implementiert)
+
+ // Switch Struktur
+ // Ein Switch funktioniert mit byte, short, char und int Datentypen.
+ // Auch Aufzählungstypen können verwendet werden, genau wie
+ // die Klasse String, und ein paar Sonderklassen, die Wrapper für
+ // Primitives sind: Character, Byte, Short und Integer
+ int month = 3;
+ string monthString;
+ switch (month)
+ {
+ case 1:
+ monthString = "Januar";
+ break;
+ case 2:
+ monthString = "Februar";
+ break;
+ case 3:
+ monthString = "März";
+ break;
+ // Man kann für mehrere Fälle auch das selbe Verhalten
+ // definieren. Jeder Block muss aber mit einem break-Statement
+ // abgeschlossen werden. Einzelne Fälle können über
+ // `goto case x` erreicht werden
+ case 6:
+ case 7:
+ case 8:
+ monthString = "Sommer!!";
+ break;
+ default:
+ monthString = "Irgendein anderer Monat";
+ break;
+ }
+
+ ///////////////////////////////////////
+ // Umwandlung von Datentypen und Typecasting
+ ///////////////////////////////////////
+
+ // Umwandlung
+
+ // von String nach Integer
+ // bei einem Fehler wirft diese Code eine Exception
+ int.Parse("123"); //gibt die Ganzzahl 123 zurück
+
+ // TryParse gibt bei einem Fehler den Default-Wert zurück
+ // (im Fall von int: 0)
+ int tryInt;
+ if (int.TryParse("123", out tryInt)) // gibt true oder false zurück
+ {
+ Console.WriteLine(tryInt); // 123
+ }
+
+ // von Integer nach String
+ // Die Klasse Convert stellt Methoden zur Konvertierung von
+ // unterschiedlichsten Daten zur Verfügung:
+ Convert.ToString(123); // "123"
+ // oder
+ tryInt.ToString(); // "123"
+ }
+
+ ///////////////////////////////////////
+ // Klassen
+ ///////////////////////////////////////
+ public static void Classes()
+ {
+
+ // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen
+ Bicycle trek = new Bicycle();
+
+ // So werden Methoden der Instanz aufgerufen
+ trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen
+ trek.Cadence = 100;
+
+ // ToString ist eine Konvention über die man üblicherweiser
+ // Informationen über eine Instanz erhält
+ Console.WriteLine("Infos zu trek: " + trek.ToString());
+
+ // Wir instantiieren ein neues Hochrad
+ PennyFarthing funbike = new PennyFarthing(1, 10);
+ Console.WriteLine("Infos zu funbike: " + funbike.ToString());
+
+ Console.Read();
+ } // Ende der Methode main
+
+ // Main als Konsolenstartpunkt
+ // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen
+ public static void Main(string[] args)
+ {
+ OtherInterestingFeatures();
+ }
+
+ ///////////////////////////////////////
+ // Interessante Features
+ ///////////////////////////////////////
+
+ // Methodensignaturen
+
+ public // Sichtbarkeit
+ static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz)
+ int // Typ des Rückgabewerts,
+ MethodSignatures(
+ // Erstes Argument, erwartet int
+ int maxCount,
+ // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird
+ int count = 0,
+ int another = 3,
+ // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats)
+ params string[] otherParams
+ )
+ {
+ return -1;
+ }
+
+ // Methoden können überladen werden, solange sie eindeutige
+ // Signaturen haben
+ public static void MethodSignatures(string maxCount)
+ {
+ }
+
+ // Generische Typen
+ // Die Typen für TKey und TValue werden erst beim Aufruf der Methode
+ // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python:
+ public static TValue SetDefault<TKey, TValue>(
+ IDictionary<TKey, TValue> dictionary,
+ TKey key,
+ TValue defaultItem)
+ {
+ TValue result;
+ if (!dictionary.TryGetValue(key, out result))
+ {
+ return dictionary[key] = defaultItem;
+ }
+ return result;
+ }
+
+ // Möglichen Typen lassen sich auch über ihr Interface beschränken:
+ public static void IterateAndPrint<T>(T toPrint) where T: IEnumerable<int>
+ {
+ // Da T ein IEnumerable ist können wir foreach benutzen
+ foreach (var item in toPrint)
+ {
+ // Item ist ein int
+ Console.WriteLine(item.ToString());
+ }
+ }
+
+ public static void OtherInterestingFeatures()
+ {
+ // Optionale Parameter
+ MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings");
+ // setzt explizit einen bestimmten Parameter, andere werden übersprungen
+ MethodSignatures(3, another: 3);
+
+ // Erweiterungsmethoden
+ int i = 3;
+ i.Print(); // Weiter unten definiert
+
+ // Nullables - perfekt für die Interaktion mit
+ // Datenbanken / Rückgabewerten
+ // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ?
+ // nullable gemacht werden: <type>? <varname> = <value>
+ int? nullable = null; // Die explizite Langform wäre Nullable<int>
+ Console.WriteLine("Mein Nullable: " + nullable);
+ bool hasValue = nullable.HasValue; // true wenn nicht null
+
+ // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall
+ // dass die Variable null ist festzulegen.
+ int notNullable = nullable ?? 0; // 0
+
+ // Implizit typisierte Variablen
+ // Man kann auch den Typ einer Variable auch vom Compiler
+ // bestimmen lassen:
+ var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren";
+ magic = 9; // funktioniert nicht da magic vom Typ String ist
+
+ // Generics
+ var phonebook = new Dictionary<string, string>() {
+ {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu
+ };
+
+ // Hier könnte man auch unser generisches SetDefault von
+ // weiter oben benutzen:
+ Console.WriteLine(SetDefault<string,string>(phonebook, "Xaver", "kein Telefon")); // kein Telefon
+ // TKey und TValue müssen nicht zwingend angegeben werden, da sie
+ // auch implizit vom Compiler ermittelt werden können
+ Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67
+
+ // Lambdas - konzise Syntax für Inline-Funktionen
+ Func<int, int> square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert
+ Console.WriteLine(square(3)); // 9
+
+ // Disposables - einfaches Management von nicht verwalteten Ressourcen
+ // So gut wie alle Objekte die auf nicht verwaltete Ressourcen
+ // (Dateien, Geräte, ...) zugreifen, implementieren das Interface
+ // IDisposable. Das using Statement stellt sicher dass die vom
+ // IDisposable benutzten Ressourcen nach der Benutzung wieder
+ // freigegeben werden:
+ using (StreamWriter writer = new StreamWriter("log.txt"))
+ {
+ writer.WriteLine("Alles bestens!");
+ // Am Ende des Codeblocks werden die Ressourcen wieder
+ // freigegeben - auch im Falle einer Exception
+ }
+
+ // Parallel Klasse
+ // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx
+ var websites = new string[] {
+ "http://www.google.com", "http://www.reddit.com",
+ "http://www.shaunmccarthy.com"
+ };
+ var responses = new Dictionary<string, string>();
+
+ // Für jeden Request wird ein neuer Thread erzeugt, der nächste
+ // Schritt wird erst nach Beendigung aller Tasks ausgeführt
+ Parallel.ForEach(websites,
+ // maximal 3 Threads gleichzeitig
+ new ParallelOptions() {MaxDegreeOfParallelism = 3},
+ website =>
+ {
+ // Hier folgt eine langwierige, asynchrone Operation
+ using (var r = WebRequest.Create(new Uri(website)).GetResponse())
+ {
+ responses[website] = r.ContentType;
+ }
+ });
+
+ // Dieser Code wird erst nach Beendigung aller Requests ausgeführt
+ foreach (var key in responses.Keys)
+ {
+ Console.WriteLine("{0}:{1}", key, responses[key]);
+ }
+
+ // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten)
+ dynamic student = new ExpandoObject();
+ // hier muss keine Typ angegeben werden
+ student.FirstName = "Christian";
+
+ // Einem solchen Objekt kann man sogar Methoden zuordnen.
+ // Das Beispiel gibt einen String zurück und erwartet einen String
+ student.Introduce = new Func<string, string>(
+ (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo));
+ Console.WriteLine(student.Introduce("Bettina"));
+
+ // IQueryable<T> - So gut wie alle Aufzählungstypen implementieren
+ // dieses Interface, welches eine Vielzahl von funktionalen Methoden
+ // wie Map / Filter / Reduce zur Verfügung stellt:
+ var bikes = new List<Bicycle>();
+ // sortiert die Liste
+ bikes.Sort();
+ // sortiert nach Anzahl Räder
+ bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels));
+ var result = bikes
+ // diese Filter können auch aneinandergehängt werden
+ .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück)
+ .Where(b => b.IsBroken && b.HasTassles)
+ // diese Zuordnung gibt ein IQueryable<String> zurück
+ .Select(b => b.ToString());
+
+ // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert
+ var sum = bikes.Sum(b => b.Wheels);
+
+ // So erzeugt man ein implizit typisiertes Objekt, basierend auf
+ // den Parametern der Elemente:
+ var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles });
+ // Auch wenn wir es hier nicht demonstrieren können:
+ // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead,
+ // da der Compiler in der Lage ist, die passenden Typen zu erkennen.
+ foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome))
+ {
+ Console.WriteLine(bikeSummary.Name);
+ }
+
+ // AsParallel-Methode
+ // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert
+ // LINQ und parallele Operationen:
+ var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name);
+ // Diese Berechnung passiert parallel! Benötigte Threads werden
+ // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt.
+ // Ein Traum für die Verarbeitung von großen Datenmengen
+ // auf mehreren Cores!
+
+ // LINQ - bildet einen Datenspeicher auf IQueryable<T> Objekte ab
+ // LinqToSql beispielsweise speichert und liest aus einer
+ // SQL-Datenbank, LinqToXml aus einem XML-Dokument.
+ // LINQ-Operationen werden "lazy" ausgeführt.
+ var db = new BikeRepository();
+
+ // Die verzögerte Ausführung ist optimal für Datenbankabfragen
+ var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage
+ // Es können noch mehr Filter hinzugefügt werden (auch mit
+ // Bedingungen) - ideal für z.B. "erweiterte Suchen"
+ if (42 > 6)
+ {
+ filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage
+ }
+
+ var query = filter
+ .OrderBy(b => b.Wheels)
+ .ThenBy(b => b.Name)
+ .Select(b => b.Name); // auch hier: immer noch keine Abfrage
+
+ // Erst hier wird die Datenbankabfrage wirklich ausgeführt,
+ // limitiert auf die Elemente die der foreach-Loop verwendet
+ foreach (string bike in query)
+ {
+ Console.WriteLine(result);
+ }
+
+ }
+
+ } // Ende der Klasse LearnCSharp
+
+ // Eine .cs-Datei kann auch mehrere Klassen enthalten
+
+ public static class Extensions
+ {
+ // Erweiterungsmethoden
+ public static void Print(this object obj)
+ {
+ Console.WriteLine(obj.ToString());
+ }
+ }
+
+ // Syntax zur Deklaration einer Klasse:
+ // <public/private/protected/internal> class <class name>{
+ // // Datenfelder, Konstruktoren und Methoden leben alle
+ // // innerhalb dieser Deklaration
+ // }
+
+ public class Bicycle
+ {
+ // Felder/Variablen der Klasse "Bicycle"
+ // Das Keyword public macht das Member von überall zugänglich
+ public int Cadence
+ {
+ get // get definiert eine Methode um die Eigenschaft abzurufen
+ {
+ return _cadence;
+ }
+ set // set definiert eine Methode um die Eigenschaft zu setzen
+ {
+ _cadence = value; // value ist der dem Setter übergebene Wert
+ }
+ }
+ private int _cadence;
+
+ // Das Keyword protected macht das Member nur für die Klasse selbst
+ // und ihre Subklassen zugänglich
+ protected virtual int Gear
+ {
+ get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird
+ set;
+ }
+
+ // Das Keyword internal macht das Member innerhalb der Assembly zugänglich
+ internal int Wheels
+ {
+ get;
+ private set; // get/set kann auch über Keywords modifiziert werden
+ }
+
+ int _speed; // Member ohne vorangestellte Keywords sind standardmäßig
+ // private, sie sind nur innerhalb der Klasse zugänglich.
+ // Man kann aber natürlich auch das Keyword private benutzen.
+ private string Name { get; set; }
+
+ // Ein Enum ist ein klar definierter Satz an benannten Konstanten.
+ // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu
+ // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für
+ // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint,
+ // long, oder ulong. Alle Werte in einem Enum sind eindeutig.
+ public enum BikeBrand
+ {
+ Colnago,
+ EddyMerckx,
+ Bianchi = 42, // so kann man den Wert explizit setzen
+ Kynast // 43
+ }
+ // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist,
+ // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren
+
+ // Nachdem das Enum deklariert ist, können wir den Typen verwenden:
+ public BikeBrand Brand;
+
+ // Als static gekennzeichnete Member gehören dem Typ selbst,
+ // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem
+ // Objekt benutzen
+ // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!");
+ static public int BicyclesCreated = 0;
+
+ // readonly-Werte werden zur Laufzeit gesetzt
+ // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor
+ // festgelegt werden
+ readonly bool _hasCardsInSpokes = false; // readonly und private
+
+ // Konstruktoren bestimmen was bei einer Instantiierung passiert.
+ // Das ist ein Default-Konstruktor:
+ public Bicycle()
+ {
+ // Member der Klasse können über das Keyword this erreicht werden
+ this.Gear = 1;
+ // oft ist das aber gar nicht nötig
+ Cadence = 50;
+ _speed = 5;
+ Name = "Bonanzarad";
+ Brand = BikeBrand.Kynast;
+ BicyclesCreated++;
+ }
+
+ // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente):
+ public Bicycle(int startCadence, int startSpeed, int startGear,
+ string name, bool hasCardsInSpokes, BikeBrand brand)
+ : base() // ruft zuerst den "base"-Konstruktor auf
+ {
+ Gear = startGear;
+ Cadence = startCadence;
+ _speed = startSpeed;
+ Name = name;
+ _hasCardsInSpokes = hasCardsInSpokes;
+ Brand = brand;
+ }
+
+ // Konstruktoren können aneinandergehängt werden:
+ public Bicycle(int startCadence, int startSpeed, BikeBrand brand) :
+ this(startCadence, startSpeed, 0, "richtig große Räder", true, brand)
+ {
+ }
+
+ // Syntax für Methoden:
+ // <public/private/protected> <return type> <function name>(<args>)
+
+ // Klassen können Getter und Setter für Werte definieren,
+ // oder diese Werte direkt als Eigenschaft implementieren
+ // (in C# der bevorzugte Weg)
+
+ // Parameter von Methoden können Default-Werte haben.
+ // "SpeedUp" kann man also auch ohne Parameter aufrufen:
+ public void SpeedUp(int increment = 1)
+ {
+ _speed += increment;
+ }
+
+ public void SlowDown(int decrement = 1)
+ {
+ _speed -= decrement;
+ }
+
+ // Eigenschaften mit get/set
+ // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu
+ // empfehlen. Diese können Getter und Setter haben, oder auch nur
+ // einen Getter bzw. einen Setter
+ private bool _hasTassles; // private Variable
+ public bool HasTassles // öffentliches Interface
+ {
+ get { return _hasTassles; }
+ set { _hasTassles = value; }
+ }
+
+ // Das kann man auch kürzer schreiben:
+ // Dieser Syntax erzeugt automatisch einen hinterlegten Wert,
+ // (entsprechend `private bool _isBroken`) der gesetzt
+ // bzw. zurückgegeben wird:
+ public bool IsBroken { get; private set; }
+ public int FrameSize
+ {
+ get;
+ // für Getter und Setter kann der Zugriff auch einzeln
+ // beschränkt werden, FrameSize kann also nur von innerhalb
+ // der Klasse "Bicycle" gesetzt werden
+ private set;
+ }
+
+ // Diese Methode gibt eine Reihe an Informationen über das Objekt aus:
+ public virtual string ToString()
+ {
+ return "Gang: " + Gear +
+ " Kadenz: " + Cadence +
+ " Geschwindigkeit: " + _speed +
+ " Name: " + Name +
+ " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") +
+ "\n------------------------------\n"
+ ;
+ }
+
+ // Auch Methoden können als static gekennzeichnet werden, nützlich
+ // beispielsweise für Helper-Methoden
+ public static bool DidWeCreateEnoughBicyclesYet()
+ {
+ // In einer statischen Methode können wir natürlich auch nur
+ // statische Member der Klasse referenzieren
+ return BicyclesCreated > 9000;
+ }
+ // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee
+ // sein die Klasse selbst als static zu kennzeichnen
+
+ } // Ende der Klasse "Bicycle"
+
+ // "PennyFarthing" ist eine Unterklasse von "Bicycle"
+ class PennyFarthing : Bicycle
+ {
+ // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder
+ // mit riesigem Vorderrad. Sie haben keine Gangschaltung.)
+
+ // hier wird einfach der Elternkonstruktor aufgerufen
+ public PennyFarthing(int startCadence, int startSpeed) :
+ base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx)
+ {
+ }
+
+ protected override int Gear
+ {
+ get
+ {
+ return 0;
+ }
+ set
+ {
+ throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!");
+ }
+ }
+
+ public override string ToString()
+ {
+ string result = "Hochrad ";
+ result += base.ToString(); // ruft die "base"-Version der Methode auf
+ return result;
+ }
+ }
+
+ // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen
+ // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung:
+ interface IJumpable
+ {
+ // Alle Member eines Interfaces sind implizit public
+ void Jump(int meters);
+ }
+
+ interface IBreakable
+ {
+ // Interfaces können Eigenschaften, Methoden und Events definieren
+ bool Broken { get; }
+ }
+
+ // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige
+ // Anzahl von Interfaces implementieren
+ class MountainBike : Bicycle, IJumpable, IBreakable
+ {
+ int damage = 0;
+
+ public void Jump(int meters)
+ {
+ damage += meters;
+ }
+
+ public bool Broken
+ {
+ get
+ {
+ return damage > 100;
+ }
+ }
+ }
+
+ // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her.
+ // EntityFramework Code First ist großartig
+ // (ähnlich zu Ruby's ActiveRecord, aber bidirektional)
+ // http://msdn.microsoft.com/de-de/data/jj193542.aspx
+ public class BikeRepository : DbSet
+ {
+ public BikeRepository()
+ : base()
+ {
+ }
+
+ public DbSet<Bicycle> Bikes { get; set; }
+ }
+} // Ende des Namespaces
+```
+
+## In dieser Übersicht nicht enthalten sind die Themen:
+
+ * Flags
+ * Attributes
+ * Statische Eigenschaften
+ * Exceptions, Abstraction
+ * ASP.NET (Web Forms/MVC/WebMatrix)
+ * Winforms
+ * Windows Presentation Foundation (WPF)
+
+## Zum Weiterlesen gibt es viele gute Anlaufpunkte:
+
+ * [DotNetPerls](http://www.dotnetperls.com)
+ * [C# in Depth](http://manning.com/skeet2)
+ * [Programming C#](http://shop.oreilly.com/product/0636920024064.do)
+ * [LINQ](http://shop.oreilly.com/product/9780596519254.do)
+ * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx)
+ * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials)
+ * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials)
+ * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials)
+ * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208)
+
+[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx) \ No newline at end of file
diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown
index 8909b251..23c1df94 100644
--- a/de-de/css-de.html.markdown
+++ b/de-de/css-de.html.markdown
@@ -8,107 +8,106 @@ lang: de-de
filename: learncss-de.css
---
-In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwickliung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard.
-CSS ist die allgemeine Sprache, die dazu da ist, damit man den HTML-Code und die Designelemente von Webseiten (strikt) unterscheiden kann.
+In den frühen Tagen des Internets gab es keine visuellen Elemente, alles war nur reiner Text. Aber mit der Weiterentwicklung von Browsern wurden auch vollständig visuelle Webseiten zu einem Standard.
+Durch Verwendung von CSS lässt sich eine strikte Trennung zwischen HTML-Code und Designelementen erreichen.
-Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente anzuvisieren und ihnen stilistische Eigenschaften zu geben.
+Kurzgefasst, CSS ermöglicht es, verschiedene HTML-Elemente innerhalb eines Dokuments auszuwählen und ihnen visuelle Eigenschaften zu geben.
CSS hat wie jede andere Sprache viele Versionen. Hier fokussieren wir uns auf CSS2.0, welche nicht die neueste, aber die am weitesten verbreitete und unterstützte Version ist.
-**NOTE:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich eine CSS-Sandbox wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen.
+**HINWEIS:** Weil die Ausgabe von CSS visuelle Eigenschaften sind, wirst du wahrscheinlich eine CSS-Sandbox wie [dabblet](http://dabblet.com/) benutzen müssen, um die Sprache richtig zu lernen.
In diesem Artikel wird am meisten auf generelle Hinweise und die Syntax geachtet.
```css
-/* kommentare werden in sternchen-schrägstrichkombinationen gepackt (genauso wie hier!) */
+/* Kommentare werden in Sternchen-Schrägstrichkombinationen gepackt (genauso wie hier!) */
/* ####################
## SELEKTOREN
####################*/
-/* Eigentlich ist die häufigste Anwendungsweise von CSS sehr simpel */
+/* Eigentlich ist das grundlegende CSS-Statement sehr simpel */
selektor { eigenschaft: wert; /* mehr eigenschaften...*/ }
-/* der selektor wird dazu benutzt, ein element auf der seite anzuvisieren
+/* Der Selektor wird dazu benutzt, ein Element auf der Seite auszuwählen.
-Aber man kann auch alle Elemente auf einer Seite anvisieren! */
+Man kann aber auch alle Elemente auf einer Seite auswählen! */
* { color:red; } /* farbe:rot */
/*
-Wenn wir so ein Element auf einer Seite haben:
+Angenommen wir haben folgendes Element auf einer Seite:
<div class='eine-klasse klasse2' id='eineId' attr='wert' />
*/
-/* kann man es so bei seiner klasse anvisieren */
+/* kann man es so über seine Klasse auswählen */
.eine-klasse { }
-/*oder bei beiden klassen! */
+/* oder über beide Klassen! */
.eine-klasse.klasse2 { }
-/* oder beim namen des tags */
+/* oder über den Namen des Tags */
div { }
-/* oder bei seiner id */
+/* oder über seine Id */
#eineId { }
-/* oder daran, dass es ein Attribut hat! */
+/* oder darüber, dass es ein Attribut hat! */
[attr] { font-size:smaller; }
-/* oder daran, dass das attribut einen bestimmten wert hat*/
+/* oder auch darüber, dass das Attribut einen bestimmten Wert hat */
[attr='wert'] { font-size:smaller; }
-/* beginnt mit einem wert*/
-[attr^='wert'] { font-size:smaller; }
+/* beginnt mit dem übergebenen Wert */
+[attr^='we'] { font-size:smaller; }
-/* oder endet mit */
+/* endet damit */
[attr$='rt'] { font-size:smaller; }
-/* oder sogar nur beinhaltet */
+/* oder beinhaltet einen Teil davon */
[attr~='er'] { font-size:smaller; }
-/* was aber noch wichtiger ist, ist dass man alle diese kombinieren
-kann - man sollte nur mit der leerzeichensetzung vorsichtig sein,
-da es mit einem leerzeichen zwei verschiedene selektoren wären*/
+/* Noch wichtiger ist aber die Möglichkeit, all das miteinander kombinieren
+zu können - man sollte hierbei nur mit der Leerzeichensetzung vorsichtig sein,
+ein Leerzeichen macht es zu zwei verschiedenen Selektoren */
+
div.eine-klasse[attr$='rt'] { } /* so ist es richtig */
-/* man kann auch ein element daran festmachen, wie sich die übergeordneten
-elemente verhalten!*/
+/* Man kann auch ein Element über seine Elternelemente auswählen */
-/*es muss allerdings ein direktes kind sein */
+/* > wählt ein direktes Kind aus */
div.ein-elternteil > .klassen-name {}
-/* oder jeder seiner eltern in der struktur */
-/* das folgende heißt also, dass jedes element mit der klasse 'klassen-name'
-und dem elternteil IN JEDER TIEFE ausgewählt wird */
+/* Mit einem Leerzeichen getrennt kann man alle Elternelemente ansprechen */
+/* Das folgende heißt also, dass jedes Element mit der Klasse 'klassen-name'
+und dem Elternteil IN JEDER TIEFE ausgewählt wird */
div.ein-elternteil .klassen-name {}
-/* achtung: dasselbe ohne das leerzeichen hat eine andere bedeutung,
+/* Achtung: das selbe ohne das Leerzeichen hat eine andere Bedeutung,
kannst du mir sagen, was? */
div.ein-elternteil.klassen-name {}
-/* man kann auch ein element nach seinem direkten vorherigen zwilling
+/* Man kann ein Element auch nach seinem direkten Nachbarelement
auswählen */
.ich-bin-vorher + .dieses-element { }
-/* oder jeden zwilling davor */
+/* Oder über jedes Geschwisterelement davor */
.ich-kann-jeder-davor-sein ~ .dieses-element {}
-/* es gibt ein paar pseudoklassen, die sich basierend auf dem
-seitenverhalten, nämlich nicht auf der seitenstruktur auswählen
-lassen können */
+/* Mit Pseudoklassen lassen sich Elemente anhand ihres momentanen Zustands
+auf der Seite auswählen (anstatt über die Seitenstruktur) */
-/* zum beispiel, wenn über ein element mit dem mauszeiger gefahren wird */
+/* Zum Beispiel, wenn über ein Element mit dem Mauszeiger gefahren wird */
:hover {}
-/* oder einen bereits besuchten link*/
+/* Oder einen bereits besuchten Link*/
:visited {}
-/* oder einen noch nicht besuchten link*/
+/* Oder einen noch nicht besuchten Link*/
:link {}
-/* oder ein eingabeelement, das zurzeit im fokus steht */
+/* Oder ein Eingabeelement, das zurzeit im Fokus steht */
:focus {}
@@ -117,64 +116,64 @@ lassen können */
####################*/
selector {
-
- /* einheiten */
- width: 50%; /* in prozent */
- font-size: 2em; /* mal der derzeitigen schriftgröße */
- width: 200px; /* in pixeln */
- font-size: 20pt; /* in punkten */
- width: 5cm; /* in zentimetern */
- width: 50mm; /* in millimetern */
- width: 5in; /* in zoll */
-
- /* farben */
- background-color: #F6E /* in kurzem hex */
- background-color: #F262E2 /* in langem hex */
- background-color: tomato /* kann auch eine genannte farbe sein */
- background-color: rgb(255, 255, 255) /* in rgb */
- background-color: rgb(10%, 20%, 50%) /* in rgb prozent */
- background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem rgb */
-
- /* bilder */
+
+ /* Einheiten */
+ width: 50%; /* in Prozent */
+ font-size: 2em; /* mal der derzeitigen Schriftgröße */
+ width: 200px; /* in Pixeln */
+ font-size: 20pt; /* in Punkten */
+ width: 5cm; /* in Zentimetern */
+ width: 50mm; /* in Millimetern */
+ width: 5in; /* in Zoll */
+
+ /* Farben */
+ background-color: #F6E /* in kurzem Hex */
+ background-color: #F262E2 /* in langem Hex */
+ background-color: tomato /* kann auch eine benannte Farbe sein */
+ background-color: rgb(255, 255, 255) /* in RGB */
+ background-color: rgb(10%, 20%, 50%) /* in RGB Prozent */
+ background-color: rgba(255, 0, 0, 0.3); /* in semi-transparentem RGB */
+
+ /* Bilder */
background-image: url(/pfad-zum-bild/image.jpg);
-
- /* schriften */
+
+ /* Schriften */
font-family: Arial;
- font-family: "Courier New"; /* wenn der name ein leerzeichen beinhält, kommt er in
- apostrophe */
- font-family: "Courier New", Trebuchet, Arial; /* wenn der erste nicht gefunden wird, wird
- der zweite benutzt, und so weiter */
+ font-family: "Courier New"; /* wenn der Name ein Leerzeichen beinhält, kommt er in
+ Anführungszeichen */
+ font-family: "Courier New", Trebuchet, Arial; /* wird die erste Schriftart
+ nicht gefunden, wird die zweite benutzt, usw. */
}
```
## Benutzung
-speichere das css, das du benutzen willst mit der endung '.css'.
+Speichere das CSS, das du benutzen willst mit der endung '.css'.
```xml
-<!-- du musst die css-datei im <head>-bereich der seite erwähnen -->
+<!-- du musst die CSS-Datei im <head>-bereich der seite einbinden -->
<link rel='stylesheet' type='text/css' href='filepath/filename.css' />
-<!-- es geht allerdings auch direkt, wobei diese methode nicht
+<!-- Einbindung funktioniert auch inline, wobei diese Methode nicht
empfohlen ist -->
<style>
selector { property:value; }
</style>
-<!-- oder direkt am element (sollte aber gelassen werden) -->
+<!-- Oder direkt auf einem Element (sollte aber vermieden werden) -->
<div style='property:value;'>
</div>
```
-## Wichtigkeit
+## Spezifität
-ein element kann von mehr als einem selektoren angezielt werden.
-und kann auch eine eigenschaft mehr als einmal zugewiesen bekommen.
-in diesen fällen gibt es regeln, die die wichtigkeit von selektoren einführen.
+Ein Element kann natürlich auch von mehr als einer Regel in einem Stylesheet
+angesprochen werdenm und kann eine Eigenschaft auch öfters als einmal zugewiesen
+bekommen. In diesen Fällen gibt es Regeln, die die Spezifität von Selektoren regeln.
-wie haben dieses CSS:
+Wir haben dieses CSS:
```css
/*A*/
@@ -194,34 +193,34 @@ p { property: wert !important; }
```
-und das folgende markup:
+und das folgende Markup:
```xml
<p style='/*F*/ property:value;' class='class1 class2' attr='value'>
</p>
```
-die wichtigkeit der stile ist wie folgt:
-(die wichtigkeit gilt nur für **eigenschaften**, nicht für ganze blöcke)
-
-* `E` hat die größte wichtigkeit wegen dem schlüsselwort `!important`.
- man sollte diese form aber vermeiden.
-* `F` ist als nächstes, da es direkt an dem element definiert ist.
-* `A` ist als nächstes, da es "spezifischer" als alle anderen ist.
- spezifischer = mehr zuweisungen: 1 tagname `p` +
- klassenname `klasse1` + 1 attribut `attr='value'`
-* `C` ist als nächstes obwohl es genau so ist wie `B`
- aber es erscheint als letztes.
-* dann ist `B`
+Die Spezifität der Stile ist wie folgt:
+(die Spezifität gilt nur für **einzelne Eigenschaften**, nicht für ganze Blöcke)
+
+* `E` hat die größte Spezifität wegen dem Schlüsselwort `!important`.
+ man sollte diese Form aber vermeiden.
+* `F` ist als nächstes dran, da es direkt an dem element definiert ist.
+* Dann folgt `A`, da es "spezifischer" als alle anderen ist.
+ spezifischer = mehr Zuweisungen: 1 Tagname `p` +
+ Klassenname `klasse1` + 1 Attribut `attr='value'`
+* `C` kommt als nächstes, obwohl es genau so ist wie `B`,
+ es erscheint aber später im Stylesheet.
+* dann kommt `B`
* und als letztes `D`.
-## Kompabilität
+## Kompatibilität
-die meisten features von CSS sind in allen browsern verfügbar.
-man sollte jedoch immer darauf achten, wenn man etwas mit CSS
-programmiert.
+Die meisten Features von CSS sind in allen Browsern verfügbar. Man sollte
+jedoch immer darauf achten die benutzten Features auf Verfügbarkeit in den
+vom Projekt unterstützten Browser zu überprüfen.
-[QuirksMode CSS](http://www.quirksmode.org/css/) ist eine der besten quellen dafür.
+[QuirksMode CSS](http://www.quirksmode.org/css/) oder [Can I Use](http://caniuse.com/) sind zwei der besten Quellen dafür.
## Weiterlesen
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/haskell-de.html.markdown b/de-de/haskell-de.html.markdown
index df6267f9..2c548961 100644
--- a/de-de/haskell-de.html.markdown
+++ b/de-de/haskell-de.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
lang: de-de
contributors:
- ["Adit Bhargava", "http://adit.io"]
diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown
index 0418b2b6..a295c1c2 100644
--- a/de-de/javascript-de.html.markdown
+++ b/de-de/javascript-de.html.markdown
@@ -9,11 +9,11 @@ lang: de-de
---
(Anmerkungen des Original-Autors:)
-JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzent zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java.
+JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java.
-Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, dass eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer.
+Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer.
-Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.id.au).
+Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@adambrenecki](https://twitter.com/adambrenecki) oder [adam@brenecki.id.au](mailto:adam@brenecki.id.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de).
```js
// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei
@@ -38,9 +38,9 @@ machWas()
3; // = 3
1.5; // = 1.5
-// Alle grundlegenden arithmetischen Operationen arbeiten wie erwartet.
+// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet.
1 + 1; // = 2
-8 - 1; // = 7
+0.1 + 0.2; // = 0.30000000000000004
10 * 2; // = 20
35 / 5; // = 7
@@ -72,13 +72,13 @@ false;
!true; // = false
!false; // = true
-// Gleichheit wird mit == geprüft.
-1 == 1; // = true
-2 == 1; // = false
+// Gleichheit wird mit === geprüft.
+1 === 1; // = true
+2 === 1; // = false
-// Ungleichheit wird mit != überprüft.
-1 != 1; // = false
-2 != 1; // = true
+// Ungleichheit wird mit !== überprüft.
+1 !== 1; // = false
+2 !== 1; // = true
// Andere Vergleichsoperatoren sind
1 < 10; // = true
@@ -92,16 +92,22 @@ false;
// und mit < und > verglichen werden.
"a" < "b"; // = true
-// Für den Vergleich von Werten wird eine Typumwandlung erzwungen...
+// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen...
"5" == 5; // = true
// ...solange man nicht === verwendet.
"5" === 5; // = false
// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode
-// charAt zugegriffen werden
+// 'charAt' zugegriffen werden
"This is a string".charAt(0); // = "T"
+// Die Methode 'substring' gibt Teilbereiche eines Strings zurück
+"Hello world".substring(0, 5); // = "Hello"
+
+// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt
+"Hello".length; // = 5
+
// Es gibt außerdem die Werte 'null' und 'undefined'
null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen
undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht
@@ -147,6 +153,13 @@ var myArray = ["Hello", 45, true];
// beginnt bei 0.
myArray[1]; // = 45
+// Arrays haben keine feste Länge
+myArray.push("World");
+myArray.length; // = 4
+
+// und sind veränderlich
+myArray[3] = "Hello";
+
// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen
// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare.
var myObj = { key1: "Hello", key2: "World" };
@@ -218,15 +231,47 @@ if (colour == "red" || colour == "blue"){
// nützlich, um einen Default-Wert zu setzen.
var name = otherName || "default";
+// Ein 'switch' Statement prüft Gleichheit mit ===
+// ohne ein 'break' nach jedem Fall
+// werden auch die Fälle nach dem korrekten aufgerufen
+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. Funktionen, Geltungsbereich und Closures
-// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert.
+// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert.
function myFunction(thing){
return thing.toUpperCase();
}
myFunction("foo"); // = "FOO"
+// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss
+// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht
+// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion
+// gibt 'undefined' zurück
+function myFunction()
+{
+ return // <- Hier wird automatisch ein Semikolon eingefügt
+ {
+ thisIsAn: 'object literal'
+ }
+}
+myFunction(); // = undefined
+
// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie
// Variablen verwendet und als Parameter anderen Funktionen übergeben werden
// - zum Beispiel, um einen 'event handler' zu 'beliefern'.
@@ -236,9 +281,9 @@ function myFunction() {
setTimeout(myFunction, 5000);
// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen.
-// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument
+// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument
// einer anderen Funktion zu definieren.
-setTimeout(function() {
+setTimeout(function(){
// wird ausgeführt, nachdem 5 Sekunden vergangen sind
}, 5000);
@@ -275,7 +320,7 @@ function sayHelloInFiveSeconds(name){
}
setTimeout(inner, 5000);
// setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds
- // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein'
+ // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein'
// aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere
// Funktion bildet, hat die innere Funktion immer noch Zugriff auf die
// Variable prompt.
@@ -320,6 +365,37 @@ var myOtherFunc = function(){
myObj.myOtherFunc = myOtherFunc;
myObj.myOtherFunc(); // = "HELLO WORLD!"
+// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs
+// verändert werden
+
+var anotherFunc = function(s){
+ return this.myString + s;
+}
+anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!"
+
+// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente
+// aber in einem Array
+
+anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!"
+
+// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente
+// übergeben kann
+
+Math.min(42, 6, 27); // = 6
+Math.min([42, 6, 27]); // = NaN (uh-oh!)
+Math.min.apply(Math, [42, 6, 27]); // = 6
+
+// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf.
+// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt.
+
+var boundFunc = anotherFunc.bind(myObj);
+boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!"
+
+// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen".
+var product = function(a, b){ return a * b; }
+var doubler = product.bind(this, 2);
+doubler(8); // = 16
+
// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird
// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser
// Art aufgerufen zu werden, werden Konstruktoren genannt.
@@ -382,23 +458,23 @@ myObj.meaningOfLife; // = 43
// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt
// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es
// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird.
-myConstructor.prototype = {
+MyConstructor.prototype = {
getMyNumber: function(){
return this.myNumber
}
};
-var myNewObj2 = new myConstructor();
+var myNewObj2 = new MyConstructor();
myNewObj2.getMyNumber(); // = 5
-// Die eingebauten Typen, also strings und numbers, haben auch Konstruktoren,
+// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren,
// die zu dem Typ äquivalente Wrapper-Objekte erzeugen.
var myNumber = 12;
var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true
// Genau genommen: Sie sind nicht exakt äquivalent.
-typeof(myNumber); // = 'number'
-typeof(myNumberObj); // = 'object'
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
// Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist.
@@ -447,4 +523,6 @@ Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den E
[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache.
+[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen.
+
Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden.
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/elixir.html.markdown b/elixir.html.markdown
index 946c0a1b..0a20e3df 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -2,6 +2,7 @@
language: elixir
contributors:
- ["Joao Marques", "http://github.com/mrshankly"]
+ - ["Dzianis Dashkevich", "https://github.com/dskecse"]
filename: learnelixir.ex
---
@@ -59,7 +60,7 @@ tail #=> [2,3]
# the tuples have different sizes.
# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
-# There's also binaries
+# There are also binaries
<<1,2,3>> # binary
# Strings and char lists
@@ -108,7 +109,7 @@ div(10, 2) #=> 5
# To get the division remainder use `rem`
rem(10, 3) #=> 1
-# There's also boolean operators: `or`, `and` and `not`.
+# There are also boolean operators: `or`, `and` and `not`.
# These operators expect a boolean as their first argument.
true and true #=> true
false or true #=> true
@@ -119,7 +120,6 @@ false or true #=> true
1 || true #=> 1
false && 1 #=> false
nil && 20 #=> nil
-
!true #=> false
# For comparisons we have: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` and `>`
@@ -165,12 +165,12 @@ case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
- "This will match and assign `x` to `:two`"
+ "This will match and bind `x` to `:two`"
_ ->
"This will match any value"
end
-# It's common practice to assign a value to `_` if we don't need it.
+# It's common to bind the value to `_` if we don't need it.
# For example, if only the head of a list matters to us:
[head | _] = [1,2,3]
head #=> 1
@@ -190,7 +190,7 @@ cond do
"But I will"
end
-# It is common to see a last condition equal to `true`, which will always match.
+# It is common to see the last condition equal to `true`, which will always match.
cond do
1 + 1 == 3 ->
"I will never be seen"
@@ -301,7 +301,7 @@ end
Recursion.sum_list([1,2,3], 0) #=> 6
# Elixir modules support attributes, there are built-in attributes and you
-# may also add custom attributes.
+# may also add custom ones.
defmodule MyMod do
@moduledoc """
This is a built-in attribute on a example module.
@@ -312,21 +312,24 @@ defmodule MyMod do
end
## ---------------------------
-## -- Records and Exceptions
+## -- Structs and Exceptions
## ---------------------------
-# Records are basically structures that allow you to associate a name with
-# a particular value.
-defrecord Person, name: nil, age: 0, height: 0
+# Structs are extensions on top of maps that bring default values,
+# compile-time guarantees and polymorphism into Elixir.
+defmodule Person do
+ defstruct name: nil, age: 0, height: 0
+end
-joe_info = Person.new(name: "Joe", age: 30, height: 180)
-#=> Person[name: "Joe", age: 30, height: 180]
+joe_info = %Person{ name: "Joe", age: 30, height: 180 }
+#=> %Person{age: 30, height: 180, name: "Joe"}
# Access the value of name
joe_info.name #=> "Joe"
# Update the value of age
-joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180]
+older_joe_info = %{ joe_info | age: 31 }
+#=> %Person{age: 31, height: 180, name: "Joe"}
# The `try` block with the `rescue` keyword is used to handle exceptions
try do
@@ -360,7 +363,7 @@ spawn(f) #=> #PID<0.40.0>
# `spawn` returns a pid (process identifier), you can use this pid to send
# messages to the process. To do message passing we use the `send` operator.
# For all of this to be useful we need to be able to receive messages. This is
-# achived with the `receive` mechanism:
+# achieved with the `receive` mechanism:
defmodule Geometry do
def area_loop do
receive do
@@ -394,5 +397,7 @@ self() #=> #PID<0.27.0>
* [Getting started guide](http://elixir-lang.org/getting_started/1.html) from [elixir webpage](http://elixir-lang.org)
* [Elixir Documentation](http://elixir-lang.org/docs/master/)
+* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) by Dave Thomas
+* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) by Fred Hebert
-* "Programming Erlang: Software for a Concurrent World" by Joe Armstrong
+* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) by Joe Armstrong
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/bash-es.html.markdown b/es-es/bash-es.html.markdown
new file mode 100644
index 00000000..fb89b2a0
--- /dev/null
+++ b/es-es/bash-es.html.markdown
@@ -0,0 +1,196 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+ - ["Anton Strömkvist", "http://lutic.org/"]
+translators:
+ - ["Daniel Zendejas", "https://github.com/danielzendejas"]
+filename: LearnBash-es.sh
+lang: es-es
+---
+
+Tutorial de Shell en español.
+
+Bash es el nombre del shell de unix, el cual también es distribuido como
+el shell del sistema operativo GNU. También es el shell
+por defecto de Linux y Mac OS X. Casi todos los ejemplos abajo pueden
+ser parte de un script shell o ser ejecutados directamente en la terminal.
+
+[Leer más aquí.](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+
+# La primera línea del script es el [shebang](http://en.wikipedia.org/wiki/Shebang_(Unix)) que le indica al sistema
+# cómo ejecutar el script.
+# Como te habrás dado cuenta, los comentarios en shell empiezan con #.
+# El shebang también es un comentario.
+
+# Ejemplo sencillo de hola mundo:
+echo ¡Hola mundo!
+
+# Cada comando empieza con una nueva línea, o después de un punto y coma:
+echo 'Esta es la primera línea'; echo 'Esta es la segunda línea'
+
+# Para declarar una variable se hace lo siguiente:
+VARIABLE="Mi string"
+
+# Pero no así:
+VARIABLE = "Mi string"
+
+# Bash decidirá que VARIABLE es un comando a ejecutar, dando un error.
+
+# Usando la variable:
+echo $VARIABLE
+echo "$VARIABLE"
+echo '$VARIABLE'
+
+# Cuando la variable es usada - o asignada, exportada, etcétera - se
+# escribe su nombre sin $. Si se quiere saber el valor de la variables,
+# entonces sí se usa $. Note que ' (comilla simple) no expandirá las
+# variables.
+
+# Sustitución de strings en variables.
+echo ${VARIABLE/Mi/Una}
+# Esto sustituirá la primera cadena "Mi" con "Una".
+
+# Substring de una variable.
+echo ${VARIABLE:0:7}
+# Esto va a regresar sólo los primeros 7 caracteres del valor.
+
+# Valor por defecto de una variable
+echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"}
+# Esto trabaja para null (VARIABLE=), string vacío (VARIABLE=""), }
+# cero (VARIABLE=0) regresa 0
+
+# Variables del sistema:
+# Aquí hay algunas variables incluídas en el sistema:
+echo "El valor de regreso del último programa: $?"
+echo "PID del sistema: $$"
+echo "Número de argumentos: $#"
+echo "Argumentos del script: $@"
+echo "Argumentos del script separados en variables: $1 $2..."
+
+# Para leer un valor del input:
+echo "¿Cuál es tu nombre?"
+read NOMBRE # Note que no necesitamos declarar una variable
+echo ¡Hola, $NOMBRE!
+
+# Tenemos la estructura 'if' usual:
+# use 'man test' para más información sobre condicionales
+if [ $NOMBRE -ne $USER ]
+then
+ echo "Tu nombre es tu usuario."
+else
+ echo "Tu nombre no es tu usuario."
+fi
+
+# También hay ejecuciones condicionadas.
+echo "Siempre ejecutado" || echo "Sólo ejecutado si el primer comando falla"
+echo "Siempre ejecutado" && echo "Sólo ejecutado si el primer comando NO falla"
+
+# Para usar && y || con condicionales, se necesitan
+# múltiples pares de corchetes:
+if [ $NOMBRE == "Steve" ] && [ $EDAD -eq 15 ]
+then
+ echo "Esto correrá si $NOMBRE es Steve Y $EDAD es 15."
+fi
+
+if [ $NOMBRE == "Daniya" ] || [ $NOMBRE == "Zach" ]
+then
+ echo "Esto correrá si $NOMBRE es Daniya O Zach."
+fi
+
+# Las expresiones se denotan con el siguiente formato:
+echo $(( 10 + 5 ))
+
+# A diferencia de otros lenguajes de programación, bash es shell , así que
+# funciona en un contexto de directorio actual. Puedes listar archivos y
+# directorios en un directorio actual con el comando 'ls':
+ls
+
+# Estos comandos tienen opciones que controlan su ejecución:
+ls -l # Lista todos los archivos y directorios en líneas distintas.
+
+# Los resultados del comando anterior pueden ser pasados al siguiente
+# como input. El comando 'grep' filtra el input con los comandos provistos.
+# Así es como podemos listar archivos .txt en el directorio actual:
+ls -l | grep "\.txt"
+
+# Puedes también redireccionar el input y el error lanzado de algún comando.
+python2 hello.py < "input.in"
+python2 hello.py > "output.out"
+python2 hello.py 2> "error.err"
+
+# El error lanzado eliminará el contenido del archivo si es que existe,
+# para después escribir el error. Para que se concatene (en lugar de eliminar)
+# use el comando ">>".
+
+# Los comandos pueden ser sustituidos dentro de otros comandos usando $():
+# El siguiente ejemplo despliega el número de archivos y directorios en el
+# directorio actual.
+echo "Hay $(ls | wc -l) elementos aquí."
+
+# Lo mismo puede ser hecho usando comillas invertidas `` pero no pueden ser
+# anidadas. El método preferido es $().
+echo "Hay `ls | wc -l` elementos aquí."
+
+# Bash usa una estructura de casos similar al switch de Java o C++:
+case "$VARIABLE" in
+ # Lista de patrones que las condiciones deben cumplir:
+ 0) echo "Hay un cero.";;
+ 1) echo "Hay un uno.";;
+ *) echo "No es null.";;
+esac
+
+# Para los ciclos, se usa la estructura 'for'. Cicla para cada argumento dado:
+# El contenido de $VARIABLE se imprime tres veces.
+for VARIABLE in {1..3}
+do
+ echo "$VARIABLE"
+done
+
+# ciclos while:
+while [true]
+do
+ echo "cuerpo del ciclo..."
+ break
+done
+
+# También se pueden definir sub-rutinas (funciones)
+# Definición:
+function miFuncion ()
+{
+ echo "Los argumentos trabajan igual que argumentos de script: $@"
+ echo "Y: $1 $2..."
+ echo "Esto es una función"
+ return 0
+}
+
+# O simplemente:
+miOtraFuncion ()
+{
+ echo "¡Otra forma de declarar funciones!"
+ return 0
+}
+
+# Para llamar a tu función
+foo "Mi nombre es:" $NOMBRE
+
+# Hay muchos comandos útiles que puedes aprender:
+# imprime las últimas 10 líneas del archivo file.txt
+tail -n 10 file.txt
+# imprime las primeras 10 líneas del archivo file.txt
+head -n 10 file.txt
+# ordena las líneas del archivo file.txt
+sort file.txt
+# identifica u omite las líneas repetidas, con -d las reporta
+uniq -d file.txt
+# imprime sólo la primera columna antes de cada ',' en el archivo|
+cut -d ',' -f 1 file.txt
+```
diff --git a/es-es/brainfuck-es.html.markdown b/es-es/brainfuck-es.html.markdown
new file mode 100644
index 00000000..e33d672d
--- /dev/null
+++ b/es-es/brainfuck-es.html.markdown
@@ -0,0 +1,87 @@
+---
+language: brainfuck
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Daniel Zendejas", "https://github.com/DanielZendejas"]
+lang: es-es
+---
+
+Brainfuck (con mayúscula sólo al inicio de una oración) es un
+lenguaje de programación mínimo, computacionalmente universal
+en tamaño con sólo 8 comandos.
+
+```
+
+Cualquier caracter que no sea "><+-.,[]" (sin incluir las comillas)
+será ignorado.
+
+Brainfuck es representado por un arreglo de 30,000 celdas inicializadas
+en cero y un apuntador en la celda actual.
+
+Existen ocho comandos:
+
++ : Incrementa 1 al valor de la celda actual.
+- : Decrementa 1 al valor de la celda actual.
+> : Mueve el apuntador a la siguiente celda. (a la derecha)
+< : Mueve el apuntador a la celda anterior. (a la izquierda)
+. : Imprime el valor en ASCII de la celda actual (i.e. 65 = 'A')
+, : Lee un caracter como input y lo escribe en la celda actual.
+[ : Si el valor en la celda actual es cero mueve el apuntador
+ hasta el primer ']' que encuentre. Si no es cero sigue a la
+ siguiente instrucción.
+] : Si el valor en la celda actual es cero, entonces sigue con
+ la siguiente instrucción. Si no entonces mueve el apuntador
+ hacia atrás hasta encontrar el primer '['.
+
+[ y ] forman un while. Obviamente, deben estar balanceados.
+
+Ahora unos ejemplos de programas escritos con brainfuck.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Este programa imprime la letra 'A'. Primero, incrementa la celda #1 a
+6. La celda #1 será usada para hacer los ciclos. Después entra al ciclo
+([) y se mueve a la celda #2 (>). Después incrementa la celda #2 10 veces,
+y se regresa a la celda #1 (<), para después decrementarla en 1 (-).
+Este ciclo ocurre 6 veces (le toma 6 decrementos a la celda #1 volverse 0),
+cuando esto pasa se salta a (]) y continúa.
+
+En este punto estamos en la celda #1, que tiene un valor de 0, mientras
+que la celda #2 tiene un valor de 60. Nos movemos a la celda #2 (>),
+la incrementamos 5 veces para tener un valor de 65 y luego imprimimos
+el valor de la celda #2 (.). 65 es 'A' en ASCII así que la letra 'A'
+se imprime.
+
+, [ > + < - ] > .
+
+Este programa lee un caracter del input y lo copia en la celda #2 (,).
+Después empieza un ciclo. Nos movemos a la celda #2 (>) e incrementamos su
+valor (+). Regresamos a la celda #1 y decrementamos su valor en 1 (-).
+Esto continúa hasta que la celda #1 contenga un cero. Cuando #1 contenga un
+cero la celda #2 tendrá el valor inicial de #1. Como este ciclo siempre
+terminara en la celda #1 nos movemos a la celda #2 e imprimimos (.).
+
+Ten en mente que los espacios son sólo para fines de legibilidad.
+Es lo mismo escribir el ejemplo de arriba que esto:
+,[>+<-]>.
+
+Intenta descrifrar lo que hace este programa:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Este programa toma dos números como input y los multiplica.
+
+Primero recibe dos números del usuario. Luego empieza el ciclo externo,
+condicionado en la celda #1. Luego se mueve a la celda #2, comenzando
+el ciclo interno condicionado en la celda #2 incrementando la celda #3.
+Sin embargo viene un problema: El ciclo interior no funcionará nuevamente
+hasta la próxima vez. Para resolver este problema también incrementamos la
+celda #4 y luego copiamos la celda #4 a la celda #2. La celda #3 contiene
+el resultado.
+```
+Y eso es brainfuck. ¿No tan difícil o sí? Como diversión, puedes escribir
+tu propio intérprete de brainfuck o tu propio programa en brainfuck. El
+intérprete es relativamente sencillo de hacer, pero si eres masoquista,
+intenta construir tu proprio intérprete de brainfuck... en brainfuck.
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/javascript-es.html.markdown b/es-es/javascript-es.html.markdown
index 9b412f6e..a1348508 100644
--- a/es-es/javascript-es.html.markdown
+++ b/es-es/javascript-es.html.markdown
@@ -471,8 +471,8 @@ var miNumeroObjeto = new Number(12);
miNumero == miNumeroObjeto; // = true
// No son exactamente iguales.
-typeof(miNumero); // = 'number'
-typeof(miNumeroObjeto); // = 'object'
+typeof miNumero; // = 'number'
+typeof miNumeroObjeto; // = 'object'
miNumero === miNumeroObjeyo; // = false
if (0){
// Este código no se ejecutara porque 0 es false.
diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown
index 41a7c68b..203ee3bb 100644
--- a/es-es/julia-es.html.markdown
+++ b/es-es/julia-es.html.markdown
@@ -1,8 +1,9 @@
---
-language: julia
+language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
- - ["Guillermo Garza" ]
+translators:
+ - ["Guillermo Garza", "http://github.com/ggarza"]
filename: learnjulia-es.jl
lang: es-es
---
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/es-es/whip-es.html.markdown b/es-es/whip-es.html.markdown
new file mode 100644
index 00000000..7c2f4bd2
--- /dev/null
+++ b/es-es/whip-es.html.markdown
@@ -0,0 +1,255 @@
+---
+language: whip
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+translators:
+ - ["Daniel Zendejas", "https://github.com/DanielZendejas"]
+author: Tenor Biel
+author_url: http://github.com/L8D
+filename: whip-es.lisp
+lang: es-es
+---
+Tutorial de Whip en español.
+
+Whip es un dialecto de LISP hecho para escribir código y conceptos
+simples. Ha tomado prestado bastante de la sintaxis de Haskell
+(un lenguaje no relacionado).
+
+Esta documentación fue escrita por el creador del lenguaje
+
+```scheme
+; Los comentarios son como en LISP, con punto y coma...
+
+; La mayoría de las sentencias de primer nivel están dentro de
+; "formas". Una forma no es más que cosas dentro de paréntesis
+no_en_la_forma
+(en_la_form)
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 1. Números, Strings y Operadores
+
+;Whip tiene un tipo para números (es el estándar 64-bit IEEE 754 double, de JS)
+3 ; => 3
+1.5 ; => 1.5
+
+; Las funciones son llamadas si son el primer elemento de una forma
+(funcion_llamada argumentos)
+
+; La mayoría de los operadores se hacen con funciones
+; Toda la aritmética básica es bastante estándar
+(+ 1 1) ; => 2
+(- 2 1) ; => 1
+(* 1 2) ; => 2
+(/ 2 1) ; => 2
+; incluso el módulo
+(% 9 4) ; => 1
+; división impar al estilo de JavaScript.
+(/ 5 2) ; => 2.5
+
+; Las formas anidadas funcionan como se espera.
+(* 2 (+ 1 3)) ; => 8
+
+; Hay un tipo booleano.
+true
+false
+
+; Los Strings son creados con comillas dobles ".
+"Hola mundo"
+
+; Los caracteres solos se declaran con comillas simples '.
+'a'
+
+; La negación usa la función 'not'.
+(not true) ; => false
+(not false) ; => true
+
+; La mayoría de las funcions que no vienen de Haskell tienen
+; atajos. La función 'not' también se puede declarar con '!'.
+(! (! true)) ; => true
+
+; La igualdad es `equal` o `=`.
+(= 1 1) ; => true
+(equal 2 1) ; => false
+
+; Por ejemplo, la desigualdad sería combinar la función 'not' con
+; la función de igualdad
+(! (= 2 1)) ; => true
+
+; Más comparaciones
+(< 1 10) ; => true
+(> 1 10) ; => false
+; y su contraparte textual.
+(lesser 1 10) ; => true
+(greater 1 10) ; => false
+
+; Los Strings pueden concatenarse con la función +.
+(+ "Hola " "mundo!") ; => "Hello world!"
+
+; También puedes usar las comparativas de JavaScript
+(< 'a' 'b') ; => true
+; ...y la coerción de tipos
+(= '5' 5)
+
+; La función 'at' o @ accesa a los caracteres dentro de los strings,
+; empezando en 0.
+(at 0 'a') ; => 'a'
+(@ 3 "foobar") ; => 'b'
+
+; También están las variables `null` and `undefined`.
+null; usado para indicar una falta de valor deliberada.
+undefined; usado para indicar un valor que aún no está definido.
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 2. Variables, Listas y Diccionarios
+
+; Las variables son declaradas con las funciones `def` o `let`.
+; Las variables que aún no son asignadas tendrán el valor `undefined`.
+(def mi_variable 5)
+; `def` asignará la variable al contexto global.
+; `let` asignará la variable al contexto local,
+; y tiene una sintaxis distinta.
+(let ((mi_variable 5)) (+ mi_variable 5)) ; => 10
+(+ mi_variable 5) ; = undefined + 5 => undefined
+
+; Las listas son arreglos de valores de cualquier tipo.
+; Básicamente, son formas sin funciones al inicio.
+(1 2 3) ; => [1, 2, 3] (sintaxis JavaScript)
+
+; Los diccionarios son el equivalente en Whip de los 'objetos' de JavaScript,
+; los 'dicts' de Python o los 'hashes' de Ruby: una colección desordenada
+; de pares llave-valor
+{"llave1" "valor1" "llave2" 2 3 3}
+
+; Las llaves son sólo valores, identificadores, números o strings.
+(def mi_diccionario {mi_llave "mi_valor" "mi otra llave" 4})
+; Pero con Whip, los diccionarios son leidos así:
+; "llave" "espacio en blanco" "valor" "espacio en blanco"
+{"llave" "valor"
+"otra llave"
+1234
+}
+
+; Las definiciones de los diccionarios pueden accesarse con la función @
+; (como los strings y las listas)
+(@ "mi otra llave" mi_diccionario) ; => 4
+
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; 3. Logica y secuencias de control
+
+; La funcion `if` es bastante simple, aunque distinta que en otros lenguajes.
+(if true "regresa esto si es true" "regresa esto si es false")
+; => "regresa esto si es true"
+
+; Y para el operador ternario `?`
+(? false true false) ; => false
+
+? `both` es un 'y' lógico, mientras que la función `either` es un 'o'.
+(both true true) ; => true
+(both true false) ; => false
+(either true false) ; => true
+(either false false) ; => false
+; Y sus atajos son '&' y '^' respectivamente
+; & => both
+; ^ => either
+(& true true) ; => true
+(^ false true) ; => true
+
+;;;;;;;;;
+; Lambdas
+
+; Las Lambdas en Whip son declaradas con las funciones `lambda` o `->`.
+; Las funciones regulares en realidad sólo son lambdas con nombre.
+(def mi_funcion (-> (x y) (+ (+ x y) 10)))
+; | | | |
+; | | | valor regresado(estas son las variables argumentos)
+; | | argumentos
+; | declaración de lambda
+; |
+; nombre de la lambda
+
+(mi_funcion 10 10) ; = (+ (+ 10 10) 10) => 30
+
+; Obviamente, todas las lambdas por definición son anónimas y
+; técnicamente siempre usadas anónimamente. Redundancia.
+((lambda (x) x) 10) ; => 10
+
+;;;;;;;;;;;;;;;;
+; Comprensiones
+
+; `range` o `..` genera una lista de números que comprende
+; cada entero dentro de los argumentos.
+(range 1 5) ; => (1 2 3 4 5)
+(.. 0 2) ; => (0 1 2)
+
+; `map` aplica su primer argumento (que debe ser una función)
+; al siguiente argumento (que es una lista).
+(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4)
+
+; Reducir
+(reduce + (.. 1 5))
+; equivale a
+((+ (+ (+ 1 2) 3) 4) 5)
+
+; Nota: map y reduce no tienen atajos.
+
+; `slice` o `\` es idéntico a la función .slice() de JavaScript
+; Pero toma la lista del primer argumento, no del último.
+(slice (.. 1 5) 2) ; => (3 4 5)
+(\ (.. 0 100) -5) ; => (96 97 98 99 100)
+
+; `append` o `<<` se explica solo.
+(append 4 (1 2 3)) ; => (1 2 3 4)
+(<< "bar" ("foo")) ; => ("foo" "bar")
+
+; Length se explica solo.
+(length (1 2 3)) ; => 3
+(_ "foobar") ; => 6
+
+;;;;;;;;;;;;;;;
+; Elementos de Haskell
+
+; Primer elemento en una lista
+(head (1 2 3)) ; => 1
+
+; Lista del segundo elemento al último en una lista
+(tail (1 2 3)) ; => (2 3)
+
+; Último elemento en una lista
+(last (1 2 3)) ; => 3
+
+; Contrario a `tail`
+(init (1 2 3)) ; => (1 2)
+
+; Lista del primer elemento al argumento
+(take 1 (1 2 3 4)) ; (1 2)
+
+; Contrario a `take`
+(drop 1 (1 2 3 4)) ; (3 4)
+
+; Valor más pequeño de una lista
+(min (1 2 3 4)) ; 1
+
+; Valor más grande de una lista
+(max (1 2 3 4)) ; 4
+
+; Comprobar que el elemento está en la lista
+(elem 1 (1 2 3)) ; true
+(elem "foo" {"foo" "bar"}) ; true
+(elem "bar" {"foo" "bar"}) ; false
+
+; Invertir el orden de la lista
+(reverse (1 2 3 4)) ; => (4 3 2 1)
+
+; Comprobar si un elemento es par o impar
+(even 1) ; => false
+(odd 1) ; => true
+
+; Separar string en una lista de strings, separados por espacios
+(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese")
+; Juntar lista de strings.
+(unwords ("foo" "bar")) ; => "foobar"
+(pred 21) ; => 20
+(succ 20) ; => 21
+```
+
+Para más información, revisa el [repositorio](http://github.com/L8D/whip)
diff --git a/es-es/xml-es.html.markdown b/es-es/xml-es.html.markdown
new file mode 100644
index 00000000..2e9326cf
--- /dev/null
+++ b/es-es/xml-es.html.markdown
@@ -0,0 +1,131 @@
+---
+language: xml
+filename: learnxml.xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Daniel Zendejas", "https://github.com/DanielZendejas"]
+lang: es-es
+---
+XML es un lenguaje diseñado para guardar y transportar datos
+
+A diferencia de HTML, XML no especifica cómo desplegar la información,
+sólo la guarda.
+
+* Sintaxis XML
+
+```xml
+<!-- Los comentarios en XML son de esta forma -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<tiendaDeLibros>
+ <libro categoria="COCINA">
+ <titulo lenguaje="en">Everyday Italian</titulo>
+ <autor>Giada De Laurentiis</autor>
+ <anio>2005</anio>
+ <precio>30.00</precio>
+ </libro>
+ <libro categoria="INFANTES">
+ <titulo lenguaje="en">Harry Potter</titulo>
+ <autor>J K. Rowling</autor>
+ <anio>2005</anio>
+ <precio>29.99</precio>
+ </libro>
+ <libro categoria="WEB">
+ <titulo lenguaje="en">Learning XML</titulo>
+ <autor>Erik T. Ray</autor>
+ <anio>2003</anio>
+ <precio>39.95</precio>
+ </libro>
+</tiendaDeLibros>
+
+<!-- Este es un archivo típico de XML.
+ Empieza con una declaración de metadatos (opcional).
+
+ XML usa una estructura de árbol. El nodo raíz es 'tiendaDeLibros', el cual
+ tiene tres nodos hijos, todos llamados 'libros'.
+ Esos nodos tienen más nodos hijos, y así continúa...
+
+ Los nodos son creados usando tags que abren y cierran, y los hijos
+ son sólo nodos entre estas tags.-->
+
+
+<!-- XML guarda dos tipos de datos:
+ 1 - Atributos -> Son los metadatos de un nodo.
+ Usualmente el parseador XML usa esta información para guardar los datos
+ apropiadamente. Aparecen con el formato (nombre="valor") dentro de la
+ tag que abre.
+ 2 - Elementos -> Ese es el dato puro.
+ Eso es lo que el parseador recuperará del archivo XML.
+ Los elementos aparecen entre las tags que abren y cierran.-->
+
+
+<!-- Debajo, un elemento con dos atributos. -->
+<archivo tipo="gif" id="4293">computer.gif</archivo>
+
+
+```
+
+* Documentos con buen formato x Validación
+
+Un documento XML está bien formado cuando es sintácticamente correcto.
+Aún esto, es posible inyectar más restricciones en el documento,
+usando definiciones de documento, así como DTD o XML Schemas.
+
+Un documento XML que sigue a una definición de documento (un esquema) es
+válida.
+
+Con esta herramienta puedes validar datos XML fuera de la aplicación
+
+```xml
+
+<!-- Debajo puedes encontrar una versión simplificada del documento
+ tiendaDeLibros en adición a la definición DTD.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE note SYSTEM "tiendaDeLibros.dtd">
+<tiendaDeLibros>
+ <libro categoriq="COCINA">
+ <titulo>Everyday Italian</titulo>
+ <precio>30.00</precio>
+ </libro>
+</tiendaDeLibros>
+
+<!-- El DTD de este documento podría verse algo así:-->
+
+<!DOCTYPE note
+[
+<!ELEMENT tiendaDeLibros (libro+)>
+<!ELEMENT libro (titulo,precio)>
+<!ATTLIST libro categoria CDATA "Literatura">
+<!ELEMENT titulo (#PCDATA)>
+<!ELEMENT precio (#PCDATA)>
+]>
+
+<!--El DTD empieza con una declaración.
+ Después el nodo raíz es declarado, requiriendo 1 o más nodos 'libro'
+ Cada 'libro' debe contener exactamente un 'titulo' y un 'precio' y
+ un atributo llamado 'categoria', con "Literatura" como su valor
+ default.
+ Los nodos 'titulo' y 'precio' contienen datos de caracteres
+ parseados.
+
+ El DTD puede ser declarado dentro del XML mismo.-->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE note
+[
+<!ELEMENT tiendaDeLibros (libro+)>
+<!ELEMENT libro (titulo,precio)>
+<!ATTLIST libro categoria CDATA "Literatura">
+<!ELEMENT titulo (#PCDATA)>
+<!ELEMENT precio (#PCDATA)>
+]>
+<tiendaDeLibros>
+ <libro categoriq="COCINA">
+ <titulo>Everyday Italian</titulo>
+ <precio>30.00</precio>
+ </libro>
+</tiendaDeLibros>
+```
diff --git a/es-es/yaml-es.html.markdown b/es-es/yaml-es.html.markdown
new file mode 100644
index 00000000..a5157b5d
--- /dev/null
+++ b/es-es/yaml-es.html.markdown
@@ -0,0 +1,151 @@
+---
+language: yaml
+lang: es-es
+filename: learnyaml-es.yaml
+contributors:
+ - ["Adam Brenecki", "https://github.com/adambrenecki"]
+translators:
+ - ["Daniel Zendejas","https://github.com/DanielZendejas"]
+---
+Tutorial de YAML en español.
+
+YAML es un lenguaje de serialización de datos diseñado para ser
+leído y escrito por humanos.
+
+Basa su funcionalidad en JSON, con la adición de líneas nuevas
+e indentación inspirada en Python. A diferencia de Python, YAML
+no permite tabs literales.
+
+```yaml
+# Los comentarios en YAML se ven así.
+
+###################
+# TIPOS ESCALARES #
+###################
+
+# Nuestro objeto raíz (el cual es el mismo a lo largo de todo el
+# documento) será un mapa, equivalente a un diccionario, hash,
+# u objeto en otros lenguajes.
+
+llave: valor
+otra_llave: Otro valor
+un_valor_numerico: 100
+notacion_cientifica: 1e+12
+booleano: true
+valor_nulo: null
+llave con espacios: valor
+# Nótese que los strings no deben estar entre comillas, aunqué también es válido.
+llave: "Un string, entre comillas."
+"Las llaves tambien pueden estar entre comillas.": "valor entre comillas"
+
+# Los strings de líneas múltiples pueden ser escritos
+# como un 'bloque literal' (usando pipes |)
+# o como un 'bloque doblado' (usando >)
+
+bloque_literal: |
+ Este bloque completo de texto será preservado como el valor de la llave
+ 'bloque_literal', incluyendo los saltos de línea.
+
+ Se continúa guardando la literal hasta que se cese la indentación.
+ Cualquier línea que tenga más indentación, mantendrá los espacios dados
+ (por ejemplo, estas líneas se guardarán con cuatro espacios)
+
+nloque_doblado: >
+ De la misma forma que el valor de 'bloque_literal', todas estas
+ líneas se guardarán como una sola literal, pero en esta ocasión todos los
+ saltos de línea serán reemplazados por espacio.
+
+ Las líneas en blanco, como la anterior, son convertidos a un salto de línea.
+
+ Las líneas con mayor indentación guardan sus saltos de línea.
+ Esta literal ocuparán dos líneas.
+
+########################
+# TIPOS DE COLECCIONES #
+########################
+
+# La indentación se usa para anidar.
+un_mapa_indentado:
+ llave: valor
+ otra_llave: otro valor
+ otro_mapa_indentado:
+ llave_interna: valor_interno
+
+# Las llaves de los mapas no deben ser strings necesariamente
+0.25: una llave numérica
+
+# Las llaves también pueden ser objetos de multi línea, usando ? para indicar
+# el inicio de una llave
+? |
+ Esto es una llave
+ que tiene múltiples líneas
+: y este es su valor
+
+# YAML tambien permite colecciones como llaves, pero muchos lenguajes de
+# programación se quejarán.
+
+# Las secuencias (equivalentes a listas o arreglos) se ven así:
+una_secuencia:
+ - Item 1
+ - Item 2
+ - 0.5 # las secuencias pueden tener distintos tipos en su contenido.
+ - Item 4
+ - llave: valor
+ otra_llave: otro_valor
+ -
+ - Esta es una secuencia
+ - ...dentro de otra secuencia
+
+# Dado que todo JSON está incluído dentro de YAML, también puedes escribir
+# mapas con la sintaxis de JSON y secuencias:
+mapa_de_json: {"llave": "valor"}
+secuencia_de_json: [3, 2, 1, "despegue"]
+
+##################################
+# CARACTERÍSTICAS EXTRAS DE YAML #
+##################################
+
+# YAML tiene funciones útiles llamadas 'anchors' (anclas), que te permiten
+# duplicar fácilmente contenido a lo largo de tu documento. En el ejemplo
+# a continuación, ambas llaves tendrán el mismo valor:
+contenido_anclado: &nombre_del_ancla Este string será el valor de las llaves
+otra_ancla: *nombre_del_ancla
+
+# YAML también tiene tags, que puedes usar para declarar tipos explícitamente.
+string_explícito: !!str 0.5
+# Algunos parseadores implementar tags específicas del lenguaje, como el
+# que se muestra a continuación, encargado de manejar números complejos en
+# Python:
+numero_complejo_python: !!python/complex 1+2j
+
+########################
+# TIPOS EXTRAS EN YAML #
+########################
+
+# Stirngs y números no son los únicos escalares que YAML puede entener.
+# YAML también puede parsear fechas en formato ISO .
+fechaHora: 2001-12-15T02:59:43.1Z
+fechaHora_con_espacios: 2001-12-14 21:59:43.10 -5
+fecha: 2002-12-14
+
+# La tag !!binary indica que un string es, en realidad, un blob
+# representado en base-64.
+archivo_gif: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAML también tiene un tipo set, que se ve de la siguiente forma:
+set:
+ ? item1
+ ? item2
+ ? item3
+
+# Al igual que Python, los sets sólo son mapas con valores nulos.
+# El ejemplo de arriba es equivalente a:
+set2:
+ item1: null
+ item2: null
+ item3: null
+```
diff --git a/fa-ir/javascript.html.markdown b/fa-ir/javascript.html.markdown
index 922fe416..5c64d24a 100644
--- a/fa-ir/javascript.html.markdown
+++ b/fa-ir/javascript.html.markdown
@@ -493,8 +493,8 @@ myNumber == myNumberObj; // = true
<p dir='rtl'>به جز این که این سازنده ها دقیقا مانند سازنده های دیگر نیستند.</p>
```js
-typeof(myNumber); // = 'number'
-typeof(myNumberObj); // = 'object'
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
// This code won't execute, because 0 is falsy.
diff --git a/forth.html.markdown b/forth.html.markdown
new file mode 100644
index 00000000..570e12ed
--- /dev/null
+++ b/forth.html.markdown
@@ -0,0 +1,225 @@
+---
+language: forth
+contributors:
+ - ["Horse M.D.", "http://github.com/HorseMD/"]
+filename: learnforth.fs
+---
+
+Forth was created by Charles H. Moore in the 70s. It is an imperative,
+stack-based language and programming environment, being used in projects
+such as Open Firmware. It's also used by NASA.
+
+Note: This article focuses predominantly on the Gforth implementation of
+Forth, but most of what is written here should work elsewhere.
+
+```forth
+\ This is a comment
+( This is also a comment but it's only used when defining words )
+
+\ --------------------------------- Precursor ----------------------------------
+
+\ All programming in Forth is done by manipulating the parameter stack (more
+\ commonly just referred to as "the stack").
+5 2 3 56 76 23 65 \ ok
+
+\ Those numbers get added to the stack, from left to right.
+.s \ <7> 5 2 3 56 76 23 65 ok
+
+\ In Forth, everything is either a word or a number.
+
+\ ------------------------------ Basic Arithmetic ------------------------------
+
+\ Arithmetic (in fact most words requiring data) works by manipulating data on
+\ the stack.
+5 4 + \ ok
+
+\ `.` pops the top result from the stack:
+. \ 9 ok
+
+\ More examples of arithmetic:
+6 7 * . \ 42 ok
+1360 23 - . \ 1337 ok
+12 12 / . \ 1 ok
+13 2 mod . \ 1 ok
+
+99 negate . \ -99 ok
+-99 abs . \ 99 ok
+52 23 max . \ 52 ok
+52 23 min . \ 23 ok
+
+\ ----------------------------- Stack Manipulation -----------------------------
+
+\ Naturally, as we work with the stack, we'll want some useful methods:
+
+3 dup - \ duplicate the top item (1st now equals 2nd): 3 - 3
+2 5 swap / \ swap the top with the second element: 5 / 2
+6 4 5 rot .s \ rotate the top 3 elements: 4 5 6
+4 0 drop 2 / \ remove the top item (dont print to screen): 4 / 2
+1 2 3 nip .s \ remove the second item (similar to drop): 1 3
+
+\ ---------------------- More Advanced Stack Manipulation ----------------------
+
+1 2 3 4 tuck \ duplicate the top item into the second slot: 1 2 4 3 4 ok
+1 2 3 4 over \ duplicate the second item to the top: 1 2 3 4 3 ok
+1 2 3 4 2 roll \ *move* the item at that position to the top: 1 3 4 2 ok
+1 2 3 4 2 pick \ *duplicate* the item at that position to the top: 1 2 3 4 2 ok
+
+\ When referring to stack indexes, they are zero-based.
+
+\ ------------------------------ Creating Words --------------------------------
+
+\ The `:` word sets Forth into compile mode until it sees the `;` word.
+: square ( n -- n ) dup * ; \ ok
+5 square . \ 25 ok
+
+\ We can view what a word does too:
+see square \ : square dup * ; ok
+
+\ -------------------------------- Conditionals --------------------------------
+
+\ -1 == true, 0 == false. However, any non-zero value is usually treated as
+\ being true:
+42 42 = \ -1 ok
+12 53 = \ 0 ok
+
+\ `if` is a compile-only word. `if` <stuff to do> `then` <rest of program>.
+: ?>64 ( n -- n ) dup 64 > if ." Greater than 64!" then ; \ ok
+100 ?>64 \ Greater than 64! ok
+
+\ Else:
+: ?>64 ( n -- n ) dup 64 > if ." Greater than 64!" else ." Less than 64!" then ;
+100 ?>64 \ Greater than 64! ok
+20 ?>64 \ Less than 64! ok
+
+\ ------------------------------------ Loops -----------------------------------
+
+\ `do` is also a compile-only word.
+: myloop ( -- ) 5 0 do cr ." Hello!" loop ; \ ok
+myloop
+\ Hello!
+\ Hello!
+\ Hello!
+\ Hello!
+\ Hello! ok
+
+\ `do` expects two numbers on the stack: the end number and the start number.
+
+\ We can get the value of the index as we loop with `i`:
+: one-to-12 ( -- ) 12 0 do i . loop ; \ ok
+one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok
+
+\ `?do` works similarly, except it will skip the loop if the end and start
+\ numbers are equal.
+: squares ( n -- ) 0 ?do i square . loop ; \ ok
+10 squares \ 0 1 4 9 16 25 36 49 64 81 ok
+
+\ Change the "step" with `+loop`:
+: threes ( n n -- ) ?do i . 3 +loop ; \ ok
+15 0 threes \ 0 3 6 9 12 ok
+
+\ Indefinite loops with `begin` <stuff to do> <flag> `unil`:
+: death ( -- ) begin ." Are we there yet?" 0 until ; \ ok
+
+\ ---------------------------- Variables and Memory ----------------------------
+
+\ Use `variable` to declare `age` to be a variable.
+variable age \ ok
+
+\ Then we write 21 to age with the word `!`.
+21 age ! \ ok
+
+\ Finally we can print our variable using the "read" word `@`, which adds the
+\ value to the stack, or use `?` that reads and prints it in one go.
+age @ . \ 21 ok
+age ? \ 21 ok
+
+\ Constants are quite simiar, except we don't bother with memory addresses:
+100 constant WATER-BOILING-POINT \ ok
+WATER-BOILING-POINT . \ 100 ok
+
+\ ----------------------------------- Arrays -----------------------------------
+
+\ Creating arrays is similar to variables, except we need to allocate more
+\ memory to them.
+
+\ You can use `2 cells allot` to create an array that's 3 cells long:
+variable mynumbers 2 cells allot \ ok
+
+\ Initialize all the values to 0
+mynumbers 3 cells erase \ ok
+
+\ Alternatively we could use `fill`:
+mynumbers 3 cells 0 fill
+
+\ or we can just skip all the above and initialize with specific values:
+create mynumbers 64 , 9001 , 1337 , \ ok (the last `,` is important!)
+
+\ ...which is equivalent to:
+
+\ Manually writing values to each index:
+64 mynumbers 0 cells + ! \ ok
+9001 mynumbers 1 cells + ! \ ok
+1337 mynumbers 2 cells + ! \ ok
+
+\ Reading values at certain array indexes:
+0 cells mynumbers + ? \ 64 ok
+1 cells mynumbers + ? \ 9001 ok
+
+\ We can simplify it a little by making a helper word for manipulating arrays:
+: of-arr ( n n -- n ) cells + ; \ ok
+mynumbers 2 of-arr ? \ 1337 ok
+
+\ Which we can use for writing too:
+20 mynumbers 1 of-arr ! \ ok
+mynumbers 1 of-arr ? \ 20 ok
+
+\ ------------------------------ The Return Stack ------------------------------
+
+\ The return stack is used to the hold pointers to things when words are
+\ executing other words, e.g. loops.
+
+\ We've already seen one use of it: `i`, which duplicates the top of the return
+\ stack. `i` is equivalent to `r@`.
+: myloop ( -- ) 5 0 do r@ . loop ; \ ok
+
+\ As well as reading, we can add to the return stack and remove from it:
+5 6 4 >r swap r> .s \ 6 5 4 ok
+
+\ NOTE: Because Forth uses the return stack for word pointers, `>r` should
+\ always be followed by `r>`.
+
+\ ------------------------- Floating Point Operations --------------------------
+
+\ Most Forths tend to eschew the use of floating point operations.
+8.3e 0.8e f+ f. \ 9.1 ok
+
+\ Usually we simply prepend words with 'f' when dealing with floats:
+variable myfloatingvar \ ok
+4.4e myfloatingvar f! \ ok
+myfloatingvar f@ f. \ 4.4 ok
+
+\ --------------------------------- Final Notes --------------------------------
+
+\ Typing a non-existent word will empty the stack. However, there's also a word
+\ specifically for that:
+clearstack
+
+\ Clear the screen:
+page
+
+\ Loading Forth files:
+\ s" forthfile.fs" included
+
+\ You can list every word that's in Forth's dictionary (but it's a huge list!):
+\ words
+
+\ Exiting Gforth:
+\ bye
+
+```
+
+##Ready For More?
+
+* [Starting Forth](http://www.forth.com/starting-forth/)
+* [Simple Forth](http://www.murphywong.net/hello/simple.htm)
+* [Thinking Forth](http://thinking-forth.sourceforge.net/)
diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown
new file mode 100644
index 00000000..0e764d7d
--- /dev/null
+++ b/fr-fr/bash-fr.html.markdown
@@ -0,0 +1,230 @@
+---
+category: tool
+tool: bash
+contributors:
+ - ["Max Yankov", "https://github.com/golergka"]
+ - ["Darren Lin", "https://github.com/CogBear"]
+ - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"]
+ - ["Denis Arh", "https://github.com/darh"]
+ - ["akirahirose", "https://twitter.com/akirahirose"]
+ - ["Anton Strömkvist", "http://lutic.org/"]
+ - ["Rahil Momin", "https://github.com/iamrahil"]
+ - ["Gregrory Kielian", "https://github.com/gskielian"]
+translators:
+ - ["Baptiste Fontaine", "http://bfontaine.net"]
+filename: LearnBash-fr.sh
+lang: fr-fr
+---
+
+Bash est le nom du shell UNIX, qui était aussi distribué avec le système
+d’exploitation GNU et est le shell par défaut sur Linux et Mac OS X.
+
+Presque tous les exemples ci-dessous peuvent être écrits dans un script shell
+ou exécutés directement dans le terminal.
+
+[Plus d’informations ici.](http://www.gnu.org/software/bash/manual/bashref.html)
+
+```bash
+#!/bin/bash
+# La première ligne du script s’appelle le « shebang, » qui indique au système
+# comment exécuter le script : http://fr.wikipedia.org/wiki/Shebang
+# Comme vous pouvez le remarquer, les commentaires commencent par #. Le shebang
+# est aussi un commentaire
+
+# Un exemple simple qui affiche « Hello world! » :
+echo Hello world!
+
+# Chaque commande commence sur une nouvelle ligne ou après un point-virgule :
+echo 'Ceci est la première ligne'; echo 'Ceci est la seconde ligne'
+
+# La déclaration d’une variable ressemble à ça :
+VARIABLE="Du texte"
+
+# Mais pas comme ça :
+VARIABLE = "Du texte"
+# Bash va penser que VARIABLE est une commande qu’il doit exécuter et va
+# afficher une erreur parce qu’elle est introuvable.
+
+# Utiliser une variable :
+echo $VARIABLE
+echo "$VARIABLE"
+echo '$VARIABLE'
+# Quand vous utilisez la variable en elle-même – en lui assignant une valeur,
+# en l’exportant ou autre – vous écrivez son nom sans $. Si vous voulez
+# utiliser sa valeur, vous devez utiliser $.
+# Notez qu’entourer une variable de deux guillemets simples (') empêche
+# l’expansion des variables !
+
+# Substitution de chaîne de caractères dans une variable
+echo ${VARIABLE/Some/A}
+# Ceci va remplacer la première occurrence de « Some » par « A »
+
+# Sous-chaîne d’une variable
+echo ${VARIABLE:0:7}
+# Ceci va retourner seulement les 7 premiers caractères de la valeur
+
+# Valeur par défaut d’une variable
+echo ${FOO:-"ValeurParDefautSiFOOestVideOuInexistant"}
+# Ceci marche pour null (FOO=), la chaîne de caractères vide (FOO=""). Zéro
+# (FOO=0) retourne 0
+
+# Variables pré-remplies :
+# Il y a quelques variables pré-remplies utiles, comme :
+echo "La valeur de retour du dernier programme : $?"
+echo "Le PID du script : $$"
+echo "Nombre d’arguments : $#"
+echo "Arguments du script : $@"
+echo "Arguments du script séparés en plusieurs variables : $1 $2..."
+
+# Lire une valeur depuis l’entrée standard :
+echo "Quel est votre nom ?"
+read NAME # Notez que l’on n’a pas eu à déclarer une nouvelle variable
+echo Bonjour, $NAME!
+
+# Nous avons l’habituelle structure « if » :
+# Utilisez 'man test' pour plus d’informations à propos des conditions
+if [ $NAME -ne $USER ]
+then
+ echo "Votre nom n’est pas votre pseudo"
+else
+ echo "Votre nom est votre pseudo"
+fi
+
+# Il y a aussi l’exécution conditionnelle
+echo "Toujours exécuté" || echo "Exécuté si la première commande ne réussit pas"
+echo "Toujours exécuté" && echo "Exécuté si la première commande réussit"
+
+# Pour utiliser && et || avec des commandes « if, » vous devez utiliser
+# plusieurs paires de crochets :
+if [ $NAME == "Steve" ] && [ $AGE -eq 15 ]
+then
+ echo "Ceci sera exécuté si $NAME est Steve ET $AGE est 15."
+fi
+
+if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ]
+then
+ echo "Ceci sera exécuté si $NAME est Daniya OU Zach."
+fi
+
+# Les expressions sont écrites dans le format suivant :
+echo $(( 10 + 5 ))
+
+# Contrairement aux autres langages de programmation, Bash est un shell — il
+# est donc exécuté dans le contexte du répertoire courant. Vous pouvez lister
+# les fichiers et dossiers dans le répertoire courant avec la commande `ls` :
+ls
+
+# Ces commandes ont des options qui contrôlent leur exécution :
+ls -l # Liste tous les fichiers et répertoires sur des lignes séparées
+
+# Les résultat de la commande précédente peuvent être passés à la commande
+# suivante en entrée.
+# La commande grep filtre l’entrée avec les motifs donnés. On peut ainsi lister
+# les fichiers .txt dans le répertoire courant :
+ls -l | grep "\.txt"
+
+# Vous pouvez aussi rediriger l’entrée et les sorties standards et d’erreur
+# d’une commande :
+python2 hello.py < "entrée.in"
+python2 hello.py > "sortie.out"
+python2 hello.py 2> "erreur.err"
+# Ceci va écraser le fichier s'il existe; si vous préférez écrire à la fin de
+# celui-ci, utilisez >> à la place.
+
+# Les commandes peuvent se substituer à l’intérieur d’autres commandes en
+# utilisant $( ) :
+# La commande ci-dessous affiche le nombre de fichiers et répertoires dans le
+# répertoire courant :
+echo "Il y a $(ls | wc -l) choses ici."
+
+# On peut faire la même chose avec les accents graves `` mais on ne peut pas
+# les imbriquer — la façon la plus courante est d’utiliser $( ).
+echo "There are `ls | wc -l` items here."
+
+# Bash a une commande case qui marche de façon similaire au switch de Java et
+# C++ :
+case "$VARIABLE" in
+ #List patterns for the conditions you want to meet
+ 0) echo "There is a zero.";;
+ 1) echo "There is a one.";;
+ *) echo "It is not null.";;
+esac
+
+# La boucle for itère autant de fois qu’elle a d’arguments :
+# Le contenu de $VARIABLE est affiché trois fois.
+for VARIABLE in {1..3}
+do
+ echo "$VARIABLE"
+done
+
+# Ou écrivez-la de façon « traditionnelle » :
+for ((a=1; a <= 3; a++))
+do
+ echo $a
+done
+
+# Elles peuvent aussi être utilisées pour agir sur des fichiers :
+# Cette boucle va exécuter la commande 'cat' sur fichier1 et fichier2
+for VARIABLE in fichier1 fichier2
+do
+ cat "$VARIABLE"
+done
+
+# …ou la sortie d’une commande :
+# Ceci va afficher la sortie de ls.
+for OUTPUT in $(ls)
+do
+ cat "$OUTPUT"
+done
+
+# Boucle while :
+while [ true ]
+do
+ echo "corps de la boucle ..."
+ break
+done
+
+# Vous pouvez aussi définir des fonctions
+# Définition :
+function foo ()
+{
+ echo "Les arguments fonctionnent comme les arguments de script : $@"
+ echo "Et : $1 $2..."
+ echo "Ceci est une fonction"
+ return 0
+}
+
+# Ou plus simplement :
+bar ()
+{
+ echo "Une autre façon de définir des fonctions !"
+ return 0
+}
+
+# Appeler votre fonction
+foo "Mon nom est" $NAME
+
+# Il y a plein de commandes utiles que vous devriez apprendre :
+# affiche les 10 dernières lignes de fichier.txt
+tail -n 10 fichier.txt
+# affiche les 10 premières lignes de fichier.txt
+head -n 10 fichier.txt
+# trie les lignes de fichier.txt
+sort fichier.txt
+# montre ou omet les lignes répétées, avec -d pour les montrer
+uniq -d fichier.txt
+# affiche uniquement la première colonne avant le caractère « , »
+cut -d ',' -f 1 fichier.txt
+# remplace chaque occurrence de 'okay' par 'super' dans fichier.txt
+# (compatible avec les expression rationnelles)
+sed -i 's/okay/super/g' fichier.txt
+# affiche toutes les lignes de fichier.txt qui correspondent à une expression
+# rationnelle, dans cet exemple les lignes qui commencent par « foo » et
+# finissent par « bar »
+grep "^foo.*bar$" fichier.txt
+# ajoutez l’option « -c » pour afficher le nombre de lignes concernées
+grep -c "^foo.*bar$" fichier.txt
+# Si vous voulez vraiment chercher une chaîne de caractères, et non
+# l’expression rationnelle, utilisez fgrep (ou grep -F)
+fgrep "^foo.*bar$" fichier.txt
+```
diff --git a/fr-fr/brainfuck-fr.html.markdown b/fr-fr/brainfuck-fr.html.markdown
new file mode 100644
index 00000000..545e407e
--- /dev/null
+++ b/fr-fr/brainfuck-fr.html.markdown
@@ -0,0 +1,87 @@
+---
+language: brainfuck
+filename: learnbrainfuck-fr.bf
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Baptiste Fontaine", "http://bfontaine.net"]
+lang: fr-fr
+---
+
+Brainfuck (sans majuscule à part au début d’une phrase) est un langage
+Turing-complet extrêmement simple avec seulement 8 commandes.
+
+```
+Tout caractère en dehors de "><+-.,[]" (en dehors des guillemets) est ignoré.
+
+Brainfuck est représenté par un tableau de 30 000 cellules initialisées à 0 et
+un pointeur de données pointant sur la cellule courante.
+
+Il y a huit commandes :
++ : Incrémente la valeur de la cellule courante de un.
+- : Décrémente la valeur de la cellule courante de un.
+> : Déplace le pointeur de données sur la cellule suivante (à droite).
+< : Déplace le pointeur de données sur la cellule précédente (à gauche).
+. : Affiche la valeur ASCII de la cellule courante (par ex. 65 = 'A').
+, : Lit un caractère et le place dans la cellule courante.
+[ : Si la valeur dans la cellule courante vaut 0, saute au ] correspondant.
+ Sinon, continue avec la commande suivante.
+] : Si la valeur dans la cellule courante vaut 0, continue avec la commande
+ suivante. Sinon, retourne au [ correspondant.
+
+[ et ] forment une boucle « tant que » (« while »). Ils doivent évidemment
+aller par paires.
+
+Regardons quelques programmes simples en brainfuck.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Ce programme affiche la lettre 'A'. Il commence par incrémenter la première
+cellule à 6. Il entre ensuite dans une boucle et se déplace sur la seconde
+cellule. Il l’incrémente 10 fois, retourne sur la première cellule, et la
+décrémente. Cette boucle est exécutée 6 fois (ce qui correspond aux 6
+décrémentations de la première cellule pour la faire atteindre 0, ce qui fait
+sortir de la boucle).
+
+À ce moment-là, nous sommes sur la première cellule, qui a une valeur de 0,
+tandis que la seconde cellule a une valeur de 60. Nous nous déplaçons sur
+celle-ci, l’incrémentons 5 fois, pour une valeur de 65, et affichons sa valeur.
+En ASCII, 65 correspond à 'A' donc le programme affiche 'A' dans le terminal.
+
+, [ > + < - ] > .
+
+Ce programme lit un caractère sur l’entrée standard et le copie dans la
+première cellule. Il commence ensuite une boucle : il bouge sur la seconde
+cellule, incrémente sa valeur, retourne sur la première et décrémente sa
+valeur. Il continue jusqu’à ce que la valeur de la première cellule soit à 0,
+et que la seconde cellule contienne l’ancienne valeur de la première. Comme
+nous sommes sur la première cellule à la fin de la boucle, il bouge sur la
+seconde et affiche sa valeur en ASCII.
+
+Souvenez-vous que les espaces sont uniquement là pour favoriser la lisibilité,
+vous pourriez tout aussi aisément écrire le programme comme ceci :
+
+,[>+<-]>.
+
+Essayez et devinez ce que ce programme fait :
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Ce programme prend deux nombres en entrée, et les multiplie.
+
+Il commence par lire deux entrées, puis commence une boucle externe, qui a une
+condition sur la première cellule. Il bouge ensuite sur la seconde, et commence
+une boucle interne sur celle-ci, en incrémentant la troisième cellule. Il y a
+cependant un problème : à la fin de la boucle interne, la valeur de la seconde
+cellule est à zéro. Dans ce cas, la boucle interne ne fonctionnera pas une
+seconde fois. Pour régler le problème, nous incrémentons aussi la quatrième
+cellule, puis recopions sa valeur dans la seconde cellule.
+À la fin, la troisième cellule contient le résultat de la multiplication.
+```
+
+Et voilà ce qu’est le brainfuck. Pas très dur, hein ? Pour le fun, vous pouvez
+écrire vos propres programmes en brainfuck, ou écrire un interpréteur brainfuck
+dans un autre langage. L’interpréteur est relativement simple à implémenter,
+mais si vous êtes un masochiste, essayez d’écrire un interpréteur brainfuck en…
+brainfuck.
diff --git a/fr-fr/css-fr.html.markdown b/fr-fr/css-fr.html.markdown
new file mode 100644
index 00000000..bdab9715
--- /dev/null
+++ b/fr-fr/css-fr.html.markdown
@@ -0,0 +1,221 @@
+---
+language: css
+contributors:
+ - ["Mohammad Valipour", "https://github.com/mvalipour"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["@prrrnd", "https://github.com/prrrnd"]
+lang: fr-fr
+---
+
+Au début du web, il n'y avait pas d'élements visuels, simplement du texte pure. Mais avec le dévelopement des navigateurs,
+des pages avec du contenu visuel sont arrivées.
+CSS est le langage standard qui existe et permet de garder une séparation entre
+le contenu (HTML) et le style d'une page web.
+
+En résumé, CSS fournit une syntaxe qui vous permet de cibler des élements présents
+sur une page HTML afin de leur donner des propriétés visuelles différentes.
+
+Comme tous les autres langages, CSS a plusieurs versions. Ici, nous allons parlons de CSS2.0
+qui n'est pas le plus récent, mais qui reste le plus utilisé et le plus compatible avec les différents navigateur.
+
+**NOTE :** Vous pouvez tester les effets visuels que vous ajoutez au fur et à mesure du tutoriel sur des sites comme [dabblet](http://dabblet.com/) afin de voir les résultats, comprendre, et vous familiariser avec le langage.
+Cet article porte principalement sur la syntaxe et quelques astuces.
+
+
+```css
+/* Les commentaires sont entourés par slash-étoile, comme cette ligne! */
+
+/* ####################
+ ## SÉLECTEURS
+ ####################*/
+
+/* Généralement, la première déclaration en CSS est très simple */
+selecteur { propriete: valeur; /* autres proprietés...*/ }
+
+/* Le sélécteur sert à cibler un élément du HTML
+
+Vous pouvez cibler tous les éléments d'une page! */
+* { color:red; }
+
+/*
+Voici un élément dans notre HTML :
+
+<div class='une-classe classe2' id='unId' attr='valeur' />
+*/
+
+/* Vous pouvez le cibler par une classe */
+.une-classe { }
+
+/* ou par deux */
+.une-classe.classe2 { }
+
+/* ou par son type */
+div { }
+
+/* ou son id */
+#unId { }
+
+/* ou par le fait qu'il a un attribut */
+[attr] { font-size:smaller; }
+
+/* ou que l'attribut a une valeur spécifique */
+[attr='valeur'] { font-size:smaller; }
+
+/* commence avec une valeur */
+[attr^='val'] { font-size:smaller; }
+
+/* termine avec une valeur */
+[attr$='eur'] { font-size:smaller; }
+
+/* contient une valeur */
+[attr~='leu'] { font-size:smaller; }
+
+
+/* Ce qu'il faut bien comprendre, c'est que vous pouvez combiner ceci -- Il ne doit pas y avoir
+d'espaces entre. */
+div.une-classe[attr$='eu'] { }
+
+/* Vous pouvez aussi cibler un élément par son parent. */
+
+/* Un élément qui est en enfant direct */
+div.un-parent > .enfant {}
+
+/* Cela cible aussi les .enfants plus profonds dans la structure HTML */
+div.un-parent .enfants {}
+
+/* Attention : le même sélecteur sans espace a un autre sens. */
+div.un-parent.classe {}
+
+/* Vous pouvez cibler un élément basé sur un enfant de même parent */
+.je-suis-avant + .cet-element { }
+
+/* ou n'importe quel enfant de même parent avec celui ci */
+.je-suis-tout-avant ~ .cet-element {}
+
+/* Il y a des pseudo-classes qui permettent de cibler un élément
+basé sur le comportement, en plus de la structure de la page */
+
+/* élément avec le curseur au-dessus */
+:hover {}
+
+/* lien visité */
+:visited {}
+
+/* lien non visité */
+:link {}
+
+/* élément avec le focus */
+:focus {}
+
+
+/* ####################
+ ## PROPRIÉTÉS
+ ####################*/
+
+selecteur {
+
+ /* Units */
+ width: 50%; /* pourcentage */
+ font-size: 2em; /* taille de la police multipliée par X */
+ width: 200px; /* pixels */
+ font-size: 20pt; /* points */
+ width: 5cm; /* centimetres */
+ width: 50mm; /* millimetres */
+ width: 5in; /* pouces */
+
+ /* Couleurs */
+ background-color: #F6E; /* court hex */
+ background-color: #F262E2; /* long hex */
+ background-color: tomato; /* couleur nommée */
+ background-color: rgb(255, 255, 255); /* rouge, vert, bleu */
+ background-color: rgb(10%, 20%, 50%); /* rouge, vert, bleu en pourcent */
+ background-color: rgba(255, 0, 0, 0.3); /* rouge, vert, bleu avec transparence */
+
+ /* Images */
+ background-image: url(/chemin-vers-image/image.jpg);
+
+ /* Polices */
+ font-family: Arial;
+ font-family: "Courier New"; /* Si espace, entre guillemets */
+ font-family: "Courier New", Trebuchet, Arial; /* Si la première n'est pas trouvée, la deuxième est utilisée, etc... */
+}
+
+```
+
+## Utilisation
+
+Le CSS s'écrit dans des fichiers `.css`.
+
+```xml
+<!-- Vous devez inclure le CSS dans la balise <head> : -->
+<link rel='stylesheet' type='text/css' href='chemin/style.css' />
+
+<!-- Vous pouvez inclure du CSS dans le HTML directement, mais ce n'est vraiment pas recommandé. -->
+<style>
+ selecteur { propriete:valeur; }
+</style>
+
+<!-- ou directement sur l'élément HTML.
+PS : à ne pas faire. -->
+<div style='propriete:valeur;'>
+</div>
+
+```
+
+## Priorités
+
+Comme on vient de le voir, un élément peut être ciblé par plus qu'un seul sélecteur
+et une même propriété peut être définie plusieurs fois.
+Dans ces cas, une des propriétés devient prioritaire.
+
+Voici du code CSS :
+
+```css
+/*A*/
+p.classe1[attr='valeur']
+
+/*B*/
+p.classe1 {}
+
+/*C*/
+p.classe2 {}
+
+/*D*/
+p {}
+
+/*E*/
+p { propriete: valeur !important; }
+
+```
+
+et le code HTML:
+
+```xml
+<p style='/*F*/ propriete:valeur;' class='classe1 classe2' attr='valeur'>
+</p>
+```
+
+Les priorités de style sont :
+Attention, les priorités s'appliquent aux **propriétés**, pas aux blocs entiers.
+
+* `E` a la priorité grâce à `!important`.
+* `F` vient ensuite, car le code se trouve directement dans le HTML.
+* `A` vient ensuite, car il est le plus spécifique.
+ plus spécifique veut dire, celui qui cible le plus l'élément
+* `C` vient ensuite. Il est aussi spécifique que `B`, mais est écrit après.
+* Puis `B`
+* Et enfin `D`.
+
+## Compatibilité
+
+La plupart des fonctionnalités de CSS2 (et de plus en plus CSS3) sont compatibles
+avec tous les navigateurs. Mais il est important de vérifier la compatibilité.
+
+[QuirksMode CSS](http://www.quirksmode.org/css/) est une très bonne source pour cela.
+
+## En savoir plus (en anglais)
+
+* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/)
+* [QuirksMode CSS](http://www.quirksmode.org/css/)
+* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context)
diff --git a/fr-fr/haskell.html.markdown b/fr-fr/haskell.html.markdown
index 989db1d5..d9d3151f 100644
--- a/fr-fr/haskell.html.markdown
+++ b/fr-fr/haskell.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
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/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown
index 922d6ebc..b4e2a161 100644
--- a/fr-fr/lua-fr.html.markdown
+++ b/fr-fr/lua-fr.html.markdown
@@ -1,5 +1,5 @@
---
-language: lua
+language: Lua
filename: learnlua-fr.lua
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown
new file mode 100644
index 00000000..29c0d65d
--- /dev/null
+++ b/fr-fr/markdown.html.markdown
@@ -0,0 +1,289 @@
+---
+language: markdown
+contributors:
+- ["Andrei Curelaru", "http://www.infinidad.fr"]
+filename: markdown.md
+lang: fr-fr
+---
+
+Markdown a été créé par John Gruber en 2004. Il se veut être d'une syntaxe
+facile à lire et à écrire, aisément convertible en HTML
+ (et beaucoup d'autres formats aussi à présent).
+
+Faites moi autant de retours que vous voulez! Sentez vous libre de "forker"
+et envoyer des pull request!
+
+
+```markdown
+<!-- Markdown est une sorte de cousin du HTML, si bien que tout document HTML
+est un document Markdown valide. Autrement dit, vous pouvez utiliser des
+balises HTML dans un fichier Markdown, comme la balise commentaire dans
+laquelle nous sommes à présent, car celle-ci ne sera pas affectée par
+le parser( analyseur syntaxique ) Markdown. -->
+
+<!-- Toutefois, si vous voulez créer un élément HTML dans un fichier Markdown,
+ vous ne pourrez pas utiliser du Markdown à l'intérieur de ce dernier. -->
+
+<!-- Le Markdown est implémenté de différentes manières, selon le parser.
+Ce guide va alors tenter de trier les fonctionnalités universelles de celles
+spécifiques à un parser. -->
+
+<!-- Headers ( En-têtes ) -->
+<!-- Vous pouvez facilement créer des éléments HTML <h1> à <h6> en précédant
+ le texte de votre futur titre par un ou plusieurs dièses ( # ), de un à six,
+ selon le niveau de titre souhaité. -->
+# Ceci est un <h1>
+## Ceci est un <h2>
+### Ceci est un <h3>
+#### Ceci est un <h4>
+##### Ceci est un <h5>
+###### Ceci est un <h6>
+
+<!--
+Markdown fournit également une façon alternative de marquer les h1 et h2
+-->
+
+Ceci est un h1
+=============
+
+Ceci est un h2
+-------------
+
+<!-- Styles basiques pour du texte -->
+<!-- On peut facilement rendre un texte "gras" ou "italique" en Markdown -->
+
+*Ce texte est en italique.*
+_Celui-ci aussi._
+
+**Ce texte est en gras.**
+__Celui-là aussi.__
+
+***Ce texte a les deux styles.***
+**_Pareil ici_**
+*__Et là!__*
+
+<!-- Dans le "Github Flavored Markdown", utilisé pour interpréter le Markdown
+sur Github, on a également le strikethrough ( texte barré ) : -->
+
+~~Ce texte est barré avec strikethrough.~~
+
+<!-- Les Paragraphes sont représentés par une ou plusieurs lignes de texte
+séparées par une ou plusieurs lignes vides. -->
+
+Ceci est un paragraphe. Là, je suis dans un paragraphe, facile non?
+
+Maintenant je suis dans le paragraphe 2.
+Je suis toujours dans le paragraphe 2!
+
+
+Puis là, eh oui, le paragraphe 3!
+
+<!--
+Si jamais vous souhaitez insérer une balise HTML <br />, vous pouvez ajouter
+un ou plusieurs espaces à la fin de votre paragraphe, et en commencer
+un nouveau.
+-->
+
+J'ai deux espaces vides à la fin (sélectionnez moi pour les voir).
+
+Bigre, il y a un <br /> au dessus de moi!
+
+<!-- Les 'Blocs de Citations' sont générés aisément, grâce au caractère > -->
+
+> Ceci est une superbe citation. Vous pouvez même
+> revenir à la ligne quand ça vous chante, et placer un `>`
+> devant chaque bout de ligne faisant partie
+> de la citation.
+> La taille ne compte pas^^ tant que chaque ligne commence par un `>`.
+
+> Vous pouvez aussi utiliser plus d'un niveau
+>> d'imbrication!
+> Classe et facile, pas vrai?
+
+<!-- les Listes -->
+<!-- les Listes non ordonnées sont marquées par des asterisques,
+signes plus ou signes moins. -->
+
+* Item
+* Item
+* Un autre item
+
+ou
+
++ Item
++ Item
++ Encore un item
+
+ou
+
+- Item
+- Item
+- Un dernier item
+
+<!-- les Listes Ordonnées sont générées via un nombre suivi d'un point -->
+
+1. Item un
+2. Item deux
+3. Item trois
+
+<!-- Vous pouvez même vous passer de tout numéroter, et Markdown générera
+les bons chiffres. Ceci dit, cette variante perd en clarté.-->
+
+1. Item un
+1. Item deux
+1. Item trois
+<!-- ( cette liste sera interprétée de la même façon que celle au dessus ) -->
+
+<!-- Vous pouvez également utiliser des sous-listes -->
+
+1. Item un
+2. Item deux
+3. Item trois
+* Sub-item
+* Sub-item
+4. Item quatre
+
+<!-- Il y a même des "listes de Taches". Elles génèrent des champs HTML
+de type checkbox. -->
+
+Les [ ] ci dessous, n'ayant pas de [ x ],
+deviendront des cases à cocher HTML non-cochées.
+
+- [ ] Première tache à réaliser.
+- [ ] Une autre chose à faire.
+La case suivante sera une case à cocher HTML cochée.
+- [x] Ça ... c'est fait!
+
+<!-- les Blocs de Code -->
+<!-- Pour marquer du texte comme étant du code, il suffit de commencer
+chaque ligne en tapant 4 espaces (ou un Tab) -->
+
+ echo "Ça, c'est du Code!";
+ var Ça = "aussi !";
+
+<!-- L'indentation par tab ou série de quatre espaces
+fonctionne aussi à l'intérieur du bloc de code -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Des bouts de code en mode 'inline' s'ajoutent en les entourant de ` -->
+
+La fonction `run()` ne vous oblige pas à aller courir!
+
+<!-- Via Github Flavored Markdown, vous pouvez utiliser
+des syntaxes spécifiques -->
+
+\`\`\`ruby
+<!-- mais enlevez les backslashes quand vous faites ça,
+gardez juste ```ruby ( ou nom de la synatxe correspondant à votre code )-->
+def foobar
+puts "Hello world!"
+end
+\`\`\` <!-- pareil, pas de backslashes, juste ``` en guise de fin -->
+
+<-- Pas besoin d'indentation pour le code juste au dessus, de plus, Github
+va utiliser une coloration syntaxique pour le langage indiqué après les ``` -->
+
+<!-- Ligne Horizontale (<hr />) -->
+<!-- Pour en insérer une, utilisez trois ou plusieurs astérisques ou tirets,
+avec ou sans espaces entre chaque un. -->
+
+***
+---
+- - -
+****************
+
+<!-- Liens -->
+<!-- Une des fonctionnalités sympathiques du Markdown est la facilité
+d'ajouter des liens. Le texte du lien entre [ ], l'url entre ( ),
+et voilà l'travail.
+-->
+
+[Clic moi!](http://test.com/)
+
+<!--
+Pour ajouter un attribut Title, collez le entre guillemets, avec le lien.
+-->
+
+[Clic moi!](http://test.com/ "Lien vers Test.com")
+
+<!-- les Liens Relatifs marchent aussi -->
+
+[En avant la musique](/music/).
+
+<!-- Les liens façon "références" sont eux aussi disponibles en Markdown -->
+
+[Cliquez ici][link1] pour plus d'information!
+[Regardez aussi par ici][foobar] si vous voulez.
+
+[link1]: http://test.com/ "Cool!"
+[foobar]: http://foobar.biz/ "Alright!"
+
+<!-- Le titre peut aussi être entouré de guillemets simples,
+entre parenthèses ou absent. Les références peuvent être placées
+un peu où vous voulez dans le document, et les identifiants
+(link1, foobar, ...) quoi que ce soit tant qu'ils sont uniques -->
+
+<!-- Il y a également le "nommage implicite" qui transforme le texte du lien
+ en identifiant -->
+
+[Ceci][] est un lien.
+
+[ceci]: http://ceciestunlien.com/
+
+<!-- mais ce n'est pas beaucoup utilisé. -->
+
+<!-- Images -->
+<!-- Pour les images, la syntaxe est identique aux liens, sauf que précédée
+ d'un point d'exclamation! -->
+
+![Attribut ALT de l'image](http://imgur.com/monimage.jpg "Titre optionnel")
+
+<!-- Là aussi, on peut utiliser le mode "références" -->
+
+![Ceci est l'attribut ALT de l'image][monimage]
+
+[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
+
+<!-- Divers -->
+<!-- Liens Automatiques -->
+
+<http://testwebsite.com/> est équivalent à :
+[http://testwebsite.com/](http://testwebsite.com/)
+
+<!-- Liens Automatiques pour emails -->
+
+<foo@bar.com>
+
+<!-- Escaping -->
+Il suffit de précéder les caractères spécifiques à ignorer par des backslash \
+
+Pour taper *ce texte* entouré d'astérisques mais pas en italique :
+Tapez \*ce texte\*.
+
+<!-- Tableaux -->
+<!-- les Tableaux ne sont disponibles que dans le Github Flavored Markdown
+ et c'est ce n'est pas super agréable d'utilisation.
+ Mais si vous en avez besoin :
+ -->
+
+| Col1 | Col2 | Col3 |
+| :----------- | :------: | ------------: |
+| Alignement Gauche | Centé | Alignement Droite |
+| bla | bla | bla |
+
+<!-- ou bien, pour un résultat équivalent : -->
+
+Col 1 | Col2 | Col3
+:-- | :-: | --:
+Ough que c'est moche | svp | arrêtez
+
+<!-- Fin! -->
+
+```
+
+Pour plus d'information :
+ consultez [ici](http://daringfireball.net/projects/markdown/syntax) le post officiel de Jhon Gruber à propos de la syntaxe,
+ et [là](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) la superbe cheatsheet de Adam Pritchard.
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/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown
index da562138..a43edf16 100644
--- a/fr-fr/scala.html.markdown
+++ b/fr-fr/scala.html.markdown
@@ -1,12 +1,11 @@
---
language: Scala
-filename: learnscala.scala
contributors:
- ["George Petrov", "http://github.com/petrovg"]
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
translators:
- - ["Anne-Catherine Dehier", "https://github.com/spellart"]
-filename: learn.scala
+ - ["Anne-Catherine Dehier", "https://github.com/spellart"]
+filename: learnscala-fr.scala
lang: fr-fr
---
diff --git a/fr-fr/xml-fr.html.markdown b/fr-fr/xml-fr.html.markdown
new file mode 100644
index 00000000..ed5f55ff
--- /dev/null
+++ b/fr-fr/xml-fr.html.markdown
@@ -0,0 +1,128 @@
+---
+language: xml
+contributors:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+translators:
+ - ["Geoffrey Liu", "https://github.com/g-liu"]
+filename: learnxml-fr.xml
+lang: fr-fr
+---
+
+XML est un langage de balisage conçu pour stocker et transporter les informations.
+
+Contrairement à HTML, XML ne spécifie pas comment afficher ou formater les informations, juste comment les porter.
+
+* La syntaxe XML
+
+```xml
+<!-- Les commentaires en XML ressemblent ceci -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<librairie>
+ <livre categorie="CUISINE">
+ <titre lang="en">Everyday Italian</titre>
+ <auteur>Giada De Laurentiis</auteur>
+ <an>2005</an>
+ <prix>30.00</prix>
+ </livre>
+ <livre categorie="ENFANTS">
+ <titre lang="en">Harry Potter</titre>
+ <auteur>J. K. Rowling</auteur>
+ <an>2005</an>
+ <prix>29.99</prix>
+ </livre>
+ <livre categorie="WEB">
+ <titre lang="en">Learning XML</titre>
+ <auteur>Erik T. Ray</auteur>
+ <an>2003</an>
+ <prix>39.95</prix>
+ </livre>
+</librairie>
+
+<!-- Ce qui suit est un fichier XML typique.
+ Il commence par une déclaration, qui informe certaines métadonnées (en option).
+
+XML utilise une structure arborescente. Ci-dessus, le nœud racine est «librairie», qui a
+   trois nœuds enfants, qui sont appelés «livres». Ces nœuds ont plus de nœuds enfants, et ainsi de suite ...
+
+On crée les nœuds avec des balises d'ouverture / fermeture, et les enfants sont les nœuds juste entre
+   les balises d'ouverture et de fermeture. -->
+
+
+<!-- XML porte deux types d'informations:
+ 1 - Les attributs -> les métadonnées sur un nœud.
+ Habituellement, l'analyseur XML utilise cette information pour bien stocker les données.
+ 2 - Les éléments -> les informations pures.
+ C'est ce que l'analyseur retrouvera du fichier XML.
+ Les éléments apparaissent entre les balises d'ouverture et de fermeture, sans parenthèses. -->
+
+
+<!-- Ci-dessous, un élément avec deux attributs -->
+<fichier type="gif" id="4293">ordinateur.gif</fichier>
+
+
+```
+
+* Un document bien formaté & le validation
+
+Un document XML est bien formaté s'il est syntaxiquement correct.
+Cependant, il est possible d'injecter plus de contraintes dans le document,
+en utilisant les définitions de documents, tels que les schémas DTD et XML.
+
+Un document XML qui suit une définition de document est dit valide,
+en ce qui concerne ce document.
+
+Avec cet outil, vous pouvez vérifier les données XML en dehors de la logique de l'application.
+
+```xml
+
+<!-- Ci-dessous, vous pouvez voir une version simplifiée du document de librairie,
+   avec l'addition de définition DTD. -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE note SYSTEM "Librairie.dtd">
+<librairie>
+ <livre categorie="CUISINE">
+ <titre>Everyday Italian</titre>
+ <prix>30.00</prix>
+ </livre>
+</librairie>
+
+<!-- Cette DTD pourrait être quelque chose comme: -->
+
+<!DOCTYPE note
+[
+<!ELEMENT librairie (livre+)>
+<!ELEMENT livre (titre,prix)>
+<!ATTLIST livre categorie CDATA "Littérature">
+<!ELEMENT titre (#PCDATA)>
+<!ELEMENT prix (#PCDATA)>
+]>
+
+<!-- La DTD commence par une déclaration.
+   Après, le nœud racine est déclaré, qui exige un ou plusieurs nœuds enfants.
+   Chaque «livre» doit contenir exactement un «titre» et «prix» et un attribut
+   appelé «catégorie», avec «littérature» comme valeur par défaut.
+   Les nœuds de «titre» et «prix» contiennent des informations de caractère analysés
+ (Anglais: «parsed character data») -->
+
+<!-- La DTD pourrait être déclarée dans le fichier XML lui-même -->
+
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!DOCTYPE note
+[
+<!ELEMENT librairie (livre+)>
+<!ELEMENT livre (titre,prix)>
+<!ATTLIST livre categorie CDATA "Littérature">
+<!ELEMENT titre (#PCDATA)>
+<!ELEMENT prix (#PCDATA)>
+]>
+
+<librairie>
+ <livre categorie="CUISINE">
+ <titre>Everyday Italian</titre>
+ <prix>30.00</prix>
+ </livre>
+</librairie>
+```
diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
new file mode 100644
index 00000000..43b1df54
--- /dev/null
+++ b/fr-fr/yaml-fr.html.markdown
@@ -0,0 +1,157 @@
+---
+language: yaml
+filename: learnyaml.yaml
+contributors:
+ - ["Andrei Curelaru", "http://www.infinidad.fr"]
+lang: fr-fr
+---
+
+Proposé à l'origine par Clark Evans en Mai 2001, YAML est un un format de
+représentation de données par sérialisation, conçu pour être aisément
+éditable et lisible par nous même, les humains.
+
+YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le découvre, plus lisible et clair que le CSV, et emprunte beaucoup au JSON dont il est un parent naturel. Toutefois, YAML emprunte également des idées et concepts de chez Python, et s'intègre bien avec bon nombre de langages.
+
+
+```yaml
+# les Commentaires sont précédés d'un signe "#", comme cette ligne.
+
+#############
+# SCALAIRES #
+#############
+
+# Les scalaires sont l'ensemble des types YAML qui ne sont pas des collections
+# ( listes ou tableaux associatifs ).
+
+# Notre objet root ( racine ), sera une map ( carte ) et englobera
+# l'intégralité du document. Cette map est l'équivalent d'un dictionnaire,
+# hash ou objet dans d'autres langages.
+clé: valeur
+aurtre_clé: une autre valeur
+valeur_numérique: 100
+notation_scientifique: 1e+12
+boolean: true
+valeur_null: null
+clé avec espaces: valeur
+# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
+# entre guillemets, cela reste possible, et parfois utile.
+toutefois: "Une chaîne, peut être contenue entre guillemets."
+"Une clé entre guillemets.": "Utile si on veut utiliser ':' dans la clé."
+
+# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
+# comme un 'bloc littéral' ( avec | ) ou bien 'bloc replié' avec ( > ).
+bloc_littéral: |
+ Tout ce bloc de texte sera la valeur de la clé 'bloc_littéral',
+ avec préservation des retours à la ligne. ( chaque ligne vide à
+ l'intérieur du même bloc, sera remplacée par "\n\n" )
+
+ Le littéral continue jusqu'à ce que l'indentation soit annulée.
+
+ Toutes lignes qui serait "d'avantage indentées" conservent leur
+ indentation, constituée de 4 espaces.
+bloc_replié: >
+ Tout ce bloc de texte sera la valeur de la clé 'bloc_replié', mais
+ cette fois ci, toutes les nouvelles lignes deviendront un simple espace.
+
+ Les lignes vides, comme ci-dessus, seront converties en caractère "\n".
+
+ Les lignes 'plus-indentées' gardent leurs retours à la ligne -
+ ce texte apparaîtra sur deux lignes.
+
+###############
+# COLLECTIONS #
+###############
+
+# l'Imbrication est créée par indentation.
+une_map_imbriquée:
+ clé: valeur
+ autre_clé: autre valeur
+ autre_map_imbriquée:
+ bonjour: bonjour
+
+# les Clés des Maps ne sont pas nécessairement des chaînes de caractères.
+0.25: une clé de type float
+
+# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
+# en utilisant le signe "?" pour indiquer le début de la clé.
+? |
+ ceci est une Clé
+ sur de multiples lignes
+: et ceci est sa Valeur
+
+# YAML autorise aussi l'usage des collections à l'intérieur des clés,
+# mais certains langages de programmation ne le tolère pas si bien.
+
+# les Séquences (équivalent des listes ou tableaux) ressemblent à cela:
+une_séquence:
+ - Item 1
+ - Item 2
+ - 0.5 # les séquences peuvent contenir des types variés.
+ - Item 4
+ - clé: valeur
+ autre_clé: autre_valeur
+ -
+ - Ceci est une séquence
+ - dans une autre séquence
+
+# YAML étant un proche parent de JSON, vous pouvez écrire directement
+# des maps et séquences façon JSON
+json_map: {"clé": "valeur"}
+json_seq: [1, 2, 3, "soleil"]
+
+#################################
+# AUTRES FONCTIONNALITÉES YAML #
+#################################
+
+# YAML possède une fonctionnalité fort utile nommée 'ancres'. Celle-ci
+# vous permet de dupliquer aisément du contenu au sein de votre document.
+
+# Les deux clés suivantes auront la même valeur:
+contenu_ancré: &nom_ancre Cette chaîne sera la valeur des deux clés.
+autre_ancre: *nom_ancre
+
+# Avec les Tags YAML, vous pouvez explicitement déclarer des types de données.
+chaine_explicite: !!str 0.5
+
+# Certains parsers implémentent des tags spécifiques à d'autres langages,
+# comme par exemple le "complex number" de Python.
+python_complex_number: !!python/complex 1+2j
+
+#####################
+# AUTRES TYPES YAML #
+#####################
+
+# YAML interprète également les données formatées ISO de type date et datetime,
+# pas seulement les chaînes et nombres.
+datetime: 2001-12-15T02:59:43.1Z
+datetime_avec_espaces: 2001-12-14 21:59:43.10 -5
+date: 2002-12-14
+
+# Le tag !!binary indique que la chaîne à suivre est la représentation binaire
+# d'un blob encodé en base64. En clair ? Une image !
+fichier_gif: !!binary |
+ R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
+ OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+ +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
+ AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
+
+# YAML a de même un type "set", qui ressemble à cela:
+set:
+ ? item1
+ ? item2
+ ? item3
+
+# Comme dans Python, les sets ne sont que des maps contenant des valeurs null ;
+# le set précédent est l'équivalent du suivant:
+set2:
+ item1: null
+ item2: null
+ item3: null
+
+```
+
+Quelques références et outils :
+
+- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
+- Une [Introduction à YAML](http://sweetohm.net/html/introduction-yaml.html) très bien construite et claire,
+- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
diff --git a/git.html.markdown b/git.html.markdown
index 618d1906..04350dd5 100644
--- a/git.html.markdown
+++ b/git.html.markdown
@@ -3,6 +3,8 @@ category: tool
tool: git
contributors:
- ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Leo Rudberg" , "http://github.com/LOZORD"]
+ - ["Betsy Lorton" , "http://github.com/schbetsy"]
filename: LearnGit.txt
---
@@ -334,6 +336,66 @@ $ git push -u origin master
$ git push
```
+### stash
+
+Stashing takes the dirty state of your working directory and saves it on a stack of unfinished changes that you can reapply at any time.
+
+Let's say you've been doing some work in your git repo, but you want to pull from the remote.
+Since you have dirty (uncommited) changes to some files, you are not able to run `git pull`.
+Instead, you can run `git stash` to save your changes onto a stack!
+
+```bash
+$ git stash
+Saved working directory and index state \
+ "WIP on master: 049d078 added the index file"
+ HEAD is now at 049d078 added the index file
+ (To restore them type "git stash apply")
+```
+
+Now you can pull!
+
+```bash
+git pull
+```
+`...changes apply...`
+
+Now check that everything is OK
+
+```bash
+$ git status
+# On branch master
+nothing to commit, working directory clean
+```
+
+You can see what "hunks" you've stashed so far using `git stash list`.
+Since the "hunks" are stored in a Last-In-First-Out stack, our most recent change will be at top.
+
+```bash
+$ git stash list
+stash@{0}: WIP on master: 049d078 added the index file
+stash@{1}: WIP on master: c264051 Revert "added file_size"
+stash@{2}: WIP on master: 21d80a5 added number to log
+```
+
+Now let's apply our dirty changes back by popping them off the stack.
+
+```bash
+$ git stash pop
+# On branch master
+# Changes not staged for commit:
+# (use "git add <file>..." to update what will be committed)
+#
+# modified: index.html
+# modified: lib/simplegit.rb
+#
+```
+
+`git stash apply` does the same thing
+
+Now you're ready to get back to work on your stuff!
+
+[Additional Reading.](http://git-scm.com/book/en/v1/Git-Tools-Stashing)
+
### rebase (caution)
Take all changes that were committed on one branch, and replay them onto another branch.
@@ -396,4 +458,4 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [GitGuys](http://www.gitguys.com/)
-* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) \ No newline at end of file
+* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
diff --git a/go.html.markdown b/go.html.markdown
index a1be08af..17f10bd9 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.
@@ -72,13 +72,13 @@ func learnMultiple(x, y int) (sum, prod int) {
// Some built-in types and literals.
func learnTypes() {
// Short declaration usually gives you what you want.
- s := "Learn Go!" // string type.
+ str := "Learn Go!" // string type.
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.
@@ -111,7 +126,7 @@ can include line breaks.` // Same string type.
// Unused variables are an error in Go.
// The underbar lets you "use" a variable but discard its value.
- _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs
+ _, _, _, _, _, _, _, _, _, _ = str, s2, g, f, u, pi, n, a3, s4, bs
// Output of course counts as using a variable.
fmt.Println(s, c, a4, s3, d2, m)
@@ -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.
@@ -177,6 +192,14 @@ func learnFlowControl() {
break // Just kidding.
continue // Unreached.
}
+
+ // You can use range to iterate over an array, a slice, a string, a map, or a channel.
+ // range returns one (channel) or two values (array, slice, string and map).
+ for key, value := range map[string]int{"one": 1, "two": 2, "three": 3} {
+ // for each pair in the map, print key and value
+ fmt.Printf("key=%s, value=%d\n", key, value)
+ }
+
// As with for, := in an if statement means to declare and assign
// y first, then test y > x.
if y := expensiveComputation(); y > x {
@@ -198,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
@@ -245,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.
@@ -253,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
@@ -297,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()
}
@@ -308,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)
@@ -326,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,
@@ -336,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.
@@ -375,13 +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/haml.html.markdown b/haml.html.markdown
new file mode 100644
index 00000000..aed3dcae
--- /dev/null
+++ b/haml.html.markdown
@@ -0,0 +1,155 @@
+---
+language: haml
+filename: learnhaml.haml
+contributors:
+ - ["Simon Neveu", "https://github.com/sneveu"]
+---
+
+Haml is a markup language predominantly used with Ruby that cleanly and simply describes the HTML of any web document without the use of inline code. It is a popular alternative to using Rails templating language (.erb) and allows you to embed Ruby code into your markup.
+
+It aims to reduce repetition in your markup by closing tags for you based on the structure of the indents in your code. The result is markup that is well-structured, DRY, logical, and easier to read.
+
+You can also use Haml on a project independent of Ruby, by installing the Haml gem on your machine and using the command line to convert it to html.
+
+$ haml input_file.haml output_file.html
+
+
+```haml
+/ -------------------------------------------
+/ Indenting
+/ -------------------------------------------
+
+/
+ Because of the importance indentation has on how your code is rendered, the
+ indents should be consistent throughout the document. Any differences in
+ indentation will throw an error. It's common-practice to use two spaces,
+ but it's really up to you, as long as they're constant.
+
+
+/ -------------------------------------------
+/ Comments
+/ -------------------------------------------
+
+/ This is what a comment looks like in Haml.
+
+/
+ To write a multi line comment, indent your commented code to be
+ wrapped by the forward slash
+
+-# This is a silent comment, which means it wont be rendered into the doc at all
+
+
+/ -------------------------------------------
+/ Html elements
+/ -------------------------------------------
+
+/ To write your tags, use the percent sign followed by the name of the tag
+%body
+ %header
+ %nav
+
+/ Notice no closing tags. The above code would output
+ <body>
+ <header>
+ <nav></nav>
+ </header>
+ </body>
+
+/ The div tag is the default element, so they can be written simply like this
+.foo
+
+/ To add content to a tag, add the text directly after the declaration
+%h1 Headline copy
+
+/ To write multiline content, nest it instead
+%p
+ This is a lot of content that we could probably split onto two
+ separate lines.
+
+/
+ You can escape html by using the ampersand and equals sign ( &= ). This
+ converts html-sensitive characters (&, /, :) into their html encoded
+ equivalents. For example
+
+%p
+ &= "Yes & yes"
+
+/ would output 'Yes &amp; yes'
+
+/ You can unescape html by using the bang and equals sign ( != )
+%p
+ != "This is how you write a paragraph tag <p></p>"
+
+/ which would output 'This is how you write a paragraph tag <p></p>'
+
+/ CSS classes can be added to your tags either by chaining .classnames to the tag
+%div.foo.bar
+
+/ or as part of a Ruby hash
+%div{:class => 'foo bar'}
+
+/ Attributes for any tag can be added in the hash
+%a{:href => '#', :class => 'bar', :title => 'Bar'}
+
+/ For boolean attributes assign the value 'true'
+%input{:selected => true}
+
+/ To write data-attributes, use the :data key with its value as another hash
+%div{:data => {:attribute => 'foo'}}
+
+
+/ -------------------------------------------
+/ Inserting Ruby
+/ -------------------------------------------
+
+/
+ To output a Ruby value as the contents of a tag, use an equals sign followed
+ by the Ruby code
+
+%h1= book.name
+
+%p
+ = book.author
+ = book.publisher
+
+
+/ To run some Ruby code without rendering it to the html, use a hyphen instead
+- books = ['book 1', 'book 2', 'book 3']
+
+/ Allowing you to do all sorts of awesome, like Ruby blocks
+- books.shuffle.each_with_index do |book, index|
+ %h1= book
+
+ if book do
+ %p This is a book
+
+/
+ Again, no need to add the closing tags to the block, even for the Ruby.
+ Indentation will take care of that for you.
+
+
+/ -------------------------------------------
+/ Inline Ruby / Ruby interpolation
+/ -------------------------------------------
+
+/ Include a Ruby variable in a line of plain text using #{}
+%p Your highest scoring game is #{best_game}
+
+
+/ -------------------------------------------
+/ Filters
+/ -------------------------------------------
+
+/
+ Use the colon to define Haml filters, one example of a filter you can
+ use is :javascript, which can be used for writing inline js
+
+:javascript
+ console.log('This is inline <script>');
+
+```
+
+## Additional resources
+
+- [What is HAML?](http://haml.info/) - A good introduction that does a much better job of explaining the benefits of using HAML.
+- [Official Docs](http://haml.info/docs/yardoc/file.REFERENCE.html) - If you'd like to go a little deeper.
diff --git a/haskell.html.markdown b/haskell.html.markdown
index e0489710..748a29da 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
contributors:
- ["Adit Bhargava", "http://adit.io"]
---
@@ -110,7 +110,7 @@ last [1..5] -- 5
-- A tuple:
("haskell", 1)
--- accessing elements of a tuple
+-- accessing elements of a pair (i.e. a tuple of length 2)
fst ("haskell", 1) -- "haskell"
snd ("haskell", 1) -- 1
@@ -171,8 +171,8 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15
-- 4. More functions
----------------------------------------------------
--- currying: if you don't pass in all the arguments to a function,
--- it gets "curried". That means it returns a function that takes the
+-- partial application: if you don't pass in all the arguments to a function,
+-- it gets "partially applied". That means it returns a function that takes the
-- rest of the arguments.
add a b = a + b
@@ -195,8 +195,8 @@ foo 5 -- 75
-- fixing precedence
-- Haskell has another function called `$`. This changes the precedence
-- so that everything to the left of it gets computed first and then applied
--- to everything on the right. You can use `.` and `$` to get rid of a lot
--- of parentheses:
+-- to everything on the right. You can use `$` (often in combination with `.`)
+-- to get rid of a lot of parentheses:
-- before
(even (fib 7)) -- true
@@ -204,6 +204,9 @@ foo 5 -- 75
-- after
even . fib $ 7 -- true
+-- equivalently
+even $ fib 7 -- true
+
----------------------------------------------------
-- 5. Type signatures
----------------------------------------------------
@@ -227,24 +230,24 @@ double :: Integer -> Integer
double x = x * 2
----------------------------------------------------
--- 6. Control Flow and If Statements
+-- 6. Control Flow and If Expressions
----------------------------------------------------
--- if statements
+-- if expressions
haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome"
--- if statements can be on multiple lines too, indentation is important
+-- if expressions can be on multiple lines too, indentation is important
haskell = if 1 == 1
then "awesome"
else "awful"
--- case statements: Here's how you could parse command line arguments
+-- case expressions: Here's how you could parse command line arguments
case args of
"help" -> printHelp
"start" -> startProgram
_ -> putStrLn "bad args"
--- Haskell doesn't have loops because it uses recursion instead.
+-- Haskell doesn't have loops; it uses recursion instead.
-- map applies a function over every element in an array
map (*2) [1..5] -- [2, 4, 6, 8, 10]
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..f08c4679 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];
@@ -123,9 +123,15 @@ public class LearnJava {
// Others to check out
// ArrayLists - Like arrays except more functionality is offered,
// and the size is mutable
- // LinkedLists
- // Maps
- // HashMaps
+ // LinkedLists - Implementation of doubly-linked list. All of the
+ // operations perform as could be expected for
+ // a doubly-linked list.
+ // Maps - A set of objects that maps keys to values. A map cannot contain
+ // duplicate keys; each key can map to at most one value.
+ // HashMaps - This class uses a hashtable to implement the Map interface.
+ // This allows the execution time of basic operations,
+ // such as get and insert element, to remain constant even
+ // for large sets.
///////////////////////////////////////
// Operators
diff --git a/javascript.html.markdown b/javascript.html.markdown
index c59a90c3..aabd5e43 100644
--- a/javascript.html.markdown
+++ b/javascript.html.markdown
@@ -39,13 +39,14 @@ doStuff()
// 1. Numbers, Strings and Operators
// JavaScript has one number type (which is a 64-bit IEEE 754 double).
-// As with Lua, don't freak out about the lack of ints: doubles have a 52-bit
-// mantissa, which is enough to store integers up to about 9✕10¹⁵ precisely.
+// Doubles have a 52-bit mantissa, which is enough to store integers
+// up to about 9✕10¹⁵ precisely.
3; // = 3
1.5; // = 1.5
-// All the basic arithmetic works as you'd expect.
+// Some basic arithmetic works as you'd expect.
1 + 1; // = 2
+0.1 + 0.2; // = 0.30000000000000004
8 - 1; // = 7
10 * 2; // = 20
35 / 5; // = 7
@@ -77,13 +78,13 @@ false;
!true; // = false
!false; // = true
-// Equality is ==
-1 == 1; // = true
-2 == 1; // = false
+// Equality is ===
+1 === 1; // = true
+2 === 1; // = false
-// Inequality is !=
-1 != 1; // = false
-2 != 1; // = true
+// Inequality is !==
+1 !== 1; // = false
+2 !== 1; // = true
// More comparisons
1 < 10; // = true
@@ -97,11 +98,17 @@ false;
// and are compared with < and >
"a" < "b"; // = true
-// Type coercion is performed for comparisons...
+// Type coercion is performed for comparisons with double equals...
"5" == 5; // = true
+null == undefined; // = true
// ...unless you use ===
"5" === 5; // = false
+null === undefined; // = false
+
+// ...which can result in some weird behaviour...
+13 + !0; // 14
+"13" + !0; // '13true'
// You can access characters in a string with charAt
"This is a string".charAt(0); // = 'T'
@@ -460,8 +467,8 @@ var myNumberObj = new Number(12);
myNumber == myNumberObj; // = true
// Except, they aren't exactly equivalent.
-typeof(myNumber); // = 'number'
-typeof(myNumberObj); // = 'object'
+typeof myNumber; // = 'number'
+typeof myNumberObj; // = 'object'
myNumber === myNumberObj; // = false
if (0){
// This code won't execute, because 0 is falsy.
diff --git a/json.html.markdown b/json.html.markdown
index 9041eaa2..f5287138 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -17,7 +17,7 @@ going to be 100% valid JSON. Luckily, it kind of speaks for itself.
{
"key": "value",
- "keys": "must always be enclosed in quotes (either double or single)",
+ "keys": "must always be enclosed in double quotes",
"numbers": 0,
"strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".",
"has bools?": true,
diff --git a/julia.html.markdown b/julia.html.markdown
index e9d3a162..3a52018c 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -1,5 +1,5 @@
---
-language: julia
+language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
filename: learnjulia.jl
@@ -12,7 +12,7 @@ This is based on the current development version of Julia, as of October 18th, 2
```ruby
-# Single line comments start with a number symbol.
+# Single line comments start with a hash (pound) symbol.
#= Multiline comments can be written
by putting '#=' before the text and '=#'
after the text. They can also be nested.
@@ -125,8 +125,9 @@ SomeOtherVar123! = 6 # => 6
# A note on naming conventions in Julia:
#
-# * Names of variables are in lower case, with word separation indicated by
-# underscores ('\_').
+# * Word separation can be indicated by underscores ('_'), but use of
+# underscores is discouraged unless the name would be hard to read
+# otherwise.
#
# * Names of Types begin with a capital letter and word separation is shown
# with CamelCase instead of underscores.
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/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown
index f651fbe7..4ca3bb5c 100644
--- a/ko-kr/javascript-kr.html.markdown
+++ b/ko-kr/javascript-kr.html.markdown
@@ -381,8 +381,8 @@ var myNumberObj = new Number(12)
myNumber == myNumberObj // = true
// 하지만 정확히 같지는 않습니다.
-typeof(myNumber) // = 'number'
-typeof(myNumberObj) // = 'object'
+typeof myNumber // = 'number'
+typeof myNumberObj // = 'object'
myNumber === myNumberObj // = false
if (0){
// 0은 거짓이라서 이 코드는 실행되지 않습니다.
diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown
index 850587a0..b4a018ef 100644
--- a/ko-kr/lua-kr.html.markdown
+++ b/ko-kr/lua-kr.html.markdown
@@ -1,5 +1,5 @@
---
-language: lua
+language: Lua
category: language
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
diff --git a/ko-kr/php-kr.html.markdown b/ko-kr/php-kr.html.markdown
index 80f324f3..1f53221f 100644
--- a/ko-kr/php-kr.html.markdown
+++ b/ko-kr/php-kr.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
category: language
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
diff --git a/lua.html.markdown b/lua.html.markdown
index be9f3141..0809215f 100644
--- a/lua.html.markdown
+++ b/lua.html.markdown
@@ -1,5 +1,5 @@
---
-language: lua
+language: Lua
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
filename: learnlua.lua
diff --git a/markdown.html.markdown b/markdown.html.markdown
index 9a863bac..7541f904 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.~~
@@ -126,6 +126,14 @@ render the numbers in order, but this may not be a good idea -->
* Sub-item
4. Item four
+<!-- There are even task lists. This creates HTML checkboxes. -->
+
+Boxes below without the 'x' are unchecked HTML checkboxes.
+- [ ] First task to complete.
+- [ ] Second task that needs done
+This checkbox below will be a checked HTML checkbox.
+- [x] This task has been completed
+
<!-- Code blocks -->
<!-- You can indicate a code block (which uses the <code> element) by indenting
a line with four spaces or a tab -->
@@ -201,11 +209,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..9de41275 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -15,10 +15,12 @@ If you have any feedback please feel free to reach me at
```matlab
% Comments start with a percent sign.
-%{ Multi line comments look
+%{
+Multi line comments look
something
like
-this %}
+this
+%}
% commands can span multiple lines, using '...':
a = 1 + 2 + ...
@@ -40,36 +42,41 @@ ctrl-c % Abort current computation
edit('myfunction.m') % Open function/script in editor
type('myfunction.m') % Print the source of function/script to Command Window
-profile viewer % Open profiler
+profile on % turns on the code profiler
+profile of % turns off the code profiler
+profile viewer % Open profiler
-help command % Displays documentation for command in Command Window
-doc command % Displays documentation for command in Help Window
-lookfor command % Searches for a given command
+help command % Displays documentation for command in Command Window
+doc command % Displays documentation for command in Help Window
+lookfor command % Searches for command in the first commented line of all functions
+lookfor command -all % searches for command in all functions
% Output formatting
-format short % 4 decimals in a floating number
-format long % 15 decimals
-format bank % only two digits after decimal point - for financial calculations
-fprintf
+format short % 4 decimals in a floating number
+format long % 15 decimals
+format bank % only two digits after decimal point - for financial calculations
+fprintf('text') % print "text" to the screen
+disp('text') % print "text" to the screen
% Variables & Expressions
-myVariable = 4 % Notice Workspace pane shows newly created variable
+myVariable = 4 % Notice Workspace pane shows newly created variable
myVariable = 4; % Semi colon suppresses output to the Command Window
-4 + 6 % ans = 10
-8 * myVariable % ans = 32
-2 ^ 3 % ans = 8
+4 + 6 % ans = 10
+8 * myVariable % ans = 32
+2 ^ 3 % ans = 8
a = 2; b = 3;
c = exp(a)*sin(pi/2) % c = 7.3891
% Calling functions can be done in either of two ways:
% Standard function syntax:
-load('myFile.mat', 'y')
+load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
% Command syntax:
-load myFile.mat y % no parentheses, and spaces instead of commas
+load myFile.mat y % no parentheses, and spaces instead of commas
% Note the lack of quote marks in command form: inputs are always passed as
% literal text - cannot pass variable values. Also, can't receive output:
-[V,D] = eig(A) % this has no equivalent in command form
+[V,D] = eig(A); % this has no equivalent in command form
+[~,D] = eig(A); % if you only want D and not V
@@ -85,7 +92,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
@@ -100,6 +107,10 @@ a = {'one', 'two', 'three'}
a(1) % ans = 'one' - returns a cell
char(a(1)) % ans = one - returns a string
+% Structures
+A.b = {'one','two'};
+A.c = [1 2];
+A.d.e = false;
% Vectors
x = [4 32 53 7 1]
@@ -160,6 +171,10 @@ A(1,:) % All columns in row 1
% 4 5 42
% 7 8 9
+% this is the same as
+vertcat(A,A);
+
+
[A , A] % Concatenation of matrices (horizontally)
%ans =
@@ -168,6 +183,8 @@ A(1,:) % All columns in row 1
% 4 5 42 4 5 42
% 7 8 9 7 8 9
+% this is the same as
+horzcat(A,A);
A(:, [3 1 2]) % Rearrange the columns of original matrix
@@ -180,10 +197,13 @@ A(:, [3 1 2]) % Rearrange the columns of original matrix
size(A) % ans = 3 3
A(1, :) =[] % Delete the first row of the matrix
+A(:, 1) =[] % Delete the first column of the matrix
+transpose(A) % Transpose the matrix, which is the same as:
+A one
ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
-transpose(A) % Transpose the matrix, without taking complex conjugate
+
diff --git a/nim.html.markdown b/nim.html.markdown
new file mode 100644
index 00000000..c74fece7
--- /dev/null
+++ b/nim.html.markdown
@@ -0,0 +1,265 @@
+---
+language: Nim
+filename: learnNim.nim
+contributors:
+ - ["Jason J. Ayala P.", "http://JasonAyala.com"]
+---
+
+Nim (formally Nimrod) is a statically typed, imperative programming language
+that gives the programmer power without compromises on runtime efficiency.
+
+Nim is efficient, expressive, and elegant.
+
+```ruby
+var # Declare (and assign) variables,
+ letter: char = 'n' # with or without type annotations
+ lang = "N" & "im"
+ nLength : int = len(lang)
+ boat: float
+ truth: bool = false
+
+let # Use let to declare and bind variables *once*.
+ legs = 400 # legs is immutable.
+ arms = 2_000 # _ are ignored and are useful for long numbers.
+ aboutPi = 3.15
+
+const # Constants are computed at compile time. This provides
+ debug = true # performance and is useful in compile time expressions.
+ compileBadCode = false
+
+when compileBadCode: # `when` is a compile time `if`
+ legs = legs + 1 # This error will never be compiled.
+ const input = readline(stdin) # Const values must be known at compile time.
+
+discard 1 > 2 # Note: The compiler will complain if the result of an expression
+ # is unused. `discard` bypasses this.
+
+discard """
+This can work as a multiline comment.
+Or for unparsable, broken code
+"""
+
+#
+# Data Structures
+#
+
+# Tuples
+
+var
+ child: tuple[name: string, age: int] # Tuples have *both* field names
+ today: tuple[sun: string, temp: float] # *and* order.
+
+child = (name: "Rudiger", age: 2) # Assign all at once with literal ()
+today.sun = "Overcast" # or individual fields.
+today.temp = 70.1
+
+# Sequences
+
+var
+ drinks: seq[string]
+
+drinks = @["Water", "Juice", "Chocolate"] # @[V1,..,Vn] is the sequence literal
+
+#
+# Defining Types
+#
+
+# Defining your own types puts the compiler to work for you. It's what makes
+# static typing powerful and useful.
+
+type
+ Name = string # A type alias gives you a new type that is interchangable
+ Age = int # with the old type but is more descriptive.
+ Person = tuple[name: Name, age: Age] # Define data structures too.
+ AnotherSyntax = tuple
+ fieldOne: string
+ secondField: int
+
+var
+ john: Person = (name: "John B.", age: 17)
+ newage: int = 18 # It would be better to use Age than int
+
+john.age = newage # But still works because int and Age are synonyms
+
+type
+ Cash = distinct int # `distinct` makes a new type incompatible with its
+ Desc = distinct string # base type.
+
+var
+ money: Cash = 100.Cash # `.Cash` converts the int to our type
+ description: Desc = "Interesting".Desc
+
+when compileBadCode:
+ john.age = money # Error! age is of type int and money is Cash
+ john.name = description # Compiler says: "No way!"
+
+#
+# More Types and Data Structures
+#
+
+# Enumerations allow a type to have one of a limited number of values
+
+type
+ Color = enum cRed, cBlue, cGreen
+ Direction = enum # Alternative formating
+ dNorth
+ dWest
+ dEast
+ dSouth
+var
+ orient = dNorth # `orient` is of type Direction, with the value `dNorth`
+ pixel = cGreen # `pixel` is of type Color, with the value `cGreen`
+
+discard dNorth > dEast # Enums are usually an "ordinal" type
+
+# Subranges specify a limited valid range
+
+type
+ DieFaces = range[1..20] # Only an int from 1 to 20 is a valid value
+var
+ my_roll: DieFaces = 13
+
+when compileBadCode:
+ my_roll = 23 # Error!
+
+# Arrays
+
+type
+ RollCounter = array[DieFaces, int] # Array's are fixed length and
+ DirNames = array[Direction, string] # indexed by any ordinal type.
+ Truths = array[42..44, bool]
+var
+ counter: RollCounter
+ directions: DirNames
+ possible: Truths
+
+possible = [false, false, false] # Literal arrays are created with [V1,..,Vn]
+possible[42] = true
+
+directions[dNorth] = "Ahh. The Great White North!"
+directions[dWest] = "No, don't go there."
+
+my_roll = 13
+counter[my_roll] += 1
+counter[my_roll] += 1
+
+var anotherArray = ["Default index", "starts at", "0"]
+
+# More data structures are available, including tables, sets, lists, queues,
+# and crit bit trees.
+# http://nimrod-lang.org/lib.html#collections-and-algorithms
+
+#
+# IO and Control Flow
+#
+
+# `case`, `readLine()`
+
+echo "Read any good books lately?"
+case readLine(stdin)
+of "no", "No":
+ echo "Go to your local library."
+of "yes", "Yes":
+ echo "Carry on, then."
+else:
+ echo "That's great; I assume."
+
+# `while`, `if`, `continue`, `break`
+
+import strutils as str # http://nimrod-lang.org/strutils.html
+echo "I'm thinking of a number between 41 and 43. Guess which!"
+let number: int = 42
+var
+ raw_guess: string
+ guess: int
+while guess != number:
+ raw_guess = readLine(stdin)
+ if raw_guess == "": continue # Skip this iteration
+ guess = str.parseInt(raw_guess)
+ if guess == 1001:
+ echo("AAAAAAGGG!")
+ break
+ elif guess > number:
+ echo("Nope. Too high.")
+ elif guess < number:
+ echo(guess, " is too low")
+ else:
+ echo("Yeeeeeehaw!")
+
+#
+# Iteration
+#
+
+for i, elem in ["Yes", "No", "Maybe so"]: # Or just `for elem in`
+ echo(elem, " is at index: ", i)
+
+for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]):
+ echo v
+
+let myString = """
+an <example>
+`string` to
+play with
+""" # Multiline raw string
+
+for line in splitLines(myString):
+ echo(line)
+
+for i, c in myString: # Index and letter. Or `for j in` for just letter
+ if i mod 2 == 0: continue # Compact `if` form
+ elif c == 'X': break
+ else: echo(c)
+
+#
+# Procedures
+#
+
+type Answer = enum aYes, aNo
+
+proc ask(question: string): Answer =
+ echo(question, " (y/n)")
+ while true:
+ case readLine(stdin)
+ of "y", "Y", "yes", "Yes":
+ return Answer.aYes # Enums can be qualified
+ of "n", "N", "no", "No":
+ return Answer.aNo
+ else: echo("Please be clear: yes or no")
+
+proc addSugar(amount: int = 2) = # Default amount is 2, returns nothing
+ assert(amount > 0 or amount < 9000, "Crazy Sugar")
+ for a in 1..amount:
+ echo(a, " sugar...")
+
+case ask("Would you like sugar in your tea?")
+of aYes:
+ addSugar(3)
+of aNo:
+ echo "Oh do take a little!"
+ addSugar()
+# No need for an `else` here. Only `yes` and `no` are possible.
+
+#
+# FFI
+#
+
+# Because Nim compiles to C, FFI is easy:
+
+proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.}
+
+let cmp = strcmp("C?", "Easy!")
+```
+
+Additionally, Nim separates itself from its peers with metaprogramming,
+performance, and compile-time features.
+
+## Further Reading
+
+* [Home Page](http://nimrod-lang.org)
+* [Download](http://nimrod-lang.org/download.html)
+* [Community](http://nimrod-lang.org/community.html)
+* [FAQ](http://nimrod-lang.org/question.html)
+* [Documentation](http://nimrod-lang.org/documentation.html)
+* [Manual](http://nimrod-lang.org/manual.html)
+* [Standard Libray](http://nimrod-lang.org/lib.html)
+* [Rosetta Code](http://rosettacode.org/wiki/Category:Nimrod)
diff --git a/nl-nl/brainfuck-nl.html.markdown b/nl-nl/brainfuck-nl.html.markdown
new file mode 100644
index 00000000..cd12b1d0
--- /dev/null
+++ b/nl-nl/brainfuck-nl.html.markdown
@@ -0,0 +1,86 @@
+---
+language: brainfuck
+contributors:
+ - ["Prajit Ramachandran", "http://prajitr.github.io/"]
+ - ["Mathias Bynens", "http://mathiasbynens.be/"]
+translators:
+ - ["Jelle Besseling", "https://github.com/Jell-E"]
+lang: nl-nl
+---
+
+Brainfuck (schrijf je niet met een hoofdletter behalve aan het begin van een
+zin) is een extreem
+minimalistische Turing-complete programmeertaal met maar acht commando's.
+
+```
+Elk karakter behalve "><+-.,[]" (en de quotes) wordt genegeerd.
+
+Brainfuck wordt gerepresenteerd door een array met 30,000 cellen die initieel
+gevuld is met nullen en een pointer die wijst naar de huidige cel.
+
+Dit zijn de acht commando's:
++ : Verhoog de huidige cell met 1.
+- : Verminder de huidige cell met 1.
+> : Beweeg de pointer naar de volgende cell (één naar rechts).
+< : Beweeg de pointer naar de vorige cell (één naar links).
+. : Print de huidige cell als een ASCII karakter(d.w.z. 65 = 'A').
+, : Lees een karakter in de huidige cell.
+[ : Als de huidige cell nul is ga dan naar de bijbehorende ] .
+ Als het geen nul is, ga dan gewoon verder.
+] : Als de huidige cell nul is ga dan gewoon verder.
+ Als het geen nul is, ga dan terug naar de bijbehorende [ .
+
+[ en ] maken een while loop. Ze moeten uiteraard wel gebalanceerd zijn
+
+Laten we een kijkje nemen naar een paar brainfuck programma's.
+
+++++++ [ > ++++++++++ < - ] > +++++ .
+
+Dit programma print het karakter 'A'. Eerst verhoogt het cell #1 tot 6.
+Cell #1 wordt gebruikt om te loopen. Dan begint het de loop ([) en gaat
+naar cell #2. Het verhoogt cell #2 tien keer, gaat terug naar cell #1, en
+verlaagt cell #1. Deze loop gebeurt zes keer (na zes keer staat cell #1
+weer op nul, waarna het doorgaat naar het einde van de loop (]) en
+verder gaat).
+
+De pointer staat nu weer op cell #1, deze heeft een waarde van 0, en cell #2
+heeft een waarde van 60. > beweegt de pointer naar cell #2, daarna verhoogt
+het de cell vijf keer, waardoor het een waarde van 65 bevat, en print dan
+de waarde van cell #2. 65 is 'A' in ASCII, dus 'A' wordt geprint in de terminal.
+
+
+, [ > + < - ] > .
+
+Dit programma leest een karakter van de gebruiker in put en kopieert dat
+karakter in cel #1. Dan start de loop. Ga naar cel #2, verhoog de waarde in
+cel #2, ga terug naar cel #1, en verklein de waarde in cel #1. Dit gaat door
+totdat cel #1 nul is en cel #2 de oude waarde heeft van cell #1. Omdat we
+op cel #1 staan verplaatst > de pointer één naar rechts en . print het
+karakter in cel #2.
+
+Houd wel in gedachten dat de spaties alleen zijn voor leesbaarheid, je kan het
+bovenstaande programma net zo goed schrijven als:
+
+,[>+<-]>.
+
+Probeer maar eens te bedenken wat het volgende programma doet:
+
+,>,< [ > [ >+ >+ << -] >> [- << + >>] <<< -] >>
+
+Dit programma neemt twee getallen als input, en vermenigvuldigt ze.
+
+In het begin leest het twee karakters in cel #1 en #2. Dan start het de
+buitenste loop, met als teller cel #1. Het beweegt naar cel #2, dan start het
+de binnenste loop met als teller cel #2, daar verhoogd het cel #3. Maar
+dan is er een probleem als cel #2 nul wordt aan het einde van de binnenste loop.
+Om dit op te lossen wordt ook cel #4 verhoogd naar het oorspronkelijke getal
+uit cel #2 en daarna wordt cel #4 weer gekopieerd naar cell #2.
+Het resultaat komt in cel #3 te staan.
+```
+
+En dat is dan brainfuck. Niet heel moeilijk, toch? Je kan zelf voor de lol
+brainfuck programma's gaan schrijven, of je kan een interpreter schrijven
+voor brainfuck in een andere taal. Het is namelijk redelijk makkelijk om te
+implementeren aangezien brainfuck maar acht commando's heeft. En als je een
+masochist bent kan je ook nog proberen om brainfuck te implementeren… in
+brainfuck.
diff --git a/nl-nl/coffeescript-nl.html.markdown b/nl-nl/coffeescript-nl.html.markdown
new file mode 100644
index 00000000..dc0b1e19
--- /dev/null
+++ b/nl-nl/coffeescript-nl.html.markdown
@@ -0,0 +1,110 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["Jelle Besseling", "https://github.com/Jell-E"]
+ - ["D.A.W. de Waal", "http://github.com/diodewaal"]
+filename: coffeescript-nl.coffee
+lang: nl-nl
+---
+
+CoffeeScript is een kleine programmeertaal die direct compileert naar
+JavaScript en er is geen interpretatie tijdens het uitvoeren.
+CoffeeScript probeert om leesbare, goed geformatteerde en goed draaiende
+JavaScript code te genereren, die in elke JavaScript runtime werkt, als een
+opvolger van JavaScript.
+
+Op [de CoffeeScript website](http://coffeescript.org/), staat een
+volledigere tutorial voor CoffeeScript.
+
+``` coffeescript
+# CoffeeScript is een taal voor hipsters.
+# Het gaat mee met alle trends van moderne talen.
+# Commentaar begint dus met een hekje, net zoals bij Python en Ruby.
+
+###
+Blokken commentaar maak je zo, ze vertalen naar JavaScripts */ en /*
+in de uitvoer van de CoffeeScript compiler.
+
+Het is belangrijk dat je ongeveer snapt hoe JavaScript
+werkt voordat je verder gaat.
+###
+
+# Toewijzing:
+getal = 42 #=> var getal = 42;
+tegengestelde = true #=> var tegengestelde = true;
+
+# Voorwaarden:
+getal = -42 if tegengestelde #=> if(tegengestelde) { getal = -42; }
+
+# Functies:
+kwadraat = (x) -> x * x #=> var kwadraat = function(x) { return x * x; }
+
+vul = (houder, vloeistof = "koffie") ->
+ "Nu de #{houder} met #{koffie} aan het vullen..."
+#=>var vul;
+#
+#vul = function(houder, vloeistof) {
+# if (vloeistof == null) {
+# vloeistof = "koffie";
+# }
+# return "Nu de " + houder + " met " + vloeistof + " aan het vullen...";
+#};
+
+# Reeksen:
+lijst = [1..5] #=> var lijst = [1, 2, 3, 4, 5];
+
+# Objecten:
+wiskunde =
+ wortel: Math.sqrt
+ kwadraat: kwadraat
+ derdemacht: (x) -> x * kwadraat x
+#=> var wiskunde = {
+# "wortel": Math.sqrt,
+# "kwadraat": kwadraat,
+# "derdemacht": function(x) { return x * kwadraat(x); }
+#}
+
+# "Splats":
+wedstrijd = (winnaar, lopers...) ->
+ print winnaar, lopers
+#=>wedstrijd = function() {
+# var lopers, winnaar;
+# winnaar = arguments[0], lopers = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
+# return print(winnaar, lopers);
+#};
+
+# Aanwezigheid:
+alert "Ik wist het!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); }
+
+# Lijst abstractie:
+derdemachten = (wiskunde.derdemacht num for num in lijst)
+#=>derdemachten = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = lijst.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(wiskunde.derdemacht(num));
+# }
+# return _results;
+# })();
+
+etenswaren = ['broccoli', 'spinazie', 'chocolade']
+eet eten for eten in etenswaren when eten isnt 'chocolade'
+#=>etenswaren = ['broccoli', 'spinazie', 'chocolade'];
+#
+#for (_k = 0, _len2 = etenswaren.length; _k < _len2; _k++) {
+# eten = etenswaren[_k];
+# if (eten !== 'chocolade') {
+# eet(eten);
+# }
+#}
+```
+
+## Handige links (in het Engels):
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
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..f9db7080
--- /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 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 92219708..b178de1e 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -7,48 +7,75 @@ contributors:
- ["Nami-Doc", "http://github.com/Nami-Doc"]
---
-Perl 6 is a highly capable, feature-rich programming language made for the upcoming hundred years.
+Perl 6 is a highly capable, feature-rich programming language made for the
+upcoming hundred years.
-Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM and [the MoarVM](http://moarvm.com).
+Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM
+and [the MoarVM](http://moarvm.com).
+
+Meta-note : the triple pound signs are here to denote headlines,
+double paragraphs, and single notes.
-Meta-note : the triple pound signs are here to denote headlines, double paragraphs, single notes.
`#=>` represents the output of a command.
```perl
# Single line comment start with a pound
#`(
- Multiline comments use #` and a quoting construct. (), [], {}, 「」, etc, will work.
+ Multiline comments use #` and a quoting construct.
+ (), [], {}, 「」, etc, will work.
)
### Variables
# In Perl 6, you declare a lexical variable using `my`
-a
-# Perl 6 has 4 variable types :
+my $variable;
+# Perl 6 has 4 kinds of variables:
## * Scalars. They represent a single value. They start with a `$`
my $str = 'String';
my $str2 = "String"; # double quotes allow for interpolation
-# variable names can contain but not end with simple quotes and dashes, and can contain (and end with) underscores :
+# variable names can contain but not end with simple quotes and dashes,
+# and can contain (and end with) underscores :
# my $weird'variable-name_ = 5; # works !
my $bool = True; # `True` and `False` are Perl 6's boolean
my $inverse = !$bool; # You can invert a bool with the prefix `!` operator
-my $forced-bool = so $str; # And you can use the prefix `so` operator which turns its operand into a Bool
+my $forced-bool = so $str; # And you can use the prefix `so` operator
+ # which turns its operand into a Bool
-## * Arrays. They represent multiple values. Their name start with `@`.
+## * Lists. They represent multiple values. Their name start with `@`.
-my @array = 1, 2, 3;
my @array = 'a', 'b', 'c';
# equivalent to :
-my @array = <a b c>; # array of words, delimited by space. similar to perl5's qw, or Ruby's %w
+my @letters = <a b c>; # array of words, delimited by space.
+ # Similar to perl5's qw, or Ruby's %w.
+my @array = 1, 2, 3;
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 [] : 1 2 3
+
+@array[0] = -1; # Assign a new value to an array index
+@array[0, 1] = 5, 6; # Assign multiple values
+
+my @keys = 0, 2;
+@array[@keys] = @letters; # Assign using an array
+say @array; #=> a 6 b
+
+# There are two more kinds of lists: Parcel and Arrays.
+# Parcels are immutable lists (you can't modify a list that's not assigned).
+# This is a parcel:
+(1, 2, 3); # Not assigned to anything. Changing an element would provoke an error
+# This is a list:
+my @a = (1, 2, 3); # Assigned to `@a`. Changing elements is okay!
+
+# Lists flatten (in list context). You'll see below how to apply item context
+# or use arrays to have real nested lists.
+
## * Hashes. Key-Value Pairs.
# Hashes are actually arrays of Pairs (`Key => Value`),
@@ -58,10 +85,12 @@ my %hash = 1 => 2,
my %hash = autoquoted => "key", # keys *can* get auto-quoted
"some other" => "value", # trailing commas are okay
;
-my %hash = <key1 value1 key2 value2>; # you can also create a hash from an even-numbered array
+my %hash = <key1 value1 key2 value2>; # you can also create a hash
+ # from an even-numbered array
my %hash = key1 => 'value1', key2 => 'value2'; # same as this
-# You can also use the "colon pair" syntax: (especially handy for named parameters that you'll see later)
+# You can also use the "colon pair" syntax:
+# (especially handy for named parameters that you'll see later)
my %hash = :w(1), # equivalent to `w => 1`
# this is useful for the `True` shortcut:
:truey, # equivalent to `:truey(True)`, or `truey => True`
@@ -70,33 +99,37 @@ my %hash = :w(1), # equivalent to `w => 1`
;
say %hash{'key1'}; # You can use {} to get the value from a key
-say %hash<key2>; # if it's a string, you can actually use <>
+say %hash<key2>; # If it's a string, you can actually use <>
+ # (`{key1}` doesn't work, as Perl6 doesn't have barewords)
-## * Subs (subroutines, or functions in most other languages). Stored in variable, they use `&`
+## * Subs (subroutines, or functions in most other languages).
+# Stored in variable, they use `&`.
sub say-hello { say "Hello, world" }
-sub say-hello-to(Str $name) { # you can provide the type of an argument
- # and it'll be checked at compile-time
+sub say-hello-to(Str $name) { # You can provide the type of an argument
+ # and it'll be checked at compile-time.
say "Hello, $name !";
}
-# since you can omit parenthesis to call a function with no arguments,
-# you need "&" in the name to capture `say-hello`
+# Since you can omit parenthesis to call a function with no arguments,
+# you need "&" in the name to capture `say-hello`.
my &s = &say-hello;
-my &other-s = sub { say "anonymous function !" }
+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".
- # Note: you can have parameters *before* (like here) a slurpy one,
- # but not *after*.
+sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything else".
+ # Note: you can have parameters *before* (like here)
+ # a slurpy one, but not *after*.
say @rest.join(' / ') ~ " !";
}
say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday !
- # Note that the splat did not consume the parameter before.
+ # Note that the splat did not consume
+ # the parameter before.
-## You can call a function with an array using the "argument list flattening" operator `|`
-# (it's not actually the only feature of the operator, but it's one of them)
+## You can call a function with an array using the
+# "argument list flattening" operator `|`
+# (it's not actually the only role of this operator, but it's one of them)
sub concat3($a, $b, $c) {
say "$a, $b, $c";
}
@@ -105,7 +138,8 @@ concat3(|@array); #=> a, b, c
## It can also have optional arguments:
sub with-optional($arg?) { # the "?" marks the argument optional
- say "I might return `(Any)` if I don't have an argument passed, or I'll return my argument";
+ say "I might return `(Any)` if I don't have an argument passed,
+ or I'll return my argument";
$arg;
}
with-optional; # returns Any
@@ -132,14 +166,15 @@ with-named(1, named => 6); #=> 7
with-named(2, :named(5)); #=> 7
with-named(3, :4named); #=> 7
- # (special colon pair syntax for numbers, mainly useful for `:2nd` etc)
+ # (special colon pair syntax for numbers,
+ # to be used with s// and such, see later)
with-named(3); # warns, because we tried to use the undefined $named in a `+`:
# by default, named arguments are *optional*
# To make a named argument mandatory, you can use `?`'s inverse, `!`
sub with-mandatory-named(:$str!) {
- say "$named !";
+ say "$str !";
}
with-mandatory-named(str => "My String"); #=> My String !
with-mandatory-named; # run time error: "Required named parameter not passed"
@@ -171,10 +206,11 @@ named-def(def => 15); #=> 15
### Containers
# In Perl 6, values are actually stored in "containers".
-# The assignment operator asks the container on the left to store the value on 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` :
+# The assignment operator asks the container on the left to store the value on
+# 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`:
sub mutate($n is rw) {
$n++;
say "\$n is now $n !";
@@ -182,24 +218,26 @@ 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 (else Perl 6 thinks it's a "term")
+mod() = 52; # in this case, the parentheses are mandatory
+ # (else Perl 6 thinks `mod` is a "term")
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
# - `if`
-# Before talking about `if`, we need to know which values are "Truthy" (represent True),
-# and which are "Falsey" (or "Falsy") -- meaning they represent False.
-# Only these values are Falsey: (), 0, "0", Nil, A type, and of course False itself.
+# Before talking about `if`, we need to know which values are "Truthy"
+# (represent True), and which are "Falsey" (or "Falsy") -- represent False.
+# Only these values are Falsey: (), 0, "0", Nil, A type (like `Str` or `Int`),
+# and of course False itself.
# Every other value is Truthy.
if True {
say "It's true !";
@@ -217,18 +255,18 @@ say "Quite truthy" if True;
# - Ternary conditional, "?? !!" (like `x ? y : z` in some other languages)
my $a = $condition ?? $value-if-true !! $value-if-false;
-# - `given`-`when` looks like other languages `switch`, but it's much more powerful thanks to smart matching,
-# and thanks to Perl 6's "topic variable", $_.
+# - `given`-`when` looks like other languages `switch`, but much more
+# powerful thanks to smart matching and thanks to Perl 6's "topic variable", $_.
# This variable contains the default argument of a block,
# a loop's current iteration (unless explicitly named), etc.
-# Given simply puts its argument into `$_` (like a block would do),
-# and `when` uses it using the "smart matching" operator.
-# Since other Perl 6 constructs use this variable (as said before, like `for`, blocks, etc),
-# this means the powerful `when` is not only applicable along with a `given`,
-# but instead anywhere a `$_` exists.
+# `given` simply puts its argument into `$_` (like a block would do),
+# and `when` compares it using the "smart matching" (`~~`) operator.
+# Since other Perl 6 constructs use this variable (as said before, like `for`,
+# blocks, etc), this means the powerful `when` is not only applicable along with
+# a `given`, but instead anywhere a `$_` exists.
given "foo bar" {
- when /foo/ { # you'll read about the smart-matching operator below -- just know `when` uses it
- # this is equivalent to `if $_ ~~ /foo/`
+ when /foo/ { # Don't worry about smart matching -- just know `when` uses it.
+ # This is equivalent to `if $_ ~~ /foo/`.
say "Yay !";
}
when $_.chars > 50 { # smart matching anything with True (`$a ~~ True`) is True,
@@ -242,15 +280,17 @@ 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` :
+# - `loop` is an infinite loop if you don't pass it arguments,
+# 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
}
loop (my $i = 0; $i < 5; $i++) {
- next if $i == 3; # `next` skips to the next iteration, like `continue` in other languages.
- # Notice that you can also use postfix conditionals, loops, etc.
+ 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.
say "This is a C-style for loop !";
}
@@ -270,28 +310,60 @@ for @array {
}
for @array {
- next if $_ == 3; # you can skip to the next iteration (like `continue` in C-like languages)
- redo if $_ == 4; # you can re-do the iteration, keeping the same topic variable (`$_`)
- last if $_ == 5; # you can also break out of a loop (like `break` in C-like languages)
+ # You can...
+ 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";
}
+## Loops can also have a label, and be jumped to through these.
+OUTER: while 1 {
+ say "hey";
+ while 1 {
+ OUTER.last; # All the control keywords must be called on the label itself
+ }
+}
+
+# Now that you've seen how to traverse a list, you need to be aware of something:
+# List context (@) flattens. If you traverse nested lists, you'll actually be traversing a
+# shallow list (except if some sub-list were put in item context ($)).
+for 1, 2, (3, (4, ((5)))) {
+ say "Got $_.";
+} #=> Got 1. Got 2. Got 3. Got 4. Got 5.
+
+# ... However: (forcing item context with `$`)
+for 1, 2, $(3, 4) {
+ say "Got $_.";
+} #=> Got 1. Got 2. Got 3 4.
+
+# Note that the last one actually joined 3 and 4.
+# While `$(...)` will apply item to context to just about anything, you can also create
+# an array using `[]`:
+for [1, 2, 3, 4] {
+ say "Got $_.";
+} #=> Got 1 2 3 4.
+
+# The other difference between `$()` and `[]` is that `[]` always returns a mutable Array
+# whereas `$()` will return a Parcel when given a Parcel.
+
+
### Operators
## Since Perl languages are very much operator-based languages
-## Perl 6 operators are actually just funny-looking subroutines, in syntactic categories,
-## like infix:<+> (addition) or prefix:<!> (bool not)
+## 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.
@@ -312,12 +384,15 @@ if long-computation() -> $result {
(1, 2) eqv (1, 3);
# - `~~` is smart matching
-# for a complete combinations list, 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` as an argument, returns True
-1 ~~ Int; # "is of type"
-1 ~~ True; # smart-matching against a boolean always returns that boolean (and will warn).
+$arg ~~ &bool-returning-function; # `True` if the function, passed `$arg`
+ # as an argument, returns `True`.
+1 ~~ Int; # "has type" (check superclasses and roles)
+1 ~~ True; # smart-matching against a boolean always returns that boolean
+ # (and will warn).
# - `===` is value identity and uses `.WHICH` on the objects to compare them
# - `=:=` is container identity and uses `VAR()` on the objects to compare them
@@ -330,38 +405,51 @@ $arg ~~ &bool-returning-function; # true if the function, passed `$arg` as an ar
3 .. 7; # 3 to 7, both included
# `^` on either side them exclusive on that side :
3 ^..^ 7; # 3 to 7, not included (basically `4 .. 6`)
-# this also works as a shortcut for `0..^N`
+# This also works as a shortcut for `0..^N`:
^10; # means 0..^10
-# This also allows us to demonstrate that Perl 6 has lazy arrays, using the Whatever Star :
-my @array = 1..*; # 1 to Infinite !
-say @array[^10]; # you can pass arrays as subscripts and it'll return an array of results
- # this will print "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !)
-# Note : when reading an infinite list, Perl 6 will "reify" the elements it needs, then keep them in memory
-# They won't be calculated more than once.
+# This also allows us to demonstrate that Perl 6 has lazy/infinite arrays,
+# using the Whatever Star:
+my @array = 1..*; # 1 to Infinite ! `1..Inf` is the same.
+say @array[^10]; # you can pass arrays as subscripts and it'll return
+ # an array of results. This will print
+ # "1 2 3 4 5 6 7 8 9 10" (and not run out of memory !)
+# Note : when reading an infinite list, Perl 6 will "reify" the elements
+# it needs, then keep them in memory. They won't be calculated more than once.
-# Warning, though: if you try this example in the REPL and juste put `1..*`,
-# Perl 6 will be forced to try and evaluate the whole array (to print it),
-# so you'll end with an infinite loop.
+# Warning, though: if you try this example in the REPL and just put `1..*`,
+# Perl 6 will be forced to try and evaluate the whole array (to print it),
+# so you'll end with an infinite loop.
+
+# You can use that in most places you'd expect, even assigning to an array
+my @numbers = ^20;
+@numbers[5..*] = 3, 9 ... * > 90; # The right hand side could be infinite as well.
+ # (but not both, as this would be an infinite loop)
+say @numbers; #=> 3 9 15 21 27 [...] 81 87
+
## * And, Or
3 && 4; # 4, which is Truthy. Calls `.Bool` on `4` and gets `True`.
0 || False; # False. Calls `.Bool` on `0`
## * Short-circuit (and tight) versions of the above
-$a && $b && $c; # returns the first argument that evaluates to False, or the last argument
+$a && $b && $c; # Returns the first argument that evaluates to False,
+ # or the last argument.
$a || $b;
-# And because you're going to want them, you also have composed assignment operators:
+# And because you're going to want them,
+# you also have composed assignment operators:
$a *= 2; # multiply and assignment
$b %%= 5; # divisible by and assignment
-$c .= say; # method call and assignment
+@array .= sort; # calls the `sort` method and assigns the result back
### More on subs !
-# As we said before, Perl 6 has *really* powerful subs.
-# We're going to see a few more key concepts that make them better than in any other language :-).
+# As we said before, Perl 6 has *really* powerful subs. We're going to see
+# a few more key concepts that make them better than in any other language :-).
-## Unpacking ! It's the ability to "extract" arrays and keys. It'll work in `my`s and parameters.
+## Unpacking !
+# It's the ability to "extract" arrays and keys.
+# It'll work in `my`s and in parameter lists.
my ($a, $b) = 1, 2;
say $a; #=> 1
my ($, $, $c) = 1, 2, 3; # keep the non-interesting anonymous
@@ -377,14 +465,17 @@ sub foo(@array [$fst, $snd]) {
foo(@tail); #=> My first is 2, my second is 3 ! All in all, I'm 2 3
-# If you're not using the array itself, you can also keep it anonymous, much like a scalar:
+# If you're not using the array itself, you can also keep it anonymous,
+# much like a scalar:
sub first-of-array(@ [$fst]) { $fst }
first-of-array(@small); #=> 1
-first-of-array(@tail); # errors with "Too many positional parameters passed" (the array is too big)
+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
- say $fst + @rest.elems;
+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`.
}
slurp-in-array(@tail); #=> 3
@@ -403,18 +494,21 @@ sub key-of(% (:value($val), :qua($qua))) {
}
# Then call it with a hash: (you need to keep the brackets for it to be a hash)
-key-of({value => 1});
+key-of({value => 'foo', qua => 1});
#key-of(%hash); # the same (for an equivalent `%hash`)
-## The last expression of a sub is returned automatically (though you may use the `return` keyword, of course):
+## The last expression of a sub is returned automatically
+# (though you may use the `return` keyword, of course):
sub next-index($n) {
$n + 1;
}
my $new-n = next-index(3); # $new-n is now 4
-# This is true for everything, except for the looping constructs (due to performance reasons):
-# there's no purpose in building a list if we're just going to discard all the results.
-# If you still want to build one, you can use the `do` prefix: (or the `gather` prefix, which we'll see later)
+# This is true for everything, except for the looping constructs
+# (due to performance reasons): there's reason to build a list
+# if we're just going to discard all the results.
+# If you still want to build one, you can use the `do` statement prefix:
+# (or the `gather` prefix, which we'll see later)
sub list-of($n) {
do for ^$n { # note the use of the range-to prefix operator `^` (`0..^N`)
$_ # current loop iteration
@@ -424,15 +518,16 @@ my @list3 = list-of(3); #=> (0, 1, 2)
## You can create a lambda with `-> {}` ("pointy block") or `{}` ("block")
my &lambda = -> $argument { "The argument passed to this lambda is $argument" }
-# `-> {}` and `{}` are pretty much the same thing, except that the former can take arguments,
-# and that the latter can be mistaken as a hash by the parser.
+# `-> {}` and `{}` are pretty much the same thing, except that the former can
+# take arguments, and that the latter can be mistaken as a hash by the parser.
# We can, for example, add 3 to each value of an array using map:
my @arrayplus3 = map({ $_ + 3 }, @array); # $_ is the implicit argument
-# a sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
-# a block doesn't have a "function context" (though it can have arguments), which means that if you
-# return from it, you're going to return from the parent function, compare:
+# A sub (`sub {}`) has different semantics than a block (`{}` or `-> {}`):
+# A block doesn't have a "function context" (though it can have arguments),
+# which means that if you return from it,
+# you're going to return from the parent function. Compare:
sub is-in(@array, $elem) {
# this will `return` out of the `is-in` sub
# once the condition evaluated to True, the loop won't be run anymore
@@ -441,28 +536,32 @@ sub is-in(@array, $elem) {
sub truthy-array(@array) {
# this will produce an array of `True` and `False`:
# (you can also say `anon sub` for "anonymous subroutine")
- map(sub { if $_ { return True } else { return False } }, @array);
+ map(sub ($i) { if $i { return True } else { return False } }, @array);
# ^ the `return` only returns from the anonymous `sub`
}
# 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
# works even in parens !
-# but if you need to have more than one argument (`$_`) in a block (without wanting to resort to `-> {}`),
+# 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 }`
+# Note : those are sorted lexicographically.
+# `{ $^b / $^a }` is like `-> $a, $b { $b / $a }`
## Multiple Dispatch
-# Perl 6 can decide which variant of a `sub` to call based on the type of the arguments,
-# or on arbitrary preconditions, like with a type or a `where`:
+# Perl 6 can decide which variant of a `sub` to call based on the type of the
+# arguments, or on arbitrary preconditions, like with a type or a `where`:
# with types
multi sub sayit(Int $n) { # note the `multi` keyword here
@@ -472,21 +571,25 @@ multi sayit(Str $s) } # the `sub` is the default
say "String: $s";
}
sayit("foo"); # prints "String: foo"
-sayit(True); # fails at *compile time* with "calling 'sayit' will never work with arguments of types ..."
+sayit(True); # fails at *compile time* with
+ # "calling 'sayit' will never work with arguments of types ..."
# with arbitrary precondition:
multi is-big(Int $n where * > 50) { "Yes !" } # using a closure
-multi is-big(Int $ where 10..50) { "Quite." } # this uses smart-matching (could use a regexp, etc)
+multi is-big(Int $ where 10..50) { "Quite." } # Using smart-matching
+ # (could use a regexp, etc)
multi is-big(Int $) { "No" }
-# you can also name these checks, by creating "subsets":
+# You can also name these checks, by creating "subsets":
subset Even of Int where * %% 2;
-multi odd-or-even(Even) { "Even" } # the main case using the type. We don't name the argument
+multi odd-or-even(Even) { "Even" } # The main case using the type.
+ # We don't name the argument.
multi odd-or-even($) { "Odd" } # "else"
# You can even dispatch based on a positional's argument presence !
-multi with-or-without-you(:$with!) { # make it mandatory to be able to dispatch against it
+multi with-or-without-you(:$with!) { # You need make it mandatory to
+ # be able to dispatch against it.
say "I can live ! Actually, I can't.";
}
multi with-or-without-you {
@@ -494,17 +597,21 @@ multi with-or-without-you {
}
# This is very, very useful for many purposes, like `MAIN` subs (covered later),
# and even the language itself is using it in several places.
-# `is`, for example, is actually a `multi sub` named `trait_mod:<is>`, and it works off that.
-# `is rw`, for example, is a dispatch to a function with this signature:
+#
+# - `is`, for example, is actually a `multi sub` named `trait_mod:<is>`,
+# and it works off that.
+# - `is rw`, is simply a dispatch to a function with this signature:
# sub trait_mod:<is>(Routine $r, :$rw!) {}
-# (commented because running this would probably lead to some very surprising side-effects !)
+#
+# (commented because running this would be a terrible idea !)
### Scoping
-# In Perl 6, contrarily to many scripting languages (Python, Ruby, PHP, for example),
-# you are to declare your variables before using them. You already saw it, with `my`.
-# (there are other declarator keywords, like `our`, `has` and `state`, but we'll talk about them later)
-# This is called "lexical scoping", where in inner blocks, you can access variables from outer blocks.
+# In Perl 6, contrarily to many scripting languages (like Python, Ruby, PHP),
+# you are to declare your variables before using them. You know `my`.
+# (there are other declarators, `our`, `state`, ..., which we'll see later).
+# This is called "lexical scoping", where in inner blocks,
+# you can access variables from outer blocks.
my $foo = 'Foo';
sub foo {
my $bar = 'Bar';
@@ -516,36 +623,40 @@ sub foo {
foo()(); #=> 'Foo Bar'
# As you can see, `$foo` and `$bar` were captured.
-# But if we were to try and use `$bar` outside of `foo`, the variable would be undefined.
-# (and you'd get a compile time error)
+# But if we were to try and use `$bar` outside of `foo`,
+# the variable would be undefined (and you'd get a compile time error).
# Perl 6 has another kind of scope : dynamic scope.
# They use the twigil (composed sigil) `*` to mark dynamically-scoped variables:
my $*a = 1;
-# Dyamically-scoped variables depend on the current call stack, instead of the current block stack.
+# Dyamically-scoped variables depend on the current call stack,
+# instead of the current block depth.
sub foo {
my $*foo = 1;
bar(); # call `bar` in-place
}
sub bar {
- say $*foo; # Perl 6 will look into the call stack instead, and find `foo`'s `$*a`,
- # even though the blocks aren't nested (they're call-nested).
+ 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
}
### Object Model
## Perl 6 has a quite comprehensive object model
-## You declare a class with the keyword `class`, fields with `has`, methods with `method`.
-## In Perl 6, every field is private, and named `$!attr`, but if you declare it with `$.`,
-## you get a public (immutable) accessor along with it.
+# You declare a class with the keyword `class`, fields with `has`,
+# methods with `method`. Every field to private, and is named `$!attr`,
+# but you have `$.` to get a public (immutable) accessor along with it.
+# (using `$.` is like using `$!` plus a `method` with the same name)
-# (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. Use `$!field` from inside the class to modify it.
- has $.other-field is rw; # You can, however, mark a public field as being read/write.
+ has $.field; # `$.field` is immutable.
+ # From inside the class, use `$!field` to modify it.
+ has $.other-field is rw; # You can obviously mark a public field `rw`.
has Int $!private-field = 10;
method get-value {
@@ -556,7 +667,7 @@ class A {
# $.field = $n; # As stated before, you can't use the `$.` immutable version.
$!field = $n; # This works, because `$!` is always mutable.
- $.other-field = 5; # This works, because `$.other-field` was declared `rw` (mutable).
+ $.other-field = 5; # This works, because `$.other-field` is `rw`.
}
method !private-method {
@@ -565,13 +676,15 @@ class A {
};
# Create a new instance of A with $.field set to 5 :
-# note : you can't set private-field from here (more later on)
+# Note: you can't set private-field from here (more later on).
my $a = A.new(field => 5);
$a.get-value; #=> 18
#$a.field = 5; # This fails, because the `has $.field` is immutable
-$a.other-field = 10; # This, however, works, because the public field is mutable (`rw`).
+$a.other-field = 10; # This, however, works, because the public field
+ # is mutable (`rw`).
-## Perl 6 also has inheritance (along with multiple inheritance ... Considered a misfeature by many)
+## Perl 6 also has inheritance (along with multiple inheritance)
+# (though considered a misfeature by many)
class A {
has $.val;
@@ -591,12 +704,14 @@ class B is A { # inheritance uses `is`
method bar { $.val * 10 } # this shadows A's `bar`
}
-my B $b .= new(val => 5); # When you use `my T $var`, `$var` starts off with `T` itself in it,
- # so you can call `new` on it.
- # (`.=` is just the compound operator composed of the dot-call and of the assignment operator
- # `$a .= b` is the same as `$a = $a.b`)
- # Also note that `BUILD` (the method called inside `new`) will set parent properties too,
- # so you can pass `val => 5`
+# When you use `my T $var`, `$var` starts off with `T` itself in it,
+# so you can call `new` on it.
+# (`.=` is just the dot-call and the assignment operator:
+# `$a .= b` is the same as `$a = $a.b`)
+# Also note that `BUILD` (the method called inside `new`)
+# will set parent properties too, so you can pass `val => 5`.
+my B $b .= new(val => 5);
+
# $b.not-inherited; # This won't work, for reasons explained above
$b.foo; # prints 5
$b.bar; #=> 50, since it calls B's `bar`
@@ -613,56 +728,81 @@ role PrintableVal {
class Item does PrintableVal {
has $.val;
- # When `does`-ed, a `role` literally "mixes in" the class :
- # the methods and fields are put together, which means a class can access
- # the private fields/methods of its roles (but not the inverse !) :
+ # When `does`-ed, a `role` literally "mixes in" the class:
+ # the methods and fields are put together, which means a class can access
+ # the private fields/methods of its roles (but not the inverse !):
method access {
say $!counter++;
}
- # However, this :
+ # However, this:
# method print {}
- # is an error, since the compiler wouldn't know which `print` to use :
- # contrarily to inheritance, methods mixed in can't be shadowed - they're put at the same "level"
+ # is ONLY valid when `print` isn't a `multi` with the same dispatch.
+ # (this means a parent class can shadow a child class's `multi print() {}`,
+ # but it's an error if a role does)
- # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods will be shadowed,
- # since the compiler will consider `ROLE` to be a class
+ # NOTE: You can use a role as a class (with `is ROLE`). In this case, methods
+ # will be shadowed, since the compiler will consider `ROLE` to be a class.
}
### Exceptions
-# Exceptions are built on top of classes, usually 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 {} }`).
-# You can redefine it using `when`s (and `default`) to handle the exceptions you want:
+# 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 {} }`).
+# You can redefine it using `when`s (and `default`)
+# to handle the exceptions you want:
try {
open 'foo';
CATCH {
when X::AdHoc { say "unable to open file !" }
- # any other exception will be re-raised, since we don't have a `default`
+ # Any other exception will be re-raised, since we don't have a `default`
+ # Basically, if a `when` matches (or there's a `default`) marks the exception as
+ # "handled" so that it doesn't get re-thrown from the `CATCH`.
+ # You still can re-throw the exception (see below) by hand.
}
}
# You can throw an exception using `die`:
die X::AdHoc.new(payload => 'Error !');
-# TODO warn
-# TODO fail
-# TODO CONTROL
+
+# You can access the last exception with `$!` (usually used in a `CATCH` block)
+
+# There are also some subtelties to exceptions. Some Perl 6 subs return a `Failure`,
+# which is a kind of "unthrown exception". They're not thrown until you tried to look
+# at their content, unless you call `.Bool`/`.defined` on them - then they're handled.
+# (the `.handled` method is `rw`, so you can mark it as `False` back yourself)
+#
+# You can throw a `Failure` using `fail`. Note that if the pragma `use fatal` is on,
+# `fail` will throw an exception (like `die`).
+fail "foo"; # We're not trying to access the value, so no problem.
+try {
+ fail "foo";
+ CATCH {
+ default { say "It threw because we try to get the fail's value!" }
+ }
+}
+
+# There is also another kind of exception: Control exceptions.
+# Those are "good" exceptions, which happen when you change your program's flow,
+# using operators like `return`, `next` or `last`.
+# You can "catch" those with `CONTROL` (not 100% working in Rakudo yet).
### Packages
-# Packages are a way to reuse code. Packages are like "namespaces", and any element of the six model
-# (`module`, `role`, `class`, `grammar`, `subset` and `enum`) are actually packages.
-# (you can say that packages are the lowest common denomitor between them)
-# Packages play a big part in a language, as Perl is well-known for CPAN,
+# 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 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`:
-module Hello::World { # bracketed form
- # if `Hello` doesn't exist yet, it'll just be created as an "empty package stub"
- # that can be redeclared as something else later.
- # declarations here
+# 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`:
+module Hello::World { # Bracketed form
+ # If `Hello` doesn't exist yet, it'll just be a "stub",
+ # that can be redeclared as something else later.
+ # ... declarations here ...
}
module Parse::Text; # file-scoped form
-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,
@@ -692,7 +832,8 @@ my $actions = JSON::Tiny::Actions.new;
module Foo::Bar {
our $n = 1; # note: you can't put a type constraint on an `our` variable
our sub inc {
- our sub available { # if you try to make scoped `sub`s `our` ... Better know what you're doing (Don't !).
+ our sub available { # If you try to make inner `sub`s `our`...
+ # Better know what you're doing (Don't !).
say "Don't do that. Seriously. You'd get burned.";
}
my sub unavailable { # `my sub` is the default
@@ -725,23 +866,24 @@ sub fixed-rand {
fixed-rand for ^10; # will print the same number 10 times
# Note, however, that they exist separately in different enclosing contexts.
-# If you declare a function with a `state` within a loop, it'll re-create the variable
-# for each iteration of loop. See:
+# If you declare a function with a `state` within a loop, it'll re-create the
+# variable for each iteration of the loop. See:
for ^5 -> $a {
sub foo {
state $val = rand; # This will be a different value for every value of `$a`
}
for ^5 -> $b {
- say foo; # This will print the same value 5 times, but only 5. Next iteration will re-run `rand`
+ say foo; # This will print the same value 5 times, but only 5.
+ # Next iteration will re-run `rand`.
}
}
### Phasers
-# Phasers in Perl 6 are blocks that happen at determined points of time in your program
-# When the program is compiled, when a for loop runs, when you leave a block, when
-# an exception gets thrown ... (`CATCH` is actually a phaser !)
+# Phasers in Perl 6 are blocks that happen at determined points of time in your
+# program. When the program is compiled, when a for loop runs, when you leave a
+# block, when an exception gets thrown ... (`CATCH` is actually a phaser !)
# Some of them can be used for their return values, some of them can't
# (those that can have a "[*]" in the beginning of their explanation text).
# Let's have a look !
@@ -782,7 +924,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
}
@@ -791,7 +933,7 @@ sub do-db-stuff {
# Those act a bit like phasers: they affect the behavior of the following code.
# Though, they run in-line with the executable code, so they're in lowercase.
# (`try` and `start` are theoretically in that list, but explained somewhere else)
-# Note: all of these (except start) don't need explicit brackets (`{` and `}`) for their block.
+# Note: all of these (except start) don't need explicit brackets `{` and `}`.
# - `do` (that you already saw) - runs a block or a statement as a term
# You can't normally use a statement as a value (or "term"):
@@ -848,8 +990,9 @@ say nilthingie.perl; #=> Nil
## Everybody loves operators ! Let's get more of them
-## The precedence list can be found here : http://perlcabal.org/syn/S03.html#Operator_precedence
-## But first, we need a little explanation about associativity :
+# The precedence list can be found here:
+# http://perlcabal.org/syn/S03.html#Operator_precedence
+# But first, we need a little explanation about associativity:
# * Binary operators:
$a ! $b ! $c; # with a left-associative `!`, this is `($a ! $b) ! $c`
@@ -864,8 +1007,9 @@ $a ! $b ! $c; # with a list-associative `!`, this is `infix:<>`
!$a! # with non-associative `!`, this is illegal
## Create your own operators !
-# Okay, you've been reading all of that, so I guess I should try to show you something exciting.
-# I'll tell you a little secret (actually not):
+# Okay, you've been reading all of that, so I guess I should try
+# to show you something exciting.
+# I'll tell you a little secret (or not-so-secret):
# In Perl 6, all operators are actually just funny-looking subroutines.
# You can declare an operator just like you declare a sub:
@@ -890,7 +1034,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
@@ -906,36 +1050,47 @@ sub circumfix:<[ ]>(Int $n) {
say [5]; #=> 3125
# circumfix is around. Again, not whitespace.
-sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is "after a term, around something"
+sub postcircumfix:<{ }>(Str $s, Int $idx) {
+ # post-circumfix is
+ # "after a term, around something"
$s.substr($idx, 1);
}
say "abc"{1}; #=> b
# after the term `"abc"`, and around the index (1)
# This really means a lot -- because everything in Perl 6 uses this.
-# For example, to delete a key from a hash, you use the `:delete` adverb (named argument)
+# For example, to delete a key from a hash, you use the `:delete` adverb
+# (a simple named argument underneath):
%h{$key}:delete;
# equivalent to:
-postcircumfix:<{ }>(%h, $key, :delete);
-# It's *all* using the same building blocks! Syntactic categories (prefix infix ...),
-# named arguments (adverbs), ..., used to build the language are available to you.
+postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that)
+# It's *all* using the same building blocks!
+# Syntactic categories (prefix infix ...), named arguments (adverbs), ...,
+# - used to build the language - are available to you.
-# (you are, obviously, recommended against making an operator out of *everything* --
-# with great power comes great responsibility)
+# (you are, obviously, recommended against making an operator out of
+# *everything* -- with great power comes great responsibility)
## Meta operators !
-# Oh boy, get ready. Get ready, because we're dwelving deep into the rabbit's hole,
-# and you probably won't want to go back to other languages after reading that.
+# Oh boy, get ready. Get ready, because we're dwelving deep
+# into the rabbit's hole, and you probably won't want to go
+# back to other languages after reading that.
# (I'm guessing you don't want to already at that point).
# Meta-operators, as their name suggests, are *composed* operators.
# Basically, they're operators that apply another operator.
## * Reduce meta-operator
-# It's a prefix meta-operator that takes a binary functions and one or many lists.
-# If it doesn't get passed any argument, it either return a "default value" for this operator
-# (a value that'd be non-meaningful if contained in a list) or `Any` if there's none.
-# 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.
+# It's a prefix meta-operator that takes a binary functions and
+# one or many lists. If it doesn't get passed any argument,
+# it either return a "default value" for this operator
+# (a value that wouldn't change the result if passed as one
+# of the element of the list to be passed to the operator),
+# or `Any` if there's none (examples below).
+#
+# 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
# equivalent to `(1+2)+3`
@@ -943,18 +1098,20 @@ say [*] 1..5; #=> 120
# equivalent to `((((1*2)*3)*4)*5)`.
# You can reduce with any operator, not just with mathematical ones.
-# For example, you could reduce with `//` to get the first defined element of a list:
+# For example, you could reduce with `//` to get
+# the first defined element of a list:
say [//] Nil, Any, False, 1, 5; #=> False
# (Falsey, but still defined)
# Default value examples:
-say [*] (); #=> 1
-say [+] (); #=> 0
- # In both cases, they're results that, if they were contained in the lists,
- # wouldn't have any impact on the final value (since N*1=N and N+0=N).
+say [*] (); #=> 1
+say [+] (); #=> 0
+ # In both cases, they're results that, were they in the lists,
+ # wouldn't have any impact on the final value
+ # (since N*1=N and N+0=N).
say [//]; #=> (Any)
- # There's no "default value" for `//`
+ # There's no "default value" for `//`.
# You can also call it with a function you made up, using double brackets:
sub add($a, $b) { $a + $b }
@@ -980,23 +1137,36 @@ say [[&add]] 1, 2, 3; #=> 6
## * Sequence operator
# The sequence operator is one of Perl 6's most powerful features:
-# it's composed of first, on the left, the list you want Perl 6 to deduce from (and might include a closure),
-# and on the right, a value or the predicate for when to stop, or even Whatever for a lazy infinite list.
+# it's composed of first, on the left, the list you want Perl 6 to deduce from
+# (and might include a closure), and on the right, a value or the predicate
+# that says when to stop (or Whatever for a lazy infinite list).
my @list = 1, 2, 3 ... 10; # basic deducing
-#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, because Perl 6 can't figure out the end
-my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element (when the predicate matches)
-my @list = 1, 3, 9 ... * > 30; # you can use a predicate (with the Whatever Star, here)
+#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop,
+ # because Perl 6 can't figure out the end
+my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element
+ # (the iteration when the predicate matches).
+my @list = 1, 3, 9 ... * > 30; # you can use a predicate
+ # (with the Whatever Star, here).
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, *+* ... *; # lazy infinite list of fibonacci series,
+ # 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.
-# That's why `@primes[^100]` will take a long time the first time you print it, then be instant
+# That's why `@primes[^100]` will take a long time the first time you print
+# it, then be instant.
## * Sort comparison
-# They return one value of the `Order` enum : `Less`, `Same` and `More` (which numerify to -1, 0 or +1).
+# They return one value of the `Order` enum : `Less`, `Same` and `More`
+# (which numerify to -1, 0 or +1).
1 <=> 4; # sort comparison for numerics
'a' leg 'b'; # sort comparison for string
$obj eqv $obj2; # sort comparison using eqv semantics
@@ -1007,21 +1177,24 @@ $obj eqv $obj2; # sort comparison using eqv semantics
## * Short-circuit default operator
# Like `or` and `||`, but instead returns the first *defined* value :
-say Any // Nil // 0 // 5; #=> 5
+say Any // Nil // 0 // 5; #=> 0
## * Short-circuit exclusive or (XOR)
# Returns `True` if one (and only one) of its arguments is true
say True ^^ False; #=> True
## * Flip Flop
-# The flip flop operators (`ff` and `fff`, equivalent to Perl 5/Ruby's `..` and `...`).
+# The flip flop operators (`ff` and `fff`, equivalent to P5's `..`/`...`).
# are operators that take two predicates to test:
-# They are `False` until their left side returns `True`, then are `True` until their right side returns `True`.
-# Like for ranges, you can exclude the iteration when it became `True`/`False` by using `^` on either side.
+# They are `False` until their left side returns `True`, then are `True` until
+# their right side returns `True`.
+# Like for ranges, you can exclude the iteration when it became `True`/`False`
+# by using `^` on either side.
# Let's start with an example :
for <well met young hero we shall meet later> {
# by default, `ff`/`fff` smart-match (`~~`) against `$_`:
- if 'met' ^ff 'meet' { # won't enter the if for "met" (explained in details below).
+ if 'met' ^ff 'meet' { # Won't enter the if for "met"
+ # (explained in details below).
.say
}
@@ -1031,35 +1204,42 @@ for <well met young hero we shall meet later> {
}
# This will print "young hero we shall meet" (excluding "met"):
# the flip-flop will start returning `True` when it first encounters "met"
-# (but will still return `False` for "met" itself, due to the leading `^` on `ff`),
-# until it sees "meet", which is when it'll start returning `False`.
+# (but will still return `False` for "met" itself, due to the leading `^`
+# on `ff`), until it sees "meet", which is when it'll start returning `False`.
# The difference between `ff` (awk-style) and `fff` (sed-style) is that
-# `ff` will test its right side just as its left side changes to `True`,
-# and can get back to `False` right away (*except* it'll be `True` for the iteration that matched)
-# while `fff` will wait for the next iteration to try its right side, once its left side changed:
+# `ff` will test its right side right when its left side changes to `True`,
+# and can get back to `False` right away
+# (*except* it'll be `True` for the iteration that matched) -
+# While `fff` will wait for the next iteration to
+# try its right side, once its left side changed:
.say if 'B' ff 'B' for <A B C B A>; #=> B B
- # because the right-hand-side was tested directly (and returned `True`).
- # "B"s are still printed since it matched that time
- # (it just went back to `False` right away)
+ # because the right-hand-side was tested
+ # directly (and returned `True`).
+ # "B"s are printed since it matched that time
+ # (it just went back to `False` right away).
.say if 'B' fff 'B' for <A B C B A>; #=> B C B
- # because the right-hand-side wasn't tested until `$_` became "C"
- # (and thus did not match directly).
+ # 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"
}
# you might also use a Whatever Star,
# which is equivalent to `True` for the left side or `False` for the right:
-for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here -- sometimes called "superstitious"
- .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50, it'll never go back to `False`
+for (1, 3, 60, 3, 40, 60) { # Note: the parenthesis are superfluous here
+ # (sometimes called "superstitious parentheses")
+ .say if $_ > 50 ff *; # Once the flip-flop reaches a number greater than 50,
+ # it'll never go back to `False`
#=> 60 3 40 60
}
-# You can also use this property to create an `If` that'll not execute the first time :
+# You can also use this property to create an `If`
+# that'll not go through the first time :
for <a b c> {
.say if * ^ff *; # the flip-flop is `True` and never goes back to `False`,
# but the `^` makes it *not run* on the first iteration
@@ -1072,37 +1252,42 @@ for <a b c> {
# Well, now that you know a good deal of Perl 6 already, we can get started.
# First off, you'll have to forget about "PCRE regexps" (perl-compatible regexps).
#
-# IMPORTANT: You may feel like you already know these because you know PCRE. You'd be wrong.
-# Some things are the same (like `?`, `+`, and `*`), but sometimes the semantics change (`|`).
+# IMPORTANT: Don't skip them because you know PCRE. They're different.
+# Some things are the same (like `?`, `+`, and `*`),
+# but sometimes the semantics change (`|`).
# Make sure you read carefully, because you might trip over a new behavior.
#
-# Perl 6 has a looot of features related to RegExps. After all, Rakudo parses itself.
-# We're first going to look at the syntax itself, then talk about grammars (PEG-like),
-# differences between the `token`, `regex` and `rule` keywords, and some more.
+# Perl 6 has many features related to RegExps. After all, Rakudo parses itself.
+# We're first going to look at the syntax itself,
+# then talk about grammars (PEG-like), differences between
+# `token`, `regex` and `rule` declarators, and some more.
# Side note: you still have access to PCRE regexps using the `:P5` modifier.
# (we won't be discussing this in this tutorial, however)
#
# In essence, Perl 6 natively implements PEG ("Parsing Expression Grammars").
-# The pecking order for ambiguous parses is determined by a multi-level tie-breaking test:
+# The pecking order for ambiguous parses is determined by a multi-level
+# tie-breaking test:
# - Longest token matching. `foo\s+` beats `foo` (by 2 or more positions)
# - Longest literal prefix. `food\w*` beats `foo\w*` (by 1)
-# - Declaration from most-derived to less derived grammars (grammars are actually classes)
+# - Declaration from most-derived to less derived grammars
+# (grammars are actually classes)
# - Earliest declaration wins
say so 'a' ~~ /a/; #=> True
say so 'a' ~~ / a /; # More readable with some spaces!
-# In all our examples, we're going to use the smart-matching operator against 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 !).
+# In all our examples, we're going to use the smart-matching operator against
+# 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 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),
# we're going to explain later how you can do it.
-# In Perl 6, you can have any alphanumeric as a literal, everything else has to be escaped,
-# using a backslash or quotes.
+# In Perl 6, you can have any alphanumeric as a literal,
+# everything else has to be escaped, using a backslash or quotes.
say so 'a|b' ~~ / a '|' b /; # `True`. Wouln't mean the same if `|` wasn't escaped
say so 'a|b' ~~ / a \| b /; # `True`. Another way to escape it.
@@ -1137,27 +1322,50 @@ 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".
-# If you squint hard enough, you might understand the why exponentation means quantity.
+# - `**` - (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)
so 'abc' ~~ / a b ** 1..3 c /; # `True` (one to three times)
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 `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
-so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # `True`.
- # We match the "abc" 1 or more time.
- # (the `+` was applied to the group)
+so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
+# The previous line returns `True`.
+# We match the "abc" 1 or more time (the `+` was applied to the group).
-# But this does not go far enough, because we can't actually get back what we matched.
+# 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 `$/`:
@@ -1165,13 +1373,15 @@ say $/; # Will print some weird stuff (we'll explain) (or "Nil" if nothing match
# As we also said before, it has array indexing:
say $/[0]; #=> 「ABC」 「ABC」
- # These weird brackets are `Match` objects. So here, we have an array of that.
-say $0; # the same as above.
+ # These weird brackets are `Match` objects.
+ # Here, we have an array of these.
+say $0; # The same as above.
# Our capture is `$0` because it's the first and only one capture in the regexp.
# You might be wondering why it's an array, and the answer is simple:
# Some capture (indexed using `$0`, `$/[0]` or a named one) will be an array
-# IF it can have more than one element (so, with `*`, `+` and any `**`, but not with `?`).
+# IFF it can have more than one element
+# (so, with `*`, `+` and `**` (whatever the operands), but not with `?`).
# Let's use examples to see that:
so 'fooABCbar' ~~ / foo ( A B C )? bar /; # `True`
say $/[0]; #=> 「ABC」
@@ -1185,29 +1395,68 @@ say $0.WHAT; #=> (Array)
# A specific quantifier will always capture an 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
+# The captures are indexed per nesting. This means a group in a group will be nested
+# under its parent group: `$/[0][0]`, for this code:
+'hello-~-world' ~~ / ( 'hello' ( <[ \- \~ ]> + ) ) 'world' /;
+say $/[0].Str; #=> hello~
+say $/[0][0].Str; #=> ~
+# This stems from a very simple fact: `$/` does not contain strings, integers or arrays,
+# it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods.
+# (but you can also just use `match<key>` for hash access and `match[idx]` for array access)
+say $/[0].list.perl; #=> (Match.new(...),).list
+ # We can see it's a list of Match objects. Those contain a bunch of infos:
+ # where the match started/ended, the "ast" (see actions later), etc.
+ # You'll see named capture below with grammars.
## Alternatives - the `or` of regexps
# WARNING: They are DIFFERENT from PCRE regexps.
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 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
# and pass them as such to the sub. It also handles named argument (`--foo`)
# and will even go as far as to autogenerate a `--help`
-sub MAIN($name) { say "Hello, you !" }
+sub MAIN($name) { say "Hello, $name !" }
# This produces:
# $ perl6 cli.pl
# Usage:
# 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` instead of `--replace=`)
-subset File of Str where *.IO.d; # convert to IO object, then check the file exists
+# (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 to check the file exists
multi MAIN('add', $key, $value, Bool :$replace) { ... }
multi MAIN('remove', $key) { ... }
@@ -1218,12 +1467,15 @@ multi MAIN('import', File, Str :$as) { ... } # omitting parameter name
# t.pl [--replace] add <key> <value>
# t.pl remove <key>
# t.pl [--as=<Str>] import (File)
-# As you can see, this is *very* powerful. It even went as far as to show inline the constants.
-# (the type is only displayed if 1. there's no argument name 2. it's a named argument)
+# As you can see, this is *very* powerful.
+# It even went as far as to show inline the constants.
+# (the type is only displayed if the argument is `$`/is named)
```
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/php.html.markdown b/php.html.markdown
index e1bb86a0..039288a0 100644
--- a/php.html.markdown
+++ b/php.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
diff --git a/pl-pl/perl-pl.html.markdown b/pl-pl/perl-pl.html.markdown
new file mode 100644
index 00000000..9e8ade5b
--- /dev/null
+++ b/pl-pl/perl-pl.html.markdown
@@ -0,0 +1,169 @@
+---
+name: perl
+category: language
+language: perl
+filename: learnperl.pl
+contributors:
+ - ["Korjavin Ivan", "http://github.com/korjavin"]
+ - ["Michał Kupczyński", "http://github.com/ukoms"]
+lang: pl-pl
+---
+
+Perl 5 jest wysoce użytecznym, bogatym w wiele opcji językiem programowania
+z ponad 25 latami nieustannego rozwoju.
+
+Perl 5 używany jest na ponad 100 różnych platformach (od przenośnych do w
+pełni stacjonarnych) i nadaje się zarówno do szybkiego prototypowania jak
+i projektów deweloperskich prowadzonych na szeroką skalę.
+
+```perl
+
+# Pojedyncza linia komentarza zaczyna się od znaku hasha (płotka) "#".
+
+#### Typy zmiennych w Perlu
+
+# Zmienna zaczyna się od symbolu dolara "$".
+# Prawidłowa nazwa zmiennej zaczyna się od litery lub podkreślnika "_",
+# po których następuje dowolna ilość liter, cyfr i podkreślników.
+
+### W Perlu występują trzy główne typy zmiennych: skalary, tablice i hasze.
+
+## Skalary
+# Skalar przechowuje pojedynczą wartość:
+my $zwierze = "wielbłąd";
+my $odpowiedź = 42;
+
+# Wartości skalarne mogą być ciągami znaków, liczbami całkowitymi lub
+# zmiennoprzecinkowymi, zaś Perl automatycznie dokonuje konwersji pomiędzy nimi,
+# w zależności od wykonywanego kodu/kontekstu.
+
+## Tablice
+# Tablica przechowuje listę wartości:
+my @zwierzęta = ("wielbłąd", "alpaka", "sowa");
+my @liczby = (23, 42, 69);
+my @mieszanka = ("wielbłąd", 42, 1.23);
+
+## Hasze
+# Hasz przechowuje zestawy par klucz-wartość:
+my %kolor_owocu = ('jabłko', 'czerwony', 'banan', 'żółty');
+
+# Możesz używać białych znaków (spacje, tabulatory) i operatora strzałki "=>"
+# by czytelniej sformatować zapis hasza:
+my %kolor_owocu = (
+ jabłko => 'czerwony',
+ banan => 'żółty',
+);
+
+# Skalary, tablice i hasze są bardziej wyczerpująco udokumentowane w dokumencie
+# [perldoc perldata](http://perldoc.perl.org/perldata.html).
+
+# Bardziej złożone typy danych mogą być stworzone poprzez używanie referencji,
+# które pozwalają Ci zbudować listy i hasze wewnątrz list i haszy.
+
+#### Warunki logiczne i pętle
+
+# W Perlu występują typowe warunki i pętle.
+if ($var) {
+ ...
+} elsif ($var eq 'bar') {
+ ...
+} else {
+ ...
+}
+
+unless (warunek) {
+ ...
+}
+# Powyższy zapis jest równoznaczny zapisowi "if (!warunek)"
+
+# Perlowy skrócony zapis warunków:
+print "Siema!" if $rozochocony;
+print "Nie mamy bananów" unless $banany;
+
+# Pętla while
+while (warunek) {
+ ...
+}
+
+# Pętle for oraz foreach
+for ($i = 0; $i <= $max; $i++) {
+ ...
+}
+
+foreach (@tablica) {
+ print "Tym elementem jest $_\n";
+}
+
+# lub
+
+foreach my $iterator (@tablica) {
+ print "Iterowanym elementem jest $iterator\n";
+}
+
+#### Wyrażenia regularne
+
+# Perlowe wyrażenia regularne są tematem tak rozległym, jak wymagającym.
+# Istnieje ogromna ilość dokumentacji w artykułach takich jak
+# [perlrequick](http://perldoc.perl.org/perlrequick.html),
+# [perlretut](http://perldoc.perl.org/perlretut.html) i inne.
+# W dużym skrócie, podstawy perlowych wyrażeń regularnych są następujące:
+
+# Proste dopasowanie:
+if (/foo/) { ... } # prawda jeżeli $_ zawiera "foo"
+if ($a =~ /foo/) { ... } # prawda jeżeli $a zawiera "foo"
+
+# Prosta zamiana:
+# Zamienia "foo" na "bar" w zmiennej $a
+$a =~ s/foo/bar/;
+# Zamienia WSZYSTKIE WYSTĄPIENIA "foo" na "bar" w zmiennej $a
+$a =~ s/foo/bar/g;
+
+#### Pliki i I/O
+
+# Możesz otworzyć plik do odczytu lub zapisu używając funkcji "open ()".
+open (my $odczyt, "<", "odczyt.txt") or die "Błąd otwierania input.txt: $!";
+open (my $zapis, ">", "zapis.txt") or die "Błąd otwierania output.txt: $!";
+open (my $dopisanie, ">>", "my.log") or die "Błąd otwierania my.log: $!";
+
+# Pliki możesz odczytywać z otworzonego handlera używając operatora "<>"
+# (operator diamentowy). W kontekście skalarnym (przypisanie wyniku do skalara)
+# operator ten zczytuje pojedynczą linię pliku, w kontekście listowym
+# (przypisanie wyniku do tablicy) zczytuje całą zawartość pliku, przypisując
+# każdą linię jako kolejny element listy:
+my $linia = <$in>;
+my @linie = <$in>;
+
+#### Perlowe funkcje (procedury)
+
+# Pisanie funkcji (procedur) jest proste:
+sub logger {
+ my $wiadomosc_do_loga = shift;
+ open (my HANDLER, ">>", "my.log") or die "Błąd otwierania my.log: $!";
+ print HANDLER $wiadomosc_do_loga;
+}
+
+# Teraz można używać napisanej funkcji, tak jak każdej innej wbudowanej
+# funkcji perlowej:
+logger ("Mamy funkcję perlową");
+
+```
+
+#### Używanie modułów perlowych
+
+Moduły perlowe dostarczają szeroki wachlarz możliwości, byś nie musiał
+wynajdywać koła na nowo. Moduły te można pobrać z [CPAN](http://www.cpan.org).
+Sam Perl zawiera w swoich dystrybucjach kilka najpopularniejszych modułów
+z repozytorium [CPAN](http://www.cpan.org).
+
+Najczęściej zadawane pytania [perlfaq](http://perldoc.perl.org/perlfaq.html)
+- zawierają pytania i odpowiedzi dotyczące wielu typowo realizowanych zadań.
+Często znajdziesz tam również sugestie dotyczące użycia najlepszego modułu
+z repozytorium CPAN do zrealizowania konkretnego zadania.
+
+
+#### Do doczytania
+
+ - [perl-tutorial](http://perl-tutorial.org/)
+ - [Naucz się Perla na www.perl.com](http://www.perl.org/learn.html)
+ - [perldoc](http://perldoc.perl.org/)
+ - wbudowane w Perla: `perldoc perlintro` \ No newline at end of file
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/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown
new file mode 100644
index 00000000..885d5b27
--- /dev/null
+++ b/pt-br/groovy-pt.html.markdown
@@ -0,0 +1,435 @@
+---
+language: Groovy
+category: language
+filename: learngroovy.groovy
+contributors:
+ - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"]
+translators:
+ - ["João Farias", "https://github.com/JoaoGFarias"]
+lang: pt-br
+---
+
+Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://groovy.codehaus.org)
+
+```groovy
+
+/*
+ Prepara-se:
+
+ 1) Instale a máquina virtual de Groovy - http://gvmtool.net/
+ 2) Intalse o Groovy: gvm install groovy
+ 3) Inicie o console groovy digitando: groovyConsole
+
+*/
+
+// Comentário de uma linha inicia-se com duas barras
+/*
+Comentário de múltiplas linhas são assim.
+*/
+
+// Olá Mundo!
+println "Olá mundo!"
+
+/*
+ Variáveis:
+
+ Você pode atribuir valores a variáveis para uso posterior
+*/
+
+def x = 1
+println x
+
+x = new java.util.Date()
+println x
+
+x = -3.1499392
+println x
+
+x = false
+println x
+
+x = "Groovy!"
+println x
+
+/*
+ Coleções e mapeamentos
+*/
+
+//Criando uma lista vazia
+def tecnologias = []
+
+/*** Adicionando elementos à lista ***/
+
+// Assim como Java
+tecnologias.add("Grails")
+
+// Shift para esquerda adiciona e retorna a lista
+tecnologias << "Groovy"
+
+// Adição de múltiplos elementos
+tecnologias.addAll(["Gradle","Griffon"])
+
+/*** Removendo elementos da lista ***/
+
+// Assim como Java
+tecnologias.remove("Griffon")
+
+// Subtração também funciona
+tecnologias = technologies - 'Grails'
+
+/*** Iterando sobre listas ***/
+
+// Itera sobre os elementos da lista
+tecnologias.each { println "Tecnologias: $it"}
+tecnologias.eachWithIndex { it, i -> println "$i: $it"}
+
+/*** Checando os elementos da lista ***/
+
+//Avalia se a lista contém o elemento 'Groovy'
+contem = tecnologias.contains( 'Groovy' )
+
+// Ou
+contem = 'Groovy' in tecnologias
+
+// Checagem por múltiplos elementos
+tecnologias.containsAll(['Groovy','Grails'])
+
+/*** Ordenando listas ***/
+
+// Ordena a lista (altera a lista in-place)
+tecnologias.sort()
+
+// Para ordenar a lista sem alterar a original
+tecnologiasOrdenadas = tecnologias.sort( false )
+
+/*** Manipulando listas ***/
+
+//Substitue todos os elementos da lista
+Collections.replaceAll(tecnologias, 'Gradle', 'gradle')
+
+//Desorganiza a lista
+Collections.shuffle(tecnologias, new Random())
+
+//Limpa a lista
+technologies.clear()
+
+//Criando um mapeamento vazio
+def devMap = [:]
+
+//Adicionando valores
+devMap = ['nome':'Roberto', 'framework':'Grails', 'linguagem':'Groovy']
+devMap.put('ultimoNome','Perez')
+
+//Iterando sobre os elementos do mapeamento
+devMap.each { println "$it.key: $it.value" }
+devMap.eachWithIndex { it, i -> println "$i: $it"}
+
+//Avalia se um mapeamento contém uma chave
+assert devMap.containsKey('nome')
+
+//Avalia se um mapeamento contém um valor
+assert devMap.containsValue('Roberto')
+
+//Pega as chaves de um mapeamento
+println devMap.keySet()
+
+//Pega os valores de um mapeamento
+println devMap.values()
+
+/*
+ Groovy Beans
+
+ GroovyBeans são JavaBeans com uma sintaxe muito mais simples.
+
+ Quando Groovy é compilado para bytecode, as seguintes regras são usadas:
+
+ * Se o nome é declarado com um modificador de acesso(public, private or
+ protected) então um atributo é gerado.
+
+ * Um nome declarado sem modificador de acesso gera um campo privado com
+ getter e setter públicos (ou seja, uma propriedade).
+
+ * Se uma propriedade é declarada como final, um campo private final é criado
+ e o setter não é gerado.
+
+ * Você pode declarar uma propriedade e também declarar seus próprios getters
+ e setters.
+
+ * Você pode declarar uma propriedade e um campo com o mesmo nome, a propriedade
+ usará este campo.
+
+ * Se você quer uma propriedade private ou protected, você deve prover seus
+ próprios getters e setter, que devem ser declarados como private ou protected.
+
+ * Se você acessar uma propriedade dentro da classe e esta propriedade é definida
+ em tempo de compilação com 'this', implícito ou explícito (por exemplo,
+ this.foo, ou simplesmente foo), Groovy acessará este campo diretamente, sem
+ passar pelo getter ou setter.
+
+ * Se você acessar uma propriedade que não existe usando foo, explicitamente ou
+ implicitamente, então Groovy irá acessar esta propriedade através da meta
+ classe, o que pode falhar em tempo de execução.
+
+*/
+
+class Foo {
+ // propriedade de leitura, apenas
+ final String nome = "Roberto"
+
+ // propriedade de leitura, apenas, com getter e setter públicos
+ String linguagem
+ protected void setLinguagem(String linguagem) { this.linguagem = linguagem }
+
+ // propriedade tipada dinamicamente
+ def ultimoNome
+}
+
+/*
+ Condicionais e loops
+*/
+
+//Groovy suporta a sintaxe if-else
+def x = 3
+
+if(x==1) {
+ println "Um"
+} else if(x==2) {
+ println "Dois"
+} else {
+ println "X é maior que Dois"
+}
+
+//Groovy também suporta o operador ternário
+def y = 10
+def x = (y > 1) ? "functionou" : "falhou"
+assert x == "functionou"
+
+//Loop 'for'
+//Itera sobre um intervalo (range)
+def x = 0
+for (i in 0 .. 30) {
+ x += i
+}
+
+//Itera sobre uma lista
+x = 0
+for( i in [5,3,2,1] ) {
+ x += i
+}
+
+//Itera sobre um array
+array = (0..20).toArray()
+x = 0
+for (i in array) {
+ x += i
+}
+
+//Itera sobre um mapa
+def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy']
+x = 0
+for ( e in map ) {
+ x += e.value
+}
+
+/*
+ Operadores
+
+ Sobrecarregamento de Operadores para uma lsita dos operadores comuns que
+ Grooby suporta:
+ http://groovy.codehaus.org/Operator+Overloading
+
+ Operadores Groovy úteis
+*/
+//Operador de espalhamento: invoca uma ação sobre todos os itens de um
+//objeto agregador.
+def tecnologias = ['Groovy','Grails','Gradle']
+tecnologias*.toUpperCase() // = to tecnologias.collect { it?.toUpperCase() }
+
+//Operador de navegação segura: usado para evitar NullPointerException.
+def usuario = User.get(1)
+def nomeUsuario = usuario?.nomeUsuario
+
+
+/*
+ Closures
+ Um closure, em Grooby, é como um "bloco de código" ou um ponteiro para método.
+ É um pedação de código que é definido e executado em um momento posterior.
+
+ Mais informação em: http://groovy.codehaus.org/Closures+-+Formal+Definition
+*/
+//Exemplo:
+def clos = { println "Hello World!" }
+
+println "Executando o closure:"
+clos()
+
+//Passando parêmetros para um closure
+def soma = { a, b -> println a+b }
+soma(2,4)
+
+//Closdures por referir-se a variáveis que não estão listadas em sua
+//lista de parêmetros.
+def x = 5
+def multiplicarPor = { num -> num * x }
+println multiplicarPor(10)
+
+// Se você tiver um closure que tem apenas um argumento, você pode omitir
+// o parâmetro na definição do closure
+def clos = { print it }
+clos( "oi" )
+
+/*
+ Groovy pode memorizar resultados de closures [1][2][3]
+*/
+def cl = {a, b ->
+ sleep(3000) // simula processamento
+ a + b
+}
+
+mem = cl.memoize()
+
+def chamaClosure(a, b) {
+ def inicio = System.currentTimeMillis()
+ mem(a, b)
+ println "Os inputs(a = $a, b = $b) - tomam ${System.currentTimeMillis() - inicio} msecs."
+}
+
+chamaClosure(1, 2)
+chamaClosure(1, 2)
+chamaClosure(2, 3)
+chamaClosure(2, 3)
+chamaClosure(3, 4)
+chamaClosure(3, 4)
+chamaClosure(1, 2)
+chamaClosure(2, 3)
+chamaClosure(3, 4)
+
+/*
+ Expando
+
+ A classe Expando é um bean dinâmico que permite adicionar propriedade e
+ closures como métodos a uma instância desta classe
+
+ http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html
+*/
+ def usuario = new Expando(nome:"Roberto")
+ assert 'Roberto' == nome.name
+
+ nome.lastName = 'Pérez'
+ assert 'Pérez' == nome.lastName
+
+ nome.showInfo = { out ->
+ out << "Name: $name"
+ out << ", Last name: $lastName"
+ }
+
+ def sw = new StringWriter()
+ println nome.showInfo(sw)
+
+
+/*
+ Metaprogramação (MOP)
+*/
+
+//Usando a ExpandoMetaClasse para adicionar comportamento
+String.metaClass.testAdd = {
+ println "adicionamos isto"
+}
+
+String x = "teste"
+x?.testAdd()
+
+//Interceptando chamadas a métodos
+class Test implements GroovyInterceptable {
+ def soma(Integer x, Integer y) { x + y }
+
+ def invocaMetodo(String name, args) {
+ System.out.println "Invoca método $name com argumentos: $args"
+ }
+}
+
+def teste = new Test()
+teste?.soma(2,3)
+teste?.multiplica(2,3)
+
+//Groovy suporta propertyMissing para lidar com tentativas de resolução de
+//propriedades.
+class Foo {
+ def propertyMissing(String nome) { nome }
+}
+def f = new Foo()
+
+assertEquals "boo", f.boo
+
+/*
+ TypeChecked e CompileStatic
+ Groovy, por natureza, é e sempre será uma linguagem dinâmica, mas ela também
+ suporta typecheked e compilestatic
+
+ Mais informações: http://www.infoq.com/articles/new-groovy-20
+*/
+//TypeChecked
+import groovy.transform.TypeChecked
+
+void testeMethod() {}
+
+@TypeChecked
+void test() {
+ testeMethod()
+
+ def nome = "Roberto"
+
+ println noomee
+
+}
+
+//Outro exemplo:
+import groovy.transform.TypeChecked
+
+@TypeChecked
+Integer test() {
+ Integer num = "1"
+
+ Integer[] numeros = [1,2,3,4]
+
+ Date dia = numeros[1]
+
+ return "Teste"
+
+}
+
+//Exemplo de CompileStatic :
+import groovy.transform.CompileStatic
+
+@CompileStatic
+int soma(int x, int y) {
+ x + y
+}
+
+assert soma(2,5) == 7
+
+
+```
+
+## Referências
+
+[Groovy documentation](http://groovy.codehaus.org/Documentation)
+
+[Groovy web console](http://groovyconsole.appspot.com/)
+
+Junte-se a um [grupo de usuários Groovy](http://groovy.codehaus.org/User+Groups)
+
+## Livro
+
+* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook)
+
+* [Groovy in Action] (http://manning.com/koenig2/)
+
+* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do)
+
+[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/
+[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize
+[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html
+
+
+
diff --git a/pt-br/haskell-pt.html.markdown b/pt-br/haskell-pt.html.markdown
index 55f90bd6..788dc1d2 100644
--- a/pt-br/haskell-pt.html.markdown
+++ b/pt-br/haskell-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
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/pt-br/php-pt.html.markdown b/pt-br/php-pt.html.markdown
index 344df43a..0e710742 100644
--- a/pt-br/php-pt.html.markdown
+++ b/pt-br/php-pt.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
diff --git a/pt-br/ruby-pt.html.markdown b/pt-br/ruby-pt.html.markdown
index 4a8a1b5c..89a051d4 100644
--- a/pt-br/ruby-pt.html.markdown
+++ b/pt-br/ruby-pt.html.markdown
@@ -33,7 +33,7 @@ Você não deve usar também
10 * 2 #=> 20
35 / 5 #=> 7
-# Aritimética é apenas açúcar sintático
+# Aritmética é apenas açúcar sintático
# para chamar um método de um objeto
1.+(3) #=> 4
10.* 5 #=> 50
@@ -129,7 +129,7 @@ array = [1, "Oi", false] #=> => [1, "Oi", false]
array[0] #=> 1
array[12] #=> nil
-# Como aritimética, o acesso via [var]
+# Como aritmética, o acesso via [var]
# é apenas açúcar sintático
# para chamar o método [] de um objeto
array.[] 0 #=> 1
@@ -171,7 +171,7 @@ end
# Desde o Ruby 1.9, temos uma sintaxe especial quando usamos símbolos como chaves (keys)
-novo_hash = { defcon: 3, acao: true}
+novo_hash = {defcon: 3, acao: true}
novo_hash.keys #=> [:defcon, :acao]
@@ -183,9 +183,9 @@ novo_hash.keys #=> [:defcon, :acao]
if true
"Se verdadeiro"
elsif false
- "else if, opicional"
+ "else if, opcional"
else
- "else, também é opicional"
+ "else, também é opcional"
end
for contador in 1..5
@@ -259,7 +259,7 @@ end
# Argumentos de métodos são separados por uma vírgula
somar 3, 4 #=> 7
-somar somar(3,4), 5 #=> 12
+somar(3,4), 5 #=> 12
# yield
# Todos os métodos possuem implicitamente um paramêntro opcional que é um bloco
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..53381f32 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -3,24 +3,25 @@ language: python
contributors:
- ["Louie Dinh", "http://ldinh.ca"]
- ["Amin Bandali", "http://aminbandali.com"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython.py
---
-Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular
+Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
languages in existence. I fell in love with Python for its syntactic clarity. It's basically
executable pseudocode.
Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service]
Note: This article applies to Python 2.7 specifically, but should be applicable
-to Python 2.x. Look for another tour of Python 3 soon!
+to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial.
```python
# Single line comments start with a number symbol.
""" Multiline strings can be written
- using three "'s, and are often used
+ using three "s, and are often used
as comments
"""
@@ -54,12 +55,23 @@ to Python 2.x. Look for another tour of Python 3 soon!
# Modulo operation
7 % 3 # => 1
+# Exponentiation (x to the yth power)
+2**4 # => 16
+
# 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
@@ -90,6 +102,9 @@ not False # => True
# Strings can be added too!
"Hello " + "world!" # => "Hello world!"
+# ... or multiplied
+"Hello" * 3 # => "HelloHelloHello"
+
# A string can be treated like a list of characters
"This is a string"[0] # => 'T'
@@ -124,11 +139,12 @@ bool("") # => False
## 2. Variables and Collections
####################################################
-# Python has a print function, available in versions 2.7 and 3...
-print("I'm Python. Nice to meet you!")
-# and an older print statement, in all 2.x versions but removed from 3.
-print "I'm also Python!"
-
+# Python has a print statement, in all 2.x versions but removed from 3.
+print "I'm Python. Nice to meet you!"
+# Python also has a print function, available in versions 2.7 and 3...
+# but for 2.7 you need to add the import (uncommented):
+# from __future__ import print_function
+print("I'm also Python! ")
# No need to declare variables before assigning to them.
some_var = 5 # Convention is to use lower_case_with_underscores
@@ -158,6 +174,10 @@ li.append(3) # li is now [1, 2, 4, 3] again.
# Access a list like you would any array
li[0] # => 1
+# Assign new values to indexes that have already been initialized with =
+li[0] = 42
+li[0] # => 42
+li[0] = 1 # Note: setting it back to the original value
# Look at the last element
li[-1] # => 3
@@ -182,7 +202,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.
+li + other_li # => [1, 2, 3, 4, 5, 6]
+# Note: values for li and for other_li are not modified.
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
@@ -243,17 +264,25 @@ filled_dict.get("four") # => None
# The get method supports a default argument when the value is missing
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
+# note that filled_dict.get("four") is still => 4
+# (get doesn't set the value in the dictionary)
+
+# set the value of a key with a syntax similar to lists
+filled_dict["four"] = 4 # now, filled_dict["four"] => 4
# "setdefault()" inserts into a dictionary only if the given key isn't present
filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5
filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5
-# Sets store ... well sets
+# Sets store ... well sets (which are like lists but can contain no duplicates)
empty_set = set()
# Initialize a "set()" with a bunch of values
some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4])
+# order is not guaranteed, even though it may sometimes look sorted
+another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4])
+
# Since Python 2.7, {} can be used to declare a set
filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
@@ -359,7 +388,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
-# positional arguments
+# positional args, which will be interpreted as a tuple if you do not use the *
def varargs(*args):
return args
@@ -367,7 +396,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
-# keyword arguments, as well
+# keyword args, as well, which will be interpreted as a map if you do not use **
def keyword_args(**kwargs):
return kwargs
@@ -386,26 +415,33 @@ all_the_args(1, 2, a=3, b=4) prints:
"""
# When calling functions, you can do the opposite of args/kwargs!
-# Use * to expand tuples and use ** to expand kwargs.
+# Use * to expand positional args and use ** to expand keyword args.
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equivalent to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
+# you can pass args and kwargs along to other functions that take args/kwargs
+# by expanding them with * and ** respectively
+def pass_all_the_args(*args, **kwargs):
+ all_the_args(*args, **kwargs)
+ print varargs(*args)
+ print keyword_args(**kwargs)
+
# Function Scope
x = 5
def setX(num):
# Local var x not the same as global variable x
x = num # => 43
- print (x) # => 43
+ print x # => 43
def setGlobalX(num):
global x
- print (x) # => 5
+ print x # => 5
x = num # global var x is now set to 6
- print (x) # => 6
+ print x # => 6
setX(43)
setGlobalX(6)
@@ -430,11 +466,11 @@ 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]
+
####################################################
## 5. Classes
####################################################
-
# We subclass from object to get a class.
class Human(object):
@@ -504,6 +540,9 @@ from math import *
# You can shorten module names
import math as m
math.sqrt(16) == m.sqrt(16) # => True
+# you can also test that the functions are equivalent
+from math import sqrt
+math.sqrt == m.sqrt == sqrt # => True
# Python modules are just ordinary python files. You
# can write your own, and import them. The name of the
@@ -530,8 +569,9 @@ def double_numbers(iterable):
# double_numbers.
# Note xrange is a generator that does the same thing range does.
# Creating a list 1-900000000 would take lot of time and space to be made.
-# xrange creates an xrange generator object instead of creating the entire list like range does.
-# We use a trailing underscore in variable names when we want to use a name that
+# xrange creates an xrange generator object instead of creating the entire list
+# like range does.
+# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
xrange_ = xrange(1, 900000000)
diff --git a/python3.html.markdown b/python3.html.markdown
index b494dc1e..0b4feccc 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -3,10 +3,11 @@ language: python3
contributors:
- ["Louie Dinh", "http://pythonpracticeprojects.com"]
- ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
filename: learnpython3.py
---
-Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular
+Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular
languages in existence. I fell in love with Python for its syntactic clarity. It's basically
executable pseudocode.
@@ -19,7 +20,7 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Single line comments start with a number symbol.
""" Multiline strings can be written
- using three "'s, and are often used
+ using three "s, and are often used
as comments
"""
@@ -50,6 +51,9 @@ Note: This article applies to Python 3 specifically. Check out the other tutoria
# Modulo operation
7 % 3 # => 1
+# Exponentiation (x to the yth power)
+2**4 # => 16
+
# Enforce precedence with parentheses
(1 + 3) * 2 # => 8
@@ -61,6 +65,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 +109,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 +143,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 +193,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 +233,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 +263,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 +483,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..c555d748 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.
@@ -179,7 +179,7 @@ c(3,3,3,2,2,1) # 3 3 3 2 2 1
# You can also have infinitely large or small numbers
class(Inf) # "numeric"
class(-Inf) # "numeric"
-# You might use "Inf", for example, in integrate( dnorm(x), 3, Inf);
+# You might use "Inf", for example, in integrate(dnorm, 3, Inf);
# this obviates Z-score tables.
# BASIC ARITHMETIC
@@ -236,11 +236,12 @@ c('Z', 'o', 'r', 'r', 'o') == "Z" # TRUE FALSE FALSE FALSE FALSE
# FACTORS
# The factor class is for categorical data
# Factors can be ordered (like childrens' grade levels) or unordered (like gender)
-factor(c("female", "female", "male", "NA", "female"))
-# female female male NA female
-# Levels: female male NA
+factor(c("female", "female", "male", NA, "female"))
+# female female male <NA> female
+# Levels: female male
# The "levels" are the values the categorical data can take
-levels(factor(c("male", "male", "female", "NA", "female"))) # "female" "male" "NA"
+# Note that missing data does not enter the levels
+levels(factor(c("male", "male", "female", NA, "female"))) # "female" "male"
# If a factor vector has length 1, its levels will have length 1, too
length(factor("male")) # 1
length(levels(factor("male"))) # 1
diff --git a/ru-ru/coffeescript-ru.html.markdown b/ru-ru/coffeescript-ru.html.markdown
new file mode 100644
index 00000000..f8416f38
--- /dev/null
+++ b/ru-ru/coffeescript-ru.html.markdown
@@ -0,0 +1,104 @@
+---
+language: coffeescript
+contributors:
+ - ["Tenor Biel", "http://github.com/L8D"]
+ - ["Xavier Yao", "http://github.com/xavieryao"]
+translators:
+ - ["asaskevich", "http://github.com/asaskevich"]
+filename: learncoffee-ru.coffee
+lang: ru-ru
+---
+
+CoffeeScript - это небольшой язык, который компилируется один-в-один в эквивалентный код на языке JavaScript, а потому он не интерпретируется во время исполнения JavaScript кода.
+Ключевой особенностью CoffeeScript является то, что он пытается создать читабельный, качественно оформленный и плавный JavaScript код, прекрасно работающий в любой среде JavaScript.
+
+Также загляните на официальный сайт [языка](http://coffeescript.org/), где можно найти весьма полное учебное пособие по CoffeeScript.
+
+```coffeescript
+# CoffeeScript - язык хипстеров.
+# Язык использует самое модное из множества современных языков.
+# Эти комментарии по стилю похожи на комментарии Ruby или Python, они используют "решетку" в качестве знака комментария.
+
+###
+Блоки комментариев выделяются тремя символами "решетки", в результирующем JavaScript коде они будут преобразованы в '/ * и '* /'.
+
+Перед тем, как идти далее, Вам нужно понимать семантику JavaScript.
+###
+
+# Присвоение:
+number = 42 #=> var number = 42;
+opposite = true #=> var opposite = true;
+
+# Условия:
+number = -42 if opposite #=> if(opposite) { number = -42; }
+
+# Функции:
+square = (x) -> x * x #=> var square = function(x) { return x * x; }
+
+fill = (container, liquid = "coffee") ->
+ "Заполняем #{container} жидкостью #{liquid}..."
+#=>var fill;
+#
+#fill = function(container, liquid) {
+# if (liquid == null) {
+# liquid = "coffee";
+# }
+# return "Заполняем " + container + " жидкостью " + liquid + "...";
+#};
+
+# Списки и диапазоны:
+list = [1..5] #=> var list = [1, 2, 3, 4, 5];
+
+# Объекты:
+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); }
+#}
+
+# Многоточия:
+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);
+#};
+
+# Проверка на существование объекта:
+alert "Так и знал!" if elvis?
+#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Так и знал!"); }
+
+# Итерации по массивам:
+cubes = (math.cube num for num in list)
+#=>cubes = (function() {
+# var _i, _len, _results;
+# _results = [];
+# for (_i = 0, _len = list.length; _i < _len; _i++) {
+# num = list[_i];
+# _results.push(math.cube(num));
+# }
+# return _results;
+# })();
+
+foods = ['broccoli', 'spinach', 'chocolate']
+eat food for food in foods when food isnt 'chocolate'
+#=>foods = ['broccoli', 'spinach', 'chocolate'];
+#
+#for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
+# food = foods[_k];
+# if (food !== 'chocolate') {
+# eat(food);
+# }
+#}
+```
+
+## На почитать
+
+- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/)
+- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read)
+- [CoffeeScript на русском](http://cidocs.ru/coffeescript/)
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/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown
index 03e66d05..e15fe6b7 100644
--- a/ru-ru/haskell-ru.html.markdown
+++ b/ru-ru/haskell-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
contributors:
- ["Adit Bhargava", "http://adit.io"]
translators:
diff --git a/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
new file mode 100644
index 00000000..005495cc
--- /dev/null
+++ b/ru-ru/java-ru.html.markdown
@@ -0,0 +1,506 @@
+---
+language: java
+contributors:
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Madison Dickson", "http://github.com/mix3d"]
+translators:
+ - ["Sergey Gaykov", "https://github.com/gaykov"]
+filename: LearnJavaRu.java
+lang: ru-ru
+---
+
+Java - это объектно ориентированный язык программирования общего назначения,
+основанный на классах и поддерживающий параллельное программирование.
+[Подробнее читайте здесь.](http://docs.oracle.com/javase/tutorial/java/index.html)
+
+```java
+// Однострочные комментарии начинаются с //.
+/*
+Многострочные комментарии
+выглядят так.
+*/
+/**
+JavaDoc-комментарии выглядят так. Они используются для описания класса
+и его членов.
+*/
+
+// Импорт класса ArrayList из пакета java.util.
+import java.util.ArrayList;
+// Импорт всех классов из пакета java.security.
+import java.security.*;
+
+// Каждый .java файл содержит один публичный класс, имя которого совпадает с
+// именем файла.
+public class LearnJavaRu {
+
+ // Программа должна содержать метод main, который является точкой входа.
+ public static void main (String[] args) {
+
+ // System.out.println используется для печати строк.
+ System.out.println("Hello World!");
+ System.out.println(
+ "Integer: " + 10 +
+ " Double: " + 3.14 +
+ " Boolean: " + true);
+
+ // Чтобы напечатать что-либо не заканчивая переводом строки
+ // используется System.out.print.
+ System.out.print("Hello ");
+ System.out.print("World");
+
+
+ ///////////////////////////////////////
+ // Типы и Переменные
+ ///////////////////////////////////////
+
+ // Переменные объявляются с использованием <тип> <имя>
+ // Byte - 8-битное целое число.
+ // (-128 <= byte <= 127)
+ byte fooByte = 100;
+
+ // Short - 16-битное целое число.
+ // (-32,768 <= short <= 32,767)
+ short fooShort = 10000;
+
+ // Integer - 32-битное целое число.
+ // (-2,147,483,648 <= int <= 2,147,483,647)
+ int fooInt = 1;
+
+ // Long - 64-битное целое число.
+ // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807)
+ long fooLong = 100000L;
+ // L используется для указания на то, что переменная имеет тип long;
+ // По умолчанию, числа без L являются integer.
+
+ // Замечание: в Java нет беззнаковых типов.
+
+ // Float - 32-битное IEEE 754 число с плавающей запятой с одинарной степенью точности.
+ float fooFloat = 234.5f;
+ // f используется для указания на то, что переменная имеет тип float;
+ // иначе, число являлось бы double.
+
+ // Double - 64-битное IEEE 754 число с плавающей запятой с двойной степенью точности.
+ double fooDouble = 123.4;
+
+ // Boolean - true или false
+ boolean fooBoolean = true;
+ boolean barBoolean = false;
+
+ // Char - Простой 16-битный символ Unicode.
+ char fooChar = 'A';
+
+ // Переменным final не может быть присвоен другой объект.
+ final int HOURS_I_WORK_PER_WEEK = 9001;
+
+ // Строки.
+ String fooString = "My String Is Here!";
+
+ // \n - это экранированный символ, который означает начало новой строки.
+ String barString = "Printing on a new line?\nNo Problem!";
+ // \t - это экранированный символ, который добавляет символ табуляции.
+ String bazString = "Do you want to add a tab?\tNo Problem!";
+ System.out.println(fooString);
+ System.out.println(barString);
+ System.out.println(bazString);
+
+ // Массивы
+ // Размер массива должен быть указан при объявлении.
+ // Объявлять массив можно в следующих форматах:
+ //<тип данных> [] <имя> = new <тип данных>[<размер массива>];
+ //<тип данных> <имя>[] = new <тип данных>[<размер массива>];
+ int [] intArray = new int[10];
+ String [] stringArray = new String[1];
+ boolean boolArray [] = new boolean[100];
+
+ // Другой способ объявления и инициализации массива:
+ int [] y = {9000, 1000, 1337};
+ String names [] = {"Bob", "John", "Fred", "Juan Pedro"};
+ boolean bools[] = new boolean[] {true, false, false};
+
+ // Индексация массива - доступ к элементу.
+ System.out.println("intArray @ 0: " + intArray[0]);
+
+ // Массивы изменяемы и индекс в них начинается с 0.
+ intArray[1] = 1;
+ System.out.println("intArray @ 1: " + intArray[1]); // => 1
+
+ // Дополнительно.
+ // ArrayLists - похож на массив, но предлагает больше возможностей,
+ // его размер изменяемый.
+ // LinkedLists - реализация двусвязного списка. Все операции
+ // выполняются так, как ожидается от двусвязного
+ // списка.
+ // Maps - набор объектов, в которых присутствует связь
+ // ключ-значение. В Map ключ не может дублироваться.
+ // Каждый ключ связан только с одним значением.
+ // HashMaps - этот класс использует хэш-таблицу для реализации
+ // интерфейса Map. Это позволяет сохранить постоянной
+ // скорость выполнения базовых операций, таких как
+ // добавление и удаление элементов, вне зависимости
+ // от размера множества.
+
+ ///////////////////////////////////////
+ // Операторы
+ ///////////////////////////////////////
+ System.out.println("\n->Операторы");
+
+ int i1 = 1, i2 = 2; // Сокращение для множественного объявления.
+
+ // Арифметика в Java проста.
+ System.out.println("1+2 = " + (i1 + i2)); // => 3
+ System.out.println("2-1 = " + (i2 - i1)); // => 1
+ System.out.println("2*1 = " + (i2 * i1)); // => 2
+ System.out.println("1/2 = " + (i1 / i2)); // => 0 (0.5 округлено)
+
+ // Остаток от деления
+ System.out.println("11%3 = "+(11 % 3)); // => 2
+
+ // Операторы сравнения.
+ System.out.println("3 == 2? " + (3 == 2)); // => false
+ System.out.println("3 != 2? " + (3 != 2)); // => true
+ System.out.println("3 > 2? " + (3 > 2)); // => true
+ System.out.println("3 < 2? " + (3 < 2)); // => false
+ System.out.println("2 <= 2? " + (2 <= 2)); // => true
+ System.out.println("2 >= 2? " + (2 >= 2)); // => true
+
+ // Побитовые операторы!
+ /*
+ ~ Унарное побитовое дополнение.
+ << Знаковый сдвиг влево.
+ >> Знаковый сдвиг вправо.
+ >>> Беззнаковый сдвиг вправо.
+ & Побитовое И.
+ ^ Побитовое исключающее ИЛИ.
+ | Побитовое ИЛИ.
+ */
+
+ // Операторы инкремента.
+ int i = 0;
+ System.out.println("\n->Inc/Dec-rementation");
+ // Операторы ++ и -- увеличивают и уменьшают значение на 1 соответственно.
+ // Если они находятся перед переменной, сначала происходит
+ // увеличение/уменьшение, затем операция, если после,
+ // то сначала выполняется операция, затем увеличение/уменьшение.
+ System.out.println(i++); //i = 1, напечатает 0 (пост-инкремент)
+ System.out.println(++i); //i = 2, напечатает 2 (пре-инкремент)
+ System.out.println(i--); //i = 1, напечатает 2 (пост-декремент)
+ System.out.println(--i); //i = 0, напечатает 0 (пре-декремент)
+
+ ///////////////////////////////////////
+ // Контролирующие операторы.
+ ///////////////////////////////////////
+ System.out.println("\n->Контролирующие операторы");
+
+ // Оператор if такой же, как и в С.
+ int j = 10;
+ if (j == 10){
+ System.out.println("Я напечатаюсь!");
+ } else if (j > 10) {
+ System.out.println("Я нет.");
+ } else {
+ System.out.println("И я тоже нет.");
+ }
+
+ // Цикл while.
+ int fooWhile = 0;
+ while(fooWhile < 100)
+ {
+ // System.out.println(fooWhile);
+ // Увеличить счетчик.
+ // Будет пройдено 100 итераций, fooWhile 0,1,2...99
+ fooWhile++;
+ }
+ System.out.println("Значение fooWhile: " + fooWhile);
+
+ // Цикл Do While.
+ int fooDoWhile = 0;
+ do
+ {
+ // System.out.println(fooDoWhile);
+ // Увеличить счетчик.
+ // Будет пройдено 100 итераций, fooDoWhile 0->99
+ fooDoWhile++;
+ } while(fooDoWhile < 100);
+ System.out.println("Значение fooDoWhile: " + fooDoWhile);
+
+ // Цикл for.
+ int fooFor;
+ // Структура цикла for => for(<начальное_состояние>; <условие>; <шаг>)
+ for(fooFor=0; fooFor<10; fooFor++){
+ // System.out.println(fooFor);
+ // Пройдет 10 итераций., fooFor 0->9
+ }
+ System.out.println("Значение fooFor: " + fooFor);
+
+ // Цикл For Each
+ // Автоматический проход через массив или список объектов.
+ int[] fooList = {1,2,3,4,5,6,7,8,9};
+ // Структура цикла for each => for(<объект> : <объект_массив>)
+ // читается как: для каждого объекта в массиве
+ // заметка: тип объекта должен совпадать с типом массива.
+
+ for( int bar : fooList ){
+ System.out.println(bar);
+ //Пройдет 9 итераций и напечатает 1-9 на новых строках.
+ }
+
+ // Switch Case
+ // switch работает с типами byte, short, char и int.
+ // Также он работает с перечислениями,
+ // классом String и с некоторыми классами-обертками над
+ // примитивными типами: Character, Byte, Short и Integer.
+ int month = 3;
+ String monthString;
+ switch (month){
+ case 1:
+ monthString = "Январь";
+ break;
+ case 2:
+ monthString = "Февраль";
+ break;
+ case 3:
+ monthString = "Март";
+ break;
+ default:
+ monthString = "Другой месяц";
+ break;
+ }
+ System.out.println("Результат Switch Case: " + monthString);
+
+ // Сокращенный синтаксис условного оператора.
+ // Вы можете использовать этот синтаксис для быстрого присвоения
+ // или логических переходов.
+ // Читается так: "Если (условие) истинно, использовать <значение 1>,
+ // в ином случае, использовать <значение 2>"
+ int foo = 5;
+ String bar = (foo < 10) ? "A" : "B";
+ System.out.println(bar); // Напечатает А, потому что условие истинно
+
+
+ ///////////////////////////////////////
+ // Преобразование и приведение типов данных.
+ ///////////////////////////////////////
+
+ // Преобразование данных.
+
+ // Преобразование строки в число.
+ Integer.parseInt("123"); // Вернет числовое представление "123".
+
+ // Преобразование числа в строку
+ Integer.toString(123); // Вернет строковое представление 123.
+
+ // Для других преобразований смотрите следующие классы:
+ // Double
+ // Long
+ // String
+
+ // Приведение типов
+ // Вы так же можете приводить типы в Java.
+ // Подробнее об этом можно узнать по ссылке:
+ // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
+
+
+ ///////////////////////////////////////
+ // Классы и Функции
+ ///////////////////////////////////////
+
+ System.out.println("\n->Классы и Функции");
+
+ // (Класс Bicycle определен ниже)
+
+ // Для создания экземпляра класса используется new.
+ Bicycle trek = new Bicycle();
+
+ // Вызов методов объекта.
+ trek.speedUp(3); // Вы должны всегда использовать сеттеры и геттеры.
+ trek.setCadence(100);
+
+ // toString возвращает строковое представление объекта.
+ System.out.println("trek info: " + trek.toString());
+
+ } // Конец метода main.
+} // Конец класса LearnJava.
+
+
+// Вы можете включать другие, не публичные классы в .java файл.
+
+
+// Синтаксис объявления класса:
+// <public/private/protected> class <имя класса>{
+// // Поля с данными, конструкторы, функции, все внутри.
+// // Функции называют методами в Java.
+// }
+
+class Bicycle {
+
+ // Поля/Переменные класса Bicycle.
+ public int cadence;// Публичные(public): Доступны из любого места.
+ private int speed; // Приватные(private): Доступны только внутри класса.
+ protected int gear;// Защищенные(protected): Доступ из класса и наследников.
+ String name; // по умолчанию: Доступны только внутри пакета.
+
+ // Конструкторы - способ создания класса.
+ // Это конструктор:
+ public Bicycle() {
+ gear = 1;
+ cadence = 50;
+ speed = 5;
+ name = "Bontrager";
+ }
+
+ // Это конструктор, который принимает аргументы:
+ public Bicycle(int startCadence, int startSpeed, int startGear, String name) {
+ this.gear = startGear;
+ this.cadence = startCadence;
+ this.speed = startSpeed;
+ this.name = name;
+ }
+
+ // Синтаксис функций:
+ // <public/private/protected> <тип возвращаемого значения> <имя>(<аргументы>)
+
+ // Классы в Java часто реализуют сеттеры и геттеры для своих полей.
+
+ // Синтаксис определения метода:
+ // <модификатор> <тип возвращаемого значения> <имя>(<аргументы>)
+ public int getCadence() {
+ return cadence;
+ }
+
+ // void-методы не возвращают значений.
+ public void setCadence(int newValue) {
+ cadence = newValue;
+ }
+
+ public void setGear(int newValue) {
+ gear = newValue;
+ }
+
+ public void speedUp(int increment) {
+ speed += increment;
+ }
+
+ public void slowDown(int decrement) {
+ speed -= decrement;
+ }
+
+ public void setName(String newName) {
+ name = newName;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ //Метод для отображения значений атрибутов объекта.
+ @Override
+ public String toString() {
+ return "gear: " + gear +
+ " cadence: " + cadence +
+ " speed: " + speed +
+ " name: " + name;
+ }
+} // конец класса Bicycle.
+
+// PennyFarthing - это класс, наследованный от Bicycle
+class PennyFarthing extends Bicycle {
+ // (Penny Farthings - это такие велосипеды с большим передним колесом,
+ // у них нет передач.)
+
+ public PennyFarthing(int startCadence, int startSpeed){
+ // Вызов конструктора родительского класса.
+ super(startCadence, startSpeed, 0, "PennyFarthing");
+ }
+
+ // Вы должны пометить метод, который переопределяете, при помощи @аннотации
+ // Чтобы узнать о том, что такое аннотации и зачем они нужны, почитайте:
+ // http://docs.oracle.com/javase/tutorial/java/annotations/
+ @Override
+ public void setGear(int gear) {
+ gear = 0;
+ }
+
+}
+
+// Интерфейсы
+// Синтаксис определения интерфейса:
+// <модификатор доступа> interface <имя> extends <базовый интерфейс> {
+// // Константы
+// // Определение методов.
+//}
+
+// Пример - Еда:
+public interface Edible {
+ // Любой класс, реализующий этот интерфейс, должен реализовать этот метод.
+ public void eat();
+}
+
+public interface Digestible {
+ public void digest();
+}
+
+
+// Сейчас мы можем создать класс, реализующий оба эти интерфейса.
+public class Fruit implements Edible, Digestible {
+ public void eat() {
+ //...
+ }
+
+ public void digest() {
+ //...
+ }
+}
+
+// В Java Вы можете наследоватьтолько один класс, однако можете реализовывать
+// несколько интерфейсов. Например:
+public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo {
+ public void InterfaceOneMethod() {
+
+ }
+
+ public void InterfaceTwoMethod() {
+
+ }
+}
+
+```
+
+## Почитать еще
+
+Здесь приведены ссылки только для того, чтобы получить общее представление о Java. Гуглите, чтобы найти какие-либо конкретные примеры.
+
+**Официальные руководства Oracle**:
+
+* [Java Tutorial Trail from Sun / Oracle](http://docs.oracle.com/javase/tutorial/index.html)
+
+* [Модификаторы доступа в Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
+
+* [Концепции объектно-ориентированного программирования](http://docs.oracle.com/javase/tutorial/java/concepts/index.html):
+ * [Наследование](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html)
+ * [Полиморфизм](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html)
+ * [Абстракция](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html)
+
+* [Исключения](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html)
+
+* [Интерфейсы](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html)
+
+* [Generics](http://docs.oracle.com/javase/tutorial/java/generics/index.html)
+
+* [Java Code Conventions](http://www.oracle.com/technetwork/java/codeconv-138413.html)
+
+**Уроки онлайн**
+
+* [Learneroo.com - Изучение Java](http://www.learneroo.com)
+
+* [Codingbat.com](http://codingbat.com/java)
+
+
+**Книги**:
+
+* [Head First Java](http://www.headfirstlabs.com/books/hfjava/)
+
+* [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660)
+
+* [Java The Complete Reference](http://www.amazon.com/gp/product/0071606300)
+
+
diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown
index cd55e116..29392604 100644
--- a/ru-ru/julia-ru.html.markdown
+++ b/ru-ru/julia-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: julia
+language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
translators:
diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown
new file mode 100644
index 00000000..eb8e4881
--- /dev/null
+++ b/ru-ru/markdown-ru.html.markdown
@@ -0,0 +1,279 @@
+---
+language: markdown
+contributors:
+ - ["Dan Turkel", "http://danturkel.com/"]
+ - ["Pirogov Alexey", "http://twitter.com/alex_pir"]
+filename: markdown-ru.md
+lang: ru-ru
+---
+
+Язык разметки Markdown создан Джоном Грубером (англ. John Gruber)
+и Аароном Шварцем (англ. Aaron H. Swartz) в 2004 году.
+Авторы задавались целью создать максимально удобочитаемый
+и удобный в публикации облегчённый язык разметки,
+пригодный для последующего преобразования в HTML
+(а также и в другие форматы).
+
+ ```markdown
+<!-- Markdown является надмножеством HTML, поэтому любой HTML-файл является
+валидным документом Markdown, что позволяет использовать напрямую
+любые элементы HTML-разметки, такие, например, как этот комментарий.
+ Встроенные в документ HTML-элементы не затрагиваются парсером Markdown
+и попадают в итоговый HTML без изменений. Однако, следует понимать,
+что эта же особенность не позволяет использовать разметку Markdown внутри
+HTML-элементов -->
+
+<!-- Ещё одна особенность формата Markdown состоит в том, что поддерживаемые
+возможности разметки зависят от конкретной реализации парсера. В данном
+руководстве возможности, поддерживаемые лишь определёнными парсерами,
+сопровождаются соответствующими примечаниями. -->
+
+<!-- Заголовки -->
+
+<!-- HTML-элементы от <h1> до <h6> размечаются очень просто:
+текст, который должен стать заголовком, предваряется
+соответствующим количеством символов "#": -->
+# Это заголовок h1
+## Это заголовок h2
+### Это заголовок h3
+#### Это заголовок h4
+##### Это заголовок h5
+###### Это заголовок h6
+
+<!-- Markdown позволяет размечать заголовки <h1> и <h2> ещё одним способом: -->
+Это заголовок h1
+================
+
+А это заголовок h2
+------------------
+
+<!-- Простейшая стилизация текста -->
+
+<!-- Текст легко сделать полужирным и/или курсивным: -->
+
+*Этот текст будет выведен курсивом.*
+_Так же, как этот._
+
+**А этот текст будет полужирным.**
+__И этот тоже.__
+
+***Полужирный курсив.***
+**_И тут!_**
+*__И даже здесь!__*
+
+<!-- В Github Flavored Markdown (версии Markdown, использующейся в Github,
+для рендеринга Markdown-документов) текст можно сделать зачёркнутым: -->
+
+~~Зачёркнутый текст.~~
+
+<!-- Абзацами являются любые строки, следующие друг за другом.
+Разделяются же абзацы одной или несколькими пустыми строками: -->
+
+Это абзац. Всё предельно просто.
+
+А тут уже параграф №2.
+Эта строка всё ещё относится к параграфу №2!
+
+
+О, а вот это уже параграф №3!
+
+<!-- Для вставки принудительных переносов можно использовать HTML-тэг <br/>: -->
+
+Принудительный <br/> перенос!
+
+<!-- Цитаты размечаются с помощью символа ">": -->
+
+> Это цитата. В цитатах можно
+> принудительно переносить строки, вставляя ">" в начало каждой следующей строки. А можно просто оставлять достаточно длинными, и такие длинные строки будут перенесены автоматически.
+> Разницы между этими двумя подходами к переносу строк нет, коль скоро
+> каждая строка начинается с символа ">"
+
+> А ещё цитаты могут быть многоуровневыми:
+>> как здесь
+>>> и здесь :)
+> Неплохо?
+
+<!-- Списки -->
+<!-- Маркированные списки размечаются вставкой в начало каждого элемента
+одного из символов "*", "+" или "-":
+(символ должен быть одним и тем же для всех элементов) -->
+
+* Список,
+* Размеченный
+* Звёздочками
+
+либо
+
++ Список,
++ Размеченный
++ Плюсами
+
+либо
+
+- Список,
+- Размеченный
+- Дефисами
+
+<!-- В нумерованных списках каждая строка начинается
+с числа и точки вслед за ним: -->
+
+1. Первый элемент
+2. Второй элемент
+3. Третий элемент
+
+<!-- Заметьте, нумеровать элементы корректно необязательно. Достаточно указать
+любое число в начале каждого элемента и рендер пронумерует элементы сам!
+Правда, злоупотреблять этим не стоит :) -->
+
+1. Первый элемент
+1. Второй элемент
+1. Третий элемент
+<!-- (Этот список будет отрендерен так же, как и предыдущий!) -->
+
+<!-- Списки могут быть вложенными: -->
+
+1. Введение
+2. Начало работы
+3. Примеры использования
+ * Простые
+ * Сложные
+4. Заключение
+
+<!-- Блоки с исходным кодом -->
+<!-- Фрагменты исходного кода выделяются очень просто - каждая строка блока должна иметь отступ в четыре пробела либо в один символ табуляции -->
+
+ Это код,
+ причём - многострочный
+
+<!-- Дополнительные отступы в коде следует делать с помощью четырёх пробелов: -->
+
+ my_array.each do |item|
+ puts item
+ end
+
+<!-- Иногда бывает нужно вставить фрагмент кода прямо в строку текста,
+не выделяя код в блок. Для этого фрагменты кода нужно обрамлять
+символами "`": -->
+
+Например, можно выделить имя функции `go_to()` прямо посреди текста.
+
+<!-- Github Flavored Markdown позволяет указать для блока кода синтаксис оного.
+В этом случае синтаксис внутри блока будет подсвечен. Пример: -->
+
+\`\`\`ruby <!-- Только нужно будет убрать символы "\", оставив лишь "```ruby" -->
+def foobar
+ puts "Hello world!"
+end
+\`\`\` <!-- И здесь тоже backslashes нужно убрать, т.е. оставить "```" -->
+
+<-- Обратите внимание: фрагмент, указанный выше, не предваряется отступами,
+поскольку Github сам в состоянии определить границы блока - по строкам "```" -->
+
+<!-- Горизонтальный разделитель (<hr />) -->
+<!-- Разделители добавляются вставкой строки из трёх и более
+(одинаковых) символов "*" или "-": -->
+
+***
+---
+- - - <!-- между символами допустимы пробелы -->
+****************
+
+<!-- Ссылки -->
+<!-- Одной из сильных сторон Markdown можно смело считать то,
+как просто размечаются гиперссылки. Для создания ссылки укажите
+текст ссылки, заключив его в квадратные скобки,
+и сразу после - url, заключенный в "круглые" -->
+
+[Ссылка!](http://test.com/)
+
+<!-- Также для ссылки можно указать всплывающую подсказку: -->
+
+[Ссылка!](http://test.com/ "Ссылка на Test.com")
+
+<!-- В url можно использовать относительные пути: -->
+
+[Перейти к музыке](/music/).
+
+<!-- Markdown позволяет размечать ссылку в виде сноски: -->
+
+[Здесь][link1] высможете узнать больше!
+А можно кликнуть [сюда][foobar], если очень хочется.
+
+<!-- где-нибудь внизу -->
+[link1]: http://test.com/ "Круто!"
+[foobar]: http://foobar.biz/ "Тоже хорошо!"
+
+<!-- Примечания:
+- Подсказка может быть заключена в одинарные кавычки вместо двойных,
+ а также в круглые скобки.
+- Сноска может находиться в любом месте документа и может иметь
+идентификатор (далее ID) произвольной длины,
+лишь бы это ID был уникальным. -->
+
+<!-- Также при разметке ссылок-сносок можно опустить ID,
+если текст ссылки уникален в пределах документа: -->
+
+Ссылка на [Google][].
+
+[google]: http://google.com/
+
+<!-- Правда, эта возможность не очень распространена. -->
+
+<!-- Изображения -->
+<!-- Разметка изображений очень похожа на разметку ссылок.
+Нужно всего лишь добавить "!" перед ссылкой! -->
+
+![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка")
+
+<!-- Изображения тоже могут быть оформлены, как сноски: -->
+
+![Альтернативный текст][myimage]
+
+![То же изображение ещё раз][myimage]
+
+[myimage]: relative/urls/cool/image.jpg "подсказка"
+
+<!-- Ещё немного ссылок: -->
+<!-- Автоссылки -->
+
+Ссылка вида <http://testwebsite.com/> эквивалентна
+[http://testwebsite.com/](http://testwebsite.com/)
+
+<!-- Автоссылки для адресов электронной почты -->
+
+<foo@bar.com>
+
+<!-- Экранирование символов -->
+
+<!-- Может потребоваться вставить спецсимвол в текст "как есть",
+т.е. защитить его от обработки парсером.
+Такой символ должен быть "экранирован" с помощью обратной косой черты
+(символа "\"): -->
+
+\*текст, заключённый в звёздочки!\*
+
+<!-- Таблицы -->
+<!-- Таблицы официально поддерживаются только в Github Flavored Markdown,
+да и синтаксис имеют не слишком удобный.
+Но если очень нужно, размечайте таблицы так: -->
+
+| Столбец 1 | Столбец 2 | Столбец 3 |
+| :----------- | :----------: | -----------: |
+| Выравнивание | Выравнивание | Выравнивание |
+| влево | по центру | вправо |
+
+<!-- Или более компактно -->
+
+Колонка 1|Колонка 2|Колонка 3
+:--|:-:|--:
+Выглядит|это|страшновато...
+
+<!-- Ну вот и всё! -->
+
+```
+
+За более подробной информацией обращайтесь к [статье](http://daringfireball.net/projects/markdown/syntax) Джона Грубера о синтаксисе Markdown.
+
+Также часто бывает полезной отличная ["шпаргалка"](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) по Markdown от Adam Pritchard.
+
+Если вдруг встретите ошибки в переводе или же захотите его дополнить, делайте pull requests - авторы всегда рады обратной связи!
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/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
index edcac4dd..53b2f916 100644
--- a/ru-ru/php-ru.html.markdown
+++ b/ru-ru/php-ru.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
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/ru-ru/python3-ru.html.markdown b/ru-ru/python3-ru.html.markdown
new file mode 100644
index 00000000..637c0157
--- /dev/null
+++ b/ru-ru/python3-ru.html.markdown
@@ -0,0 +1,630 @@
+---
+language: python3
+lang: ru-ru
+contributors:
+ - ["Louie Dinh", "http://ldinh.ca"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+translators:
+ - ["Andre Polykanine", "https://github.com/Oire"]
+filename: learnpython3-ru.py
+---
+
+Язык Python был создан Гвидо ван Россумом в начале 90-х. Сейчас это один из
+самых популярных языков. Я люблю его за понятный и доходчивый синтаксис — это
+почти что исполняемый псевдокод.
+
+С благодарностью жду ваших отзывов: [@louiedinh](http://twitter.com/louiedinh)
+или louiedinh [at] [почтовый сервис Google]
+
+Замечание: Эта статья относится только к Python 3.
+Если вы хотите изучить Python 2.7, обратитесь к другой статье.
+
+```python
+# Однострочные комментарии начинаются с символа решётки.
+""" Многострочный текст может быть
+ записан, используя 3 знака " и обычно используется
+ в качестве встроенной документации
+"""
+
+####################################################
+## 1. Примитивные типы данных и операторы
+####################################################
+
+# У вас есть числа
+3 #=> 3
+
+# Математика работает вполне ожидаемо
+1 + 1 #=> 2
+8 - 1 #=> 7
+10 * 2 #=> 20
+
+# Кроме деления, которое по умолчанию возвращает число с плавающей запятой
+35 / 5 # => 7.0
+
+# Результат целочисленного деления округляется в меньшую сторону
+# как для положительных, так и для отрицательных чисел.
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # работает и для чисел с плавающей запятой
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# Когда вы используете числа с плавающей запятой,
+# результатом будет также число с плавающей запятой
+3 * 2.0 # => 6.0
+
+# Остаток от деления
+7 % 3 # => 1
+
+# Возведение в степень
+2 ** 4 # => 16
+
+# Приоритет операций указывается скобками
+(1 + 3) * 2 #=> 8
+
+# Для логических (булевых) значений существует отдельный примитивный тип
+True
+False
+
+# Для отрицания используется ключевое слово not
+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
+2 >= 2 #=> True
+
+# Сравнения могут быть записаны цепочкой:
+1 < 2 < 3 #=> True
+2 < 3 < 2 #=> False
+
+# Строки определяются символом " или '
+"Это строка."
+'Это тоже строка.'
+
+# И строки тоже могут складываться! Хотя лучше этого не делайте.
+"Привет " + "мир!" #=> "Привет мир!"
+
+# Со строкой можно работать, как со списком символов
+"Это строка"[0] #=> 'Э'
+
+# Метод format используется для форматирования строк:
+"{0} могут быть {1}".format("строки", "форматированы")
+
+# Вы можете повторять аргументы форматирования, чтобы меньше печатать.
+"Ехал {0} через реку, видит {0} - в реке {1}! Сунул {0} руку в реку, {1} за руку греку цап!".format("грека", "рак")
+#=> "Ехал грека через реку, видит грека - в реке рак! Сунул грека руку в реку, рак за руку греку цап!"
+# Если вы не хотите считать, можете использовать ключевые слова.
+"{name} хочет есть {food}".format(name="Боб", food="лазанью")
+
+# Если ваш код на Python 3 нужно запускать также и под Python 2.5 и ниже,
+# вы также можете использовать старый способ форматирования:
+"%s можно %s %s способом" % ("строки", "интерполировать", "старым")
+
+# None является объектом
+None #=> None
+
+# Не используйте оператор равенства '==' для сравнения
+# объектов с None. Используйте для этого 'is'
+"etc" is None #=> False
+None is None #=> True
+
+# Оператор «is» проверяет идентичность объектов. Он не
+# очень полезен при работе с примитивными типами, но
+# зато просто незаменим при работе с объектами.
+
+# None, 0 и пустые строки/списки/словари приводятся к False.
+# Все остальные значения равны True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+
+
+####################################################
+## 2. Переменные и коллекции
+####################################################
+
+# У Python есть функция Print
+print("Я Python. Приятно познакомиться!")
+
+# Необязательно объявлять переменные перед их инициализацией.
+# По соглашению используется нижний_регистр_с_подчёркиваниями
+some_var = 5
+some_var #=> 5
+
+# При попытке доступа к неинициализированной переменной
+# выбрасывается исключение.
+# Об исключениях см. раздел «Поток управления и итерируемые объекты».
+some_unknown_var # Выбрасывает ошибку именования
+
+# Списки хранят последовательности
+li = []
+# Можно сразу начать с заполненным списком
+other_li = [4, 5, 6]
+
+# Объекты добавляются в конец списка методом append
+li.append(1) # [1]
+li.append(2) # [1, 2]
+li.append(4) # [1, 2, 4]
+li.append(3) # [1, 2, 4, 3]
+# И удаляются с конца методом pop
+li.pop() #=> возвращает 3 и li становится равен [1, 2, 4]
+# Положим элемент обратно
+li.append(3) # [1, 2, 4, 3].
+
+# Обращайтесь со списком, как с обычным массивом
+li[0] #=> 1
+# Обратимся к последнему элементу
+li[-1] #=> 3
+
+# Попытка выйти за границы массива приведёт к ошибке индекса
+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 не изменяются
+
+# Объединять списки можно методом extend
+li.extend(other_li) # Теперь li содержит [1, 2, 3, 4, 5, 6]
+
+# Проверить элемент на вхождение в список можно оператором in
+1 in li #=> True
+
+# Длина списка вычисляется функцией len
+len(li) #=> 6
+
+
+# Кортежи — это такие списки, только неизменяемые
+tup = (1, 2, 3)
+tup[0] #=> 1
+tup[0] = 3 # Выдаёт TypeError
+
+# Всё то же самое можно делать и с кортежами
+len(tup) #=> 3
+tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6)
+tup[:2] #=> (1, 2)
+2 in tup #=> True
+
+# Вы можете распаковывать кортежи (или списки) в переменные
+a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3
+# Кортежи создаются по умолчанию, если опущены скобки
+d, e, f = 4, 5, 6
+# Обратите внимание, как легко поменять местами значения двух переменных
+e, d = d, e # теперь d == 5, а e == 4
+
+
+# Словари содержат ассоциативные массивы
+empty_dict = {}
+# Вот так описывается предзаполненный словарь
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# Значения ищутся по ключу с помощью оператора []
+filled_dict["one"] #=> 1
+
+# Все значения в виде списка получаются с помощью метода keys().
+# Его вызов нужно обернуть в list(), так как обратно мы получаем
+# итерируемый объект, о которых поговорим позднее.
+list(filled_dict.keys()) # => ["three", "two", "one"]
+# Замечание: сохранение порядка ключей в словаре не гарантируется
+# Ваши результаты могут не совпадать с этими.
+
+# Все значения в виде списка можно получить с помощью values().
+# И снова нам нужно обернуть вызов в list(), чтобы превратить
+# итерируемый объект в список.
+list(filled_dict.values()) # => [3, 2, 1]
+# То же самое замечание насчёт порядка ключей справедливо и здесь
+
+# При помощи оператора in можно проверять ключи на вхождение в словарь
+"one" in filled_dict #=> True
+1 in filled_dict #=> False
+
+# Попытка получить значение по несуществующему ключу выбросит ошибку ключа
+filled_dict["four"] # KeyError
+
+# Чтобы избежать этого, используйте метод get
+filled_dict.get("one") #=> 1
+filled_dict.get("four") #=> None
+# Метод get также принимает аргумент по умолчанию, значение которого будет
+# возвращено при отсутствии указанного ключа
+filled_dict.get("one", 4) #=> 1
+filled_dict.get("four", 4) #=> 4
+
+# Метод setdefault вставляет пару ключ-значение, только если такого ключа нет
+filled_dict.setdefault("five", 5) #filled_dict["five"] возвращает 5
+filled_dict.setdefault("five", 6) #filled_dict["five"] по-прежнему возвращает 5
+
+# Удаляйте ключи из словаря с помощью оператора del
+del filled_dict["one"] # Удаляет ключ «one» из словаря
+
+
+# Множества содержат... ну, в общем, множества
+empty_set = set()
+# Инициализация множества набором значений.
+# Да, оно выглядит примерно как словарь… ну извините, так уж вышло.
+filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4}
+
+# Множеству можно назначать новую переменную
+filled_set = some_set
+
+# Добавление новых элементов в множество
+filled_set.add(5) # filled_set равно {1, 2, 3, 4, 5}
+
+# Пересечение множеств: &
+other_set = {3, 4, 5, 6}
+filled_set & other_set #=> {3, 4, 5}
+
+# Объединение множеств: |
+filled_set | other_set #=> {1, 2, 3, 4, 5, 6}
+
+# Разность множеств: -
+{1,2,3,4} - {2,3,5} #=> {1, 4}
+
+# Проверка на вхождение во множество: in
+2 in filled_set #=> True
+10 in filled_set #=> False
+
+
+####################################################
+## 3. Поток управления и итерируемые объекты
+####################################################
+
+# Для начала заведём переменную
+some_var = 5
+
+# Так выглядит выражение if. Отступы в python очень важны!
+# результат: «some_var меньше, чем 10»
+if some_var > 10:
+ print("some_var намного больше, чем 10.")
+elif some_var < 10: # Выражение elif необязательно.
+ print("some_var меньше, чем 10.")
+else: # Это тоже необязательно.
+ print("some_var равно 10.")
+
+
+# Циклы For проходят по спискам. Результат:
+ # собака — это млекопитающее
+ # кошка — это млекопитающее
+ # мышь — это млекопитающее
+for animal in ["собака", "кошка", "мышь"]:
+ # Можете использовать format() для интерполяции форматированных строк
+ print("{} — это млекопитающее".format(animal))
+
+"""
+«range(число)» возвращает список чисел
+от нуля до заданного числа
+Результат:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+Циклы while продолжаются до тех пор, пока указанное условие не станет ложным.
+Результат:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # Краткая запись для x = x + 1
+
+# Обрабатывайте исключения блоками try/except
+try:
+ # Чтобы выбросить ошибку, используется raise
+ raise IndexError("Это ошибка индекса")
+except IndexError as e:
+ # pass это просто отсутствие оператора. Обычно здесь происходит
+ # восстановление после ошибки.
+ pass
+except (TypeError, NameError):
+ pass # Несколько исключений можно обработать вместе, если нужно.
+else: # Необязательное выражение. Должно следовать за последним блоком except
+ print("Всё хорошо!") # Выполнится, только если не было никаких исключений
+
+# Python предоставляет фундаментальную абстракцию,
+# которая называется итерируемым объектом (an iterable).
+# Итерируемый объект — это объект, который воспринимается как последовательность.
+# Объект, который возвратила функция range(), итерируемый.
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) #=> range(1,10). Это объект, реализующий интерфейс iterable
+
+# Мы можем проходить по нему циклом.
+for i in our_iterable:
+ print(i) # Выводит one, two, three
+
+# Но мы не можем обращаться к элементу по индексу.
+our_iterable[1] # Выбрасывает ошибку типа
+
+# Итерируемый объект знает, как создавать итератор.
+our_iterator = iter(our_iterable)
+
+# Итератор может запоминать состояние при проходе по объекту.
+# Мы получаем следующий объект, вызывая функцию __next__.
+our_iterator.__next__() #=> "one"
+
+# Он сохраняет состояние при вызове __next__.
+our_iterator.__next__() #=> "two"
+our_iterator.__next__() #=> "three"
+
+# Возвратив все данные, итератор выбрасывает исключение StopIterator
+our_iterator.__next__() # Выбрасывает исключение остановки итератора
+
+# Вы можете получить сразу все элементы итератора, вызвав на нём функцию list().
+list(filled_dict.keys()) #=> Возвращает ["one", "two", "three"]
+
+
+####################################################
+## 4. Функции
+####################################################
+
+# Используйте def для создания новых функций
+def add(x, y):
+ print("x равен %s, а y равен %s" % (x, y))
+ return x + y # Возвращайте результат выражением return
+
+# Вызов функции с аргументами
+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
+
+# Вызовем эту функцию и посмотрим, что из этого получится
+keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"}
+
+# Если хотите, можете использовать оба способа одновременно
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) выводит:
+ (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)
+
+# Область определения функций
+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
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) #=> 13
+
+# Также есть и анонимные функции
+(lambda x: x > 2)(3) #=> True
+
+# Есть встроенные функции высшего порядка
+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]
+
+####################################################
+## 5. Классы
+####################################################
+
+# Чтобы получить класс, мы наследуемся от object.
+class Human(object):
+
+ # Атрибут класса. Он разделяется всеми экземплярами этого класса
+ species = "H. sapiens"
+
+ # Обычный конструктор, вызывается при инициализации экземпляра класса
+ # Обратите внимание, что двойное подчёркивание в начале и в конце имени
+ # означает объекты и атрибуты, которые используются Python, но находятся
+ # в пространствах имён, управляемых пользователем.
+ # Не придумывайте им имена самостоятельно.
+ def __init__(self, name):
+ # Присваивание значения аргумента атрибуту класса name
+ self.name = name
+
+ # Метод экземпляра. Все методы принимают self в качестве первого аргумента
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
+
+ # Метод класса разделяется между всеми экземплярами
+ # Они вызываются с указыванием вызывающего класса в качестве первого аргумента
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # Статический метод вызывается без ссылки на класс или экземпляр
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# Инициализация экземпляра класса
+i = Human(name="Иван")
+print(i.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"
+
+# Вызов статического метода
+Human.grunt() #=> "*grunt*"
+
+
+####################################################
+## 6. Модули
+####################################################
+
+# Вы можете импортировать модули
+import math
+print(math.sqrt(16)) #=> 4
+
+# Вы можете импортировать отдельные функции модуля
+from math import ceil, floor
+print(ceil(3.7)) #=> 4.0
+print(floor(3.7)) #=> 3.0
+
+# Можете импортировать все функции модуля.
+# (Хотя это и не рекомендуется)
+from math import *
+
+# Можете сокращать имена модулей
+import math as m
+math.sqrt(16) == m.sqrt(16) #=> True
+
+# Модули в Python — это обычные Python-файлы. Вы
+# можете писать свои модули и импортировать их. Название
+# модуля совпадает с названием файла.
+
+# Вы можете узнать, какие функции и атрибуты определены
+# в модуле
+import math
+dir(math)
+
+####################################################
+## 7. Дополнительно
+####################################################
+
+# Генераторы помогут выполнить ленивые вычисления
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# Генератор создаёт значения на лету.
+# Он не возвращает все значения разом, а создаёт каждое из них при каждой
+# итерации. Это значит, что значения больше 15 в double_numbers
+# обработаны не будут.
+# Обратите внимание: range — это тоже генератор.
+# Создание списка чисел от 1 до 900000000 требует много места и времени.
+# Если нам нужно имя переменной, совпадающее с ключевым словом Python,
+# мы используем подчёркивание в конце
+range_ = range(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/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+* [Официальная документация](http://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/3/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+
+### Платные
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/ruby.html.markdown b/ruby.html.markdown
index 962853a2..7cf5bdc7 100644
--- a/ruby.html.markdown
+++ b/ruby.html.markdown
@@ -9,6 +9,8 @@ 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"]
+ - ["Levi Bostian", "https://github.com/levibostian"]
---
@@ -35,7 +37,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 +80,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 +135,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 +162,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 +175,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 +185,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 +221,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,34 +246,45 @@ 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"
+# exception handling:
+begin
+ # code here that might raise an exception
+ raise NoMemoryError, 'You ran out of memory.'
+rescue NoMemoryError => exception_variable
+ puts 'NoMemoryError was raised', exception_variable
+rescue RuntimeError => other_exception_variable
+ puts 'RuntimeError was raised now'
+else
+ puts 'This runs if no exceptions were thrown at all'
+ensure
+ puts 'This code always runs no matter what'
+end
# Functions
@@ -284,23 +300,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 +327,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 +372,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 +395,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 +414,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 +430,7 @@ class Human
end
end
-# derived class
+# derived class
class Worker < Human
end
@@ -451,8 +466,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 +482,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 +515,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 edition](http://ruby-doc.com/docs/ProgrammingRuby/) is available online.
+- [Ruby Style Guide](https://github.com/bbatsov/ruby-style-guide) - A community-driven Ruby coding style guide.
diff --git a/rust.html.markdown b/rust.html.markdown
index 0b9a5e58..3717a7d9 100644
--- a/rust.html.markdown
+++ b/rust.html.markdown
@@ -255,8 +255,8 @@ fn main() {
## Further reading
There’s a lot more to Rust—this is just the basics of Rust so you can
-understand the most important things. To learn more about Rust, read the
-[Rust tutorial](http://doc.rust-lang.org/tutorial.html) and check out the
+understand the most important things. To learn more about Rust, read [The Rust
+Guide](http://doc.rust-lang.org/guide.html) and check out the
[/r/rust](http://reddit.com/r/rust) subreddit. The folks on the #rust channel
on irc.mozilla.org are also always keen to help newcomers.
diff --git a/scala.html.markdown b/scala.html.markdown
index 432933c2..5a478f2a 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -4,12 +4,13 @@ filename: learnscala.scala
contributors:
- ["George Petrov", "http://github.com/petrovg"]
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
+ - ["Geoff Liu", "http://geoffliu.me"]
filename: learn.scala
---
Scala - the scalable language
-```cpp
+```scala
/*
Set yourself up:
@@ -20,34 +21,50 @@ Scala - the scalable language
scala>
- This is the so called REPL. You can run commands in the REPL. Let's do just
- that:
+ This is the so called REPL (Read-Eval-Print Loop). You may type any valid
+ Scala expression into it, and the result will be printed. We will explain what
+ Scala files look like further into this tutorial, but for now, let's start
+ with some basics.
*/
-println(10) // prints the integer 10
-println("Boo!") // printlns the string Boo!
+/////////////////////////////////////////////////
+// 1. Basics
+/////////////////////////////////////////////////
+// Single line comments start with two forward slashes
-// Some basics
+/*
+ Multi line comments, as you can already see from above, look like this.
+*/
// Printing, and forcing a new line on the next print
println("Hello world!")
+println(10)
+
// Printing, without forcing a new line on next print
print("Hello world")
-// Declaring values is done using either var or val
-// val declarations are immutable, whereas var's are mutable. Immutability is
+// Declaring values is done using either var or val.
+// val declarations are immutable, whereas var's are mutable. Immutability is
// a good thing.
val x = 10 // x is now 10
x = 20 // error: reassignment to val
-var x = 10
-x = 20 // x is now 20
+var y = 10
+y = 20 // y is now 20
-// Single line comments start with two forward slashes
-/*
-Multi line comments look like this.
+/*
+ Scala is a statically typed language, yet note that in the above declarations,
+ we did not specify a type. This is due to a language feature called type
+ inference. In most cases, Scala compiler can guess what the type of a variable
+ is, so you don't have to type it every time. We can explicitly declare the
+ type of a variable like so:
*/
+val z: Int = 10
+val a: Double = 1.0
+
+// Notice automatic conversion from Int to Double, result is 10.0, not 10
+val b: Double = 10
// Boolean values
true
@@ -64,9 +81,11 @@ true == false // false
2 - 1 // 1
5 * 3 // 15
6 / 2 // 3
+6 / 4 // 1
+6.0 / 4 // 1.5
-// Evaluating a command in the REPL gives you the type and value of the result
+// Evaluating an expression in the REPL gives you the type and value of the result
1 + 7
@@ -78,153 +97,128 @@ true == false // false
This means the result of evaluating 1 + 7 is an object of type Int with a
value of 8
- 1+7 will give you the same result
-*/
-
-
-// Everything is an object, including a function. Type these in the REPL:
-
-7 // results in res30: Int = 7 (res30 is just a generated var name for the result)
-
-// The next line gives you a function that takes an Int and returns it squared
-(x:Int) => x * x
-
-// You can assign this function to an identifier, like this:
-val sq = (x:Int) => x * x
-
-/* The above says this
-
- sq: Int => Int = <function1>
-
- Which means that this time we gave an explicit name to the value - sq is a
- function that take an Int and returns Int.
-
- sq can be executed as follows:
+ Note that "res29" is a sequentially generated variable name to store the
+ results of the expressions you typed, your output may differ.
*/
-sq(10) // Gives you this: res33: Int = 100.
-
-// The colon explicitly defines the type of a value, in this case a function
-// taking an Int and returning an Int.
-val add10: Int => Int = _ + 10
-
-// Scala allows methods and functions to return, or take as parameters, other
-// functions or methods.
-
-List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
-
-// Anonymous functions can be used instead of named functions:
-List(1, 2, 3) map (x => x + 10)
-
-// And the underscore symbol, can be used if there is just one argument to the
-// anonymous function. It gets bound as the variable
-List(1, 2, 3) map (_ + 10)
-
-// If the anonymous block AND the function you are applying both take one
-// argument, you can even omit the underscore
-List("Dom", "Bob", "Natalia") foreach println
-
-
-
-// Data structures
-
-val a = Array(1, 2, 3, 5, 8, 13)
-a(0)
-a(3)
-a(21) // Throws an exception
-
-val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
-m("fork")
-m("spoon")
-m("bottle") // Throws an exception
-
-val safeM = m.withDefaultValue("no lo se")
-safeM("bottle")
-
-val s = Set(1, 3, 7)
-s(0)
-s(1)
-
-/* Look up the documentation of map here -
- * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
- * and make sure you can read it
- */
-
-
-// Tuples
-
-(1, 2)
-
-(4, 3, 2)
-
-(1, 2, "three")
-
-(a, 2, "three")
-
-// Why have this?
-val divideInts = (x:Int, y:Int) => (x / y, x % y)
-
-divideInts(10,3) // The function divideInts gives you the result and the remainder
-
-// To access the elements of a tuple, use _._n where n is the 1-based index of
-// the element
-val d = divideInts(10,3)
+"Scala strings are surrounded by double quotes"
+'a' // A Scala Char
+// 'Single quote strings don't exist' <= This causes an error
-d._1
+// Strings have the usual Java methods defined on them
+"hello world".length
+"hello world".substring(2, 6)
+"hello world".replace("C", "3")
-d._2
+// They also have some extra Scala methods. See also: scala.collection.immutable.StringOps
+"hello world".take(5)
+"hello world".drop(5)
+// String interpolation: notice the prefix "s"
+val n = 45
+s"We have $n apples" // => "We have 45 apples"
+// Expressions inside interpolated strings are also possible
+val a = Array(11, 9, 6)
+s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old."
+s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples."
+s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4"
-// Combinators
+// Formatting with interpolated strings with the prefix "f"
+f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25"
+f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454"
-s.map(sq)
+// Raw strings, ignoring special characters.
+raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r."
-val sSquared = s. map(sq)
+// Some characters need to be "escaped", e.g. a double quote inside a string:
+"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown""
-sSquared.filter(_ < 10)
+// Triple double-quotes let strings span multiple rows and contain quotes
+val html = """<form id="daform">
+ <p>Press belo', Joe</p>
+ <input type="submit">
+ </form>"""
-sSquared.reduce (_+_)
-// The filter function takes a predicate (a function from A -> Boolean) and
-// selects all elements which satisfy the predicate
-List(1, 2, 3) filter (_ > 2) // List(3)
-List(
- Person(name = "Dom", age = 23),
- Person(name = "Bob", age = 30)
-).filter(_.age > 25) // List(Person("Bob", 30))
+/////////////////////////////////////////////////
+// 2. Functions
+/////////////////////////////////////////////////
+
+// Functions are defined like so:
+//
+// def functionName(args...): ReturnType = { body... }
+//
+// If you come from more traditional languages, notice the omission of the
+// return keyword. In Scala, the last expression in the function block is the
+// return value.
+def sumOfSquares(x: Int, y: Int): Int = {
+ val x2 = x * x
+ val y2 = y * y
+ x2 + y2
+}
+// The { } can be omitted if the function body is a single expression:
+def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
-// Scala a foreach method defined on certain collections that takes a type
-// returning Unit (a void method)
-aListOfNumbers foreach (x => println(x))
-aListOfNumbers foreach println
+// Syntax for calling functions is familiar:
+sumOfSquares(3, 4) // => 25
+// In most cases (with recursive functions the most notable exception), function
+// return type can be omitted, and the same type inference we saw with variables
+// will work with function return values:
+def sq(x: Int) = x * x // Compiler can guess return type is Int
+// Functions can have default parameters:
+def addWithDefault(x: Int, y: Int = 5) = x + y
+addWithDefault(1, 2) // => 3
+addWithDefault(1) // => 6
-// For comprehensions
+// Anonymous functions look like this:
+(x:Int) => x * x
-for { n <- s } yield sq(n)
+// Unlike defs, even the input type of anonymous functions can be omitted if the
+// context makes it clear. Notice the type "Int => Int" which means a function
+// that takes Int and returns Int.
+val sq: Int => Int = x => x * x
-val nSquared2 = for { n <- s } yield sq(n)
+// Anonymous functions can be called as usual:
+sq(10) // => 100
-for { n <- nSquared2 if n < 10 } yield n
+// If your anonymous function has one or two arguments, and each argument is
+// used only once, Scala gives you an even shorter way to define them. These
+// anonymous functions turn out to be extremely common, as will be obvious in
+// the data structure section.
+val addOne: Int => Int = _ + 1
+val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3)
-for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+addOne(5) // => 6
+weirdSum(2, 4) // => 16
-/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas
- a for-comprehension defines a relationship between two sets of data. */
+// The return keyword exists in Scala, but it only returns from the inner-most
+// def that surrounds it. It has no effect on anonymous functions. For example:
+def foo(x: Int) = {
+ val anonFunc: Int => Int = { z =>
+ if (z > 5)
+ return z // This line makes z the return value of foo!
+ else
+ z + 2 // This line is the return value of anonFunc
+ }
+ anonFunc(x) // This line is the return value of foo
+}
-// Loops and iteration
+/////////////////////////////////////////////////
+// 3. Flow Control
+/////////////////////////////////////////////////
1 to 5
val r = 1 to 5
r.foreach( println )
-r foreach println
+r foreach println
// NB: Scala is quite lenient when it comes to dots and brackets - study the
// rules separately. This helps write DSLs and APIs that read like English
@@ -238,12 +232,12 @@ while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why
i // Show the value of i. Note that while is a loop in the classical sense -
// it executes sequentially while changing the loop variable. while is very
- // fast, faster that Java // loops, but using the combinators and
+ // fast, faster that Java loops, but using the combinators and
// comprehensions above is easier to understand and parallelize
// A do while loop
do {
- println("x is still less then 10");
+ println("x is still less than 10");
x += 1
} while (x < 10)
@@ -255,7 +249,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = {
if (a < b)
showNumbersInRange(a + 1, b)
}
-
+showNumbersInRange(1,14)
// Conditionals
@@ -270,37 +264,146 @@ if (x == 11) println ("yeah") else println("nay")
println(if (x == 10) "yeah" else "nope")
val text = if (x == 10) "yeah" else "nope"
-var i = 0
-while (i < 10) { println("i " + i); i+=1 }
+/////////////////////////////////////////////////
+// 4. Data Structures
+/////////////////////////////////////////////////
+
+val a = Array(1, 2, 3, 5, 8, 13)
+a(0)
+a(3)
+a(21) // Throws an exception
+
+val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
+m("fork")
+m("spoon")
+m("bottle") // Throws an exception
+val safeM = m.withDefaultValue("no lo se")
+safeM("bottle")
-// Object oriented features
+val s = Set(1, 3, 7)
+s(0)
+s(1)
-// Classname is Dog
-class Dog {
- //A method called bark, returning a String
- def bark: String = {
- // the body of the method
- "Woof, woof!"
- }
+/* Look up the documentation of map here -
+ * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
+ * and make sure you can read it
+ */
+
+
+// Tuples
+
+(1, 2)
+
+(4, 3, 2)
+
+(1, 2, "three")
+
+(a, 2, "three")
+
+// Why have this?
+val divideInts = (x:Int, y:Int) => (x / y, x % y)
+
+divideInts(10,3) // The function divideInts gives you the result and the remainder
+
+// To access the elements of a tuple, use _._n where n is the 1-based index of
+// the element
+val d = divideInts(10,3)
+
+d._1
+
+d._2
+
+
+/////////////////////////////////////////////////
+// 5. Object Oriented Programming
+/////////////////////////////////////////////////
+
+/*
+ Aside: Everything we've done so far in this tutorial has been simple
+ expressions (values, functions, etc). These expressions are fine to type into
+ the command-line interpreter for quick tests, but they cannot exist by
+ themselves in a Scala file. For example, you cannot have just "val x = 5" in
+ a Scala file. Instead, the only top-level constructs allowed in Scala are:
+
+ - objects
+ - classes
+ - case classes
+ - traits
+
+ And now we will explain what these are.
+*/
+
+// classes are similar to classes in other languages. Constructor arguments are
+// declared after the class name, and initialization is done in the class body.
+class Dog(br: String) {
+ // Constructor code here
+ var breed: String = br
+
+ // Define a method called bark, returning a String
+ def bark = "Woof, woof!"
+
+ // Values and methods are assumed public. "protected" and "private" keywords
+ // are also available.
+ private def sleep(hours: Int) =
+ println(s"I'm sleeping for $hours hours")
+
+ // Abstract methods are simply methods with no body. If we uncomment the next
+ // line, class Dog would need to be declared abstract
+ // abstract class Dog(...) { ... }
+ // def chaseAfter(what: String): String
}
-// Classes can contain nearly any other construct, including other classes,
-// functions, methods, objects, case classes, traits etc.
+val mydog = new Dog("greyhound")
+println(mydog.breed) // => "greyhound"
+println(mydog.bark) // => "Woof, woof!"
+// The "object" keyword creates a type AND a singleton instance of it. It is
+// common for Scala classes to have a "companion object", where the per-instance
+// behavior is captured in the classes themselves, but behavior related to all
+// instance of that class go in objects. The difference is similar to class
+// methods vs static methods in other languages. Note that objects and classes
+// can have the same name.
+object Dog {
+ def allKnownBreeds = List("pitbull", "shepherd", "retriever")
+ def createDog(breed: String) = new Dog(breed)
+}
-// Case classes
-case class Person(name:String, phoneNumber:String)
+// Case classes are classes that have extra functionality built in. A common
+// question for Scala beginners is when to use classes and when to use case
+// classes. The line is quite fuzzy, but in general, classes tend to focus on
+// encapsulation, polymorphism, and behavior. The values in these classes tend
+// to be private, and only methods are exposed. The primary purpose of case
+// classes is to hold immutable data. They often have few methods, and the
+// methods rarely have side-effects.
+case class Person(name: String, phoneNumber: String)
+
+// Create a new instance. Note cases classes don't need "new"
+val george = Person("George", "1234")
+val kate = Person("Kate", "4567")
+
+// With case classes, you get a few perks for free, like getters:
+george.phoneNumber // => "1234"
-Person("George", "1234") == Person("Kate", "1236")
+// Per field equality (no need to override .equals)
+Person("George", "1234") == Person("Kate", "1236") // => false
+// Easy way to copy
+// otherGeorge == Person("george", "9876")
+val otherGeorge = george.copy(phoneNumber = "9876")
+// And many others. Case classes also get pattern matching for free, see below.
-// Pattern matching
+// Traits coming soon!
+
+
+/////////////////////////////////////////////////
+// 6. Pattern Matching
+/////////////////////////////////////////////////
val me = Person("George", "1234")
@@ -322,50 +425,147 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy"
// Regular expressions
-
val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex
+val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax
+
+val matcher = (value: String) => {
+ println(value match {
+ case email(name, domain) => s"It was an email: $name"
+ case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4"
+ case _ => s"No match on '$value'" // default if no match found
+ })
+}
-val email(user, domain) = "henry@zkpr.com"
+matcher("mrbean@pyahoo.com") // => "It was an email: mrbean"
+matcher("nope..") // => "No match on 'nope..'"
+matcher("52917") // => "No match on '52917'"
+matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917"
-"mrbean@pyahoo.com" match {
- case email(name, domain) => "I know your name, " + name
-}
+/////////////////////////////////////////////////
+// 7. Functional Programming
+/////////////////////////////////////////////////
+// Scala allows methods and functions to return, or take as parameters, other
+// functions or methods.
-// Strings
+List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
-"Scala strings are surrounded by double quotes" //
-'a' // A Scala Char
-'Single quote strings don't exist' // Error
-"Strings have the usual Java methods defined on them".length
-"They also have some extra Scala methods.".reverse
+// Anonymous functions can be used instead of named functions:
+List(1, 2, 3) map (x => x + 10)
+
+// And the underscore symbol, can be used if there is just one argument to the
+// anonymous function. It gets bound as the variable
+List(1, 2, 3) map (_ + 10)
+
+// If the anonymous block AND the function you are applying both take one
+// argument, you can even omit the underscore
+List("Dom", "Bob", "Natalia") foreach println
-// Seealso: scala.collection.immutable.StringOps
-println("ABCDEF".length)
-println("ABCDEF".substring(2, 6))
-println("ABCDEF".replace("C", "3"))
+// Combinators
-val n = 45
-println(s"We have $n apples")
+s.map(sq)
-val a = Array(11, 9, 6)
-println(s"My second daughter is ${a(2-1)} years old")
+val sSquared = s. map(sq)
-// Some characters need to be 'escaped', e.g. a double quote inside a string:
-val a = "They stood outside the \"Rose and Crown\""
+sSquared.filter(_ < 10)
-// Triple double-quotes let strings span multiple rows and contain quotes
+sSquared.reduce (_+_)
-val html = """<form id="daform">
- <p>Press belo', Joe</p>
- | <input type="submit">
- </form>"""
+// The filter function takes a predicate (a function from A -> Boolean) and
+// selects all elements which satisfy the predicate
+List(1, 2, 3) filter (_ > 2) // List(3)
+case class Person(name:String, phoneNumber:String)
+List(
+ Person(name = "Dom", age = 23),
+ Person(name = "Bob", age = 30)
+).filter(_.age > 25) // List(Person("Bob", 30))
+
+
+// Scala a foreach method defined on certain collections that takes a type
+// returning Unit (a void method)
+val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100)
+aListOfNumbers foreach (x => println(x))
+aListOfNumbers foreach println
+
+// For comprehensions
+for { n <- s } yield sq(n)
+
+val nSquared2 = for { n <- s } yield sq(n)
+
+for { n <- nSquared2 if n < 10 } yield n
+
+for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
+/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas
+ a for-comprehension defines a relationship between two sets of data. */
-// Application structure and organization
+
+/////////////////////////////////////////////////
+// 8. Implicits
+/////////////////////////////////////////////////
+
+/* WARNING WARNING: Implicits are a set of powerful features of Scala, and
+ * therefore it is easy to abuse them. Beginners to Scala should resist the
+ * temptation to use them until they understand not only how they work, but also
+ * best practices around them. We only include this section in the tutorial
+ * because they are so commonplace in Scala libraries that it is impossible to
+ * do anything meaningful without using a library that has implicits. This is
+ * meant for you to understand and work with implicts, not declare your own.
+ */
+
+// Any value (vals, functions, objects, etc) can be declared to be implicit by
+// using the, you guessed it, "implicit" keyword. Note we are using the Dog
+// class from section 5 in these examples.
+implicit val myImplicitInt = 100
+implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed)
+
+// By itself, implicit keyword doesn't change the behavior of the value, so
+// above values can be used as usual.
+myImplicitInt + 2 // => 102
+myImplicitFunction("Pitbull").breed // => "Golden Pitbull"
+
+// The difference is that these values are now eligible to be used when another
+// piece of code "needs" an implicit value. One such situation is implicit
+// function arguments:
+def sendGreetings(toWhom: String)(implicit howMany: Int) =
+ s"Hello $toWhom, $howMany blessings to you and yours!"
+
+// If we supply a value for "howMany", the function behaves as usual
+sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!"
+
+// But if we omit the implicit parameter, an implicit value of the same type is
+// used, in this case, "myImplicitInt":
+sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!"
+
+// Implicit function parameters enable us to simulate type classes in other
+// functional languages. It is so often used that it gets its own shorthand. The
+// following two lines mean the same thing:
+def foo[T](implicit c: C[T]) = ...
+def foo[T : C] = ...
+
+
+// Another situation in which the compiler looks for an implicit is if you have
+// obj.method(...)
+// but "obj" doesn't have "method" as a method. In this case, if there is an
+// implicit conversion of type A => B, where A is the type of obj, and B has a
+// method called "method", that conversion is applied. So having
+// myImplicitFunction above in scope, we can say:
+"Retriever".breed // => "Golden Retriever"
+"Sheperd".bark // => "Woof, woof!"
+
+// Here the String is first converted to Dog using our function above, and then
+// the appropriate method is called. This is an extremely powerful feature, but
+// again, it is not to be used lightly. In fact, when you defined the implicit
+// function above, your compiler should have given you a warning, that you
+// shouldn't do this unless you really know what you're doing.
+
+
+/////////////////////////////////////////////////
+// 9. Misc
+/////////////////////////////////////////////////
// Importing things
import scala.collection.immutable.List
@@ -403,7 +603,10 @@ for(line <- Source.fromFile("myfile.txt").getLines())
println(line)
// To write a file use Java's PrintWriter
-
+val writer = new PrintWriter("myfile.txt")
+writer.write("Writing line for line" + util.Properties.lineSeparator)
+writer.write("Another line here" + util.Properties.lineSeparator)
+writer.close()
```
diff --git a/self.html.markdown b/self.html.markdown
new file mode 100644
index 00000000..69524a84
--- /dev/null
+++ b/self.html.markdown
@@ -0,0 +1,161 @@
+---
+language: self
+contributors:
+ - ["Russell Allen", "http://github.com/russellallen"]
+filename: learnself.self
+---
+
+Self is a fast prototype based OO language which runs in its own JIT vm. Most development is done through interacting with live objects through a visual development environment called *morphic* with integrated browsers and debugger.
+
+Everything in Self is an object. All computation is done by sending messages to objects. Objects in Self can be understood as sets of key-value slots.
+
+# Constructing objects
+
+The inbuild Self parser can construct objects, including method objects.
+
+```
+"This is a comment"
+
+"A string:"
+'This is a string with \'escaped\' characters.\n'
+
+"A 30 bit integer"
+23
+
+"A 30 bit float"
+3.2
+
+"-20"
+-14r16
+
+"An object which only understands one message, 'x' which returns 20"
+(|
+ x = 20.
+|)
+
+"An object which also understands 'x:' which sets the x slot"
+(|
+ x <- 20.
+|)
+
+"An object which understands the method 'doubleX' which
+doubles the value of x and then returns the object"
+(|
+ x <- 20.
+ doubleX = (x: x * 2. self)
+|)
+
+"An object which understands all the messages
+that 'traits point' understands". The parser
+looks up 'traits point' by sending the messages
+'traits' then 'point' to a known object called
+the 'lobby'. It looks up the 'true' object by
+also sending the message 'true' to the lobby."
+(| parent* = traits point.
+ x = 7.
+ y <- 5.
+ isNice = true.
+|)
+```
+
+# Sending messages to objects
+
+Messages can either be unary, binary or keyword. Precedence is in that order. Unlike Smalltalk, the precedence of binary messages must be specified, and all keywords after the first must start with a capital letter. Messages are separeated from their destination by whitespace.
+
+```
+"unary message, sends 'printLine' to the object '23'
+which prints the string '23' to stdout and returns the receiving object (ie 23)"
+23 printLine
+
+"sends the message '+' with '7' to '23', then the message '*' with '8' to the result"
+(23 + 7) * 8
+
+"sends 'power:' to '2' with '8' returns 256"
+2 power: 8
+
+"sends 'keyOf:IfAbsent:' to 'hello' with arguments 'e' and '-1'.
+Returns 1, the index of 'e' in 'hello'."
+'hello' keyOf: 'e' IfAbsent: -1
+```
+
+# Blocks
+
+Self defines flow control like Smalltalk and Ruby by way of blocks. Blocks are delayed computations of the form:
+
+```
+[|:x. localVar| x doSomething with: localVar]
+```
+
+Examples of the use of a block:
+
+```
+"returns 'HELLO'"
+'hello' copyMutable mapBy: [|:c| c capitalize]
+
+"returns 'Nah'"
+'hello' size > 5 ifTrue: ['Yay'] False: ['Nah']
+
+"returns 'HaLLO'"
+'hello' copyMutable mapBy: [|:c|
+ c = 'e' ifTrue: [c capitalize]
+ False: ['a']]
+```
+
+Multiple expressions are separated by a period. ^ returns immediately.
+
+```
+"returns An 'E'! How icky!"
+'hello' copyMutable mapBy: [|:c. tmp <- ''|
+ tmp: c capitalize.
+ tmp = 'E' ifTrue: [^ 'An \'E\'! How icky!'].
+ c capitalize
+ ]
+```
+
+Blocks are performed by sending them the message 'value' and inherit (delegate to) their contexts:
+```
+"returns 0"
+[|x|
+ x: 15.
+ "Repeatedly sends 'value' to the first block while the result of sending 'value' to the
+ second block is the 'true' object"
+ [x > 0] whileTrue: [x: x - 1].
+ x
+] value
+```
+
+# Methods
+
+Methods are like blocks but they are not within a context but instead are stored as values of slots. Unlike Smalltalk, methods by default return their final value not 'self'.
+
+```
+"Here is an object with one assignable slot 'x' and a method 'reduceXTo: y'.
+Sending the message 'reduceXTo: 10' to this object will put
+the object '10' in the 'x' slot and return the original object"
+(|
+ x <- 50.
+ reduceXTo: y = (
+ [x > y] whileTrue: [x: x - 1].
+ self)
+|)
+.
+```
+
+# Prototypes
+
+Self has no classes. The way to get an object is to find a prototype and copy it.
+
+```
+| d |
+d: dictionary copy.
+d at: 'hello' Put: 23 + 8.
+d at: 'goodbye' Put: 'No!.
+"Prints No!"
+( d at: 'goodbye' IfAbsent: 'Yes! ) printLine.
+"Prints 31"
+( d at: 'hello' IfAbsent: -1 ) printLine.
+```
+
+# Further information
+
+The [Self handbook](http://handbook.selflanguage.org) has much more information, and nothing beats hand-on experience with Self by downloading it from the [homepage](http://www.selflanguage.org).
diff --git a/swift.html.markdown b/swift.html.markdown
index a47b085a..005e511c 100644
--- a/swift.html.markdown
+++ b/swift.html.markdown
@@ -2,130 +2,247 @@
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
+// import a module
+import UIKit
+
//
-// 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")
+
+// variables (var) value can change after being set
+// constants (let) value can NOT be changed after being set
+
var myVariable = 42
-let myConstant = 3.1415926
+let øπΩ = "value" // unicode variable names
+let π = 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
-optionalString = nil
+let intValue = 0007 // 7
+let largeIntValue = 77_000 // 77000
+let label = "some text " + String(myVariable) // Casting
+let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
+
+// Build Specific values
+// uses -D build configuration
+#if false
+ println("Not printed")
+ let buildValue = 3
+#else
+ let buildValue = 7
+#endif
+println("Build value: \(buildValue)") // Build value: 7
+
+/*
+ Optionals are a Swift language feature that allows you to store a `Some` or
+ `None` value.
+
+ Because Swift requires every property to have a value, even nil must be
+ explicitly stored as an Optional value.
+
+ Optional<T> is an enum.
+*/
+var someOptionalString: String? = "optional" // Can be nil
+// same as above, but ? is a postfix operator (syntax candy)
+var someOptionalString2: Optional<String> = "optional"
+
+if someOptionalString != nil {
+ // I am not nil
+ if someOptionalString!.hasPrefix("opt") {
+ println("has the prefix")
+ }
+
+ let empty = someOptionalString?.isEmpty
+}
+someOptionalString = nil
+
+// implicitly unwrapped optional
+var unwrappedString: String! = "Value is expected."
+// same as above, but ! is a postfix operator (more syntax candy)
+var unwrappedString2: ImplicitlyUnwrappedOptional<String> = "Value is expected."
+if let someOptionalStringConstant = someOptionalString {
+ // has `Some` value, non-nil
+ if !someOptionalStringConstant.hasPrefix("ok") {
+ // does not have the prefix
+ }
+}
+
+// Swift has support for storing a value of any type.
+// AnyObject == id
+// Unlike Objective-C `id`, AnyObject works with any value (Class, Int, struct, etc)
+var anyObjectVar: AnyObject = 7
+anyObjectVar = "Changed value to a string, not good practice, but possible."
+
+/*
+Comment here
+ /*
+ Nested comments are also supported
+ */
+*/
//
-// Arrays and Dictionaries
+// MARK: Collections
//
+/*
+ Array and Dictionary types are structs. So `let` and `var` also indicate
+ that they are mutable (var) or immutable (let) when declaring these types.
+*/
+
// Array
var shoppingList = ["catfish", "water", "lemons"]
shoppingList[1] = "bottle of water"
-let emptyArray = [String]()
+let emptyArray = [String]() // immutable
+var emptyMutableArray = [String]() // mutable
+
// Dictionary
var occupations = [
- "Malcolm": "Captain",
- "kaylee": "Mechanic"
+ "Malcolm": "Captain",
+ "kaylee": "Mechanic"
]
occupations["Jayne"] = "Public Relations"
-let emptyDictionary = Dictionary<String, Float>()
+let emptyDictionary = [String: Float]() // immutable
+var emptyMutableDictionary = [String: Float]() // mutable
//
-// 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)
+for i in -1...shoppingList.count {
+ println(i)
}
+shoppingList[1...2] = ["steak", "peacons"]
// 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)
+}
+let pricesTuple = getGasPrices()
+let price = pricesTuple.2 // 3.79
+// Ignore Tuple (or other) values by using _ (underscore)
+let (_, price1, _) = pricesTuple // price1 == 3.69
+println(price1 == pricesTuple.1) // true
+println("Gas price: \(price)")
+
+// Variadic Args
+func setup(numbers: Int...) {
+ // its an array
+ let number = numbers[0]
+ let argCount = numbers.count
}
-
-// 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)
+// pass by ref
+func swapTwoInts(inout a: Int, inout b: Int) {
+ let tempA = a
+ a = b
+ b = tempA
+}
+var someIntA = 7
+var someIntB = 3
+swapTwoInts(&someIntA, &someIntB)
+println(someIntB) // 7
+
//
-// Closures
+// MARK: Closures
//
var numbers = [1, 2, 6]
@@ -135,93 +252,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
-
- // Custom getter and setter property
- var perimeter: Int {
- get {
- return 4 * sideLength
+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
+ }
}
- set {
- sideLength = newValue / 4
+
+ // 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)
+ }
}
- }
-
- init(sideLength: Int) {
- super.init()
- self.sideLength = sideLength
- }
-
- func shrink() {
- if sideLength > 0 {
- --sideLength
+
+ init(sideLength: Int) {
+ self.sideLength = sideLength
+ // always super.init last when init custom properties
+ super.init()
+ }
+
+ func shrink() {
+ if sideLength > 0 {
+ --sideLength
+ }
+ }
+
+ override func getArea() -> Int {
+ return sideLength * sideLength
}
- }
+}
- 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`: Similar to Java interfaces.
-// `extension`s: Add extra functionality to an already created type
-// Generics: Similar to Java. Use the `where` keyword to specify the
+// `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
+//
+
+// `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 and C#. 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..9eb96303
--- /dev/null
+++ b/tmux.html.markdown
@@ -0,0 +1,243 @@
+---
+category: tool
+tool: tmux
+contributors:
+ - ["wzsk", "https://github.com/wzsk"]
+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.10
+
+
+### General
+###########################################################################
+
+# Enable UTF-8
+setw -g utf8 on
+set-option -g status-utf8 on
+
+# Scrollback/History limit
+set -g history-limit 2048
+
+# Index Start
+set -g base-index 1
+
+# Mouse
+set-option -g mouse-select-pane on
+
+# Force reload of config file
+unbind r
+bind r source-file ~/.tmux.conf
+
+
+### Keybinds
+###########################################################################
+
+# Unbind C-b as the default prefix
+unbind C-b
+
+# Set new default prefix
+set-option -g prefix `
+
+# Return to previous window when prefix is pressed twice
+bind C-a last-window
+bind ` last-window
+
+# Allow swapping C-a and ` using F11/F12
+bind F11 set-option -g prefix C-a
+bind F12 set-option -g prefix `
+
+# Keybind preference
+setw -g mode-keys vi
+set-option -g status-keys vi
+
+# 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
+
+# Window Cycle/Swap
+bind e previous-window
+bind f next-window
+bind E swap-window -t -1
+bind F swap-window -t +1
+
+# Easy split pane commands
+bind = split-window -h
+bind - split-window -v
+unbind '"'
+unbind %
+
+# Activate inner-most session (when nesting tmux) to send commands
+bind a send-prefix
+
+
+### Theme
+###########################################################################
+
+# Statusbar Color Palatte
+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
+###########################################################################
+
+# Notification
+setw -g monitor-activity on
+set -g visual-activity on
+set-option -g bell-action any
+set-option -g visual-bell off
+
+# Automatically set window titles
+set-option -g set-titles on
+set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not)
+
+# Statusbar Adjustments
+set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]"
+
+# Show performance counters in statusbar
+# Requires https://github.com/thewtex/tmux-mem-cpu-load/
+set -g status-interval 4
+set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]"
+
+```
+
+<a href="http://tmux.sourceforge.net/">Tmux | Home</a><br>
+<a href="http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux">Tmux Manual page</a><br>
+<a href="http://wiki.gentoo.org/wiki/Tmux">Gentoo Wiki</a><br>
+<a href="https://wiki.archlinux.org/index.php/Tmux">Archlinux Wiki</a><br>
+<a href="https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux">Display CPU/MEM % in statusbar</a><br>
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/tr-tr/php-tr.html.markdown b/tr-tr/php-tr.html.markdown
index 3db437cf..5258d785 100644
--- a/tr-tr/php-tr.html.markdown
+++ b/tr-tr/php-tr.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
filename: learnphp-tr.php
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
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/git-vi.html.markdown b/vi-vn/git-vi.html.markdown
index bdb88204..1bcc94a0 100644
--- a/vi-vn/git-vi.html.markdown
+++ b/vi-vn/git-vi.html.markdown
@@ -2,14 +2,15 @@
category: tool
tool: git
contributors:
- - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Jake Prather", "http://github.com/JakeHP"]
+ - ["Vinh Nguyen", "https://twitter.com/vinhnx"]
filename: LearnGit-vi.txt
lang: vi-vn
---
Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system).
-Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, and nó hoạt động
+Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động
với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và
quản lý mã nguồn của bạn.
@@ -19,7 +20,7 @@ quản lý mã nguồn của bạn.
Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian.
-### Centralized Versioning VS Distributed Versioning
+### So sánh giữa Centralized Versioning và Distributed Versioning
* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin.
* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất.
@@ -75,7 +76,7 @@ con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nh
### HEAD và head (thành phần của thư mục .git)
-HEAD là một con trỏ đến nhánh hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
+HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*.
head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head.
### Các Tài Nguyên Mang Tính Khái Niệm
@@ -165,29 +166,29 @@ $ git add ./*.java
### branch
-Quản lý nhánh. Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
+Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này.
```bash
-# liệt kê các nhanh đang có và ở remote
+# liệt kê các branch đang có và ở remote
$ git branch -a
-# tạo nhánh mới
+# tạo branch mới
$ git branch myNewBranch
-# xóa một nhánh
+# xóa một branch
$ git branch -d myBranch
-# đặt tên lại một nhánh
+# đặt tên lại một branch
# git branch -m <oldname> <newname>
$ git branch -m myBranchName myNewBranchName
-# chỉnh sủa diễn giải của một nhánh
+# chỉnh sửa diễn giải của một branch
$ git branch myBranchName --edit-description
```
### checkout
-Cập nhật tất cả các file torng tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
+Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể.
```bash
# Checkout (chuyển) một repo - mặc định là nhánh master
@@ -201,8 +202,8 @@ $ git checkout -b newBranch
### clone
Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm
-các nhánh có remote-tracking cho mỗi nhánh trong một repo được nhân bản, mà
-cho phép bạn push đến một nhánh remote.
+các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà
+cho phép bạn push đến một remote branch.
```bash
# Nhân bản learnxinyminutes-docs
@@ -211,7 +212,7 @@ $ git clone https://github.com/adambard/learnxinyminutes-docs.git
### commit
-Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một lời nhắn (ghi chú) tạo ra bởi người dùng.
+Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng.
```bash
# commit với một ghi chú
@@ -279,7 +280,7 @@ $ git log --merges
"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại.
```bash
-# Merge nhánh cụ thể vào nhánh hiện tại.
+# Merge branch cụ thể vào branch hiện tại.
$ git merge branchName
# Luôn khởi tạo một merge commit khi trộn (merge)
@@ -304,30 +305,35 @@ $ git mv -f myFile existingFile
### pull
-Kéo (tải) về từ một repo và merge nó vào nhánh khác.
+Pull về từ một repo và merge nó vào branch khác.
```bash
-# Cập nhật repo cục bộ của bạn, bằng cách merge các thay đổi mới
+# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới
# từ remote "origin" và nhánh "master".
# git pull <remote> <branch>
# git pull => hoàn toàn mặc định như => git pull origin master
$ git pull origin master
-# Merge các thay đổi từ nhánh remote và rebase
-# các commit nhánh lên trên thư mục cục bộ, như: "git pull <remote> <branch>, git rebase <branch>"
+# Merge các thay đổi từ remote branch và rebase
+# các commit trong branch lên trên local repo, như sau: "git pull <remote> <branch>, git rebase <branch>"
$ git pull origin master --rebase
```
### push
-Đẩy và trộn (mege) các tay đổi từ một nhánh đế một remote & nhánh.
-
-```bash
-# Push và merge các thay đổi từ repo cục bộ đến một
-# remote tên là "origin" và nhánh "master".
-# git push <remote> <branch>
-# git push => hoàn toàn defaults to => git push origin master
-$ git push origin master
+push và merge các thay đổi từ một branch đến một remote & branch.
+
+```bash
+# Push và merge các thay đổi từ một repo local đến một
+# remote có tên là "origin" và nhánh "master".
+# git push <remote> <branch>
+# git push => mặc định ẩn đến => git push origin master
+$ git push origin master
+
+# Để liên kết đến một branch local với một branch remote, thêm vào cờ -u:
+$ git push -u origin master
+# Từ lúc này, bất cứ khi nào bạn muốn push từ cùng một nhánh local đó, sử dụng lối tắt:
+$ git push
```
### rebase (thận trọng)
@@ -390,4 +396,8 @@ $ git rm /pather/to/the/file/HelloWorld.c
* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf)
-* [GitGuys](http://www.gitguys.com/)
+* [GitGuys](http://www.gitguys.com/)
+
+* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html)
+
+
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/whip.html.markdown b/whip.html.markdown
index dc5a0b39..3faee98a 100644
--- a/whip.html.markdown
+++ b/whip.html.markdown
@@ -31,7 +31,7 @@ not_in_form
(called_function args)
; Majority of operations are done with functions
-; All the basic arihmetic is pretty straight forward
+; All the basic arithmetic is pretty straight forward
(+ 1 1) ; => 2
(- 2 1) ; => 1
(* 1 2) ; => 2
@@ -48,7 +48,7 @@ not_in_form
true
false
-; String are created with ".
+; Strings are created with ".
"Hello, world"
; Single chars are created with '.
@@ -66,7 +66,7 @@ false
(= 1 1) ; => true
(equal 2 1) ; => false
-; For example, inequality would be combinding the not and equal functions.
+; For example, inequality would be combining the not and equal functions.
(! (= 2 1)) ; => true
; More comparisons
@@ -96,10 +96,10 @@ undefined ; user to indicate a value that hasn't been set
; 2. Vairbles, Lists, and Dicts
; Variables are declared with the `def` or `let` functions.
-; Variab;es that haven't been set will be `undefined`.
+; Variables that haven't been set will be `undefined`.
(def some_var 5)
; `def` will keep the variable in the global context.
-; `let` will only have the variable inside it's context, and has a wierder syntax.
+; `let` will only have the variable inside its context, and has a wierder syntax.
(let ((a_var 5)) (+ a_var 5)) ; => 10
(+ a_var 5) ; = undefined + 5 => undefined
@@ -129,7 +129,7 @@ undefined ; user to indicate a value that hasn't been set
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; 3. Logic and Control sequences
-; The `if` function is pretty simple, though different than most imperitave langs.
+; The `if` function is pretty simple, though different than most imperative langs.
(if true "returned if first arg is true" "returned if first arg is false")
; => "returned if first arg is true"
@@ -159,12 +159,12 @@ undefined ; user to indicate a value that hasn't been set
; | | arguments
; | lambda declaration function
; |
-; name of the to-be-decalred lambda
+; name of the to-be-declared lambda
(my_function 10 10) ; = (+ (+ 10 10) 10) => 30
; Obiously, all lambdas by definition are anonymous and
-; technically always used anonymouesly. Redundancy.
+; technically always used anonymously. Redundancy.
((lambda (x) x) 10) ; => 10
;;;;;;;;;;;;;;;;
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown
index 223f6e35..1e10416e 100644
--- a/zh-cn/c-cn.html.markdown
+++ b/zh-cn/c-cn.html.markdown
@@ -566,7 +566,7 @@ typedef void (*my_fnp_type)(char *);
'\'' // 单引号
'\"' // 双引号
'\xhh' // 十六进制数字. 例子: '\xb' = vertical tab
-'\ooo' // 十进制数字. 例子: '\013' = vertical tab
+'\ooo' // 八进制数字. 例子: '\013' = vertical tab
// 打印格式:
"%d" // 整数
@@ -579,7 +579,7 @@ typedef void (*my_fnp_type)(char *);
"%c" // 字母
"%p" // 指针
"%x" // 十六进制
-"%o" // 十进制
+"%o" // 八进制
"%%" // 打印 %
///////////////////////////////////////
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/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown
index 8d51f144..cb7ccdee 100644
--- a/zh-cn/haskell-cn.html.markdown
+++ b/zh-cn/haskell-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: haskell
+language: Haskell
filename: learn-haskell-zh.hs
contributors:
- ["Adit Bhargava", "http://adit.io"]
diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown
index 86ad1d07..7dee9cc4 100644
--- a/zh-cn/javascript-cn.html.markdown
+++ b/zh-cn/javascript-cn.html.markdown
@@ -363,8 +363,8 @@ var myNumberObj = new Number(12)
myNumber == myNumberObj // = true
// 但是它们并非严格等价
-typeof(myNumber) // = 'number'
-typeof(myNumberObj) // = 'object'
+typeof myNumber // = 'number'
+typeof myNumberObj // = 'object'
myNumber === myNumberObj // = false
if (0){
// 这段代码不会执行,因为0代表假
diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown
index 7afc9043..1f91d52c 100644
--- a/zh-cn/julia-cn.html.markdown
+++ b/zh-cn/julia-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: julia
+language: Julia
filename: learn-julia-zh.jl
contributors:
- ["Jichao Ouyang", "http://oyanglul.us"]
diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown
new file mode 100644
index 00000000..fea00bc1
--- /dev/null
+++ b/zh-cn/livescript-cn.html.markdown
@@ -0,0 +1,322 @@
+---
+language: LiveScript
+filename: learnLivescript.ls
+contributors:
+ - ["Christina Whyte", "http://github.com/kurisuwhyte/"]
+translators:
+ - ["ShengDa Lyu", "http://github.com/SDLyu/"]
+lang: zh-cn
+---
+
+LiveScript 是一种具有函数式特性且编译成 JavaScript 的语言,能对应 JavaScript 的基本语法。
+还有些额外的特性如:柯里化,组合函数,模式匹配,还有借镜于 Haskell,F# 和 Scala 的许多特点。
+
+LiveScript 诞生于 [Coco][],而 Coco 诞生于 [CoffeeScript][]。
+LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多特性。
+
+[Coco]: http://satyr.github.io/coco/
+[CoffeeScript]: http://coffeescript.org/
+
+非常期待您的反馈,你可以通过
+[@kurisuwhyte](https://twitter.com/kurisuwhyte) 与我连系 :)
+
+
+```coffeescript
+# 与 CoffeeScript 一样,LiveScript 使用 # 单行注解。
+
+/*
+ 多行注解与 C 相同。使用注解可以避免被当成 JavaScript 输出。
+*/
+```
+```coffeescript
+# 语法的部份,LiveScript 使用缩进取代 {} 来定义区块,
+# 使用空白取代 () 来执行函数。
+
+
+########################################################################
+## 1. 值类型
+########################################################################
+
+# `void` 取代 `undefined` 表示未定义的值
+void # 与 `undefined` 等价但更安全(不会被覆写)
+
+# 空值则表示成 Null。
+null
+
+
+# 最基本的值类型数据是罗辑类型:
+true
+false
+
+# 罗辑类型的一些别名,等价于前者:
+on; off
+yes; no
+
+
+# 数字与 JS 一样,使用倍精度浮点数表示。
+10
+0.4 # 开头的 0 是必要的
+
+
+# 可以使用底线及单位后缀提高可读性,编译器会自动略过底线及单位后缀。
+12_344km
+
+
+# 字串与 JS 一样,是一种不可变的字元序列:
+"Christina" # 单引号也可以!
+"""Multi-line
+ strings
+ are
+ okay
+ too."""
+
+# 在前面加上 \ 符号也可以表示字串:
+\keyword # => 'keyword'
+
+
+# 数组是值的有序集合。
+fruits =
+ * \apple
+ * \orange
+ * \pear
+
+# 可以用 [] 简洁地表示数组:
+fruits = [ \apple, \orange, \pear ]
+
+
+# 你可以更方便地建立字串数组,并使用空白区隔元素。
+fruits = <[ apple orange pear ]>
+
+# 以 0 为起始值的数组下标获取元素:
+fruits[0] # => "apple"
+
+
+# 对象是无序键值对集合(更多给节将在下面章节讨论)。
+person =
+ name: "Christina"
+ likes:
+ * "kittens"
+ * "and other cute stuff"
+
+# 你也可以用更简洁的方式表示对象:
+person = {name: "Christina", likes: ["kittens", "and other cute stuff"]}
+
+# 可以通过键值获取值:
+person.name # => "Christina"
+person["name"] # => "Christina"
+
+
+# 正则表达式的使用跟 JavaScript 一样:
+trailing-space = /\s$/ # dashed-words 变成 dashedWords
+
+# 你也可以用多行描述表达式!(注解和空白会被忽略)
+funRE = //
+ function\s+(.+) # name
+ \s* \((.*)\) \s* # arguments
+ { (.*) } # body
+ //
+
+
+########################################################################
+## 2. 基本运算
+########################################################################
+
+# 数值操作符与 JavaScript 一样:
+1 + 2 # => 3
+2 - 1 # => 1
+2 * 3 # => 6
+4 / 2 # => 2
+3 % 2 # => 1
+
+
+# 比较操作符大部份也一样,除了 `==` 等价于 JS 中的 `===`,
+# JS 中的 `==` 在 LiveScript 里等价于 `~=`,
+# `===` 能进行对象、数组和严格比较。
+2 == 2 # => true
+2 == "2" # => false
+2 ~= "2" # => true
+2 === "2" # => false
+
+[1,2,3] == [1,2,3] # => false
+[1,2,3] === [1,2,3] # => true
+
++0 == -0 # => true
++0 === -0 # => false
+
+# 其它关系操作符包括 <、<=、> 和 >=
+
+# 罗辑值可以通过 `or`、`and` 和 `not` 结合:
+true and false # => false
+false or true # => true
+not false # => true
+
+
+# 集合也有一些便利的操作符
+[1, 2] ++ [3, 4] # => [1, 2, 3, 4]
+'a' in <[ a b c ]> # => true
+'name' of { name: 'Chris' } # => true
+
+
+########################################################################
+## 3. 函数
+########################################################################
+
+# 因为 LiveScript 是函数式特性的语言,你可以期待函数在语言里被高规格的对待。
+add = (left, right) -> left + right
+add 1, 2 # => 3
+
+# 加上 ! 防止函数执行后的返回值
+two = -> 2
+two!
+
+# LiveScript 与 JavaScript 一样使用函式作用域,且一样拥有闭包的特性。
+# 与 JavaScript 不同的地方在于,`=` 变量赋值时,左边的对象永远不用变量宣告。
+
+# `:=` 操作符允许*重新賦值*父作用域里的变量。
+
+
+# 你可以解构函数的参数,从不定长度的参数结构里获取感兴趣的值。
+tail = ([head, ...rest]) -> rest
+tail [1, 2, 3] # => [2, 3]
+
+# 你也可以使用一元或二元操作符转换参数。当然也可以预设传入的参数值。
+foo = (a = 1, b = 2) -> a + b
+foo! # => 3
+
+# 你可以以拷贝的方式传入参数来避免副作用,例如:
+copy = (^^target, source) ->
+ for k,v of source => target[k] = v
+ target
+a = { a: 1 }
+copy a, { b: 2 } # => { a: 1, b: 2 }
+a # => { a: 1 }
+
+
+# 使用长箭号取代短箭号来柯里化一个函数:
+add = (left, right) --> left + right
+add1 = add 1
+add1 2 # => 3
+
+# 函式里有一个隐式的 `it` 变量,意谓着你不用宣告它。
+identity = -> it
+identity 1 # => 1
+
+# 操作符在 LiveScript 里不是一個函数,但你可以简单地将它们转换成函数!
+# Enter the operator sectioning:
+divide-by-2 = (/ 2)
+[2, 4, 8, 16].map(divide-by-2) .reduce (+)
+
+
+# LiveScript 里不只有应用函数,如同其它良好的函数式语言,你可以合并函数获得更多发挥:
+double-minus-one = (- 1) . (* 2)
+
+# 除了普通的数学公式合并 `f . g` 之外,还有 `>>` 和 `<<` 操作符定义函数的合并顺序。
+double-minus-one = (* 2) >> (- 1)
+double-minus-one = (- 1) << (* 2)
+
+
+# 说到合并函数的参数, LiveScript 使用 `|>` 和 `<|` 操作符将参数传入:
+map = (f, xs) --> xs.map f
+[1 2 3] |> map (* 2) # => [2 4 6]
+
+# 你也可以选择填入值的位置,只需要使用底线 _ 标记:
+reduce = (f, xs, initial) --> xs.reduce f, initial
+[1 2 3] |> reduce (+), _, 0 # => 6
+
+
+# 你也能使 _ 让任何函数变成偏函数应用:
+div = (left, right) -> left / right
+div-by-2 = div _, 2
+div-by-2 4 # => 2
+
+
+# 最后,也很重要的,LiveScript 拥有後呼叫特性, 可以是基於回调的代码
+# (你可以试试其它函数式特性的解法,比如 Promises):
+readFile = (name, f) -> f name
+a <- readFile 'foo'
+b <- readFile 'bar'
+console.log a + b
+
+# 等同於:
+readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b
+
+
+########################################################################
+## 4. 模式、判断和流程控制
+########################################################################
+
+# 流程控制可以使用 `if...else` 表达式:
+x = if n > 0 then \positive else \negative
+
+# 除了 `then` 你也可以使用 `=>`
+x = if n > 0 => \positive
+ else \negative
+
+# 过於复杂的流程可以用 `switch` 表达式代替:
+y = {}
+x = switch
+ | (typeof y) is \number => \number
+ | (typeof y) is \string => \string
+ | 'length' of y => \array
+ | otherwise => \object # `otherwise` 和 `_` 是等价的。
+
+# 函数主体、宣告式和赋值式可以表式成 `switch`,这可以省去一些代码:
+take = (n, [x, ...xs]) -->
+ | n == 0 => []
+ | _ => [x] ++ take (n - 1), xs
+
+
+########################################################################
+## 5. 推导式
+########################################################################
+
+# 在 JavaScript 的标准函式库里有一些辅助函数能帮助处理列表及对象
+#(LiveScript 则带有一个 prelude.ls ,作为标准函式库的补充 ),
+# 推导式能让你使用优雅的语法且快速地处理这些事:
+oneToTwenty = [1 to 20]
+evens = [x for x in oneToTwenty when x % 2 == 0]
+
+# 在推导式里 `when` 和 `unless` 可以当成过滤器使用。
+
+# 对象推导式在使用上也是同样的方式,差别在于你使用的是对象而不是数组:
+copy = { [k, v] for k, v of source }
+
+
+########################################################################
+## 6. OOP
+########################################################################
+
+# 虽然 LiveScript 是一门函数式语言,但具有一些命令式及面向对象的特性。
+# 像是 class 语法和一些借镜於 CoffeeScript 的类别继承语法糖:
+class Animal
+ (@name, kind) ->
+ @kind = kind
+ action: (what) -> "*#{@name} (a #{@kind}) #{what}*"
+
+class Cat extends Animal
+ (@name) -> super @name, 'cat'
+ purr: -> @action 'purrs'
+
+kitten = new Cat 'Mei'
+kitten.purr! # => "*Mei (a cat) purrs*"
+
+# 除了类别的单一继承模式之外,还提供了像混入 (Mixins) 这种特性。
+# Mixins 在语言里被当成普通对象:
+Huggable =
+ hug: -> @action 'is hugged'
+
+class SnugglyCat extends Cat implements Huggable
+
+kitten = new SnugglyCat 'Purr'
+kitten.hug! # => "*Mei (a cat) is hugged*"
+```
+
+## 延伸阅读
+
+LiveScript 还有许多强大之处,但这些应该足够启发你写些小型函数式程式了。
+[LiveScript](http://livescript.net/)有更多关于 LiveScript 的资讯
+和线上编译器等着你来试!
+
+你也可以参考
+[prelude.ls](http://gkz.github.io/prelude-ls/),和一些 `#livescript`
+的网络聊天室频道。
diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown
index 95a94c76..53a603a2 100644
--- a/zh-cn/lua-cn.html.markdown
+++ b/zh-cn/lua-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: lua
+language: Lua
lang: zh-cn
contributors:
- ["Tyler Neylon", "http://tylerneylon.com/"]
@@ -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..1c577efb
--- /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/php-cn.html.markdown b/zh-cn/php-cn.html.markdown
index 24939681..2def7f1c 100644
--- a/zh-cn/php-cn.html.markdown
+++ b/zh-cn/php-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: php
+language: PHP
contributors:
- ["Malcolm Fell", "http://emarref.net/"]
- ["Trismegiste", "https://github.com/Trismegiste"]
diff --git a/zh-cn/python3-cn.html.markdown b/zh-cn/python3-cn.html.markdown
new file mode 100644
index 00000000..c223297c
--- /dev/null
+++ b/zh-cn/python3-cn.html.markdown
@@ -0,0 +1,629 @@
+---
+language: python3
+contributors:
+ - ["Louie Dinh", "http://pythonpracticeprojects.com"]
+ - ["Steven Basart", "http://github.com/xksteven"]
+ - ["Andre Polykanine", "https://github.com/Oire"]
+translators:
+ - ["Geoff Liu", "http://geoffliu.me"]
+filename: learnpython3-cn.py
+lang: zh-cn
+---
+
+Python是由吉多·范罗苏姆(Guido Van Rossum)在90年代早期设计。它是如今最常用的编程
+语言之一。它的语法简洁且优美,几乎就是可执行的伪代码。
+
+欢迎大家斧正。英文版原作Louie Dinh [@louiedinh](http://twitter.com/louiedinh)
+或着Email louiedinh [at] [谷歌的信箱服务]。中文翻译Geoff Liu。
+
+注意:这篇教程是特别为Python3写的。如果你想学旧版Python2,我们特别有另一篇教程。
+
+```python
+
+# 用井字符开头的是单行注释
+
+""" 多行字符串用三个引号
+ 包裹,也常被用来做多
+ 行注释
+"""
+
+####################################################
+## 1. 原始数据类型和运算符
+####################################################
+
+# 整数
+3 # => 3
+
+# 算术没有什么出乎意料的
+1 + 1 # => 2
+8 - 1 # => 7
+10 * 2 # => 20
+
+# 但是除法例外,会自动转换成浮点数
+35 / 5 # => 7.0
+5 / 3 # => 1.6666666666666667
+
+# 整数除法的结果都是向下取整
+5 // 3 # => 1
+5.0 // 3.0 # => 1.0 # 浮点数也可以
+-5 // 3 # => -2
+-5.0 // 3.0 # => -2.0
+
+# 浮点数的运算结果也是浮点数
+3 * 2.0 # => 6.0
+
+# 模除
+7 % 3 # => 1
+
+# x的y次方
+2**4 # => 16
+
+# 用括号决定优先级
+(1 + 3) * 2 # => 8
+
+# 布尔值
+True
+False
+
+# 用not取非
+not True # => False
+not False # => True
+
+# 逻辑运算符,注意and和or都是小写
+True and False #=> False
+False or True #=> True
+
+# 整数也可以当作布尔值
+0 and 2 #=> 0
+-5 or 0 #=> -5
+0 == False #=> True
+2 == True #=> False
+1 == True #=> True
+
+# 用==判断相等
+1 == 1 # => True
+2 == 1 # => False
+
+# 用!=判断不等
+1 != 1 # => False
+2 != 1 # => True
+
+# 比较大小
+1 < 10 # => True
+1 > 10 # => False
+2 <= 2 # => True
+2 >= 2 # => True
+
+# 大小比较可以连起来!
+1 < 2 < 3 # => True
+2 < 3 < 2 # => False
+
+# 字符串用单引双引都可以
+"这是个字符串"
+'这也是个字符串'
+
+# 用加号连接字符串
+"Hello " + "world!" # => "Hello world!"
+
+# 字符串可以被当作字符列表
+"This is a string"[0] # => 'T'
+
+# 用.format来格式化字符串
+"{} can be {}".format("strings", "interpolated")
+
+# 可以重复参数以节省时间
+"{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"
+
+# 如果不想数参数,可以用关键字
+"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna"
+
+# 如果你的Python3程序也要在Python2.5以下环境运行,也可以用老式的格式化语法
+"%s can be %s the %s way" % ("strings", "interpolated", "old")
+
+# None是一个对象
+None # => None
+
+# 当与None进行比较时不要用 ==,要用is。is是用来比较两个变量是否指向同一个对象。
+"etc" is None # => False
+None is None # => True
+
+# None,0,空字符串,空列表,空字典都算是False
+# 所有其他值都是True
+bool(0) # => False
+bool("") # => False
+bool([]) #=> False
+bool({}) #=> False
+
+
+####################################################
+## 2. 变量和集合
+####################################################
+
+# print是内置的打印函数
+print("I'm Python. Nice to meet you!")
+
+# 在给变量赋值前不用提前声明
+# 传统的变量命名是小写,用下划线分隔单词
+some_var = 5
+some_var # => 5
+
+# 访问未赋值的变量会抛出异常
+# 参考流程控制一段来学习异常处理
+some_unknown_var # 抛出NameError
+
+# 用列表(list)储存序列
+li = []
+# 创建列表时也可以同时赋给元素
+other_li = [4, 5, 6]
+
+# 用append在列表最后追加元素
+li.append(1) # li现在是[1]
+li.append(2) # li现在是[1, 2]
+li.append(4) # li现在是[1, 2, 4]
+li.append(3) # li现在是[1, 2, 4, 3]
+# 用pop从列表尾部删除
+li.pop() # => 3 且li现在是[1, 2, 4]
+# 把3再放回去
+li.append(3) # li变回[1, 2, 4, 3]
+
+# 列表存取跟数组一样
+li[0] # => 1
+# 取出最后一个元素
+li[-1] # => 3
+
+# 越界存取会造成IndexError
+li[4] # 抛出IndexError
+
+# 列表有切割语法
+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] # li is now [1, 2, 3]
+
+# 列表可以相加
+# 注意:li和other_li的值都不变
+li + other_li # => [1, 2, 3, 4, 5, 6]
+
+# 用extend拼接列表
+li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6]
+
+# 用in测试列表是否包含值
+1 in li # => True
+
+# 用len取列表长度
+len(li) # => 6
+
+
+# 元组是不可改变的序列
+tup = (1, 2, 3)
+tup[0] # => 1
+tup[0] = 3 # 抛出TypeError
+
+# 列表允许的操作元组大都可以
+len(tup) # => 3
+tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
+tup[:2] # => (1, 2)
+2 in tup # => True
+
+# 可以把元组合列表解包,赋值给变量
+a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3
+# 元组周围的括号是可以省略的
+d, e, f = 4, 5, 6
+# 交换两个变量的值就这么简单
+e, d = d, e # 现在d是5,e是4
+
+
+# 用字典表达映射关系
+empty_dict = {}
+# 初始化的字典
+filled_dict = {"one": 1, "two": 2, "three": 3}
+
+# 用[]取值
+filled_dict["one"] # => 1
+
+
+# 用keys获得所有的键。因为keys返回一个可迭代对象,所以在这里把结果包在list里。我们下面会详细介绍可迭代。
+# 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。
+list(filled_dict.keys()) # => ["three", "two", "one"]
+
+
+# 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。
+list(filled_dict.values()) # => [3, 2, 1]
+
+
+# 用in测试一个字典是否包含一个键
+"one" in filled_dict # => True
+1 in filled_dict # => False
+
+# 访问不存在的键会导致KeyError
+filled_dict["four"] # KeyError
+
+# 用get来避免KeyError
+filled_dict.get("one") # => 1
+filled_dict.get("four") # => None
+# 当键不存在的时候get方法可以返回默认值
+filled_dict.get("one", 4) # => 1
+filled_dict.get("four", 4) # => 4
+
+# setdefault方法只有当键不存在的时候插入新值
+filled_dict.setdefault("five", 5) # filled_dict["five"]设为5
+filled_dict.setdefault("five", 6) # filled_dict["five"]还是5
+
+# 字典赋值
+filled_dict.update({"four":4}) #=> {"one": 1, "two": 2, "three": 3, "four": 4}
+filled_dict["four"] = 4 # 另一种赋值方法
+
+# 用del删除
+del filled_dict["one"] # 从filled_dict中把one删除
+
+
+# 用set表达集合
+empty_set = set()
+# 初始化一个集合,语法跟字典相似。
+some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4}
+
+# 可以把集合赋值于变量
+filled_set = some_set
+
+# 为集合添加元素
+filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5}
+
+# & 取交集
+other_set = {3, 4, 5, 6}
+filled_set & other_set # => {3, 4, 5}
+
+# | 取并集
+filled_set | other_set # => {1, 2, 3, 4, 5, 6}
+
+# - 取补集
+{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
+
+# in 测试集合是否包含元素
+2 in filled_set # => True
+10 in filled_set # => False
+
+
+####################################################
+## 3. 流程控制和迭代器
+####################################################
+
+# 先随便定义一个变量
+some_var = 5
+
+# 这是个if语句。注意缩进在Python里是有意义的
+# 印出"some_var比10小"
+if some_var > 10:
+ print("some_var比10大")
+elif some_var < 10: # elif句是可选的
+ print("some_var比10小")
+else: # else也是可选的
+ print("some_var就是10")
+
+
+"""
+用for循环语句遍历列表
+打印:
+ dog is a mammal
+ cat is a mammal
+ mouse is a mammal
+"""
+for animal in ["dog", "cat", "mouse"]:
+ print("{} is a mammal".format(animal))
+
+"""
+"range(number)"返回数字列表从0到给的数字
+打印:
+ 0
+ 1
+ 2
+ 3
+"""
+for i in range(4):
+ print(i)
+
+"""
+while循环直到条件不满足
+打印:
+ 0
+ 1
+ 2
+ 3
+"""
+x = 0
+while x < 4:
+ print(x)
+ x += 1 # x = x + 1 的简写
+
+# 用try/except块处理异常状况
+try:
+ # 用raise抛出异常
+ raise IndexError("This is an index error")
+except IndexError as e:
+ pass # pass是无操作,但是应该在这里处理错误
+except (TypeError, NameError):
+ pass # 可以同时处理不同类的错误
+else: # else语句是可选的,必须在所有的except之后
+ print("All good!") # 只有当try运行完没有错误的时候这句才会运行
+
+
+# Python提供一个叫做可迭代(iterable)的基本抽象。一个可迭代对象是可以被当作序列
+# 的对象。比如说上面range返回的对象就是可迭代的。
+
+filled_dict = {"one": 1, "two": 2, "three": 3}
+our_iterable = filled_dict.keys()
+print(our_iterable) # => range(1,10) 是一个实现可迭代接口的对象
+
+# 可迭代对象可以遍历
+for i in our_iterable:
+ print(i) # 打印 one, two, three
+
+# 但是不可以随机访问
+our_iterable[1] # 抛出TypeError
+
+# 可迭代对象知道怎么生成迭代器
+our_iterator = iter(our_iterable)
+
+# 迭代器是一个可以记住遍历的位置的对象
+# 用__next__可以取得下一个元素
+our_iterator.__next__() #=> "one"
+
+# 再一次调取__next__时会记得位置
+our_iterator.__next__() #=> "two"
+our_iterator.__next__() #=> "three"
+
+# 当迭代器所有元素都取出后,会抛出StopIteration
+our_iterator.__next__() # 抛出StopIteration
+
+# 可以用list一次取出迭代器所有的元素
+list(filled_dict.keys()) #=> Returns ["one", "two", "three"]
+
+
+
+####################################################
+## 4. 函数
+####################################################
+
+# 用def定义新函数
+def add(x, y):
+ print("x is {} and y is {}".format(x, y))
+ return x + y # 用return语句返回
+
+# 调用函数
+add(5, 6) # => 印出"x is 5 and y is 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
+
+# 我们来看看结果是什么:
+keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
+
+
+# 这两种可变参数可以混着用
+def all_the_args(*args, **kwargs):
+ print(args)
+ print(kwargs)
+"""
+all_the_args(1, 2, a=3, b=4) prints:
+ (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)
+
+
+# 函数作用域
+x = 5
+
+def setX(num):
+ # 局部作用域的x和全局域的x是不同的
+ x = num # => 43
+ print (x) # => 43
+
+def setGlobalX(num):
+ global x
+ print (x) # => 5
+ x = num # 现在全局域的x被赋值
+ print (x) # => 6
+
+setX(43)
+setGlobalX(6)
+
+
+# 函数在Python是一等公民
+def create_adder(x):
+ def adder(y):
+ return x + y
+ return adder
+
+add_10 = create_adder(10)
+add_10(3) # => 13
+
+# 也有匿名函数
+(lambda x: x > 2)(3) # => True
+
+# 内置的高阶函数
+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]
+
+####################################################
+## 5. 类
+####################################################
+
+
+# 定义一个继承object的类
+class Human(object):
+
+ # 类属性,被所有此类的实例共用。
+ species = "H. sapiens"
+
+ # 构造方法,当实例被初始化时被调用。注意名字前后的双下划线,这是表明这个属
+ # 性或方法对Python有特殊意义,但是允许用户自行定义。你自己取名时不应该用这
+ # 种格式。
+ def __init__(self, name):
+ # Assign the argument to the instance's name attribute
+ self.name = name
+
+ # 实例方法,第一个参数总是self,就是这个实例对象
+ def say(self, msg):
+ return "{name}: {message}".format(name=self.name, message=msg)
+
+ # 类方法,被所有此类的实例共用。第一个参数是这个类对象。
+ @classmethod
+ def get_species(cls):
+ return cls.species
+
+ # 静态方法。调用时没有实例或类的绑定。
+ @staticmethod
+ def grunt():
+ return "*grunt*"
+
+
+# 构造一个实例
+i = Human(name="Ian")
+print(i.say("hi")) # 印出 "Ian: hi"
+
+j = Human("Joel")
+print(j.say("hello")) # 印出 "Joel: hello"
+
+# 调用一个类方法
+i.get_species() # => "H. sapiens"
+
+# 改一个共用的类属性
+Human.species = "H. neanderthalensis"
+i.get_species() # => "H. neanderthalensis"
+j.get_species() # => "H. neanderthalensis"
+
+# 调用静态方法
+Human.grunt() # => "*grunt*"
+
+
+####################################################
+## 6. 模块
+####################################################
+
+# 用import导入模块
+import math
+print(math.sqrt(16)) # => 4
+
+# 也可以从模块中导入个别值
+from math import ceil, floor
+print(ceil(3.7)) # => 4.0
+print(floor(3.7)) # => 3.0
+
+# 可以导入一个模块中所有值
+# 警告:不建议这么做
+from math import *
+
+# 如此缩写模块名字
+import math as m
+math.sqrt(16) == m.sqrt(16) # => True
+
+# Python模块其实就是普通的Python文件。你可以自己写,然后导入,
+# 模块的名字就是文件的名字。
+
+# 你可以这样列出一个模块里所有的值
+import math
+dir(math)
+
+
+####################################################
+## 7. 高级用法
+####################################################
+
+# 用生成器(generators)方便地写惰性运算
+def double_numbers(iterable):
+ for i in iterable:
+ yield i + i
+
+# 生成器只有在需要时才计算下一个值。它们每一次循环只生成一个值,而不是把所有的
+# 值全部算好。这意味着double_numbers不会生成大于15的数字。
+#
+# range的返回值也是一个生成器,不然一个1到900000000的列表会花很多时间和内存。
+#
+# 如果你想用一个Python的关键字当作变量名,可以加一个下划线来区分。
+range_ = range(1, 900000000)
+# 当找到一个 >=30 的结果就会停
+for i in double_numbers(range_):
+ print(i)
+ if i >= 30:
+ break
+
+
+# 装饰器(decorators)
+# 这个例子中,beg装饰say
+# beg会先调用say。如果返回的say_please为真,beg会改变返回的字符串。
+from functools import wraps
+
+
+def beg(target_function):
+ @wraps(target_function)
+ def wrapper(*args, **kwargs):
+ msg, say_please = target_function(*args, **kwargs)
+ if say_please:
+ return "{} {}".format(msg, "Please! I am poor :(")
+ return msg
+
+ return wrapper
+
+
+@beg
+def say(say_please=False):
+ msg = "Can you buy me a beer?"
+ return msg, say_please
+
+
+print(say()) # Can you buy me a beer?
+print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :(
+```
+
+## 想继续学吗?
+
+### 线上免费材料(英文)
+
+* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/)
+* [Dive Into Python](http://www.diveintopython.net/)
+* [Ideas for Python Projects](http://pythonpracticeprojects.com)
+
+* [The Official Docs](http://docs.python.org/3/)
+* [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)
+* [Python Module of the Week](http://pymotw.com/3/)
+* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)
+
+### 书籍(也是英文)
+
+* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20)
+* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20)
+* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20)
+
diff --git a/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
//
// 基础
//