diff options
-rw-r--r-- | coffeescript.html.markdown | 32 | ||||
-rw-r--r-- | forth.html.markdown | 4 | ||||
-rw-r--r-- | fr-fr/scala.html.markdown | 9 | ||||
-rw-r--r-- | fr-fr/yaml-fr.html.markdown | 92 | ||||
-rw-r--r-- | git.html.markdown | 2 | ||||
-rw-r--r-- | go.html.markdown | 9 | ||||
-rw-r--r-- | java.html.markdown | 209 | ||||
-rw-r--r-- | javascript.html.markdown | 20 | ||||
-rw-r--r-- | json.html.markdown | 7 | ||||
-rw-r--r-- | julia.html.markdown | 26 | ||||
-rw-r--r-- | matlab.html.markdown | 54 | ||||
-rw-r--r-- | perl6.html.markdown | 93 | ||||
-rw-r--r-- | php.html.markdown | 37 | ||||
-rw-r--r-- | pt-pt/scala-pt.html.markdown | 651 | ||||
-rw-r--r-- | python.html.markdown | 3 | ||||
-rw-r--r-- | python3.html.markdown | 3 | ||||
-rw-r--r-- | ruby.html.markdown | 21 | ||||
-rw-r--r-- | scala.html.markdown | 16 | ||||
-rw-r--r-- | swift.html.markdown | 16 |
19 files changed, 1094 insertions, 210 deletions
diff --git a/coffeescript.html.markdown b/coffeescript.html.markdown index 85a5f81f..89a29677 100644 --- a/coffeescript.html.markdown +++ b/coffeescript.html.markdown @@ -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. @@ -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' diff --git a/forth.html.markdown b/forth.html.markdown index f7c0bf34..b4a5581b 100644 --- a/forth.html.markdown +++ b/forth.html.markdown @@ -117,7 +117,7 @@ one-to-12 \ 0 1 2 3 4 5 6 7 8 9 10 11 12 ok : threes ( n n -- ) ?do i . 3 +loop ; \ ok 15 0 threes \ 0 3 6 9 12 ok -\ Indefinite loops with `begin` <stuff to do> <flag> `unil`: +\ Indefinite loops with `begin` <stuff to do> <flag> `until`: : death ( -- ) begin ." Are we there yet?" 0 until ; \ ok \ ---------------------------- Variables and Memory ---------------------------- @@ -133,7 +133,7 @@ variable age \ ok age @ . \ 21 ok age ? \ 21 ok -\ Constants are quite simiar, except we don't bother with memory addresses: +\ Constants are quite similar, except we don't bother with memory addresses: 100 constant WATER-BOILING-POINT \ ok WATER-BOILING-POINT . \ 100 ok diff --git a/fr-fr/scala.html.markdown b/fr-fr/scala.html.markdown index a43edf16..c6d06361 100644 --- a/fr-fr/scala.html.markdown +++ b/fr-fr/scala.html.markdown @@ -208,6 +208,7 @@ sSquared.reduce (_+_) // La fonction filter prend un prédicat (une fonction de type A -> Booléen) et // sélectionne tous les éléments qui satisfont ce prédicat List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -217,6 +218,7 @@ List( // Scala a une méthode foreach définie pour certaines collections // qui prend en argument une fonction renvoyant Unit (une méthode void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -271,11 +273,12 @@ i // Montre la valeur de i. Notez que while est une boucle au sens classique. // mais utiliser des combinateurs et des compréhensions comme ci-dessus est plus // facile pour comprendre et pour faire la parallélisation +i = 0 // La boucle do while do { println("x is still less then 10"); - x += 1 -} while (x < 10) + i += 1 +} while (i < 10) // La récursivité est un moyen idiomatique de faire une chose répétitive en Scala. @@ -370,7 +373,7 @@ val email(user, domain) = "henry@zkpr.com" "Les chaînes de caractères Scala sont entourées de doubles guillements" 'a' // Un caractère de Scala -'Les simples guillemets n'existent pas en Scala // Erreur +// 'Les simples guillemets n'existent pas en Scala' // Erreur "Les chaînes de caractères possèdent les méthodes usuelles de Java".length "Il y a aussi quelques méthodes extra de Scala.".reverse diff --git a/fr-fr/yaml-fr.html.markdown b/fr-fr/yaml-fr.html.markdown index 43b1df54..1e8296d3 100644 --- a/fr-fr/yaml-fr.html.markdown +++ b/fr-fr/yaml-fr.html.markdown @@ -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. diff --git a/git.html.markdown b/git.html.markdown index b1347309..72079f6c 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -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) diff --git a/go.html.markdown b/go.html.markdown index 34b855e3..646a5650 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -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.) diff --git a/java.html.markdown b/java.html.markdown index fc7948d6..ba602d2e 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -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 achive 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,26 +478,26 @@ 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 - public void eat() { - // ... - } + public void eat() { + // ... + } @Override - public void digest() { - // ... - } + public void digest() { + // ... + } } // In Java, you can extend only one class, but you can implement many @@ -491,81 +505,120 @@ public class Fruit implements Edible, Digestible { public class ExampleClass extends ExampleClassParent implements InterfaceOne, InterfaceTwo { @Override - public void InterfaceOneMethod() { - } + public void InterfaceOneMethod() { + } @Override - public void InterfaceTwoMethod() { - } + public void InterfaceTwoMethod() { + } } - // 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(); - - // 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; - - 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"); - } + 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; + } + + // 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); + } + + // 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: 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 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(); + } +} + +// 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 diff --git a/javascript.html.markdown b/javascript.html.markdown index 754832f1..6ea0b0bb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -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"; diff --git a/json.html.markdown b/json.html.markdown index 6aff2ce2..a1629137 100644 --- a/json.html.markdown +++ b/json.html.markdown @@ -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 { diff --git a/julia.html.markdown b/julia.html.markdown index 66329feb..c5089dc3 100644 --- a/julia.html.markdown +++ b/julia.html.markdown @@ -81,10 +81,13 @@ false # Strings are created with " "This is a string." +# Julia has several types of strings, including ASCIIString and UTF8String. +# More on this in the Types section. + # Character literals are written with ' 'a' -# A string can be indexed like an array of characters +# Some strings can be indexed like an array of characters "This is a string"[1] # => 'T' # Julia indexes from 1 # However, this is will not work well for UTF8 strings, # so iterating over strings is recommended (map, for loops, etc). @@ -314,7 +317,7 @@ end # For loops iterate over iterables. -# Iterable types include Range, Array, Set, Dict, and String. +# Iterable types include Range, Array, Set, Dict, and AbstractString. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") # You can use $ to interpolate variables or expression into strings @@ -537,6 +540,17 @@ subtypes(Number) # => 6-element Array{Any,1}: # Real subtypes(Cat) # => 0-element Array{Any,1} +# AbstractString, as the name implies, is also an abstract type +subtypes(AbstractString) # 8-element Array{Any,1}: + # Base.SubstitutionString{T<:AbstractString} + # DirectIndexString + # RepString + # RevString{T<:AbstractString} + # RopeString + # SubString{T<:AbstractString} + # UTF16String + # UTF8String + # Every type has a super type; use the `super` function to get it. typeof(5) # => Int64 super(Int64) # => Signed @@ -546,17 +560,21 @@ super(Number) # => Any super(super(Signed)) # => Number super(Any) # => Any # All of these type, except for Int64, are abstract. +typeof("fire") # => ASCIIString +super(ASCIIString) # => DirectIndexString +super(DirectIndexString) # => AbstractString +# Likewise here with ASCIIString # <: is the subtyping operator type Lion <: Cat # Lion is a subtype of Cat mane_color - roar::String + roar::AbstractString end # You can define more constructors for your type # Just define a function of the same name as the type # and call an existing constructor to get a value of the correct type -Lion(roar::String) = Lion("green",roar) +Lion(roar::AbstractString) = Lion("green",roar) # This is an outer constructor because it's outside the type definition type Panther <: Cat # Panther is also a subtype of Cat diff --git a/matlab.html.markdown b/matlab.html.markdown index 02fe5962..0cbc6f57 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -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 diff --git a/perl6.html.markdown b/perl6.html.markdown index 2b45f661..0f015b45 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -75,7 +75,7 @@ say @array; #=> a 6 b # except they get "flattened" (hash context), removing duplicated keys. my %hash = 1 => 2, 3 => 4; -my %hash = autoquoted => "key", # keys get auto-quoted +my %hash = foo => "bar", # keys get auto-quoted "some other" => "value", # trailing commas are okay ; my %hash = <key1 value1 key2 value2>; # you can also create a hash @@ -96,7 +96,6 @@ say %hash<key2>; # If it's a string, you can actually use <> # (`{key1}` doesn't work, as Perl6 doesn't have barewords) ## * Subs (subroutines, or functions in most other languages). -# Stored in variable, they use `&`. sub say-hello { say "Hello, world" } sub say-hello-to(Str $name) { # You can provide the type of an argument @@ -107,8 +106,8 @@ sub say-hello-to(Str $name) { # You can provide the type of an argument ## It can also have optional arguments: sub with-optional($arg?) { # the "?" marks the argument optional - say "I might return `(Any)` if I don't have an argument passed, - or I'll return my argument"; + say "I might return `(Any)` (Perl's "null"-like value) if I don't have + an argument passed, or I'll return my argument"; $arg; } with-optional; # returns Any @@ -125,7 +124,7 @@ hello-to('You'); #=> Hello, You ! ## You can also, by using a syntax akin to the one of hashes (yay unified syntax !), ## pass *named* arguments to a `sub`. -# They're optional, and will default to "Any" (Perl's "null"-like value). +# They're optional, and will default to "Any". sub with-named($normal-arg, :$named) { say $normal-arg + $named; } @@ -162,7 +161,7 @@ named-def; #=> 5 named-def(def => 15); #=> 15 # Since you can omit parenthesis to call a function with no arguments, -# you need "&" in the name to capture `say-hello`. +# you need "&" in the name to store `say-hello` in a variable. my &s = &say-hello; my &other-s = sub { say "Anonymous function !" } @@ -173,8 +172,8 @@ sub as-many($head, *@rest) { # `*@` (slurpy) will basically "take everything els say @rest.join(' / ') ~ " !"; } say as-many('Happy', 'Happy', 'Birthday'); #=> Happy / Birthday ! - # Note that the splat did not consume - # the parameter before. + # Note that the splat (the *) did not + # consume the parameter before. ## You can call a function with an array using the # "argument list flattening" operator `|` @@ -380,7 +379,9 @@ say join(' ', @array[-> $n { 15..$n }]); # You can use that in most places you'd expect, even assigning to an array my @numbers = ^20; -my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99 + +# Here numbers increase by "6"; more on `...` operator later. +my @seq = 3, 9 ... * > 95; # 3 9 15 21 27 [...] 81 87 93 99; @numbers[5..*] = 3, 9 ... *; # even though the sequence is infinite, # only the 15 needed values will be calculated. say @numbers; #=> 0 1 2 3 4 3 9 15 21 [...] 81 87 @@ -525,7 +526,7 @@ map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # The constructs for declaring types are "class", "role", # which you'll see later. -# For now, let us examinate "subset": +# For now, let us examine "subset": # a "subset" is a "sub-type" with additional checks. # For example: "a very big integer is an Int that's greater than 500" # You can specify the type you're subtyping (by default, Any), @@ -608,27 +609,26 @@ sub foo { bar(); # call `bar` in-place } sub bar { - say $*foo; # `$*a` will be looked in the call stack, and find `foo`'s, + say $*foo; # `$*foo` will be looked in the call stack, and find `foo`'s, # even though the blocks aren't nested (they're call-nested). #=> 1 } ### Object Model -## Perl 6 has a quite comprehensive object model # You declare a class with the keyword `class`, fields with `has`, -# methods with `method`. Every field to private, and is named `$!attr`, -# but you have `$.` to get a public (immutable) accessor along with it. -# (using `$.` is like using `$!` plus a `method` with the same name) +# methods with `method`. Every attribute that is private is named `$!attr`. +# Immutable public attributes are named `$.attr` +# (you can make them mutable with `is rw`) -# (Perl 6's object model ("SixModel") is very flexible, +# Perl 6's object model ("SixModel") is very flexible, # and allows you to dynamically add methods, change semantics, etc ... # (this will not be covered here, and you should refer to the Synopsis). class A { has $.field; # `$.field` is immutable. # From inside the class, use `$!field` to modify it. - has $.other-field is rw; # You can obviously mark a public field `rw`. + has $.other-field is rw; # You can mark a public attribute `rw`. has Int $!private-field = 10; method get-value { @@ -656,7 +656,6 @@ $a.other-field = 10; # This, however, works, because the public field # is mutable (`rw`). ## Perl 6 also has inheritance (along with multiple inheritance) -# (though considered a misfeature by many) class A { has $.val; @@ -751,7 +750,7 @@ fail "foo"; # We're not trying to access the value, so no problem. try { fail "foo"; CATCH { - default { say "It threw because we try to get the fail's value!" } + default { say "It threw because we tried to get the fail's value!" } } } @@ -763,7 +762,7 @@ try { ### Packages # Packages are a way to reuse code. Packages are like "namespaces", and any # element of the six model (`module`, `role`, `class`, `grammar`, `subset` -# and `enum`) are actually packages. (Packages are the lowest common denomitor) +# and `enum`) are actually packages. (Packages are the lowest common denominator) # Packages are important - especially as Perl is well-known for CPAN, # the Comprehensive Perl Archive Network. # You usually don't use packages directly: you use `class Package::Name::Here;`, @@ -773,7 +772,7 @@ module Hello::World { # Bracketed form # that can be redeclared as something else later. # ... declarations here ... } -module Parse::Text; # file-scoped form +unit module Parse::Text; # file-scoped form grammar Parse::Text::Grammar { # A grammar is a package, which you could `use` } @@ -797,10 +796,8 @@ my $actions = JSON::Tiny::Actions.new; # You've already seen `my` and `has`, we'll now explore the others. ## * `our` (happens at `INIT` time -- see "Phasers" below) -# Along with `my`, there are several others declarators you can use. -# The first one you'll want for the previous part is `our`. +# It's like `my`, but it also creates a package variable. # (All packagish things (`class`, `role`, etc) are `our` by default) -# it's like `my`, but it also creates a package variable: module Foo::Bar { our $n = 1; # note: you can't put a type constraint on an `our` variable our sub inc { @@ -829,7 +826,7 @@ constant why-not = 5, 15 ... *; say why-not[^5]; #=> 5 15 25 35 45 ## * `state` (happens at run time, but only once) -# State variables are only executed one time +# State variables are only initialized one time # (they exist in other langages such as C as `static`) sub fixed-rand { state $val = rand; @@ -862,7 +859,7 @@ for ^5 -> $a { ## * Compile-time phasers BEGIN { say "[*] Runs at compile time, as soon as possible, only once" } -CHECK { say "[*] Runs at compile time, instead as late as possible, only once" } +CHECK { say "[*] Runs at compile time, as late as possible, only once" } ## * Run-time phasers INIT { say "[*] Runs at run time, as soon as possible, only once" } @@ -870,10 +867,13 @@ END { say "Runs at run time, as late as possible, only once" } ## * Block phasers ENTER { say "[*] Runs everytime you enter a block, repeats on loop blocks" } -LEAVE { say "Runs everytime you leave a block, even when an exception happened. Repeats on loop blocks." } +LEAVE { say "Runs everytime you leave a block, even when an exception + happened. Repeats on loop blocks." } -PRE { say "Asserts a precondition at every block entry, before ENTER (especially useful for loops)" } -POST { say "Asserts a postcondition at every block exit, after LEAVE (especially useful for loops)" } +PRE { say "Asserts a precondition at every block entry, + before ENTER (especially useful for loops)" } +POST { say "Asserts a postcondition at every block exit, + after LEAVE (especially useful for loops)" } ## * Block/exceptions phasers sub { @@ -891,12 +891,12 @@ for ^5 { ## * Role/class phasers COMPOSE { "When a role is composed into a class. /!\ NOT YET IMPLEMENTED" } -# They allow for cute trick or clever code ...: -say "This code took " ~ (time - CHECK time) ~ "s to run"; +# They allow for cute tricks or clever code ...: +say "This code took " ~ (time - CHECK time) ~ "s to compile"; # ... or clever organization: sub do-db-stuff { - ENTER $db.start-transaction; # New transaction everytime we enter the sub + $db.start-transaction; # start a new transaction KEEP $db.commit; # commit the transaction if all went well UNDO $db.rollback; # or rollback if all hell broke loose } @@ -1020,7 +1020,7 @@ sub circumfix:<[ ]>(Int $n) { $n ** $n } say [5]; #=> 3125 - # circumfix is around. Again, not whitespace. + # circumfix is around. Again, no whitespace. sub postcircumfix:<{ }>(Str $s, Int $idx) { # post-circumfix is @@ -1052,9 +1052,9 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # Basically, they're operators that apply another operator. ## * Reduce meta-operator -# It's a prefix meta-operator that takes a binary functions and +# It's a prefix meta-operator that takes a binary function and # one or many lists. If it doesn't get passed any argument, -# it either return a "default value" for this operator +# it either returns a "default value" for this operator # (a meaningless value) or `Any` if there's none (examples below). # # Otherwise, it pops an element from the list(s) one at a time, and applies @@ -1089,7 +1089,7 @@ say [[&add]] 1, 2, 3; #=> 6 # This one is an infix meta-operator than also can be used as a "normal" operator. # It takes an optional binary function (by default, it just creates a pair), # and will pop one value off of each array and call its binary function on these -# until it runs out of elements. It runs the an array with all these new elements. +# until it runs out of elements. It returns an array with all of these new elements. (1, 2) Z (3, 4); # ((1, 3), (2, 4)), since by default, the function makes an array 1..3 Z+ 4..6; # (5, 7, 9), using the custom infix:<+> function @@ -1109,8 +1109,7 @@ say [[&add]] 1, 2, 3; #=> 6 # (and might include a closure), and on the right, a value or the predicate # that says when to stop (or Whatever for a lazy infinite list). my @list = 1, 2, 3 ... 10; # basic deducing -#my @list = 1, 3, 6 ... 10; # this throws you into an infinite loop, - # because Perl 6 can't figure out the end +#my @list = 1, 3, 6 ... 10; # this dies because Perl 6 can't figure out the end my @list = 1, 2, 3 ...^ 10; # as with ranges, you can exclude the last element # (the iteration when the predicate matches). my @list = 1, 3, 9 ... * > 30; # you can use a predicate @@ -1222,7 +1221,7 @@ so 'abbbbbbc' ~~ / a b ** 3..* c /; # `True` (infinite ranges are okay) # they use a more perl6-ish syntax: say 'fooa' ~~ / f <[ o a ]>+ /; #=> 'fooa' # You can use ranges: -say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'aeiou' +say 'aeiou' ~~ / a <[ e..w ]> /; #=> 'ae' # Just like in normal regexes, if you want to use a special character, escape it # (the last one is escaping a space) say 'he-he !' ~~ / 'he-' <[ a..z \! \ ]> + /; #=> 'he-he !' @@ -1244,7 +1243,7 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /; # The previous line returns `True`. -# We match the "abc" 1 or more time (the `+` was applied to the group). +# We match the "ABC" 1 or more time (the `+` was applied to the group). # But this does not go far enough, because we can't actually get back what # we matched. @@ -1287,10 +1286,12 @@ say $/[0][0].Str; #=> ~ # This stems from a very simple fact: `$/` does not contain strings, integers or arrays, # it only contains match objects. These contain the `.list`, `.hash` and `.Str` methods. -# (but you can also just use `match<key>` for hash access and `match[idx]` for array access) +# (but you can also just use `match<key>` for hash access +# and `match[idx]` for array access) say $/[0].list.perl; #=> (Match.new(...),).list - # We can see it's a list of Match objects. Those contain a bunch of infos: - # where the match started/ended, the "ast" (see actions later), etc. + # We can see it's a list of Match objects. Those contain + # a bunch of infos: where the match started/ended, + # the "ast" (see actions later), etc. # You'll see named capture below with grammars. ## Alternatives - the `or` of regexps @@ -1328,7 +1329,7 @@ so 'ayc' ~~ / a [ b | y ] c /; # `True`. Obviously enough ... ### Extra: the MAIN subroutime # The `MAIN` subroutine is called when you run a Perl 6 file directly. -# It's very powerful, because Perl 6 actually parses the argument +# It's very powerful, because Perl 6 actually parses the arguments # and pass them as such to the sub. It also handles named argument (`--foo`) # and will even go as far as to autogenerate a `--help` sub MAIN($name) { say "Hello, $name !" } @@ -1346,7 +1347,7 @@ multi MAIN('add', $key, $value, Bool :$replace) { ... } multi MAIN('remove', $key) { ... } multi MAIN('import', File, Str :$as) { ... } # omitting parameter name # This produces: -# $ perl 6 cli.pl +# $ perl6 cli.pl # Usage: # t.pl [--replace] add <key> <value> # t.pl remove <key> @@ -1429,7 +1430,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, diff --git a/php.html.markdown b/php.html.markdown index 2b1fe1dc..39ec5aef 100644 --- a/php.html.markdown +++ b/php.html.markdown @@ -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).
\ No newline at end of file +[PSR standards](https://github.com/php-fig/fig-standards). diff --git a/pt-pt/scala-pt.html.markdown b/pt-pt/scala-pt.html.markdown new file mode 100644 index 00000000..a4c1c02b --- /dev/null +++ b/pt-pt/scala-pt.html.markdown @@ -0,0 +1,651 @@ +--- +language: Scala +filename: learnscala-pt.scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] +translators: + - ["João Costa", "http://joaocosta.eu"] +lang: pt-pt +--- + +Scala - a linguagem escalável + +```scala + +/* + Prepare tudo: + + 1) Faça Download do Scala - http://www.scala-lang.org/downloads + 2) Faça unzip/untar para onde preferir e coloque o subdirectório `bin` na + variável de ambiente `PATH` + 3) Inicie a REPL de Scala correndo o comando `scala`. Deve aparecer: + + scala> + + Isto é chamado de REPL (Read-Eval-Print Loop / Lê-Avalia-Imprime Repete). + Pode escrever qualquer expressão de Scala e o resultado será imprimido. + Vamos mostrar ficheiros de Scala mais à frente neste tutorial mas, para já, + vamos começar com os básicos. + +*/ + + +///////////////////////////////////////////////// +// 1. Basicos +///////////////////////////////////////////////// + +// Uma linha de comentários é marcada com duas barras + +/* + Comentários de multiplas linhas, como se pode ver neste exemplo, são assim. +*/ + +// Imprimir, forçando uma nova linha no final +println("Hello world!") +println(10) + +// Imprimir, sem forçar uma nova linha no final +print("Hello world") + +// Valores são declarados com var ou val. +// As declarações val são imutáveis, enquanto que vars são mutáveis. +// A immutabilidade é uma propriedade geralmente vantajosa. +val x = 10 // x é agora 10 +x = 20 // erro: reatribuição de um val +var y = 10 +y = 20 // y é agora 12 + +/* + Scala é uma linguagem estaticamente tipada, no entanto, nas declarações acima + não especificamos um tipo. Isto é devido a uma funcionalidade chamada + inferência de tipos. Na maior parte dos casos, o compilador de scala consegue + inferir qual o tipo de uma variável, pelo que não o temos de o declarar sempre. + Podemos declarar o tipo de uma variável da seguinte forma: +*/ +val z: Int = 10 +val a: Double = 1.0 + +// Note a conversão automática de Int para Double: o resultado é 10.0, não 10 +val b: Double = 10 + +// Valores booleanos +true +false + +// Operações booleanas +!true // false +!false // true +true == false // false +10 > 5 // true + +// A matemática funciona da maneira habitual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +// Avaliar expressões na REPL dá o tipo e valor do resultado + +1 + 7 + +/* A linha acima resulta em: + + scala> 1 + 7 + res29: Int = 8 + + Isto significa que o resultado de avaliar 1 + 7 é um objecto do tipo Int com + o valor 8. + + Note que "res29" é um nome de uma variavel gerado sequencialmente para + armazenar os resultados das expressões que escreveu, por isso o resultado + pode ser ligeiramente diferente. +*/ + +"Strings em scala são rodeadas por aspas" +'a' // Um caracter de Scala +// 'Strings entre plicas não existem' <= Isto causa um erro + +// Strings tem os métodos de Java habituais definidos +"olá mundo".length +"olá mundo".substring(2, 6) +"olá mundo".replace("á", "é") + +// Para além disso, também possuem métodos de Scala. +// Ver: scala.collection.immutable.StringOps +"olá mundo".take(5) +"olá mundo".drop(5) + +// Interpolação de Strings: repare no prefixo "s" +val n = 45 +s"Temos $n maçãs" // => "Temos 45 maçãs" + +// Expressões dentro de Strings interpoladas também são possíveis +val a = Array(11, 9, 6) +s"A minha segunda filha tem ${a(0) - a(2)} anos." // => "A minha segunda filha tem 5 anos." +s"Temos o dobro de ${n / 2.0} em maçãs." // => "Temos o dobro de 22.5 em maçãs." +s"Potência de 2: ${math.pow(2, 2)}" // => "Potência de 2: 4" + +// Strings interpoladas são formatadas com o prefixo "f" +f"Potência de 5: ${math.pow(5, 2)}%1.0f" // "Potência de 5: 25" +f"Raíz quadrada 122: ${math.sqrt(122)}%1.4f" // "Raíz quadrada de 122: 11.0454" + +// Strings prefixadas com "raw" ignoram caracteres especiais +raw"Nova linha: \n. Retorno: \r." // => "Nova Linha: \n. Retorno: \r." + +// Alguns caracteres tem de ser "escapados", e.g. uma aspa dentro de uma string: +"Esperaram fora do \"Rose and Crown\"" // => "Esperaram fora do "Rose and Crown"" + +// Strings rodeadas por três aspas podem-se estender por varias linhas e conter aspas +val html = """<form id="daform"> + <p>Carrega aqui, Zé</p> + <input type="submit"> + </form>""" + + +///////////////////////////////////////////////// +// 2. Funções +///////////////////////////////////////////////// + +// Funções são definidas como: +// +// def nomeDaFuncao(args...): TipoDeRetorno = { corpo... } +// +// Se vem de linugagens mais tradicionais, repare na omissão da palavra +// return keyword. Em Scala, a ultima expressão de um bloco é o seu +// valor de retorno +def somaQuadrados(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// As { } podem ser omitidas se o corpo da função for apenas uma expressão: +def somaQuadradosCurto(x: Int, y: Int): Int = x * x + y * y + +// A sintaxe para chamar funções deve ser familiar: +somaQuadrados(3, 4) // => 25 + +// Na maior parte dos casos (sendo funções recursivas a principal excepção), o +// tipo de retorno da função pode ser omitido, sendo que a inferencia de tipos +// é aplicada aos valores de retorno +def quadrado(x: Int) = x * x // O compilador infere o tipo de retorno Int + +// Funções podem ter parâmetros por omissão: +def somaComOmissão(x: Int, y: Int = 5) = x + y +somaComOmissão(1, 2) // => 3 +somaComOmissão(1) // => 6 + + +// Funções anónimas são definidas da seguinte forma: +(x: Int) => x * x + +// Ao contrário de defs, o tipo de input de funções anónimas pode ser omitido +// se o contexto o tornar óbvio. Note que o tipo "Int => Int" representa uma +// funão que recebe Int e retorna Int. +val quadrado: Int => Int = x => x * x + +// Funcões anónimas são chamadas como funções normais: +quadrado(10) // => 100 + +// Se cada argumento de uma função anónima for usado apenas uma vez, existe +// uma forma ainda mais curta de os definir. Estas funções anónumas são +// extremamente comuns, como será visto na secção sobre estruturas de dados. +val somaUm: Int => Int = _ + 1 +val somaEstranha: (Int, Int) => Int = (_ * 2 + _ * 3) + +somaUm(5) // => 6 +somaEstranha(2, 4) // => 16 + + +// O código return existe em Scala, mas apenas retorna do def mais interior +// que o rodeia. +// AVISO: Usar return em Scala deve ser evitado, pois facilmente leva a erros. +// Não tem qualquer efeito em funções anónimas, por exemplo: +def foo(x: Int): Int = { + val funcAnon: Int => Int = { z => + if (z > 5) + return z // Esta linha faz com que z seja o retorno de foo! + else + z + 2 // Esta linha define o retorno de funcAnon + } + funcAnon(x) // Esta linha define o valor de retorno de foo +} + + +///////////////////////////////////////////////// +// 3. Controlo de fluxo +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach(println) + +r foreach println +// NB: Scala é bastante brando no que toca a pontos e parentisis - estude as +// regras separadamente. Isto permite escrever APIs e DSLs bastante legiveis + +(5 to 1 by -1) foreach (println) + +// Ciclos while +var i = 0 +while (i < 10) { println("i " + i); i += 1 } + +while (i < 10) { println("i " + i); i += 1 } // Sim, outra vez. O que aconteceu? Porquê? + +i // Mostra o valor de i. Note que o while é um ciclo no sentido clássico - + // executa sequencialmente enquanto muda uma variável. Ciclos while são + // rápidos, por vezes até mais que ciclos de Java, mas combinadores e + // compreensões (usados anteriormente) são mais fáceis de entender e + // paralelizar + +// Um ciclo do while +i = 0 +do { + println("i ainda é menor que 10") + i += 1 +} while (i < 10) + +// A forma idiomática em Scala de definir acções recorrentes é através de +// recursão em cauda. +// Funções recursivas necessitam de um tipo de retorno definido explicitamente. +// Neste caso, é Unit. +def mostraNumerosEntre(a: Int, b: Int): Unit = { + print(a) + if (a < b) + mostraNumerosEntre(a + 1, b) +} +mostraNumerosEntre(1, 14) + + +// Condicionais + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. Estruturas de dados +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // Lança uma excepção + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // Lança uma excepção + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Veja a documentação de mapas de scala em - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * e verifique que a consegue aceder + */ + + +// Tuplos + +(1, 2) + +(4, 3, 2) + +(1, 2, "três") + +(a, 2, "três") + +// Porquê ter isto? +val divideInts = (x: Int, y: Int) => (x / y, x % y) + +divideInts(10, 3) // A função divideInts returna o resultado e o resto + +// Para aceder aos elementos de um tuplo, pode-se usar _._n, onde n é o indice +// (começado em 1) do elemento +val d = divideInts(10, 3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Programação Orientada a Objectos +///////////////////////////////////////////////// + +/* + Aparte: Até agora tudo o que fizemos neste tutorial foram expressões simples + (valores, funções, etc). Estas expressões são suficientes para executar no + interpretador da linha de comandos para testes rápidos, mas não podem existir + isoladas num ficheiro de Scala. Por exemplo, não é possivel correr um + ficheiro scala que apenas contenha "val x = 5". Em vez disso, as únicas + construções de topo permitidas são: + + - object + - class + - case class + - trait + + Vamos agora explicar o que são: +*/ + +// Classes são semelhantes a classes noutras linguagens. Os argumentos do +// construtor são declarados após o nome da classe, sendo a inicialização feita +// no corpo da classe. +class Cão(rc: String) { + // Código de construção + var raça: String = rc + + // Define um método chamado "ladra", que retorna uma String + def ladra = "Woof, woof!" + + // Valores e métodos são assumidos como públicos, mas é possivel usar + // os códigos "protected" and "private". + private def dormir(horas: Int) = + println(s"Vou dormir por $horas horas") + + // Métodos abstractos são métodos sem corpo. Se descomentarmos a próxima + // linha, a classe Cão é declarada como abstracta + // abstract class Cão(...) { ... } + // def persegue(oQue: String): String +} + +val oMeuCão = new Cão("greyhound") +println(oMeuCão.raça) // => "greyhound" +println(oMeuCão.ladra) // => "Woof, woof!" + + +// O termo "object" cria um tipo e uma instancia singleton desse tipo. É comum +// que classes de Scala possuam um "objecto companheiro", onde o comportamento +// por instância é capturado nas classes, equanto que o comportamento +// relacionado com todas as instancias dessa classe ficam no objecto. +// A diferença é semelhante a métodos de classes e métodos estáticos noutras +// linguagens. Note que objectos e classes podem ter o mesmo nome. +object Cão { + def raçasConhecidas = List("pitbull", "shepherd", "retriever") + def criarCão(raça: String) = new Cão(raça) +} + + +// Case classes são classes com funcionalidades extra incluidas. Uma questão +// comum de iniciantes de scala é quando devem usar classes e quando devem usar +// case classes. A linha é difusa mas, em geral, classes tendem a concentrar-se +// em encapsulamento, polimorfismo e comportamento. Os valores nestas classes +// tendem a ser privados, sendo apenas exposotos métodos. O propósito principal +// das case classes é armazenarem dados imutáveis. Geralmente possuem poucos +// métods, sendo que estes raramente possuem efeitos secundários. +case class Pessoa(nome: String, telefone: String) + +// Cria uma nova instancia. De notar que case classes não precisam de "new" +val jorge = Pessoa("Jorge", "1234") +val cátia = Pessoa("Cátia", "4567") + +// Case classes trazem algumas vantagens de borla, como acessores: +jorge.telefone // => "1234" + +// Igualdade por campo (não é preciso fazer override do .equals) +Pessoa("Jorge", "1234") == Pessoa("Cátia", "1236") // => false + +// Cópia simples +// outroJorge == Person("jorge", "9876") +val outroJorge = jorge.copy(telefone = "9876") + +// Entre outras. Case classes também suportam correspondência de padrões de +// borla, como pode ser visto de seguida. + + +// Traits em breve! + + +///////////////////////////////////////////////// +// 6. Correspondência de Padrões +///////////////////////////////////////////////// + +// A correspondência de padrões é uma funcionalidade poderosa e bastante +// utilizada em Scala. Eis como fazer correspondência de padrões numa case class: +// Nota: Ao contrário de outras linguagens, cases em scala não necessitam de +// breaks, a computação termina no primeiro sucesso. + +def reconhecePessoa(pessoa: Pessoa): String = pessoa match { + // Agora, especifique os padrões: + case Pessoa("Jorge", tel) => "Encontramos o Jorge! O seu número é " + tel + case Pessoa("Cátia", tel) => "Encontramos a Cátia! O seu número é " + tel + case Pessoa(nome, tel) => "Econtramos alguém : " + nome + ", telefone : " + tel +} + +val email = "(.*)@(.*)".r // Define uma regex para o próximo exemplo. + +// A correspondência de padrões pode parecer familiar aos switches em linguagens +// derivadas de C, mas é muto mais poderoso. Em Scala, é possível fazer +// correspondências com muito mais: +def correspondeTudo(obj: Any): String = obj match { + // Pode-se corresponder valores: + case "Olá mundo" => "Recebi uma string Olá mundo." + + // Corresponder por tipo: + case x: Double => "Recebi um Double: " + x + + // Corresponder tendo em conta condições especificas: + case x: Int if x > 10000 => "Recebi um número bem grande!" + + // Fazer correspondências com case classes (visto anteriormente): + case Pessoa(nome, tel) => s"Recebi o contacto para $nome!" + + // Fazer correspondência com expressões regulares: + case email(nome, dominio) => s"Recebi o endereço de email $nome@$dominio" + + // Corresponder tuplos: + case (a: Int, b: Double, c: String) => s"Recebi o tuplo: $a, $b, $c" + + // Corresponder estruturas de dados: + case List(1, b, c) => s"Recebi uma lista de 3 elementos começada em 1: 1, $b, $c" + + // Combinar padrões: + case List(List((1, 2, "YAY"))) => "Recebi uma lista de lista de triplo" +} + +// Na realidade, é possível fazer correspondência com qualquer objecto que +// defina o método "unapply". Esta funcionalidade é tão poderosa que permite +// definir funções sob a forma de padrões: +val funcPaddrao: Pessoa => String = { + case Pessoa("Jorge", tel) => s"Número do Jorge: $tel" + case Pessoa(nome, tel) => s"Número de alguém: $tel" +} + + +///////////////////////////////////////////////// +// 7. Programação Funcional +///////////////////////////////////////////////// + +// Scala permite que funções e métodos retornem, ou recebam como parámetros, +// outras funções ou métodos + +val soma10: Int => Int = _ + 10 // Função que recebe um Int e retorna um Int +List(1, 2, 3) map soma10 // List(11, 12, 13) - soma10 é aplicado a cada elemento + +// Funções anónimas também podem ser usadas +List(1, 2, 3) map (x => x + 10) + +// Sendo que o símbolo _ também pode ser usado se a função anónima só receber +// um argumento. Este fica com o valor da variável +List(1, 2, 3) map (_ + 10) + +// Se tanto o bloco como a função apenas receberem um argumento, o próprio +// _ pode ser omitido +List("Dom", "Bob", "Natalia") foreach println + + +// Combinadores + +s.map(quadrado) + +val sQuadrado = s.map(quadrado) + +sQuadrado.filter(_ < 10) + +sQuadrado.reduce (_+_) + +// O método filter recebe um predicado (uma função de A => Boolean) e escolhe +// todos os elementos que satisfazem o predicado +List(1, 2, 3) filter (_ > 2) // List(3) +case class Pessoa(nome: String, idade: Int) +List( + Pessoa(nome = "Dom", idade = 23), + Pessoa(nome = "Bob", idade = 30) +).filter(_.idade > 25) // List(Pessoa("Bob", 30)) + + +// O método foreach recebe uma função de A => Unit, executando essa função em +// cada elemento da colecção +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// Compreensões For + +for { n <- s } yield quadrado(n) + +val nQuadrado2 = for { n <- s } yield quadrado(n) + +for { n <- nQuadrado2 if n < 10 } yield n + +for { n <- s; nQuadrado = n * n if nQuadrado < 10} yield nQuadrado + +/* Nota: isto não são ciclos for: A semântica de um ciclo é 'repetir', enquanto + que uma compreensão define a relação entre dois conjuntos de dados. */ + + +///////////////////////////////////////////////// +// 8. Implicitos +///////////////////////////////////////////////// + +/* AVISO IMPORTANTE: Implicitos são um conjunto de funcionalidades muito + * poderosas em Scala, que podem ser fácilmente abusadas. Iniciantes devem + * resistir a tentação de usá-los até que compreendam não só como funcionam, + * mas também as melhores práticas. Apenas incluimos esta secção no tutorial + * devido a estes serem tão comuns em bibliotecas de Scala que muitas delas + * se tornam impossíveis de usar sem conhecer implicitos. Este capítulo serve + * para compreender como trabalhar com implicitos, não como declará-los. +*/ + +// Qualquer valor (vals, funções, objectos, etc) pode ser declarado como +// implicito usando a palavra "implicit". Vamos usar a classe Cão da secção 5 +// nestes exemplos + +implicit val oMeuIntImplicito = 100 +implicit def aMinhaFunçãoImplicita(raça: String) = new Cão("Golden " + raça) + +// Por si só, a palavra implicit não altera o comportamento de um valor, sendo +// que estes podem ser usados da forma habitual. +oMeuIntImplicito + 2 // => 102 +aMinhaFunçãoImplicita("Pitbull").raça // => "Golden Pitbull" + +// A diferença é que estes valores podem ser utilizados quando outro pedaço de +// código "necessite" de uma valor implicito. Um exemplo são argumentos +// implicitos de funções: +def enviaCumprimentos(aQuem: String)(implicit quantos: Int) = + s"Olá $aQuem, $quantos cumprimentos para ti e para os teus!" + +// Se dermos um valor a "quantos", a função comporta-se normalmente +enviaCumprimentos("João")(1000) // => "Olá João, 1000 cumprimentos para ti e para os teus!" + +// Mas, se omitirmos o parâmetro implicito, um valor implicito do mesmo tipo é +// usado, neste caso, "oMeuInteiroImplicito" +enviaCumprimentos("Joana") // => "Olá Joana, 100 cumprimentos para ti e para os teus!" + +// Parâmentros implicitos de funções permitem-nos simular classes de tipos de +// outras linguagens funcionais. Isto é tão comum que tem a sua própria notação. +// As seguintes linhas representam a mesma coisa +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... + + +// Outra situação em que o compilador prouca um implicito é se encontrar uma +// expressão +// obj.método(...) +// mas "obj" não possuir um método chamado "método". Neste cso, se houver uma +// conversão implicita A => B, onde A é o tipo de obj, e B possui um método +// chamado "método", a conversão é aplicada. Ou seja, tendo +// aMinhaFunçãoImplicita definida, podemos dizer +"Retriever".raça // => "Golden Retriever" +"Sheperd".ladra // => "Woof, woof!" + +// Neste caso, a String é primeiro convertida para Cão usando a nossa funão, +// sendo depois chamado o método apropriado. Esta é uma funcionalidade +// incrivelmente poderosa, sendo que deve ser usada com cautela. Na verdade, +// ao definir a função implicita, o compilador deve lançar um aviso a insisitir +// que só deve definir a função se souber o que está a fazer. + + +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// + +// Importar coisas +import scala.collection.immutable.List + +// Importar todos os "sub pacotes" +import scala.collection.immutable._ + +// Importar multiplas classes numa linha +import scala.collection.immutable.{List, Map} + +// Renomear uma classe importada usando '=>' +import scala.collection.immutable.{List => ImmutableList} + +// Importar todas as classes excepto algumas. Set e Map são excluidos: +import scala.collection.immutable.{Map => _, Set => _, _} + +// O ponto de entrada de um programa em Scala é definido por un ficheiro .scala +// com um método main: +object Aplicação { + def main(args: Array[String]): Unit = { + // código aqui. + } +} + +// Ficheiros podem conter várias classes o objectos. Compilar com scalac + + + + +// Input e output + +// Ler um ficheiro linha a linha +import scala.io.Source +for(linha <- Source.fromFile("ficheiro.txt").getLines()) + println(linha) + +// Escrever um ficheiro usando o PrintWriter de Java +val writer = new PrintWriter("ficheiro.txt") +writer.write("Escrevendo linha por linha" + util.Properties.lineSeparator) +writer.write("Outra linha aqui" + util.Properties.lineSeparator) +writer.close() + +``` + +## Mais recursos + +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) diff --git a/python.html.markdown b/python.html.markdown index 5572e38e..6cfb5dca 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -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 diff --git a/python3.html.markdown b/python3.html.markdown index acd6187c..cd1a83cc 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -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 diff --git a/ruby.html.markdown b/ruby.html.markdown index 8f23b2e6..fe142365 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -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 diff --git a/scala.html.markdown b/scala.html.markdown index c482752d..7f545196 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -6,7 +6,6 @@ contributors: - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] - ["Ha-Duong Nguyen", "http://reference-error.org"] -filename: learn.scala --- Scala - the scalable language @@ -43,9 +42,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 @@ -240,10 +243,11 @@ i // Show the value of i. Note that while is a loop in the classical sense - // comprehensions above is easier to understand and parallelize // A do while loop +i = 0 do { - println("x is still less than 10") - x += 1 -} while (x < 10) + println("i is still less than 10") + i += 1 +} while (i < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. @@ -562,8 +566,8 @@ sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" // Implicit function parameters enable us to simulate type classes in other // functional languages. It is so often used that it gets its own shorthand. The // following two lines mean the same thing: -def foo[T](implicit c: C[T]) = ... -def foo[T : C] = ... +// def foo[T](implicit c: C[T]) = ... +// def foo[T : C] = ... // Another situation in which the compiler looks for an implicit is if you have diff --git a/swift.html.markdown b/swift.html.markdown index 75535e43..f451288d 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -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]() |