From 3f5251edf9acb6c64d6f3dfadafe587a218b902b Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 12:12:50 +0200 Subject: Intial file created for TypeScript Not all content but it's a good start --- typescript.html.markdown | 75 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 typescript.html.markdown diff --git a/typescript.html.markdown b/typescript.html.markdown new file mode 100644 index 00000000..f0667d49 --- /dev/null +++ b/typescript.html.markdown @@ -0,0 +1,75 @@ +--- +language: TypeScript +contributors: + - ["Philippe Vlérick", "https://github.com/pvlerick"]] +--- + +TypeScript is a language that aims at easing development of large scale applications written in JavaScript. +TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. +It is a superset of JavaScript: any JavaScript code is valid TypeScript code so it can be added seamlessly to any project. +TypeScript code compiles down to JavaScript. + +This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). + +```ts +//There are 4 basic types in TypeScript +var isDone: boolean = false; +var lines: number = 42; +var name: string = "Anders"; + +//However, when it's impossible to know, there is the "Any" type +var notSure: any = 4; +notSure = "maybe a string instead"; +notSure = false; // okay, definitely a boolean + +//For collections, there are typed arrays and generic arrays +var list: number[] = [1, 2, 3]; +//Or, using the generic array type +var list: Array = [1, 2, 3]; + +//For enumerations +enum Color {Red, Green, Blue}; +var c: Color = Color.Green; + +//Lastly, "void" is used in the special case of a function not returning anything +function bigHorribleAlert(): void { + alert("I'm a little annoying box!"); +} + +//Interfaces are structural, anything that has the properties is compliant with the interface. +//In the bellow example, any object that has a name which is a string and an age which is a number is a Person. +//This is called "duck typing". +interface Person { + name: string; + age: number; + + //Interfaces also support optional properties + phone?: number; +} + +//Interfaces can also describe a function type, to describe a function signature +interface SearchFunc { + (source: string, subString: string): boolean; +} +//The type can then be used for functions, and the compiler will be able to check that types are compliants +//Note that only the parameters' types are important, names are not important. +var mySearch: SearchFunc; +mySearch = function(src: string, sub: string) { + var result = source.search(subString); + if (result == -1) { + return false; + } + else { + return true; + } +} + + +``` + +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground). + +## Further Reading + * [TypeScript Official website] (http://www.typescriptlang.org/) + * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) + * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) -- cgit v1.2.3 From fda947d93997ac1253c11ebed6a8c615c49c71f5 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 13:34:41 +0200 Subject: Some re-phrasing and typos --- typescript.html.markdown | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index f0667d49..410cd6e4 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -6,18 +6,19 @@ contributors: TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: any JavaScript code is valid TypeScript code so it can be added seamlessly to any project. -TypeScript code compiles down to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. In turn, the TypeScript compiler transform the code to JavaScript. This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the resulting JavaScript. + ```ts -//There are 4 basic types in TypeScript +//There are 3 basic types in TypeScript var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//However, when it's impossible to know, there is the "Any" type +//When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean @@ -67,7 +68,7 @@ mySearch = function(src: string, sub: string) { ``` -To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground). + ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) -- cgit v1.2.3 From 7f2256b2e65cb72ef87a5cff0a63bc4982a5e496 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:40:21 +0200 Subject: Tutorial on classes and functions added TODO: more on indexers, check the comment emitted twice for f2 function --- typescript.html.markdown | 82 ++++++++++++++++++++++++++++++++++-------------- 1 file changed, 59 insertions(+), 23 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 410cd6e4..3363426a 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -6,11 +6,11 @@ contributors: TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. In turn, the TypeScript compiler transform the code to JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emitts JavaScript. -This article will focus only on TypeScript added syntax, everything else is plain [JavaScript] (../javascript/). +This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). -To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the resulting JavaScript. +To test TypeScript's compiler, head to the [Playground] (http://www.typescriptlang.org/Playground) where you will be able to type code, have auto completion and directly see the emitted JavaScript. ```ts //There are 3 basic types in TypeScript @@ -25,10 +25,10 @@ notSure = false; // okay, definitely a boolean //For collections, there are typed arrays and generic arrays var list: number[] = [1, 2, 3]; -//Or, using the generic array type +//Alternatively, using the generic array type var list: Array = [1, 2, 3]; -//For enumerations +//For enumerations: enum Color {Red, Green, Blue}; var c: Color = Color.Green; @@ -37,40 +37,76 @@ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Interfaces are structural, anything that has the properties is compliant with the interface. -//In the bellow example, any object that has a name which is a string and an age which is a number is a Person. -//This is called "duck typing". +//Functions are first class citizens, have a shortened definition and can leverage the strong type inference +//All examples are equivalent, the same signature will be infered by the compiler and the same JavaScript will be emitted +var f1 = function(i: number) : number { return i * i; } +var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! +var f3 = (i : number) : number => { return i * i; } +var f4 = (i: number) => { return i * i; } //Return type infered +var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed + +//Interfaces are structural, anything that has the properties is compliant with the interface (duck typing) interface Person { name: string; - age: number; - - //Interfaces also support optional properties - phone?: number; + //Optional properties, marked with a "?" + age?: number; +} +//Object that implements the "Person" interface +var p : Person = { name: "Bobby" }; //Can be treated as a Person since it has the name and age properties +//Objects that have the optional property: +var validPerson : Person = { name: "Bobby", age: 42 }; +var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number + +//Interfaces can also define method signatures: +interface PersonWhoCanTalk { + sayHello(otherPersonsName: string): void; +} + +//And also indexers, both with number and string +interface PersonWhoCanBeIndexed { + [index: number]: string; } +//TODO -//Interfaces can also describe a function type, to describe a function signature +//Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//The type can then be used for functions, and the compiler will be able to check that types are compliants -//Note that only the parameters' types are important, names are not important. +//Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { - var result = source.search(subString); - if (result == -1) { - return false; - } - else { - return true; - } + return src.search(sub) != -1; } +//Classes +class Point { + //Properties + x: number; + + //Constructor - the public keyword is a shortcut to generate the code for a property and it's initialization, equivalent to "x" in this case + constructor(x: number, public y: number) { + this.x = x; + } + + //Functions + dist() { return Math.sqrt(this.x * this.x + this.y * this.y); } + + //Static members + static origin = new Point(0, 0); +} -``` +var p = new Point(10 ,20); +//Generics +//Including references to a definition file +/// + +``` ## Further Reading * [TypeScript Official website] (http://www.typescriptlang.org/) * [TypeScript language specifications (pdf)] (http://go.microsoft.com/fwlink/?LinkId=267238) * [Anders Hejlsberg - Introducing TypeScript on Channel 9] (http://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript) + * [Source Code on GitHub] (https://github.com/Microsoft/TypeScript) + * [Definitely Typed - repository for type definitions] (http://definitelytyped.org/) -- cgit v1.2.3 From 7d0adf66eab5d391d63c2bcf0fd6b1291d781a22 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:56:30 +0200 Subject: Added inheritance and overwrite examples --- typescript.html.markdown | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3363426a..3da7bca2 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -83,8 +83,10 @@ class Point { //Properties x: number; - //Constructor - the public keyword is a shortcut to generate the code for a property and it's initialization, equivalent to "x" in this case - constructor(x: number, public y: number) { + //Constructor - the public/private keywords are shortcuts to generate the code for a property and its initialization + //Equivalent to "x" in this case + //Default values are also supported + constructor(x: number, public y: number = 0) { this.x = x; } @@ -95,7 +97,23 @@ class Point { static origin = new Point(0, 0); } -var p = new Point(10 ,20); +var p1 = new Point(10 ,20); +var p2 = new Point(25); //y will be 0 + +//Inheritance +class Point3D extends Point { + constructor(x: number, y: number, public z: number = 0) { + super(x, y); //Explicit call to the super class constructor is mandatory + } + + /Overwrite + dist() { + var d = super.dist(); + return Math.sqrt(d * d + this.z * this.z); + } +} + +//Modules //Generics -- cgit v1.2.3 From b5ccc1d83cfbc1d11ca32e44708fc1eb339027c0 Mon Sep 17 00:00:00 2001 From: Philippe Date: Thu, 14 Aug 2014 15:58:34 +0200 Subject: Small typos --- typescript.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3da7bca2..8209fedb 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -37,8 +37,8 @@ function bigHorribleAlert(): void { alert("I'm a little annoying box!"); } -//Functions are first class citizens, have a shortened definition and can leverage the strong type inference -//All examples are equivalent, the same signature will be infered by the compiler and the same JavaScript will be emitted +//Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference +//All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted var f1 = function(i: number) : number { return i * i; } var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! var f3 = (i : number) : number => { return i * i; } @@ -106,7 +106,7 @@ class Point3D extends Point { super(x, y); //Explicit call to the super class constructor is mandatory } - /Overwrite + //Overwrite dist() { var d = super.dist(); return Math.sqrt(d * d + this.z * this.z); @@ -117,7 +117,7 @@ class Point3D extends Point { //Generics -//Including references to a definition file +//Including references to a definition file: /// ``` -- cgit v1.2.3 From 7bfbec395acc3ddd61b9cc1d7c4b0ee3877f250b Mon Sep 17 00:00:00 2001 From: Samuel Marks Date: Sat, 23 Aug 2014 16:54:13 +1000 Subject: -ne not equal --- bash.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bash.html.markdown b/bash.html.markdown index 061d35b0..57fb5c55 100644 --- a/bash.html.markdown +++ b/bash.html.markdown @@ -73,9 +73,9 @@ echo Hello, $NAME! # use 'man test' for more info about conditionals if [ $NAME -ne $USER ] then - echo "Your name is your username" -else echo "Your name isn't your username" +else + echo "Your name is your username" fi # There is also conditional execution -- cgit v1.2.3 From 53696bd547736eafd3233e9626838610b696a1d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Ferrero?= Date: Sun, 24 Aug 2014 22:42:11 +0200 Subject: Update perl-es.html.markdown Typos, passive form eliminated --- es-es/perl-es.html.markdown | 106 ++++++++++++++++++++------------------------ 1 file changed, 49 insertions(+), 57 deletions(-) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index 4f0c26c1..fecaf5c4 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -7,23 +7,24 @@ contributors: - ["Korjavin Ivan", "http://github.com/korjavin"] translators: - ["Francisco Gomez", "http://github.com/frncscgmz"] + - ["Joaquín Ferrero", "http://github.com/joaquinferrero"] lang: es-es --- -Perl 5 es un lenguaje de programación altamente capaz, rico en características con mas de 25 años de desarrollo. +Perl 5 es un lenguaje de programación altamente capaz, rico en características, con más de 25 años de desarrollo. -Perl 5 corre en mas de 100 plataformas desde portales hasta mainframes y es adecuado para realizar prototipos rápidos hasta desarrollar proyectos a gran escala. +Perl 5 corre en más de 100 plataformas, desde portátiles hasta ordenadores centrales, y es adecuado para realizar desde prototipos rápidos hasta desarrollar proyectos a gran escala. ```perl -# Comentarios de una sola linea con un carácter hash. +# Comentarios de una sola línea con un carácter hash #### Tipos de variables en Perl -# Las variables comienzan con el símbolo $. -# Un nombre de variable valido empieza con una letra o un guión bajo, -# seguido por cualquier numero de letras, números o guiones bajos. +# Las variables comienzan con el símbolo $ +# Un nombre de variable válido empieza con una letra o un guión bajo, +# seguido por cualquier número de letras, números o guiones bajos -### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes. +### Perl tiene tres tipos principales de variables: escalares, arreglos y hashes ## Escalares # Un escalar representa un solo valor: @@ -31,7 +32,7 @@ my $animal = "camello"; my $respuesta = 42; # Los valores escalares pueden ser cadenas de caracteres, números enteros o -# de punto flotante, Perl automáticamente los convertirá como sea requerido. +# de punto flotante; Perl automáticamente los convertirá como sea requerido ## Arreglos # Un arreglo representa una lista de valores: @@ -39,91 +40,86 @@ my @animales = {"camello","llama","buho"}; my @numeros = {23,42,69}; my @mixto = {"camello",42,1.23}; - - ## Hashes -# Un hash representa un conjunto de pares llave/valor: - +# Un hash representa un conjunto de pares llave/valor: my %color_fruta = {"manzana","rojo","banana","amarillo"}; -# Puedes usar un espacio en blanco y el operador "=>" para asignarlos mas -# fácilmente. - +# Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente my %color_fruta = ( manzana => "rojo", banana => "amarillo", ); -# Los escalares, arreglos y hashes están mas documentados en perldata. (perldoc perldata). -# Los tipos de datos mas complejos pueden ser construidos utilizando -# referencias, las cuales te permiten construir listas y hashes dentro -# de listas y hashes. +# Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata) -#### Estructuras condicionales y de ciclos +# Los tipos de datos más complejos se pueden construir utilizando +# referencias, las cuales le permiten construir listas y hashes dentro +# de listas y hashes -# Perl tiene la mayoría de las estructuras condicionales y de ciclos mas comunes. +#### Estructuras condicionales y de ciclos +# Perl tiene la mayoría de las estructuras condicionales y de ciclos más comunes if ( $var ) { - ... + ...; } elsif ( $var eq 'bar' ) { - ... + ...; } else { - ... + ...; } unless ( condicion ) { - ... - } -# Esto es proporcionado como una version mas fácil de leer que "if (!condición)" + ...; +} + +# Esto se ofrece como una versión más fácil de leer que "if (!condición)" -# La post condición al modo Perl +# La postcondición al modo Perl: print "Yow!" if $zippy; print "No tenemos bananas" unless $bananas; # while - while ( condicion ) { - ... - } - +while ( condicion ) { + ...; +} # for y foreach for ($i = 0; $i <= $max; $i++) { - ... - } + ...; +} foreach (@array) { - print "Este elemento es $_\n"; - } + print "Este elemento es $_\n"; +} #### Expresiones regulares -# El soporte de expresiones regulares en Perl es muy amplio y profundo, y es -# sujeto a una extensa documentación en perlrequick, perlretut, entre otros. +# El soporte de expresiones regulares en Perl es muy amplio y profundo, y +# está sujeto a una extensa documentación en perlrequick, perlretut, entre otros. # Sin embargo, resumiendo: -# Pareo simple +# Coincidencia simple if (/foo/) { ... } # verdadero si $_ contiene "foo" if ($a =~ /foo/) { ... } # verdadero si $a contiene "foo" # Substitución simple -$a =~ s/foo/bar/; # remplaza foo con bar en $a -$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de foo con bar en $a +$a =~ s/foo/bar/; # remplaza "foo" con "bar" en $a +$a =~ s/foo/bar/g; # remplaza TODAS LAS INSTANCIAS de "foo" con "bar" en $a -#### Archivos e I/O +#### Archivos y E/S -# Puedes abrir un archivo para obtener datos o escribirlos utilizando la -# función "open()". +# Puede abrir un archivo para obtener datos o escribirlos utilizando la +# función "open()" open(my $entrada, "<" "entrada.txt") or die "No es posible abrir entrada.txt: $!"; open(my $salida, ">", "salida.txt") or die "No es posible abrir salida.txt: $!"; open(my $log, ">>", "mi.log") or die "No es posible abrir mi.log: $!"; -# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>" -# operador. En contexto escalar leer una sola linea desde el gestor de -# archivo, y en contexto de lista leer el archivo completo en donde, asigna -# cada linea a un elemento de la lista. +# Es posible leer desde un gestor de archivo abierto utilizando el operador "<>". +# En contexto escalar, leer una sola línea desde el gestor de archivo, y +# en contexto de lista, leer el archivo completo en donde asigna +# cada línea a un elemento de la lista my $linea = <$entrada>; my @lineas = <$entrada>; @@ -131,30 +127,26 @@ my @lineas = <$entrada>; #### Escribiendo subrutinas # Escribir subrutinas es fácil: - sub logger { my $mensajelog = shift; open my $archivolog, ">>", "mi.log" or die "No es posible abrir mi.log: $!"; print $archivolog $mensajelog; } -# Ahora podemos utilizar la subrutina al igual que cualquier otra función -# incorporada: - +# Ahora podemos utilizar la subrutina al igual que cualquier otra función incorporada: logger("Tenemos una subrutina logger!"); - ``` #### Utilizando módulos Perl -Los módulos en Perl proveen una gama de funciones que te pueden ayudar a evitar reinventar la rueda, estas pueden ser descargadas desde CPAN( http://www.cpan.org/ ). Algunos de los módulos mas populares ya están incluidos con la misma distribución de Perl. +Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl. -perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos CPAN para usar. +perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar. #### Material de Lectura - [perl-tutorial](http://perl-tutorial.org/) - - [Aprende en www.perl.com](http://www.perl.org/learn.html) + - [Learn Perl](http://www.perl.org/learn.html) - [perldoc](http://perldoc.perl.org/) - - y perl incorporado: `perldoc perlintro` + - y en su propio perl: `perldoc perlintro` -- cgit v1.2.3 From 5f15d684efd831a6b048f2d42ea66f2494728d7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joaqu=C3=ADn=20Ferrero?= Date: Sun, 24 Aug 2014 22:56:09 +0200 Subject: Update perl-es.html.markdown Perl syntax errors. --- es-es/perl-es.html.markdown | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index fecaf5c4..644182ff 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -36,19 +36,19 @@ my $respuesta = 42; ## Arreglos # Un arreglo representa una lista de valores: -my @animales = {"camello","llama","buho"}; -my @numeros = {23,42,69}; -my @mixto = {"camello",42,1.23}; +my @animales = ("camello","llama","buho"}; +my @numeros = (23, 42, 69); +my @mixto = ("camello", 42, 1.23); ## Hashes # Un hash representa un conjunto de pares llave/valor: -my %color_fruta = {"manzana","rojo","banana","amarillo"}; +my %color_fruta = ("manzana","rojo","banana","amarillo"); # Puede usar un espacio en blanco y el operador "=>" para asignarlos más fácilmente my %color_fruta = ( manzana => "rojo", banana => "amarillo", - ); +); # Los escalares, arreglos y hashes están más documentados en perldata (perldoc perldata) @@ -87,6 +87,10 @@ for ($i = 0; $i <= $max; $i++) { ...; } +for $i (0 .. $max) { + ...; +} + foreach (@array) { print "Este elemento es $_\n"; } -- cgit v1.2.3 From 3771906a8c93eeca9333189db5cf3374c69e085a Mon Sep 17 00:00:00 2001 From: Michael Bock Date: Mon, 25 Aug 2014 00:13:59 -0700 Subject: Fix typo in scala "less then" -> "less than" --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 6b398b4b..379c092c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less then 10"); + println("x is still less than 10"); x += 1 } while (x < 10) -- cgit v1.2.3 From 54bd312f8de72d4ca109fb12351b44203a482d23 Mon Sep 17 00:00:00 2001 From: "Janne R." Date: Tue, 26 Aug 2014 20:48:35 +0300 Subject: Use preferred shorthand syntax for dictionary type --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index a47b085a..a0ea8519 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -39,7 +39,7 @@ var occupations = [ "kaylee": "Mechanic" ] occupations["Jayne"] = "Public Relations" -let emptyDictionary = Dictionary() +let emptyDictionary = [String: Float]() // -- cgit v1.2.3 From 013112b9b338d5f05d33e6d1d85e39e7f061285d Mon Sep 17 00:00:00 2001 From: Nami-Doc Date: Wed, 27 Aug 2014 12:38:23 +0200 Subject: Clarifications about *+* and ... with a sub mrf++ --- perl6.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 4ab90914..fe5b197c 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -488,6 +488,7 @@ sub truthy-array(@array) { # (it'll stop at the furthest operator in the current expression) my @arrayplus3 = map(*+3, @array); # `*+3` is the same as `{ $_ + 3 }` my @arrayplus3 = map(*+*+3, @array); # Same as `-> $a, $b { $a + $b + 3 }` + # also `sub ($a, $b) { $a + $b + 3 }` say (*/2)(4); #=> 2 # Immediatly execute the function Whatever created. say ((*+3)/5)(5); #=> 1.6 @@ -496,7 +497,8 @@ say ((*+3)/5)(5); #=> 1.6 # But if you need to have more than one argument (`$_`) # in a block (without wanting to resort to `-> {}`), # you can also use the implicit argument syntax, `$^` : -map({ $^a + $^b + 3 }, @array); # same as the above +map({ $^a + $^b + 3 }, @array); # equivalent to following: +map(sub ($a, $b) { $a + $b + 3 }, @array); # (here with `sub`) # Note : those are sorted lexicographically. # `{ $^b / $^a }` is like `-> $a, $b { $b / $a }` @@ -1072,6 +1074,11 @@ my @list = 1, 3, 9 ... { $_ > 30 }; # (equivalent to the above) my @fib = 1, 1, *+* ... *; # lazy infinite list of prime numbers, # computed using a closure! my @fib = 1, 1, -> $a, $b { $a + $b } ... *; # (equivalent to the above) +my @fib = 1, 1, { $^a + $^b } ... *; #(... also equivalent to the above) +# $a and $b will always take the previous values, meaning here +# they'll start with $a = 1 and $b = 1 (values we set by hand). +# then $a = 1 and $b = 2 (result from previous $a+$b), and so on. + say @fib[^10]; #=> 1 1 2 3 5 8 13 21 34 55 # (using a range as the index) # Note : as for ranges, once reified, elements aren't re-calculated. -- cgit v1.2.3 From 0d022b14c0d11314d29211b862ac65095ceba26c Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 27 Aug 2014 15:41:12 +0200 Subject: Added section on Modules Indented comments and edited the Interfaces part. Still missing indexers and Generics. --- typescript.html.markdown | 50 ++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 8209fedb..74e98d14 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -18,7 +18,7 @@ var isDone: boolean = false; var lines: number = 42; var name: string = "Anders"; -//When it's impossible to know, there is the "Any" type +//..When it's impossible to know, there is the "Any" type var notSure: any = 4; notSure = "maybe a string instead"; notSure = false; // okay, definitely a boolean @@ -50,40 +50,32 @@ interface Person { name: string; //Optional properties, marked with a "?" age?: number; -} -//Object that implements the "Person" interface -var p : Person = { name: "Bobby" }; //Can be treated as a Person since it has the name and age properties -//Objects that have the optional property: -var validPerson : Person = { name: "Bobby", age: 42 }; -var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number - -//Interfaces can also define method signatures: -interface PersonWhoCanTalk { - sayHello(otherPersonsName: string): void; + //And of course functions + move(): void; } -//And also indexers, both with number and string -interface PersonWhoCanBeIndexed { - [index: number]: string; -} -//TODO +//..Object that implements the "Person" interface +var p : Person = { name: "Bobby", move : () => {} }; //Can be treated as a Person since it has the name and age properties +//..Objects that have the optional property: +var validPerson : Person = { name: "Bobby", age: 42, move: () => {} }; +var invalidPerson : Person = { name: "Bobby", age: true }; //Is not a person because age is not a number -//Interfaces can also describe a function type +//..Interfaces can also describe a function type interface SearchFunc { (source: string, subString: string): boolean; } -//Only the parameters' types are important, names are not important. +//..Only the parameters' types are important, names are not important. var mySearch: SearchFunc; mySearch = function(src: string, sub: string) { return src.search(sub) != -1; } -//Classes +//Classes - members are public by default class Point { //Properties x: number; - //Constructor - the public/private keywords are shortcuts to generate the code for a property and its initialization + //Constructor - the public/private keywords in this context are shortcuts to generate the code for a property //Equivalent to "x" in this case //Default values are also supported constructor(x: number, public y: number = 0) { @@ -113,7 +105,23 @@ class Point3D extends Point { } } -//Modules +//Modules, "." can be used as separators for sub modules +module Geometry { + export class Square { + constructor(public sideLength: number = 0) { + } + area() { + return Math.pow(this.sideLength, 2); + } + } +} + +var s1 = new Geometry.Square(5); + +//..Local alias for rreferencing a module +import G = Geometry; + +var s2 = new G.Square(10); //Generics -- cgit v1.2.3 From bfa04112e8e788bea9dc53cdef1659961c7882cb Mon Sep 17 00:00:00 2001 From: Philippe Date: Wed, 27 Aug 2014 16:14:57 +0200 Subject: Added filename in header --- typescript.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index 74e98d14..fd22cbef 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -2,6 +2,7 @@ language: TypeScript contributors: - ["Philippe Vlérick", "https://github.com/pvlerick"]] +filename: learntypescript.ts --- TypeScript is a language that aims at easing development of large scale applications written in JavaScript. -- cgit v1.2.3 From c9400c2a7d5262651884fffecda83ace1bfc4d97 Mon Sep 17 00:00:00 2001 From: Assaf Gelber Date: Thu, 28 Aug 2014 14:00:25 +0300 Subject: Change swift class name to Square --- swift.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/swift.html.markdown b/swift.html.markdown index a0ea8519..6d98b067 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -157,7 +157,7 @@ print(numbers) // [3, 6, 18] // structured object, you should use a `struct` // A simple class `Square` extends `Shape` -class Rect: Shape { +class Square: Shape { var sideLength: Int = 1 // Custom getter and setter property -- cgit v1.2.3 From 2c56f7bed41f7b7e26989374020d68f1f0f9ebe5 Mon Sep 17 00:00:00 2001 From: Philippe Date: Sun, 31 Aug 2014 17:57:44 +0200 Subject: Generics added And a few typos corrected, ready for pull request --- typescript.html.markdown | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index fd22cbef..3ba1300d 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -41,7 +41,7 @@ function bigHorribleAlert(): void { //Functions are first class citizens, support the lambda "fat arrow" syntax and use type inference //All examples are equivalent, the same signature will be infered by the compiler, and same JavaScript will be emitted var f1 = function(i: number) : number { return i * i; } -var f2 = function(i: number) { return i * i; } //Return type infered #TODO bug! +var f2 = function(i: number) { return i * i; } //Return type infered var f3 = (i : number) : number => { return i * i; } var f4 = (i: number) => { return i * i; } //Return type infered var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed @@ -119,12 +119,30 @@ module Geometry { var s1 = new Geometry.Square(5); -//..Local alias for rreferencing a module +//..Local alias for referencing a module import G = Geometry; var s2 = new G.Square(10); //Generics +//..Classes +class Tuple { + constructor(public item1: T1, public item2: T2) { + } +} + +//..Interfaces +interface Pair { + item1: T; + item2: T; +} + +//..And functions +var pairToTuple = function(p: Pair) { + return new Tuple(p.item1, p.item2); +}; + +var tuple = pairToTuple({ item1:"hello", item2:"world"}); //Including references to a definition file: /// -- cgit v1.2.3 From 199e2e8726fd913b4accc9e94c386c0cb26fb447 Mon Sep 17 00:00:00 2001 From: Fredrik Dyrkell Date: Sun, 31 Aug 2014 23:26:56 +0200 Subject: Learn Purescript in Y minutes --- purescript.html.markdown | 195 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 purescript.html.markdown diff --git a/purescript.html.markdown b/purescript.html.markdown new file mode 100644 index 00000000..6bff7545 --- /dev/null +++ b/purescript.html.markdown @@ -0,0 +1,195 @@ +--- +language: purescript +contributors: + - ["Fredrik Dyrkell", "http://www.lexicallyscoped.com"] +--- + +PureScript is a small strongly, statically typed language compiling to Javascript. + +* Learn more at [http://www.purescript.org/](http://www.purescript.org/) +* Documentation: [http://docs.purescript.org/en/latest/](http://docs.purescript.org/en/latest/) +* Book: Purescript by Example, [https://leanpub.com/purescript/](https://leanpub.com/purescript/) + +```haskell + +-- +-- 1. Primitive datatypes that corresponds to their Javascript +-- equivalents at runtime. + +-- Numbers +1 + 7*5 :: Number -- 36 +-- Types are inferred, so the following works fine +9 / 2.5 + 4.4 -- 8 +-- Hexadecimal literals +0xff + 1 -- 256 +-- Unary negation +6 * -3 -- -18 +6 * negate 3 -- -18 +-- Modulus +3 % 2 -- 1 +4 % 2 -- 0 +-- Inspect the type of an expression in psci +:t 9 / 2.5 + 4.4 -- Prim.Number + +-- Booleans +true :: Boolean -- true +false :: Boolean -- false +-- Negation +not true --false +23 == 23 -- true +1 /= 4 -- true +1 >= 4 -- false +-- Comparisions < <= > >= +-- are defined in terms of compare +compare 1 2 -- LT +compare 2 2 -- EQ +compare 3 2 -- GT +-- Conjunction and Disjunction +true && (9 >= 19 || 1 < 2) -- true + +-- Strings +"Hellow" :: String -- "Hellow" +-- Multiline string +"Hellow\ +\orld" -- "Helloworld" +-- Concatenate +"such " ++ "amaze" -- "such amaze" + +-- +-- 2. Arrays are Javascript arrays, but must be homogeneous + +[1,1,2,3,5,8] :: [Number] -- [1,1,2,3,5,8] +[true, true, false] :: [Boolean] -- [true,true,false] +-- [1,2, true, "false"] won't work +-- `Cannot unify Prim.Number with Prim.Boolean` +-- Cons (prepend) +1 : [2,4,3] -- [1,2,4,3] + +-- Requires purescript-arrays (Data.Array) +-- and purescript-maybe (Data.Maybe) + +-- Safe access return Maybe a +head [1,2,3] -- Just (1) +tail [3,2,1] -- Just ([2,1]) +init [1,2,3] -- Just ([1,2]) +last [3,2,1] -- Just (1) +-- Random access - indexing +[3,4,5,6,7] !! 2 -- Just (5) +-- Range +1..5 -- [1,2,3,4,5] +length [2,2,2] -- 3 +drop 3 [5,4,3,2,1] -- [2,1] +take 3 [5,4,3,2,1] -- [5,4,3] +append [1,2,3] [4,5,6] -- [1,2,3,4,5,6] + +-- +-- 3. Records are Javascript objects, with zero or more fields, which +-- can have different types +let book = {title: "Foucault's pendulum", author: "Umberto Eco"} +-- Access properties +book.title -- "Foucault's pendulum" + +getTitle b = b.title +-- Works on all records with a title (but doesn't require any other field) +getTitle book -- "Foucault's pendulum" +getTitle {title: "Weekend in Monaco", artist: "The Rippingtons"} -- "Weekend in Monaco" +-- Update a record +changeTitle b t = b {title = t} +changeTitle book "Ill nome della rosa" -- {title: "Ill nome della + -- rosa", author: "Umberto Eco"} + +-- +-- 4. Functions +sumOfSquares x y = x*x+y*y +sumOfSquares 3 4 -- 25 +-- In psci you have to write `let` in front of the function to get a +-- top level binding +mod x y = x % y +mod 3 2 -- 1 +-- Infix application of function +3 `mod` 2 -- 1 + +-- function application have higher precedence than all other +-- operators +sumOfSquares 3 4 * sumOfSquares 4 5 -- 1025 + +-- Conditional +abs' n = if n>=0 then n else -n +abs' (-3) -- 3 + +-- Guarded equations +abs n | n >= 0 = n + | otherwise = -n + +-- Pattern matching + +-- Note the type signature, input is an array of numbers The pattern +-- matching destructures and binds the array into parts +first :: [Number] -> Number +first (x:_) = x +first [3,4,5] -- 3 +second :: [Number] -> Number +second (_:y:_) = y +second [3,4,5] -- 4 +sumTwo :: [Number] -> [Number] +sumTwo (x:y:rest) = (x+y) : rest +sumTwo [2,3,4,5,6] -- [5,4,5,6] + +-- sumTwo doesn't handle when the array is empty or just have one +-- element in which case you get an error +sumTwo [1] -- Failed pattern match + +-- Complementing patterns to match +-- Good ol' Fibonacci +fib 1 = 1 +fib 2 = 2 +fib x = fib (x-1) + fib (x-2) +fib 10 -- 89 + +-- Use underscore to match any, where you don't care about the binding name +isZero 0 = true +isZero _ = false + +-- Pattern matching on records +ecoTitle {author = "Umberto Eco", title = t} = Just t +ecoTitle _ = Nothing + +ecoTitle book -- Just ("Foucault's pendulum") +ecoTitle {title: "The Quantum Thief", author: "Hannu Rajaniemi"} -- Nothing +-- ecoTitle requires both field to type check: +ecoTitle {title: "The Quantum Thief"} -- Object does not have property author + +-- Lambda expressions +(\x -> x*x) 3 -- 9 +(\x y -> x*x + y*y) 4 5 -- 41 +sqr = \x -> x*x + +-- Currying +add x y = x + y -- is equivalent with +add = \x -> (\y -> x+y) +add3 = add 3 +:t add3 -- Prim.Number -> Prim.Number + +-- Forward and backward function composition +-- drop 3 followed by taking 5 +(drop 3 >>> take 5) (1..20) -- [4,5,6,7,8] +-- take 5 followed by dropping 3 +(drop 3 <<< take 5) (1..20) -- [4,5] + +-- Operations using higher order functions +even x = x % 2 == 0 +filter even (1..10) -- [2,4,6,8,10] +map (\x -> x+11) (1..5) -- [12,13,14,15,16] + +-- Requires purescript-foldable-traversabe (Data.Foldable) + +foldr (+) 0 (1..10) -- 55 +sum (1..10) -- 55 +product (1..10) -- 3628800 + +-- Testing with predicate +any even [1,2,3] -- true +all even [1,2,3] -- false + +``` + -- cgit v1.2.3 From ef37db634aa8fc1b21a1542c176339f250678cb2 Mon Sep 17 00:00:00 2001 From: Philippe Date: Mon, 1 Sep 2014 10:51:43 +0200 Subject: Fixed errors and typos After review from from Nami-Doc --- typescript.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/typescript.html.markdown b/typescript.html.markdown index 3ba1300d..8173aac8 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -1,13 +1,13 @@ --- language: TypeScript contributors: - - ["Philippe Vlérick", "https://github.com/pvlerick"]] + - ["Philippe Vlérick", "https://github.com/pvlerick"] filename: learntypescript.ts --- TypeScript is a language that aims at easing development of large scale applications written in JavaScript. TypeScript adds common concepts such as classes, modules, interfaces, generics and (optional) static typing to JavaScript. -It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emitts JavaScript. +It is a superset of JavaScript: all JavaScript code is valid TypeScript code so it can be added seamlessly to any project. The TypeScript compiler emits JavaScript. This article will focus only on TypeScript extra syntax, as oposed to [JavaScript] (../javascript/). @@ -46,7 +46,7 @@ var f3 = (i : number) : number => { return i * i; } var f4 = (i: number) => { return i * i; } //Return type infered var f5 = (i: number) => i * i; //Return type infered, one-liner means no return keyword needed -//Interfaces are structural, anything that has the properties is compliant with the interface (duck typing) +//Interfaces are structural, anything that has the properties is compliant with the interface interface Person { name: string; //Optional properties, marked with a "?" @@ -76,8 +76,9 @@ class Point { //Properties x: number; - //Constructor - the public/private keywords in this context are shortcuts to generate the code for a property - //Equivalent to "x" in this case + //Constructor - the public/private keywords in this context will generate the boiler plate code + // for the property and the initialization in the constructor. + // In this example, "y" will be defined just like "x" is, but with less code //Default values are also supported constructor(x: number, public y: number = 0) { this.x = x; @@ -106,7 +107,7 @@ class Point3D extends Point { } } -//Modules, "." can be used as separators for sub modules +//Modules, "." can be used as separator for sub modules module Geometry { export class Square { constructor(public sideLength: number = 0) { -- cgit v1.2.3 From 12c9653b03271abbd13906058ece129c13f9c055 Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Mon, 1 Sep 2014 11:01:30 -0500 Subject: Fix arrow => array java typo. --- java.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/java.html.markdown b/java.html.markdown index 3484aee5..dffc3828 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -101,7 +101,7 @@ public class LearnJava { // Arrays //The array size must be decided upon instantiation - //The following formats work for declaring an arrow + //The following formats work for declaring an array // [] = new []; // [] = new []; int [] intArray = new int[10]; -- cgit v1.2.3