mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2024-12-24 01:51:38 +00:00
Merge remote-tracking branch 'adambard/master' into forth-es
This commit is contained in:
commit
46b746e8c6
@ -7,7 +7,7 @@ filename: coffeescript.coffee
|
||||
---
|
||||
|
||||
CoffeeScript is a little language that compiles one-to-one into the equivalent JavaScript, and there is no interpretation at runtime.
|
||||
As one of the succeeders of JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript codes working well in every JavaScript runtime.
|
||||
As one of the successors to JavaScript, CoffeeScript tries its best to output readable, pretty-printed and smooth-running JavaScript code, which works well in every JavaScript runtime.
|
||||
|
||||
See also [the CoffeeScript website](http://coffeescript.org/), which has a complete tutorial on CoffeeScript.
|
||||
|
||||
@ -57,7 +57,7 @@ math =
|
||||
# "root": Math.sqrt,
|
||||
# "square": square,
|
||||
# "cube": function(x) { return x * square(x); }
|
||||
#}
|
||||
# };
|
||||
|
||||
# Splats:
|
||||
race = (winner, runners...) ->
|
||||
|
@ -8,13 +8,17 @@ 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 #
|
||||
@ -27,67 +31,67 @@ YAML est plus concis que le XML auquel il est parfois comparé par ceux qui le d
|
||||
# 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 ( > ).
|
||||
# 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
|
||||
-
|
||||
@ -99,22 +103,22 @@ une_séquence:
|
||||
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 :
|
||||
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
|
||||
|
||||
#####################
|
||||
@ -135,7 +139,7 @@ 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
|
||||
@ -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.
|
||||
|
@ -484,6 +484,8 @@ $ git rm /pather/to/the/file/HelloWorld.c
|
||||
|
||||
* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/)
|
||||
|
||||
* [Git Immersion - A Guided tour that walks through the fundamentals of git](http://gitimmersion.com/)
|
||||
|
||||
* [git-scm - Video Tutorials](http://git-scm.com/videos)
|
||||
|
||||
* [git-scm - Documentation](http://git-scm.com/docs)
|
||||
|
@ -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,8 +109,11 @@ 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
|
||||
}
|
||||
@ -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;
|
||||
@ -499,18 +513,21 @@ public class ExampleClass extends ExampleClassParent implements InterfaceOne,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 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
|
||||
{
|
||||
@ -527,7 +544,7 @@ public abstract class Animal
|
||||
// No need to initialize, however in an interface
|
||||
// a variable is implicitly final and hence has
|
||||
// to be initialized.
|
||||
private int age;
|
||||
protected int age;
|
||||
|
||||
public void printAge()
|
||||
{
|
||||
@ -566,6 +583,42 @@ class Dog extends Animal
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
{
|
||||
|
@ -3,6 +3,7 @@ language: Matlab
|
||||
contributors:
|
||||
- ["mendozao", "http://github.com/mendozao"]
|
||||
- ["jamesscottbrown", "http://jamesscottbrown.com"]
|
||||
- ["Colton Kohnke", "http://github.com/voltnor"]
|
||||
|
||||
---
|
||||
|
||||
@ -464,6 +465,59 @@ mean % mean value
|
||||
std % standard deviation
|
||||
perms(x) % list all permutations of elements of x
|
||||
|
||||
|
||||
% Classes
|
||||
% Matlab can support object-oriented programming.
|
||||
% Classes must be put in a file of the class name with a .m extension.
|
||||
% To begin, we create a simple class to store GPS waypoints.
|
||||
% Begin WaypointClass.m
|
||||
classdef WaypointClass % The class name.
|
||||
properties % The properties of the class behave like Structures
|
||||
latitude
|
||||
longitude
|
||||
end
|
||||
methods
|
||||
% This method that has the same name of the class is the constructor.
|
||||
function obj = WaypointClass(lat, lon)
|
||||
obj.latitude = lat;
|
||||
obj.longitude = lon;
|
||||
end
|
||||
|
||||
% Other functions that use the Waypoint object
|
||||
function r = multiplyLatBy(obj, n)
|
||||
r = n*[obj.latitude];
|
||||
end
|
||||
|
||||
% If we want to add two Waypoint objects together without calling
|
||||
% a special function we can overload Matlab's arithmetic like so:
|
||||
function r = plus(o1,o2)
|
||||
r = WaypointClass([o1.latitude] +[o2.latitude], ...
|
||||
[o1.longitude]+[o2.longitude]);
|
||||
end
|
||||
end
|
||||
end
|
||||
% End WaypointClass.m
|
||||
|
||||
% We can create an object of the class using the constructor
|
||||
a = WaypointClass(45.0, 45.0)
|
||||
|
||||
% Class properties behave exactly like Matlab Structures.
|
||||
a.latitude = 70.0
|
||||
a.longitude = 25.0
|
||||
|
||||
% Methods can be called in the same way as functions
|
||||
ans = multiplyLatBy(a,3)
|
||||
|
||||
% The method can also be called using dot notation. In this case, the object
|
||||
% does not need to be passed to the method.
|
||||
ans = a.multiplyLatBy(a,1/3)
|
||||
|
||||
% Matlab functions can be overloaded to handle objects.
|
||||
% In the method above, we have overloaded how Matlab handles
|
||||
% the addition of two Waypoint objects.
|
||||
b = WaypointClass(15.0, 32.0)
|
||||
c = a + b
|
||||
|
||||
```
|
||||
|
||||
## More on Matlab
|
||||
|
@ -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,
|
||||
|
@ -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
|
||||
|
@ -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]()
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user