mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-23 17:41:41 +00:00
Merge remote-tracking branch 'adambard/master'
Conflicts: java.html.markdown
This commit is contained in:
commit
fc3c56ee93
@ -633,7 +633,7 @@ writeln( toThisArray );
|
||||
// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j;
|
||||
// exhibits a runtime error.
|
||||
// Even though the domain of the array and the loop-expression are
|
||||
// the same size, the body of the expression can be though of as an iterator.
|
||||
// the same size, the body of the expression can be thought of as an iterator.
|
||||
// Because iterators can yield nothing, that iterator yields a different number
|
||||
// of things than the domain of the array or loop, which is not allowed.
|
||||
|
||||
|
@ -54,19 +54,19 @@ math =
|
||||
square: square
|
||||
cube: (x) -> x * square x
|
||||
#=> var math = {
|
||||
# "root": Math.sqrt,
|
||||
# "square": square,
|
||||
# "cube": function(x) { return x * square(x); }
|
||||
#}
|
||||
# "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);
|
||||
#};
|
||||
# var runners, winner;
|
||||
# winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
|
||||
# return print(winner, runners);
|
||||
# };
|
||||
|
||||
# Existence:
|
||||
alert "I knew it!" if elvis?
|
||||
@ -75,14 +75,14 @@ alert "I knew it!" if elvis?
|
||||
# Array comprehensions:
|
||||
cubes = (math.cube num for num in list)
|
||||
#=>cubes = (function() {
|
||||
# var _i, _len, _results;
|
||||
# _results = [];
|
||||
# var _i, _len, _results;
|
||||
# _results = [];
|
||||
# for (_i = 0, _len = list.length; _i < _len; _i++) {
|
||||
# num = list[_i];
|
||||
# _results.push(math.cube(num));
|
||||
# }
|
||||
# return _results;
|
||||
# })();
|
||||
# num = list[_i];
|
||||
# _results.push(math.cube(num));
|
||||
# }
|
||||
# return _results;
|
||||
# })();
|
||||
|
||||
foods = ['broccoli', 'spinach', 'chocolate']
|
||||
eat food for food in foods when food isnt 'chocolate'
|
||||
|
@ -8,113 +8,117 @@ 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.
|
||||
modifiable et lisible par nous-mêmes, 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 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 Python, et s'intègre bien avec bon nombre de langages.
|
||||
Contrairement à ce dernier, YAML interdit l'utilisation des tabulations.
|
||||
|
||||
|
||||
```yaml
|
||||
# les Commentaires sont précédés d'un signe "#", comme cette ligne.
|
||||
# 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 ).
|
||||
# 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,
|
||||
# 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
|
||||
autre_clé: une autre valeur
|
||||
valeur_numérique: 100
|
||||
notation_scientifique: 1e+12
|
||||
boolean: true
|
||||
booléen: true
|
||||
valeur_null: null
|
||||
clé avec espaces: valeur
|
||||
# Bien qu'il ne soit pas nécessaire d'enfermer les chaînes de caractères
|
||||
# Bien qu'il ne soit pas nécessaire de mettre 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é."
|
||||
"Une clé entre guillemets.": "Utile si l'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 ( > ).
|
||||
# Les chaînes couvrant plusieurs lignes, peuvent être écrites au choix,
|
||||
# comme un "bloc littéral" (avec '|') ou bien un "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" )
|
||||
Tout ce bloc de texte sera la valeur de la clé "bloc_littéral",
|
||||
avec préservation des retours à la ligne.
|
||||
|
||||
Le littéral continue jusqu'à ce que l'indentation soit annulée.
|
||||
|
||||
Toutes lignes qui serait "d'avantage indentées" conservent leur
|
||||
Toutes lignes qui seraient "davantage 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.
|
||||
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 vides, comme ci-dessus, seront converties en caractère de
|
||||
nouvelle ligne.
|
||||
|
||||
Les lignes 'plus-indentées' gardent leurs retours à la ligne -
|
||||
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.
|
||||
# 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 des maps ne sont pas nécessairement des chaînes de caractères.
|
||||
0.25: une clé de type flottant
|
||||
|
||||
# les Clés peuvent également être des objets s'étendant sur plusieurs lignes,
|
||||
# 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é
|
||||
ceci est une clé
|
||||
sur de multiples lignes
|
||||
: et ceci est sa Valeur
|
||||
: 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:
|
||||
# Les séquences (équivalent des listes ou tableaux) ressemblent à cela :
|
||||
une_séquence:
|
||||
- Item 1
|
||||
- Item 2
|
||||
- Objet 1
|
||||
- Objet 2
|
||||
- 0.5 # les séquences peuvent contenir des types variés.
|
||||
- Item 4
|
||||
- Objet 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
|
||||
# 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
|
||||
# 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:
|
||||
# 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.
|
||||
# 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.
|
||||
# Certains analyseurs syntaxiques (parsers) implémentent des tags spécifiques à
|
||||
# d'autres langages, comme par exemple celui des nombres complexes de Python.
|
||||
python_complex_number: !!python/complex 1+2j
|
||||
|
||||
#####################
|
||||
@ -122,7 +126,7 @@ python_complex_number: !!python/complex 1+2j
|
||||
#####################
|
||||
|
||||
# YAML interprète également les données formatées ISO de type date et datetime,
|
||||
# pas seulement les chaînes et nombres.
|
||||
# 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
|
||||
@ -135,14 +139,14 @@ fichier_gif: !!binary |
|
||||
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
|
||||
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
|
||||
|
||||
# YAML a de même un type "set", qui ressemble à cela:
|
||||
# YAML a de même un type "set", semblable à ceci :
|
||||
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:
|
||||
# le set précédent est l'équivalent du suivant :
|
||||
set2:
|
||||
item1: null
|
||||
item2: null
|
||||
@ -152,6 +156,6 @@ set2:
|
||||
|
||||
Quelques références et outils :
|
||||
|
||||
- Doc officielle [YAML 1.2](http://www.yaml.org/spec/1.2/spec.html) *anglais*,
|
||||
- Documentation 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.
|
||||
- Un outil pour tester [en ligne](http://yaml-online-parser.appspot.com/) la syntaxe YAML, avec des exemples.
|
||||
|
@ -119,7 +119,7 @@ printfn "A string %s, and something generic %A" "hello" [1;2;3;4]
|
||||
// ================================================
|
||||
|
||||
// F# is a true functional language -- functions are first
|
||||
// class entities and can be combined easy to make powerful
|
||||
// class entities and can be combined easily to make powerful
|
||||
// constructs
|
||||
|
||||
// Modules are used to group functions together
|
||||
|
@ -10,6 +10,7 @@ contributors:
|
||||
- ["Quint Guvernator", "https://github.com/qguv"]
|
||||
- ["Jose Donizetti", "https://github.com/josedonizetti"]
|
||||
- ["Alexej Friesen", "https://github.com/heyalexej"]
|
||||
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||
---
|
||||
|
||||
Go was created out of the need to get work done. It's not the latest trend
|
||||
@ -115,7 +116,7 @@ can include line breaks.` // Same string type.
|
||||
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,
|
||||
// trailing ellipsis, 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]
|
||||
@ -129,7 +130,7 @@ can include line breaks.` // Same string type.
|
||||
m["one"] = 1
|
||||
|
||||
// Unused variables are an error in Go.
|
||||
// The underbar lets you "use" a variable but discard its value.
|
||||
// The underscore lets you "use" a variable but discard its value.
|
||||
_, _, _, _, _, _, _, _, _, _ = 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)
|
||||
@ -164,7 +165,7 @@ func expensiveComputation() float64 {
|
||||
}
|
||||
|
||||
func learnFlowControl() {
|
||||
// If statements require brace brackets, and do not require parens.
|
||||
// If statements require brace brackets, and do not require parentheses.
|
||||
if true {
|
||||
fmt.Println("told ya")
|
||||
}
|
||||
@ -407,6 +408,8 @@ 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.
|
||||
Aside from a tour, [the docs](https://golang.org/doc/) contain information on
|
||||
how to write clean and effective Go code, package and command docs, and release history.
|
||||
|
||||
The language definition itself is highly recommended. It's easy to read
|
||||
and amazingly short (as language definitions go these days.)
|
||||
|
@ -5,6 +5,7 @@ contributors:
|
||||
- ["Jakukyo Friel", "http://weakish.github.io"]
|
||||
- ["Madison Dickson", "http://github.com/mix3d"]
|
||||
- ["Simon Morgan", "http://sjm.io/"]
|
||||
- ["Zachary Ferguson", "http://github.com/zfergus2"]
|
||||
filename: LearnJava.java
|
||||
---
|
||||
|
||||
@ -31,7 +32,7 @@ import java.security.*;
|
||||
// the file.
|
||||
public class LearnJava {
|
||||
|
||||
// A program must have a main method as an entry point.
|
||||
// In order to run a java program, it must have a main method as an entry point.
|
||||
public static void main (String[] args) {
|
||||
|
||||
// Use System.out.println() to print lines.
|
||||
@ -45,6 +46,8 @@ public class LearnJava {
|
||||
System.out.print("Hello ");
|
||||
System.out.print("World");
|
||||
|
||||
// Use System.out.printf() for easy formatted printing.
|
||||
System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159
|
||||
|
||||
///////////////////////////////////////
|
||||
// Variables
|
||||
@ -93,7 +96,7 @@ public class LearnJava {
|
||||
|
||||
// Float - Single-precision 32-bit IEEE 754 Floating Point
|
||||
float fooFloat = 234.5f;
|
||||
// f is used to denote that this variable value is of type float;
|
||||
// f or F is used to denote that this variable value is of type float;
|
||||
// otherwise it is treated as double.
|
||||
|
||||
// Double - Double-precision 64-bit IEEE 754 Floating Point
|
||||
@ -106,9 +109,12 @@ public class LearnJava {
|
||||
// Char - A single 16-bit Unicode character
|
||||
char fooChar = 'A';
|
||||
|
||||
// final variables can't be reassigned to another object.
|
||||
// final variables can't be reassigned to another object,
|
||||
final int HOURS_I_WORK_PER_WEEK = 9001;
|
||||
|
||||
// but they can be initialized later.
|
||||
final double E;
|
||||
E = 2.71828;
|
||||
|
||||
// Strings
|
||||
String fooString = "My String Is Here!";
|
||||
|
||||
@ -166,6 +172,7 @@ public class LearnJava {
|
||||
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 truncated down)
|
||||
System.out.println("1/2 = " + (i1 / (i2*1.0))); // => 0.5
|
||||
|
||||
// Modulo
|
||||
System.out.println("11%3 = "+(11 % 3)); // => 2
|
||||
@ -178,12 +185,17 @@ public class LearnJava {
|
||||
System.out.println("2 <= 2? " + (2 <= 2)); // => true
|
||||
System.out.println("2 >= 2? " + (2 >= 2)); // => true
|
||||
|
||||
// Boolean operators
|
||||
System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false
|
||||
System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true
|
||||
System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true
|
||||
|
||||
// Bitwise operators!
|
||||
/*
|
||||
~ Unary bitwise complement
|
||||
<< Signed left shift
|
||||
>> Signed right shift
|
||||
>>> Unsigned right shift
|
||||
>> Signed/Arithmetic right shift
|
||||
>>> Unsigned/Logical right shift
|
||||
& Bitwise AND
|
||||
^ Bitwise exclusive OR
|
||||
| Bitwise inclusive OR
|
||||
@ -236,9 +248,8 @@ public class LearnJava {
|
||||
System.out.println("fooDoWhile Value: " + fooDoWhile);
|
||||
|
||||
// For Loop
|
||||
int fooFor;
|
||||
// for loop structure => for(<start_statement>; <conditional>; <step>)
|
||||
for (fooFor = 0; fooFor < 10; fooFor++) {
|
||||
for (int fooFor = 0; fooFor < 10; fooFor++) {
|
||||
System.out.println(fooFor);
|
||||
// Iterated 10 times, fooFor 0->9
|
||||
}
|
||||
@ -332,9 +343,9 @@ public class LearnJava {
|
||||
|
||||
private static final Set<String> COUNTRIES = new HashSet<String>();
|
||||
static {
|
||||
validCodes.add("DENMARK");
|
||||
validCodes.add("SWEDEN");
|
||||
validCodes.add("FINLAND");
|
||||
validCodes.add("DENMARK");
|
||||
validCodes.add("SWEDEN");
|
||||
validCodes.add("FINLAND");
|
||||
}
|
||||
|
||||
// But there's a nifty way to achieve the same thing in an
|
||||
@ -357,7 +368,8 @@ public class LearnJava {
|
||||
} // End LearnJava class
|
||||
|
||||
|
||||
// You can include other, non-public outer-level classes in a .java file
|
||||
// You can include other, non-public outer-level classes in a .java file,
|
||||
// but it is good practice. Instead split classes into separate files.
|
||||
|
||||
|
||||
// Class Declaration Syntax:
|
||||
@ -377,6 +389,8 @@ class Bicycle {
|
||||
// Constructors are a way of creating classes
|
||||
// This is a constructor
|
||||
public Bicycle() {
|
||||
// You can also call another constructor:
|
||||
// this(1, 50, 5, "Bontrager");
|
||||
gear = 1;
|
||||
cadence = 50;
|
||||
speed = 5;
|
||||
@ -392,13 +406,13 @@ class Bicycle {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Function Syntax:
|
||||
// Method Syntax:
|
||||
// <public/private/protected> <return type> <function name>(<args>)
|
||||
|
||||
// Java classes often implement getters and setters for their fields
|
||||
|
||||
// Method declaration syntax:
|
||||
// <scope> <return type> <method name>(<args>)
|
||||
// <access modifier> <return type> <method name>(<args>)
|
||||
public int getCadence() {
|
||||
return cadence;
|
||||
}
|
||||
@ -429,7 +443,7 @@ class Bicycle {
|
||||
}
|
||||
|
||||
//Method to display the attribute values of this Object.
|
||||
@Override
|
||||
@Override // Inherited from the Object class.
|
||||
public String toString() {
|
||||
return "gear: " + gear + " cadence: " + cadence + " speed: " + speed +
|
||||
" name: " + name;
|
||||
@ -464,18 +478,19 @@ class PennyFarthing extends Bicycle {
|
||||
|
||||
// Example - Food:
|
||||
public interface Edible {
|
||||
public void eat(); // Any class that implements this interface, must
|
||||
public void eat(); // Any class that implements this interface, must
|
||||
// implement this method.
|
||||
}
|
||||
|
||||
public interface Digestible {
|
||||
public void digest();
|
||||
public void digest();
|
||||
}
|
||||
|
||||
|
||||
// We can now create a class that implements both of these interfaces.
|
||||
public class Fruit implements Edible, Digestible {
|
||||
@Override
|
||||
<<<<<<< HEAD
|
||||
public void eat() {
|
||||
// awesome code goes here
|
||||
}
|
||||
@ -484,6 +499,16 @@ public class Fruit implements Edible, Digestible {
|
||||
public void digest() {
|
||||
// awesome code goes here
|
||||
}
|
||||
=======
|
||||
public void eat() {
|
||||
// ...
|
||||
}
|
||||
|
||||
@Override
|
||||
public void digest() {
|
||||
// ...
|
||||
}
|
||||
>>>>>>> adambard/master
|
||||
}
|
||||
|
||||
// In Java, you can extend only one class, but you can implement many
|
||||
@ -491,6 +516,7 @@ public class Fruit implements Edible, Digestible {
|
||||
public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
InterfaceTwo {
|
||||
@Override
|
||||
<<<<<<< HEAD
|
||||
public void InterfaceOneMethod() {
|
||||
// awesome code goes here
|
||||
}
|
||||
@ -499,75 +525,122 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
public void InterfaceTwoMethod() {
|
||||
// awesome code goes here
|
||||
}
|
||||
=======
|
||||
public void InterfaceOneMethod() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void InterfaceTwoMethod() {
|
||||
}
|
||||
>>>>>>> adambard/master
|
||||
}
|
||||
|
||||
|
||||
// Abstract Classes
|
||||
|
||||
// Abstract Class declaration syntax
|
||||
// <access-level> abstract <abstract-class-name> extends <super-abstract-classes> {
|
||||
// // Constants and variables
|
||||
// // Method declarations
|
||||
// }
|
||||
|
||||
// Methods can't have bodies in an interface, unless the method is
|
||||
// static. Also variables are NOT final by default, unlike an interface.
|
||||
// Also abstract classes CAN have the "main" method.
|
||||
// Abstract classes solve these problems.
|
||||
// Marking a class as abstract means that it contains abstract methods that must
|
||||
// be defined in a child class. Similar to interfaces, abstract classes cannot
|
||||
// be instantiated, but instead must be extended and the abstract methods
|
||||
// defined. Different from interfaces, abstract classes can contain a mixture of
|
||||
// concrete and abstract methods. Methods in an interface cannot have a body,
|
||||
// unless the method is static, and variables are final by default, unlike an
|
||||
// abstract class. Also abstract classes CAN have the "main" method.
|
||||
|
||||
public abstract class Animal
|
||||
{
|
||||
public abstract void makeSound();
|
||||
public abstract void makeSound();
|
||||
|
||||
// Method can have a body
|
||||
public void eat()
|
||||
{
|
||||
System.out.println("I am an animal and I am Eating.");
|
||||
// Note: We can access private variable here.
|
||||
age = 30;
|
||||
}
|
||||
// Method can have a body
|
||||
public void eat()
|
||||
{
|
||||
System.out.println("I am an animal and I am Eating.");
|
||||
// Note: We can access private variable here.
|
||||
age = 30;
|
||||
}
|
||||
|
||||
// No need to initialize, however in an interface
|
||||
// a variable is implicitly final and hence has
|
||||
// to be initialized.
|
||||
private int age;
|
||||
// No need to initialize, however in an interface
|
||||
// a variable is implicitly final and hence has
|
||||
// to be initialized.
|
||||
protected int age;
|
||||
|
||||
public void printAge()
|
||||
{
|
||||
System.out.println(age);
|
||||
}
|
||||
public void printAge()
|
||||
{
|
||||
System.out.println(age);
|
||||
}
|
||||
|
||||
// Abstract classes can have main function.
|
||||
public static void main(String[] args)
|
||||
{
|
||||
System.out.println("I am abstract");
|
||||
}
|
||||
// Abstract classes can have main function.
|
||||
public static void main(String[] args)
|
||||
{
|
||||
System.out.println("I am abstract");
|
||||
}
|
||||
}
|
||||
|
||||
class Dog extends Animal
|
||||
{
|
||||
// Note still have to override the abstract methods in the
|
||||
// abstract class.
|
||||
@Override
|
||||
public void makeSound()
|
||||
{
|
||||
System.out.println("Bark");
|
||||
// age = 30; ==> ERROR! age is private to Animal
|
||||
}
|
||||
// Note still have to override the abstract methods in the
|
||||
// abstract class.
|
||||
@Override
|
||||
public void makeSound()
|
||||
{
|
||||
System.out.println("Bark");
|
||||
// age = 30; ==> ERROR! age is private to Animal
|
||||
}
|
||||
|
||||
// NOTE: You will get an error if you used the
|
||||
// @Override annotation here, since java doesn't allow
|
||||
// overriding of static methods.
|
||||
// What is happening here is called METHOD HIDING.
|
||||
// Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Dog pluto = new Dog();
|
||||
pluto.makeSound();
|
||||
pluto.eat();
|
||||
pluto.printAge();
|
||||
}
|
||||
// NOTE: You will get an error if you used the
|
||||
// @Override annotation here, since java doesn't allow
|
||||
// overriding of static methods.
|
||||
// What is happening here is called METHOD HIDING.
|
||||
// Check out this awesome SO post: http://stackoverflow.com/questions/16313649/
|
||||
public static void main(String[] args)
|
||||
{
|
||||
Dog pluto = new Dog();
|
||||
pluto.makeSound();
|
||||
pluto.eat();
|
||||
pluto.printAge();
|
||||
}
|
||||
}
|
||||
|
||||
// Final Classes
|
||||
|
||||
// Final Class declaration syntax
|
||||
// <access-level> final <final-class-name> {
|
||||
// // Constants and variables
|
||||
// // Method declarations
|
||||
// }
|
||||
|
||||
// Final classes are classes that cannot be inherited from and are therefore a
|
||||
// final child. In a way, final classes are the opposite of abstract classes
|
||||
// because abstract classes must be extended, but final classes cannot be
|
||||
// extended.
|
||||
public final class SaberToothedCat extends Animal
|
||||
{
|
||||
// Note still have to override the abstract methods in the
|
||||
// abstract class.
|
||||
@Override
|
||||
public void makeSound()
|
||||
{
|
||||
System.out.println("Roar");
|
||||
}
|
||||
}
|
||||
|
||||
// Final Methods
|
||||
public abstract class Mammal()
|
||||
{
|
||||
// Final Method Syntax:
|
||||
// <access modifier> final <return type> <function name>(<args>)
|
||||
|
||||
// Final methods, like, final classes cannot be overridden by a child class,
|
||||
// and are therefore the final implementation of the method.
|
||||
public final boolean isWarmBlooded()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Further Reading
|
||||
|
@ -218,6 +218,26 @@ for (var i = 0; i < 5; i++){
|
||||
// will run 5 times
|
||||
}
|
||||
|
||||
//The For/In statement loops iterates over every property across the entire prototype chain
|
||||
var description = "";
|
||||
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||
for (var x in person){
|
||||
description += person[x] + " ";
|
||||
}
|
||||
|
||||
//If only want to consider properties attached to the object itself,
|
||||
//and not its prototypes use hasOwnProperty() check
|
||||
var description = "";
|
||||
var person = {fname:"Paul", lname:"Ken", age:18};
|
||||
for (var x in person){
|
||||
if (person.hasOwnProperty(x)){
|
||||
description += person[x] + " ";
|
||||
}
|
||||
}
|
||||
|
||||
//for/in should not be used to iterate over an Array where the index order is important.
|
||||
//There is no guarantee that for/in will return the indexes in any particular order
|
||||
|
||||
// && is logical and, || is logical or
|
||||
if (house.size == "big" && house.colour == "blue"){
|
||||
house.contains = "bear";
|
||||
|
@ -10,8 +10,11 @@ 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
|
||||
going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
||||
C-style (`//`, `/* */`) comments. Some parsers also tolerate a trailing comma
|
||||
(i.e. a comma after the last element of an array or the after the last property of an object),
|
||||
but they should be avoided for better compatibility.
|
||||
|
||||
For the purposes of this, however, everything is going to be 100% valid JSON. Luckily, it kind of speaks for itself.
|
||||
|
||||
```json
|
||||
{
|
||||
|
@ -235,7 +235,7 @@ proc ask(question: string): Answer =
|
||||
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")
|
||||
assert(amount > 0 and amount < 9000, "Crazy Sugar")
|
||||
for a in 1..amount:
|
||||
echo(a, " sugar...")
|
||||
|
||||
|
@ -15,7 +15,7 @@ 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
|
||||
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:
|
||||
|
@ -132,7 +132,7 @@ sub with-named($normal-arg, :$named) {
|
||||
with-named(1, named => 6); #=> 7
|
||||
# There's one gotcha to be aware of, here:
|
||||
# If you quote your key, Perl 6 won't be able to see it at compile time,
|
||||
# and you'll have a single Pair object as a positional paramater,
|
||||
# and you'll have a single Pair object as a positional parameter,
|
||||
# which means this fails:
|
||||
with-named(1, 'named' => 6);
|
||||
|
||||
@ -197,7 +197,7 @@ sub mutate($n is rw) {
|
||||
say "\$n is now $n !";
|
||||
}
|
||||
|
||||
# If what you want is a copy instead, use `is copy`.
|
||||
# If what you want a copy instead, use `is copy`.
|
||||
|
||||
# A sub itself returns a container, which means it can be marked as rw:
|
||||
my $x = 42;
|
||||
@ -234,7 +234,7 @@ 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 much more
|
||||
# - `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,
|
||||
@ -1429,7 +1429,7 @@ for <well met young hero we shall meet later> {
|
||||
# A flip-flop can change state as many times as needed:
|
||||
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"
|
||||
#=> "print it print again"
|
||||
}
|
||||
|
||||
# you might also use a Whatever Star,
|
||||
@ -1461,4 +1461,3 @@ If you want to go further, you can:
|
||||
- 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 language design documents](http://design.perl6.org). They explain P6 from an implementor point-of-view, but it's still very interesting.
|
||||
|
||||
|
@ -693,8 +693,43 @@ use My\Namespace as SomeOtherNamespace;
|
||||
|
||||
$cls = new SomeOtherNamespace\MyClass();
|
||||
|
||||
/**********************
|
||||
* Error Handling
|
||||
*
|
||||
*/
|
||||
|
||||
// Simple error handling can be done with try catch block
|
||||
|
||||
try {
|
||||
// Do something
|
||||
} catch ( Exception $e) {
|
||||
// Handle exception
|
||||
}
|
||||
|
||||
// When using try catch blocks in a namespaced enviroment use the following
|
||||
|
||||
try {
|
||||
// Do something
|
||||
} catch (\Exception $e) {
|
||||
// Handle exception
|
||||
}
|
||||
|
||||
// Custom exceptions
|
||||
|
||||
class MyException extends Exception {}
|
||||
|
||||
try {
|
||||
|
||||
$condition = true;
|
||||
|
||||
if ($condition) {
|
||||
throw new MyException('Something just happend');
|
||||
}
|
||||
|
||||
} catch (MyException $e) {
|
||||
// Handle my exception
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## More Information
|
||||
@ -709,4 +744,4 @@ If you're coming from a language with good package management, check out
|
||||
[Composer](http://getcomposer.org/).
|
||||
|
||||
For common standards, visit the PHP Framework Interoperability Group's
|
||||
[PSR standards](https://github.com/php-fig/fig-standards).
|
||||
[PSR standards](https://github.com/php-fig/fig-standards).
|
||||
|
@ -473,9 +473,12 @@ add_10(3) # => 13
|
||||
|
||||
# There are also anonymous functions
|
||||
(lambda x: x > 2)(3) # => True
|
||||
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||
|
||||
# There are built-in higher order functions
|
||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
|
||||
|
||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||
|
||||
# We can use list comprehensions for nice maps and filters
|
||||
|
@ -550,10 +550,13 @@ add_10(3) # => 13
|
||||
|
||||
# There are also anonymous functions
|
||||
(lambda x: x > 2)(3) # => True
|
||||
(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5
|
||||
|
||||
# TODO - Fix for iterables
|
||||
# There are built-in higher order functions
|
||||
map(add_10, [1, 2, 3]) # => [11, 12, 13]
|
||||
map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3]
|
||||
|
||||
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
|
||||
|
||||
# We can use list comprehensions for nice maps and filters
|
||||
|
@ -106,8 +106,14 @@ placeholder = 'use string interpolation'
|
||||
'hello ' + 3 #=> TypeError: can't convert Fixnum into String
|
||||
'hello ' + 3.to_s #=> "hello 3"
|
||||
|
||||
# print to the output
|
||||
# print to the output with a newline at the end
|
||||
puts "I'm printing!"
|
||||
#=> I'm printing!
|
||||
#=> nil
|
||||
|
||||
# print to the output without a newline
|
||||
print "I'm printing!"
|
||||
#=> I'm printing! => nill
|
||||
|
||||
# Variables
|
||||
x = 25 #=> 25
|
||||
@ -269,6 +275,19 @@ end
|
||||
#=> iteration 4
|
||||
#=> iteration 5
|
||||
|
||||
# There are a bunch of other helpful looping functions in Ruby,
|
||||
# for example "map", "reduce", "inject", the list goes on. Map,
|
||||
# for instance, takes the array it's looping over, does something
|
||||
# to it as defined in your block, and returns an entirely new array.
|
||||
array = [1,2,3,4,5]
|
||||
doubled = array.map do |element|
|
||||
element * 2
|
||||
end
|
||||
puts doubled
|
||||
#=> [2,4,6,8,10]
|
||||
puts array
|
||||
#=> [1,2,3,4,5]
|
||||
|
||||
grade = 'B'
|
||||
|
||||
case grade
|
||||
|
@ -43,9 +43,13 @@ Scala - the scalable language
|
||||
// Printing, and forcing a new line on the next print
|
||||
println("Hello world!")
|
||||
println(10)
|
||||
// Hello world!
|
||||
// 10
|
||||
|
||||
// Printing, without forcing a new line on next print
|
||||
print("Hello world")
|
||||
print(10)
|
||||
// Hello world!10
|
||||
|
||||
// Declaring values is done using either var or val.
|
||||
// val declarations are immutable, whereas vars are mutable. Immutability is
|
||||
|
@ -5,6 +5,7 @@ contributors:
|
||||
- ["Christopher Bess", "http://github.com/cbess"]
|
||||
- ["Joey Huang", "http://github.com/kamidox"]
|
||||
- ["Anthony Nguyen", "http://github.com/anthonyn60"]
|
||||
- ["Clayton Walker", "https://github.com/cwalk"]
|
||||
filename: learnswift.swift
|
||||
---
|
||||
|
||||
@ -57,8 +58,9 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation
|
||||
print("Build value: \(buildValue)") // Build value: 7
|
||||
|
||||
/*
|
||||
Optionals are a Swift language feature that allows you to store a `Some` or
|
||||
`None` value.
|
||||
Optionals are a Swift language feature that either contains a value,
|
||||
or contains nil (no value) to indicate that a value is missing.
|
||||
A question mark (?) after the type marks the value as optional.
|
||||
|
||||
Because Swift requires every property to have a value, even nil must be
|
||||
explicitly stored as an Optional value.
|
||||
@ -79,6 +81,12 @@ if someOptionalString != nil {
|
||||
}
|
||||
someOptionalString = nil
|
||||
|
||||
/*
|
||||
Trying to use ! to access a non-existent optional value triggers a runtime
|
||||
error. Always make sure that an optional contains a non-nil value before
|
||||
using ! to force-unwrap its value.
|
||||
*/
|
||||
|
||||
// implicitly unwrapped optional
|
||||
var unwrappedString: String! = "Value is expected."
|
||||
// same as above, but ! is a postfix operator (more syntax candy)
|
||||
@ -93,7 +101,7 @@ if let someOptionalStringConstant = someOptionalString {
|
||||
|
||||
// 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)
|
||||
// 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."
|
||||
|
||||
@ -295,7 +303,7 @@ print(numbers) // [3, 6, 18]
|
||||
// MARK: Structures
|
||||
//
|
||||
|
||||
// Structures and classes have very similar capabilites
|
||||
// Structures and classes have very similar capabilities
|
||||
struct NamesTable {
|
||||
let names = [String]()
|
||||
|
||||
@ -574,4 +582,18 @@ print(mySquare.sideLength) // 4
|
||||
// change side length using custom !!! operator, increases size by 3
|
||||
!!!mySquare
|
||||
print(mySquare.sideLength) // 12
|
||||
|
||||
// Operators can also be generics
|
||||
infix operator <-> {}
|
||||
func <-><T: Equatable> (inout a: T, inout b: T) {
|
||||
let c = a
|
||||
a = b
|
||||
b = c
|
||||
}
|
||||
|
||||
var foo: Float = 10
|
||||
var bar: Float = 20
|
||||
|
||||
foo <-> bar
|
||||
print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user