summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--bash.html.markdown64
-rw-r--r--c++.html.markdown129
-rw-r--r--fr-fr/json-fr.html.markdown62
-rw-r--r--fr-fr/typescript-fr.html.markdown174
-rw-r--r--haskell.html.markdown2
-rw-r--r--json.html.markdown2
-rw-r--r--julia.html.markdown8
-rw-r--r--perl6.html.markdown2
-rw-r--r--python.html.markdown10
-rw-r--r--python3.html.markdown42
-rw-r--r--standard-ml.html.markdown24
11 files changed, 455 insertions, 64 deletions
diff --git a/bash.html.markdown b/bash.html.markdown
index 35bed9a2..937d2c96 100644
--- a/bash.html.markdown
+++ b/bash.html.markdown
@@ -10,6 +10,7 @@ contributors:
- ["Anton Strömkvist", "http://lutic.org/"]
- ["Rahil Momin", "https://github.com/iamrahil"]
- ["Gregrory Kielian", "https://github.com/gskielian"]
+ - ["Etan Reisner", "https://github.com/deryni"]
filename: LearnBash.sh
---
@@ -31,32 +32,41 @@ echo Hello world!
echo 'This is the first line'; echo 'This is the second line'
# Declaring a variable looks like this:
-VARIABLE="Some string"
+Variable="Some string"
# But not like this:
-VARIABLE = "Some string"
-# Bash will decide that VARIABLE is a command it must execute and give an error
-# because it couldn't be found.
+Variable = "Some string"
+# Bash will decide that Variable is a command it must execute and give an error
+# because it can't be found.
+
+# Or like this:
+Variable= 'Some string'
+# Bash will decide that 'Some string' is a command it must execute and give an
+# error because it can't be found. (In this case the 'Variable=' part is seen
+# as a variable assignment valid only for the scope of the 'Some string'
+# command.)
# Using the variable:
-echo $VARIABLE
-echo "$VARIABLE"
-echo '$VARIABLE'
+echo $Variable
+echo "$Variable"
+echo '$Variable'
# When you use the variable itself — assign it, export it, or else — you write
# its name without $. If you want to use variable's value, you should use $.
# Note that ' (single quote) won't expand the variables!
# String substitution in variables
-echo ${VARIABLE/Some/A}
+echo ${Variable/Some/A}
# This will substitute the first occurance of "Some" with "A"
# Substring from a variable
-echo ${VARIABLE:0:7}
+Length=7
+echo ${Variable:0:Length}
# This will return only the first 7 characters of the value
# Default value for variable
-echo ${FOO:-"DefaultValueIfFOOIsMissingOrEmpty"}
-# This works for null (FOO=), empty string (FOO=""), zero (FOO=0) returns 0
+echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"}
+# This works for null (Foo=) and empty string (Foo=""); zero (Foo=0) returns 0.
+# Note that it only returns default value and doesn't change variable value.
# Builtin variables:
# There are some useful builtin variables, like
@@ -68,12 +78,12 @@ echo "Scripts arguments seperated in different variables: $1 $2..."
# Reading a value from input:
echo "What's your name?"
-read NAME # Note that we didn't need to declare a new variable
-echo Hello, $NAME!
+read Name # Note that we didn't need to declare a new variable
+echo Hello, $Name!
# We have the usual if structure:
# use 'man test' for more info about conditionals
-if [ $NAME -ne $USER ]
+if [ $Name -ne $USER ]
then
echo "Your name isn't your username"
else
@@ -85,14 +95,14 @@ echo "Always executed" || echo "Only executed if first command fails"
echo "Always executed" && echo "Only executed if first command does NOT fail"
# To use && and || with if statements, you need multiple pairs of square brackets:
-if [ $NAME == "Steve" ] && [ $AGE -eq 15 ]
+if [ $Name == "Steve" ] && [ $Age -eq 15 ]
then
- echo "This will run if $NAME is Steve AND $AGE is 15."
+ echo "This will run if $Name is Steve AND $Age is 15."
fi
-if [ $NAME == "Daniya" ] || [ $NAME == "Zach" ]
+if [ $Name == "Daniya" ] || [ $Name == "Zach" ]
then
- echo "This will run if $NAME is Daniya OR Zach."
+ echo "This will run if $Name is Daniya OR Zach."
fi
# Expressions are denoted with the following format:
@@ -161,7 +171,7 @@ echo "There are $(ls | wc -l) items here."
echo "There are `ls | wc -l` items here."
# Bash uses a case statement that works similarly to switch in Java and C++:
-case "$VARIABLE" in
+case "$Variable" in
#List patterns for the conditions you want to meet
0) echo "There is a zero.";;
1) echo "There is a one.";;
@@ -169,10 +179,10 @@ case "$VARIABLE" in
esac
# for loops iterate for as many arguments given:
-# The contents of $VARIABLE is printed three times.
-for VARIABLE in {1..3}
+# The contents of $Variable is printed three times.
+for Variable in {1..3}
do
- echo "$VARIABLE"
+ echo "$Variable"
done
# Or write it the "traditional for loop" way:
@@ -183,16 +193,16 @@ done
# They can also be used to act on files..
# This will run the command 'cat' on file1 and file2
-for VARIABLE in file1 file2
+for Variable in file1 file2
do
- cat "$VARIABLE"
+ cat "$Variable"
done
# ..or the output from a command
# This will cat the output from ls.
-for OUTPUT in $(ls)
+for Output in $(ls)
do
- cat "$OUTPUT"
+ cat "$Output"
done
# while loop:
@@ -220,7 +230,7 @@ bar ()
}
# Calling your function
-foo "My name is" $NAME
+foo "My name is" $Name
# There are a lot of useful commands you should learn:
# prints last 10 lines of file.txt
diff --git a/c++.html.markdown b/c++.html.markdown
index 1a84efa4..66d4aeb1 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -32,8 +32,7 @@ one of the most widely-used programming languages.
// variable declarations, primitive types, and functions.
// Just like in C, your program's entry point is a function called
-// main with an integer return type,
-// though void main() is also accepted by most compilers (gcc, clang, etc.)
+// main with an integer return type.
// This value serves as the program's exit status.
// See http://en.wikipedia.org/wiki/Exit_status for more information.
int main(int argc, char** argv)
@@ -434,6 +433,84 @@ int main () {
}
/////////////////////
+// Templates
+/////////////////////
+
+// Templates in C++ are mostly used for generic programming, though they are
+// much more powerful than generics constructs in other languages. It also
+// supports explicit and partial specialization, functional-style type classes,
+// and also it's Turing-complete.
+
+// We start with the kind of generic programming you might be familiar with. To
+// define a class or function that takes a type parameter:
+template<class T>
+class Box {
+ // In this class, T can be used as any other type.
+ void insert(const T&) { ... }
+};
+
+// During compilation, the compiler actually generates copies of each template
+// with parameters substituted, and so the full definition of the class must be
+// present at each invocation. This is why you will see template classes defined
+// entirely in header files.
+
+// To instantiate a template class on the stack:
+Box<int> intBox;
+
+// and you can use it as you would expect:
+intBox.insert(123);
+
+// You can, of course, nest templates:
+Box<Box<int> > boxOfBox;
+boxOfBox.insert(intBox);
+
+// Up until C++11, you muse place a space between the two '>'s, otherwise '>>'
+// will be parsed as the right shift operator.
+
+// You will sometimes see
+// template<typename T>
+// instead. The 'class' keyword and 'typename' keyword are _mostly_
+// interchangeable in this case. For full explanation, see
+// http://en.wikipedia.org/wiki/Typename
+// (yes, that keyword has its own Wikipedia page).
+
+// Similarly, a template function:
+template<class T>
+void barkThreeTimes(const T& input)
+{
+ input.bark();
+ input.bark();
+ input.bark();
+}
+
+// Notice that nothing is specified about the type parameters here. The compiler
+// will generate and then type-check every invocation of the template, so the
+// above function works with any type 'T' that has a const 'bark' method!
+
+Dog fluffy;
+fluffy.setName("Fluffy")
+barkThreeTimes(fluffy); // Prints "Fluffy barks" three times.
+
+// Template parameters don't have to be classes:
+template<int Y>
+void printMessage() {
+ cout << "Learn C++ in " << Y << " minutes!" << endl;
+}
+
+// And you can explicitly specialize templates for more efficient code. Of
+// course, most real-world uses of specialization are not as trivial as this.
+// Note that you still need to declare the function (or class) as a template
+// even if you explicitly specified all parameters.
+template<>
+void printMessage<10>() {
+ cout << "Learn C++ faster in only 10 minutes!" << endl;
+}
+
+printMessage<20>(); // Prints "Learn C++ in 20 minutes!"
+printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!"
+
+
+/////////////////////
// Exception Handling
/////////////////////
@@ -586,6 +663,54 @@ void doSomethingWithAFile(const std::string& filename)
// vector (i.e. self-resizing array), hash maps, and so on
// all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock
+
+
+/////////////////////
+// Fun stuff
+/////////////////////
+
+// Aspects of C++ that may be surprising to newcomers (and even some veterans).
+// This section is, unfortunately, wildly incomplete; C++ is one of the easiest
+// languages with which to shoot yourself in the foot.
+
+// You can override private methods!
+class Foo {
+ virtual void bar();
+};
+class FooSub : public Foo {
+ virtual void bar(); // overrides Foo::bar!
+};
+
+
+// 0 == false == NULL (most of the time)!
+bool* pt = new bool;
+*pt = 0; // Sets the value points by 'pt' to false.
+pt = 0; // Sets 'pt' to the null pointer. Both lines compile without warnings.
+
+// nullptr is supposed to fix some of that issue:
+int* pt2 = new int;
+*pt2 = nullptr; // Doesn't compile
+pt2 = nullptr; // Sets pt2 to null.
+
+// But somehow 'bool' type is an exception (this is to make `if (ptr)` compile).
+*pt = nullptr; // This still compiles, even though '*pt' is a bool!
+
+
+// '=' != '=' != '='!
+// Calls Foo::Foo(const Foo&) or some variant copy constructor.
+Foo f2;
+Foo f1 = f2;
+
+// Calls Foo::Foo(const Foo&) or variant, but only copies the 'Foo' part of
+// 'fooSub'. Any extra members of 'fooSub' are discarded. This sometimes
+// horrifying behavior is called "object slicing."
+FooSub fooSub;
+Foo f1 = fooSub;
+
+// Calls Foo::operator=(Foo&) or variant.
+Foo f1;
+f1 = f2;
+
```
Futher Reading:
diff --git a/fr-fr/json-fr.html.markdown b/fr-fr/json-fr.html.markdown
new file mode 100644
index 00000000..49c95820
--- /dev/null
+++ b/fr-fr/json-fr.html.markdown
@@ -0,0 +1,62 @@
+---
+language: json
+filename: learnjson-fr.json
+contributors:
+ - ["Anna Harren", "https://github.com/iirelu"]
+ - ["Marco Scannadinari", "https://github.com/marcoms"]
+translators:
+ - ["Alois de Gouvello","https://github.com/aloisdg"]
+lang: fr-fr
+---
+
+Comme JSON est un format d'échange de données extrêmement simple, ce Apprendre X en Y minutes
+est susceptible d'être le plus simple jamais réalisé.
+
+JSON dans son état le plus pur n'a aucun commentaire, mais la majorité des parseurs accepterons
+les commentaires du langage C (`//`, `/* */`). Pour les besoins de ce document, cependant,
+tout sera du JSON 100% valide. Heureusement, il s'explique par lui-même.
+
+
+```json
+{
+ "Clé": "valeur",
+
+ "Clés": "devront toujours être entourées par des guillemets",
+ "nombres": 0,
+ "chaînes de caractères": "Hellø, wørld. Tous les caractères Unicode sont autorisés, accompagné d'un \"caractère d'échappement\".",
+ "a des booléens ?": true,
+ "rien": null,
+
+ "grand nombre": 1.2e+100,
+
+ "objets": {
+ "commentaire": "La majorité de votre strucutre sera des objets.",
+
+ "tableau": [0, 1, 2, 3, "Les tableaux peuvent contenir n'importe quoi.", 5],
+
+ "un autre objet": {
+ "commentaire": "Ces choses peuvent être imbriquées. C'est très utile."
+ }
+ },
+
+ "bêtises": [
+ {
+ "sources de potassium": ["bananes"]
+ },
+ [
+ [1, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 1, "neo"],
+ [0, 0, 0, 1]
+ ]
+ ],
+
+ "style alternatif": {
+ "commentaire": "regarde ça !"
+ , "position de la virgule": "n'a pas d'importance - aussi longtemps qu'elle est avant la valeur, alors elle est valide."
+ , "un autre commentaire": "comme c'est gentil"
+ },
+
+ "C'était court": "Et, vous avez terminé. Maintenant, vous savez tout ce que JSON a à offrir."
+}
+```
diff --git a/fr-fr/typescript-fr.html.markdown b/fr-fr/typescript-fr.html.markdown
new file mode 100644
index 00000000..b8807104
--- /dev/null
+++ b/fr-fr/typescript-fr.html.markdown
@@ -0,0 +1,174 @@
+---
+language: TypeScript
+contributors:
+ - ["Philippe Vlérick", "https://github.com/pvlerick"]
+translators:
+ - ["Alois de Gouvello", "https://github.com/aloisdg"]
+filename: learntypescript-fr.ts
+lang: fr-fr
+---
+
+TypeScript est un langage visant à faciliter le développement d'applications larges et scalables, écrites en JavaScript.
+TypeScript ajoute des concepts classiques comme les classes, les modules, les interfaces, les génériques et le typage statique (optionnel) à JavaScript.
+C'est une surcouche de JavaScript : tout le code JavaScript est valide en TypeScript ce qui permet de l'ajouter de façon transparente à n'importe quel projet. Le code TypeScript est transcompilé en JavaScript par le compilateur.
+
+Cet article se concentrera seulement sur la syntaxe supplémentaire de TypeScript, plutôt que celle de [JavaScript] (../javascript/).
+
+Pour tester le compilateur de TypeScript, rendez-vous au [Playground] (http://www.typescriptlang.org/Playground) où vous pourrez coder, profiter d'une autocomplétion et accéder directement au rendu JavaScript.
+
+```js
+// Il y a 3 types basiques en TypeScript
+var isDone: boolean = false;
+var lines: number = 42;
+var name: string = "Anders";
+
+// Si nous ne pouvons pas déterminer le type, on utilise `Any`
+var notSure: any = 4;
+notSure = "maybe a string instead";
+notSure = false; // ok, définitivement un booléen
+
+// Pour les collections, il y a les tableaux typés et les tableaux génériques
+var list: number[] = [1, 2, 3]; // Un tableaux typé
+var list: Array<number> = [1, 2, 3]; // un tableau générique
+
+// Pour les énumeration
+enum Color { Red, Green, Blue };
+var c: Color = Color.Green;
+
+// Enfin, `void` est utilisé dans le cas spécifique
+// d'une fonction ne retournant rien
+function bigHorribleAlert(): void {
+ alert("Je suis une petite boîte ennuyeuse !");
+}
+
+// Les fonctions sont des entités de première classe. Le langage supporte
+// les expressions lambda et utilise l'inférence de type
+
+// Les fonctions ci-dessous sont équivalentes, une signature identique
+// sera inférée par le compilateur, et le même JavaScript sera généré
+var f1 = function(i: number): number { return i * i; }
+// Retourne un type inféré
+var f2 = function(i: number) { return i * i; }
+var f3 = (i: number): number => { return i * i; }
+// Retourne un type inféré
+var f4 = (i: number) => { return i * i; }
+// Retourne un type inféré, ici le mot clé `return` n'est pas nécessaire
+var f5 = (i: number) => i * i;
+
+// Les interfaces sont structurées, tout les objets qui ont ces propriétés
+// sont compatible avec l'interface
+interface Person {
+ name: string;
+ // Les propriétés optionnelles sont identifiées avec un "?"
+ age?: number;
+ // Et bien sûr, les fonctions
+ move(): void;
+}
+
+// Un objet implémentant l'interface "Person" peut être traité comme
+// une Person car il a les propriétés "name" et "move"
+var p: Person = { name: "Bobby", move: () => {} };
+// Des objets implémentants la propriété optionnelle :
+// valide car "age" est un nombre
+var validPerson: Person = { name: "Bobby", age: 42, move: () => {} };
+// invalide car "age" n'est pas un nombre
+var invalidPerson: Person = { name: "Bobby", age: true };
+
+// Les interfaces peuvent aussi décrire un type de fonction
+interface SearchFunc {
+ (source: string, subString: string): boolean;
+}
+
+// Seul les types des paramètres sont importants. Les noms ne le sont pas.
+var mySearch: SearchFunc;
+mySearch = function(src: string, sub: string) {
+ return src.search(sub) != -1;
+}
+
+// Les membres des classes sont publiques par défaut.
+class Point {
+ // Propriétés
+ x: number;
+
+ // Constructeur - Les mots clés "public" et "private" dans ce contexte
+ // génèrent le code de la propriété et son initialisation dans le
+ // constructeur. Ici, "y" sera défini de la même façon que "x",
+ // mais avec moins de code. Les valeurs par défaut sont supportées.
+ constructor(x: number, public y: number = 0) {
+ this.x = x;
+ }
+
+ // Fonctions
+ dist() { return Math.sqrt(this.x * this.x + this.y * this.y); }
+
+ // Membres statiques
+ static origin = new Point(0, 0);
+}
+
+var p1 = new Point(10 ,20);
+var p2 = new Point(25); // y sera 0
+
+// Héritage
+class Point3D extends Point {
+ constructor(x: number, y: number, public z: number = 0) {
+ // Un appel explicite au constructeur de la super classe
+ // est obligatoire.
+ super(x, y);
+ }
+
+ // Redéfinition
+ dist() {
+ var d = super.dist();
+ return Math.sqrt(d * d + this.z * this.z);
+ }
+}
+
+// Modules, "." peut être utilisé comme un séparateur de sous modules.
+module Geometry {
+ export class Square {
+ constructor(public sideLength: number = 0) {
+ }
+ area() {
+ return Math.pow(this.sideLength, 2);
+ }
+ }
+}
+
+var s1 = new Geometry.Square(5);
+
+// Alias local pour référencer un module
+import G = Geometry;
+
+var s2 = new G.Square(10);
+
+// Génériques
+// Classes
+class Tuple<T1, T2> {
+ constructor(public item1: T1, public item2: T2) {
+ }
+}
+
+// Interfaces
+interface Pair<T> {
+ item1: T;
+ item2: T;
+}
+
+// Et fonctions
+var pairToTuple = function<T>(p: Pair<T>) {
+ return new Tuple(p.item1, p.item2);
+};
+
+var tuple = pairToTuple({ item1:"hello", item2:"world"});
+
+// Inclure des références à un fichier :
+/// <reference path="jquery.d.ts" />
+
+```
+
+## Lectures complémentaires
+ * [Site officiel de TypeScript] (http://www.typescriptlang.org/)
+ * [Spécification du langage TypeScript (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238)
+ * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript)
+ * [Code source sur GitHub] (https://github.com/Microsoft/TypeScript)
+ * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/)
diff --git a/haskell.html.markdown b/haskell.html.markdown
index f28fcfe7..6a64442f 100644
--- a/haskell.html.markdown
+++ b/haskell.html.markdown
@@ -282,7 +282,7 @@ foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43
foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16
-- This is now the same as
-(2 * 3 + (2 * 2 + (2 * 1 + 4)))
+(2 * 1 + (2 * 2 + (2 * 3 + 4)))
----------------------------------------------------
-- 7. Data Types
diff --git a/json.html.markdown b/json.html.markdown
index f5287138..f57b82b8 100644
--- a/json.html.markdown
+++ b/json.html.markdown
@@ -10,7 +10,7 @@ As JSON is an extremely simple data-interchange format, this is most likely goin
to be the simplest Learn X in Y Minutes ever.
JSON in its purest form has no actual comments, but most parsers will accept
-C-style (//, /\* \*/) comments. For the purposes of this, however, everything is
+C-style (`//`, `/* */`) comments. For the purposes of this, however, everything is
going to be 100% valid JSON. Luckily, it kind of speaks for itself.
```json
diff --git a/julia.html.markdown b/julia.html.markdown
index 3a52018c..5ccd6484 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -8,7 +8,7 @@ filename: learnjulia.jl
Julia is a new homoiconic functional language focused on technical computing.
While having the full power of homoiconic macros, first-class functions, and low-level control, Julia is as easy to learn and use as Python.
-This is based on the current development version of Julia, as of October 18th, 2013.
+This is based on Julia 0.3.
```ruby
@@ -91,7 +91,7 @@ false
# $ can be used for string interpolation:
"2 + 2 = $(2 + 2)" # => "2 + 2 = 4"
-# You can put any Julia expression inside the parenthesis.
+# You can put any Julia expression inside the parentheses.
# Another way to format strings is the printf macro.
@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000
@@ -190,7 +190,7 @@ end
# inside the julia folder to find these files.
# You can initialize arrays from ranges
-a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5]
+a = [1:5;] # => 5-element Int64 Array: [1,2,3,4,5]
# You can look at ranges with slice syntax.
a[1:3] # => [1, 2, 3]
@@ -264,7 +264,7 @@ in(("two", 3), filled_dict) # => false
haskey(filled_dict, "one") # => true
haskey(filled_dict, 1) # => false
-# Trying to look up a non-existant key will raise an error
+# Trying to look up a non-existent key will raise an error
try
filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489
catch e
diff --git a/perl6.html.markdown b/perl6.html.markdown
index b2d7d48c..c3626057 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -211,7 +211,7 @@ say $x; #=> 52
# - `if`
# Before talking about `if`, we need to know which values are "Truthy"
# (represent True), and which are "Falsey" (or "Falsy") -- represent False.
-# Only these values are Falsey: (), 0, "0", "", Nil, A type (like `Str` or `Int`),
+# Only these values are Falsey: (), 0, "", Nil, A type (like `Str` or `Int`),
# and of course False itself.
# Every other value is Truthy.
if True {
diff --git a/python.html.markdown b/python.html.markdown
index 7281a330..ace3f794 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -46,7 +46,7 @@ to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://lea
2.0 # This is a float
11.0 / 4.0 # => 2.75 ahhh...much better
-# Result of integer division truncated down both for positive and negative.
+# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
@@ -191,14 +191,14 @@ li[2:] # => [4, 3]
li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
-# Revert the list
+# Reverse a copy of the list
li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
# Remove arbitrary elements from a list with "del"
del li[2] # li is now [1, 2, 3]
-
+r
# You can add lists
li + other_li # => [1, 2, 3, 4, 5, 6]
# Note: values for li and for other_li are not modified.
@@ -439,14 +439,14 @@ def pass_all_the_args(*args, **kwargs):
print varargs(*args)
print keyword_args(**kwargs)
-# Function Scope
+# Function Scope
x = 5
def setX(num):
# Local var x not the same as global variable x
x = num # => 43
print x # => 43
-
+
def setGlobalX(num):
global x
print x # => 5
diff --git a/python3.html.markdown b/python3.html.markdown
index 470eb6e4..a112912f 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -39,7 +39,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea
# Except division which returns floats by default
35 / 5 # => 7.0
-# Result of integer division truncated down both for positive and negative.
+# Result of integer division truncated down both for positive and negative.
5 // 3 # => 1
5.0 // 3.0 # => 1.0 # works on floats too
-5 // 3 # => -2
@@ -73,8 +73,8 @@ False or True #=> True
# Note using Bool operators with ints
0 and 2 #=> 0
-5 or 0 #=> -5
-0 == False #=> True
-2 == True #=> False
+0 == False #=> True
+2 == True #=> False
1 == True #=> True
# Equality is ==
@@ -145,7 +145,7 @@ bool({}) #=> False
# Python has a print function
print("I'm Python. Nice to meet you!")
-# No need to declare variables before assigning to them.
+# No need to declare variables before assigning to them.
# Convention is to use lower_case_with_underscores
some_var = 5
some_var # => 5
@@ -186,7 +186,7 @@ li[2:] # => [4, 3]
li[:3] # => [1, 2, 4]
# Select every second entry
li[::2] # =>[1, 4]
-# Revert the list
+# Return a reversed copy of the list
li[::-1] # => [3, 4, 2, 1]
# Use any combination of these to make advanced slices
# li[start:end:step]
@@ -196,7 +196,7 @@ del li[2] # li is now [1, 2, 3]
# You can add lists
# Note: values for li and for other_li are not modified.
-li + other_li # => [1, 2, 3, 4, 5, 6]
+li + other_li # => [1, 2, 3, 4, 5, 6]
# Concatenate lists with "extend()"
li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6]
@@ -213,7 +213,7 @@ tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # Raises a TypeError
-# You can do all those list thingies on tuples too
+# You can do most of the list operations on tuples too
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
@@ -235,15 +235,15 @@ filled_dict = {"one": 1, "two": 2, "three": 3}
# Look up values with []
filled_dict["one"] # => 1
-# Get all keys as a list with "keys()".
-# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later.
-# Note - Dictionary key ordering is not guaranteed.
-# Your results might not match this exactly.
+# Get all keys as an iterable with "keys()". We need to wrap the call in list()
+# to turn it into a list. We'll talk about those later. Note - Dictionary key
+# ordering is not guaranteed. Your results might not match this exactly.
list(filled_dict.keys()) # => ["three", "two", "one"]
-# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable.
-# Note - Same as above regarding key ordering.
+# Get all values as an iterable with "values()". Once again we need to wrap it
+# in list() to get it out of the iterable. Note - Same as above regarding key
+# ordering.
list(filled_dict.values()) # => [3, 2, 1]
@@ -281,7 +281,7 @@ some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4}
# Can set new variables to a set
filled_set = some_set
-# Add one more item to the set
+# Add one more item to the set
filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5}
# Do set intersection with &
@@ -328,7 +328,7 @@ for animal in ["dog", "cat", "mouse"]:
print("{} is a mammal".format(animal))
"""
-"range(number)" returns a list of numbers
+"range(number)" returns an iterable of numbers
from zero to the given number
prints:
0
@@ -340,7 +340,7 @@ for i in range(4):
print(i)
"""
-"range(lower, upper)" returns a list of numbers
+"range(lower, upper)" returns an iterable of numbers
from the lower number to the upper number
prints:
4
@@ -458,14 +458,14 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4)
-# Function Scope
+# Function Scope
x = 5
def setX(num):
# Local var x not the same as global variable x
x = num # => 43
print (x) # => 43
-
+
def setGlobalX(num):
global x
print (x) # => 5
@@ -512,8 +512,8 @@ class Human(object):
# Basic initializer, this is called when this class is instantiated.
# Note that the double leading and trailing underscores denote objects
# or attributes that are used by python but that live in user-controlled
- # namespaces. Methods(or objects or attributes) like: __init__, __str__,
- # __repr__ etc. are called magic methods (or sometimes called dunder methods)
+ # namespaces. Methods(or objects or attributes) like: __init__, __str__,
+ # __repr__ etc. are called magic methods (or sometimes called dunder methods)
# You should not invent such names on your own.
def __init__(self, name):
# Assign the argument to the instance's name attribute
@@ -600,7 +600,7 @@ def double_numbers(iterable):
# double_numbers.
# Note range is a generator too. Creating a list 1-900000000 would take lot of
# time to be made
-# We use a trailing underscore in variable names when we want to use a name that
+# We use a trailing underscore in variable names when we want to use a name that
# would normally collide with a python keyword
range_ = range(1, 900000000)
# will double all numbers until a result >=30 found
diff --git a/standard-ml.html.markdown b/standard-ml.html.markdown
index b545f3e1..07896beb 100644
--- a/standard-ml.html.markdown
+++ b/standard-ml.html.markdown
@@ -3,13 +3,14 @@ language: "Standard ML"
contributors:
- ["Simon Shine", "http://shine.eu.org/"]
- ["David Pedersen", "http://lonelyproton.com/"]
+ - ["James Baker", "http://www.jbaker.io/"]
---
Standard ML is a functional programming language with type inference and some
side-effects. Some of the hard parts of learning Standard ML are: Recursion,
pattern matching, type inference (guessing the right types but never allowing
-implicit type conversion). If you have an imperative background, not being able
-to update variables can feel severely inhibiting.
+implicit type conversion). Standard ML is distinguished from Haskell by including
+references, allowing variables to be updated.
```ocaml
(* Comments in Standard ML begin with (* and end with *). Comments can be
@@ -383,6 +384,25 @@ val test_poem = readPoem "roses.txt" (* gives [ "Roses are red,",
"Violets are blue.",
"I have a gun.",
"Get in the van." ] *)
+
+(* We can create references to data which can be updated *)
+val counter = ref 0 (* Produce a reference with the ref function *)
+
+(* Assign to a reference with the assignment operator *)
+fun set_five reference = reference := 5
+
+(* Read a reference with the dereference operator *)
+fun equals_five reference = !reference = 5
+
+(* We can use while loops for when recursion is messy *)
+fun decrement_to_zero r = if !r < 0
+ then r := 0
+ else while !r >= 0 do r := !r - 1
+
+(* This returns the unit value (in practical terms, nothing, a 0-tuple) *)
+
+(* To allow returning a value, we can use the semicolon to sequence evaluations *)
+fun decrement_ret x y = (x := !x - 1; y)
```
## Further learning