summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--fr-fr/yaml-fr.html.markdown3
-rw-r--r--matlab.html.markdown2
-rw-r--r--perl6.html.markdown2
-rw-r--r--python.html.markdown60
-rw-r--r--ru-ru/java-ru.html.markdown2
-rw-r--r--scala.html.markdown152
-rw-r--r--zh-cn/markdown-cn.html.markdown2
7 files changed, 168 insertions, 55 deletions
diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown
index d9b94aa6..43b1df54 100644
--- a/fr-fr/yaml-fr.html.markdown
+++ b/fr-fr/yaml-fr.html.markdown
@@ -3,6 +3,7 @@ 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
@@ -153,4 +154,4 @@ 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. \ No newline at end of file
+- Un outil pour tester [live](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
diff --git a/matlab.html.markdown b/matlab.html.markdown
index 2b9077d5..9de41275 100644
--- a/matlab.html.markdown
+++ b/matlab.html.markdown
@@ -200,7 +200,7 @@ 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'
+A one
ctranspose(A) % Hermitian transpose the matrix
% (the transpose, followed by taking complex conjugate of each element)
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 9f3a03ba..b178de1e 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1177,7 +1177,7 @@ $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
diff --git a/python.html.markdown b/python.html.markdown
index f7b0082c..53381f32 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -102,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'
@@ -136,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
@@ -170,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
@@ -194,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]
@@ -255,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}
@@ -371,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
@@ -379,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
@@ -398,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)
@@ -442,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):
@@ -516,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
@@ -542,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/ru-ru/java-ru.html.markdown b/ru-ru/java-ru.html.markdown
index 460086e3..005495cc 100644
--- a/ru-ru/java-ru.html.markdown
+++ b/ru-ru/java-ru.html.markdown
@@ -181,7 +181,7 @@ public class LearnJavaRu {
// Если они находятся перед переменной, сначала происходит
// увеличение/уменьшение, затем операция, если после,
// то сначала выполняется операция, затем увеличение/уменьшение.
- System.out.println(i++); //i = 1, напечатает 0 (пре-инкремент)
+ 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 (пре-декремент)
diff --git a/scala.html.markdown b/scala.html.markdown
index dc039f0c..529347be 100644
--- a/scala.html.markdown
+++ b/scala.html.markdown
@@ -54,14 +54,17 @@ var y = 10
y = 20 // y is now 20
/*
- 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:
+ 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
-val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10
+
+// Notice automatic conversion from Int to Double, result is 10.0, not 10
+val b: Double = 10
// Boolean values
true
@@ -94,8 +97,8 @@ true == false // false
This means the result of evaluating 1 + 7 is an object of type Int with a
value of 8
- Note that "res29" is a sequentially generated variable name to store the results of the
- expressions you typed, your output may differ.
+ Note that "res29" is a sequentially generated variable name to store the
+ results of the expressions you typed, your output may differ.
*/
"Scala strings are surrounded by double quotes"
@@ -142,27 +145,69 @@ val html = """<form id="daform">
// 2. Functions
/////////////////////////////////////////////////
-// The next line gives you a function that takes an Int and returns it squared
-(x:Int) => x * x
+// 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
+}
-// You can assign this function to an identifier, like this:
-val sq = (x:Int) => x * x
+// The { } can be omitted if the function body is a single expression:
+def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y
-/* The above says this
+// Syntax for calling functions is familiar:
+sumOfSquares(3, 4) // => 25
- sq: Int => Int = <function1>
+// 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
- Which means that this time we gave an explicit name to the value - sq is a
- function that take an Int and returns Int.
+// Functions can have default parameters:
+def addWithDefault(x: Int, y: Int = 5) = x + y
+addWithDefault(1, 2) // => 3
+addWithDefault(1) // => 6
- sq can be executed as follows:
-*/
-sq(10) // Gives you this: res33: Int = 100.
+// Anonymous functions look like this:
+(x:Int) => x * x
-// 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
+// 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
+
+// Anonymous functions can be called as usual:
+sq(10) // => 100
+
+// 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)
+
+addOne(5) // => 6
+weirdSum(2, 4) // => 16
+
+
+// The return keyword exists in Scala, but it only returns from the inner-most
+// def that surrounds it. It has no effect on anonymous functions. For example:
+def foo(x: Int) = {
+ 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
+}
/////////////////////////////////////////////////
@@ -187,7 +232,7 @@ 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
@@ -290,13 +335,24 @@ d._2
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
- //A method called bark, returning a String
- def bark: String = {
- // the body of the method
- "Woof, woof!"
- }
+
+ // 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
}
val mydog = new Dog("greyhound")
@@ -304,17 +360,45 @@ println(mydog.breed) // => "greyhound"
println(mydog.bark) // => "Woof, woof!"
-// Classes can contain nearly any other construct, including other classes,
-// functions, methods, objects, case classes, traits etc.
+// 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"
+
+// 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")
-Person("George", "1234") == Person("Kate", "1236")
+// And many others. Case classes also get pattern matching for free, see below.
-// Objects and traits coming soon!
+// Traits coming soon!
/////////////////////////////////////////////////
@@ -423,7 +507,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
// 8. Implicits
/////////////////////////////////////////////////
-Coming soon!
+// Coming soon!
/////////////////////////////////////////////////
diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown
index eecb8c5b..1c577efb 100644
--- a/zh-cn/markdown-cn.html.markdown
+++ b/zh-cn/markdown-cn.html.markdown
@@ -1,5 +1,5 @@
---
-language: Markdown
+language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
translators: