diff options
-rw-r--r-- | d.html.markdown | 247 | ||||
-rw-r--r-- | fr-fr/livescript-fr.html.markdown | 360 | ||||
-rw-r--r-- | fr-fr/markdown.html.markdown | 2 | ||||
-rw-r--r-- | git.html.markdown | 2 | ||||
-rw-r--r-- | it-it/coffeescript-it.html.markdown | 107 | ||||
-rw-r--r-- | it-it/elixir-it.html.markdown | 418 | ||||
-rw-r--r-- | make.html.markdown | 243 | ||||
-rw-r--r-- | perl6.html.markdown | 2 | ||||
-rw-r--r-- | pt-br/perl-pt.html.markdown | 166 | ||||
-rw-r--r-- | ruby-ecosystem.html.markdown | 2 | ||||
-rw-r--r-- | rust.html.markdown | 2 | ||||
-rw-r--r-- | tr-tr/swift-tr.html.markdown | 590 | ||||
-rw-r--r-- | zh-cn/bash-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/go-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/markdown-cn.html.markdown | 2 |
15 files changed, 2140 insertions, 7 deletions
diff --git a/d.html.markdown b/d.html.markdown new file mode 100644 index 00000000..88c7e37f --- /dev/null +++ b/d.html.markdown @@ -0,0 +1,247 @@ +--- +language: D +filename: learnd.d +contributors: + - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] +lang: en +--- + +```d +// You know what's coming... +module hello; + +import std.stdio; + +// args is optional +void main(string[] args) { + writeln("Hello, World!"); +} +``` + +If you're like me and spend way too much time on the internet, odds are you've heard +about [D](http://dlang.org/). The D programming language is a modern, general-purpose, +multi-paradigm language with support for everything from low-level features to +expressive high-level abstractions. + +D is actively developed by Walter Bright and Andrei Alexandrescu, two super smart, really cool +dudes. With all that out of the way, let's look at some examples! + +```d +import std.stdio; + +void main() { + + // Conditionals and loops work as expected. + for(int i = 0; i < 10000; i++) { + writeln(i); + } + + auto n = 1; // use auto for type inferred variables + + // Numeric literals can use _ as a digit seperator for clarity + while(n < 10_000) { + n += n; + } + + do { + n -= (n / 2); + } while(n > 0); + + // For and while are nice, but in D-land we prefer foreach + // The .. creates a continuous range, excluding the end + foreach(i; 1..1_000_000) { + if(n % 2 == 0) + writeln(i); + } + + foreach_reverse(i; 1..int.max) { + if(n % 2 == 1) { + writeln(i); + } else { + writeln("No!"); + } + } +} +``` + +We can define new types with `struct`, `class`, `union`, and `enum`. Structs and unions +are passed to functions by value (i.e. copied) and classes are passed by reference. Futhermore, +we can use templates to parameterize all of these on both types and values! + +```d +// Here, T is a type parameter. Think <T> from C++/C#/Java +struct LinkedList(T) { + T data = null; + LinkedList!(T)* next; // The ! is used to instaniate a parameterized type. Again, think <T> +} + +class BinTree(T) { + T data = null; + + // If there is only one template parameter, we can omit parens + BinTree!T left; + BinTree!T right; +} + +enum Day { + Sunday, + Monday, + Tuesday, + Wednesday, + Thursday, + Friday, + Saturday, +} + +// Use alias to create abbreviations for types + +alias IntList = LinkedList!int; +alias NumTree = BinTree!double; + +// We can create function templates as well! + +T max(T)(T a, T b) { + if(a < b) + return b; + + return a; +} + +// Use the ref keyword to ensure pass by referece. +// That is, even if a and b are value types, they +// will always be passed by reference to swap +void swap(T)(ref T a, ref T b) { + auto temp = a; + + a = b; + b = temp; +} + +// With templates, we can also parameterize on values, not just types +class Matrix(uint m, uint n, T = int) { + T[m] rows; + T[n] columns; +} + +auto mat = new Matrix!(3, 3); // We've defaulted type T to int + +``` + +Speaking of classes, let's talk about properties for a second. A property +is roughly a function that may act like an lvalue, so we can +have the syntax of POD structures (`structure.x = 7`) with the semantics of +getter and setter methods (`object.setX(7)`)! + +```d +// Consider a class parameterized on a types T, U + +class MyClass(T, U) { + T _data; + U _other; + +} + +// And "getter" and "setter" methods like so +class MyClass(T, U) { + T _data; + U _other; + + // Constructors are always named `this` + this(T t, U u) { + data = t; + other = u; + } + + // getters + @property T data() { + return _data; + } + + @property U other() { + return _other; + } + + // setters + @property void data(T t) { + _data = t; + } + + @property void other(U u) { + _other = u; + } +} +// And we use them in this manner + +void main() { + auto mc = MyClass!(int, string); + + mc.data = 7; + mc.other = "seven"; + + writeln(mc.data); + writeln(mc.other); +} +``` + +With properties, we can add any amount of logic to +our getter and setter methods, and keep the clean syntax of +accessing members directly! + +Other object-oriented goodies at our disposal +include `interface`s, `abstract class`es, +and `override`ing methods. D does inheritance just like Java: +Extend one class, implement as many interfaces as you please. + +We've seen D's OOP facilities, but let's switch gears. D offers +functional programming with first-class functions, `pure` +functions, and immutable data. In addition, all of your favorite +functional algorithms (map, filter, reduce and friends) can be +found in the wonderful `std.algorithm` module! + +```d +import std.algorithm : map, filter, reduce; +import std.range : iota; // builds an end-exclusive range + +void main() { + // We want to print the sum of a list of squares of even ints + // from 1 to 100. Easy! + + // Just pass lambda expressions as template parameters! + // You can pass any old function you like, but lambdas are convenient here. + auto num = iota(1, 101).filter!(x => x % 2 == 0) + .map!(y => y ^^ 2) + .reduce!((a, b) => a + b); + + writeln(num); +} +``` + +Notice how we got to build a nice Haskellian pipeline to compute num? +That's thanks to a D innovation know as Uniform Function Call Syntax. +With UFCS, we can choose whether to write a function call as a method +or free function call! Walter wrote a nice article on this +[here.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +In short, you can call functions whose first parameter +is of some type A on any expression of type A as a method. + +I like parallelism. Anyone else like parallelism? Sure you do. Let's do some! + +```d +import std.stdio; +import std.parallelism : parallel; +import std.math : sqrt; + +void main() { + // We want take the square root every number in our array, + // and take advantage of as many cores as we have available. + auto arr = new double[1_000_000]; + + // Use an index, and an array element by referece, + // and just call parallel on the array! + foreach(i, ref elem; parallel(arr)) { + ref = sqrt(i + 1.0); + } +} + + +``` diff --git a/fr-fr/livescript-fr.html.markdown b/fr-fr/livescript-fr.html.markdown new file mode 100644 index 00000000..9c3b8003 --- /dev/null +++ b/fr-fr/livescript-fr.html.markdown @@ -0,0 +1,360 @@ +--- +language: LiveScript +filename: learnLivescript-fr.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: + - ["Morgan Bohn", "https://github.com/morganbohn"] +lang: fr-fr +--- + +LiveScript est un langage qui compile en JavaScript. Il a un rapport direct +avec JavaScript, et vous permet d'écrire du JavaScript plus simplement, plus +efficacement et sans répétitivité. LiveScript ajoute non seulement des +fonctionnalités pour écrire du code fonctionnel, mais possède aussi nombre +d'améliorations pour la programmation orientée objet et la programmation +impérative. + +LiveScript est un descendant direct de [Coco][], indirect de [CoffeeScript][], +avec lequel il a beaucoup plus de compatibilité. + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +Vous pouvez contacter l'auteur du guide original en anglais ici : +[@kurisuwhyte](https://twitter.com/kurisuwhyte) + + +```coffeescript +# Comme son cousin CoffeeScript, LiveScript utilise le symbole dièse pour les +# commentaires sur une ligne. + +/* + Les commentaires sur plusieurs lignes utilisent la syntaxe du C. Utilisez-les + si vous voulez préserver les commentaires dans la sortie JavaScript. + */ +``` +```coffeescript +# LiveScript utilise l'indentation pour délimiter les blocs de code plutôt que +# les accolades, et les espaces pour appliquer les fonctions (bien que les +# parenthèses soient utilisables). + + +######################################################################## +## 1. Valeurs basiques +######################################################################## + +# Les valeurs non définies sont représentées par le mot clé `void` à la place de +# `undefined` +void # comme `undefined` mais plus sûr (ne peut pas être redéfini) + +# Une valeur non valide est représentée par Null. +null + + +# Les booléens s'utilisent de la façon suivante: +true +false + +# Et il existe divers alias les représentant également: +on; off +yes; no + + +# Puis viennent les nombres entiers et décimaux. +10 +0.4 # Notez que le `0` est requis + +# Dans un souci de lisibilité, vous pouvez utiliser les tirets bas et les +# suffixes sur les nombres. Il seront ignorés à la compilation. +12_344km + + +# Les chaînes sont des séquences immutables de caractères, comme en JS: +"Christina" # Les apostrophes fonctionnent également! +"""Multi-line + strings + are + okay + too.""" + +# De temps à autre, vous voulez encoder un mot clé; la notation en backslash +# rend cela facile: +\keyword # => 'keyword' + + +# Les tableaux sont des collections ordonnées de valeurs. +fruits = + * \apple + * \orange + * \pear + +# Il peuvent être écrits de manière plus consises à l'aide des crochets: +fruits = [ \apple, \orange, \pear ] + +# Vous pouvez également utiliser la syntaxe suivante, à l'aide d'espaces, pour +# créer votre liste de valeurs: +fruits = <[ apple orange pear ]> + +# Vous pouvez récupérer une entrée à l'aide de son index: +fruits[0] # => "apple" + +# Les objets sont une collection non ordonnées de paires clé/valeur, et +# d'autres choses (que nous verrons plus tard). +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# A nouveau, vous pouvez utiliser une expression plus consise à l'aide des +# accolades: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# Vous pouvez récupérer une entrée via sa clé: +person.name # => "Christina" +person["name"] # => "Christina" + + +# Les expressions régulières utilisent la même syntaxe que JavaScript: +trailing-space = /\s$/ # les mots-composés deviennent motscomposés + +# A l'exception que vous pouvez pouvez utiliser des expressions sur plusieurs +# lignes! +# (les commentaires et les espaces seront ignorés) +funRE = // + function\s+(.+) # nom + \s* \((.*)\) \s* # arguments + { (.*) } # corps + // + + +######################################################################## +## 2. Les opérations basiques +######################################################################## + +# Les opérateurs arithmétiques sont les mêmes que pour JavaScript: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# Les comparaisons sont presque identiques, à l'exception que `==` équivaut au +# `===` de JS, là où le `==` de JS est `~=` en LiveScript, et `===` active la +# comparaison d'objets et de tableaux, ainsi que les comparaisons strictes +# (sans conversion de type) +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# Les opérateurs suivants sont également disponibles: <, <=, > et >= + +# Les valeurs logiques peuvent être combinéees grâce aux opérateurs logiques +# `or`, `and` et `not` +true and false # => false +false or true # => true +not false # => true + + +# Les collections ont également des opérateurs additionnels +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. Fonctions +######################################################################## + +# Puisque LiveScript est fonctionnel, vous vous attendez à une bonne prise en +# charge des fonctions. En LiveScript, il est encore plus évident que les +# fonctions sont de premier ordre: +add = (left, right) -> left + right +add 1, 2 # => 3 + +# Les fonctions qui ne prennent pas d'arguments peuvent être appelées avec un +# point d'exclamation! +two = -> 2 +two! + +# LiveScript utilise l'environnement de la fonction, comme JavaScript. +# A l'inverse de JavaScript, le `=` fonctionne comme un opérateur de +# déclaration, et il déclarera toujours la variable située à gauche (sauf si +# la variable a été déclarée dans l'environnement parent). + +# L'opérateur `:=` est disponible pour réutiliser un nom provenant de +# l'environnement parent. + + +# Vous pouvez extraire les arguments d'une fonction pour récupérer +# rapidement les valeurs qui vous intéressent dans une structure de données +# complexe: +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# Vous pouvez également transformer les arguments en utilisant les opérateurs +# binaires et unaires. Définir des arguments par défaut est aussi possible. +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# You pouvez utiliser cela pour cloner un argument en particulier pour éviter +# les effets secondaires. Par exemple: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# Une fonction peut être curryfiée en utilisant une longue flèche à la place +# d'une courte: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# Les fonctions ont un argument `it` implicite si vous n'en déclarez pas: +identity = -> it +identity 1 # => 1 + +# Les opérateurs ne sont pas des fonctions en LiveScript, mais vous pouvez +# facilement les transformer en fonction: +divide-by-two = (/ 2) +[2, 4, 8, 16].map(divide-by-two).reduce (+) + +# Comme dans tout bon langage fonctionnel, vous pouvez créer des fonctions +# composées d'autres fonctions: +double-minus-one = (- 1) . (* 2) + +# En plus de la formule mathématique `f . g`, vous avez les opérateurs `>>` +# et `<<`, qui décrivent l'ordre d'application des fonctions composées. +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# Pour appliquer une valeur à une fonction, vous pouvez utiliser les opérateurs +# `|>` et `<|`: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# La version sans pipe correspond à: +((map (* 2)) [1, 2, 3]) + +# You pouvez aussi choisir où vous voulez que la valeur soit placée, en +# marquant la position avec un tiret bas (_): +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# Le tiret bas est également utilisé pour l'application partielle, +# que vous pouvez utiliser pour toute fonction: +div = (left, right) -> left / right +div-by-two = div _, 2 +div-by-two 4 # => 2 + + +# Pour conclure, LiveScript vous permet d'utiliser les fonctions de rappel. +# (mais vous devriez essayer des approches plus fonctionnelles, comme +# Promises). +# Un fonction de rappel est une fonction qui est passée en argument à une autre +# fonction: +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# Equivalent à: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. Conditionnalités +######################################################################## + +# Vous pouvez faire de la conditionnalité à l'aide de l'expression `if...else`: +x = if n > 0 then \positive else \negative + +# A la place de `then`, vous pouvez utiliser `=>` +x = if n > 0 => \positive + else \negative + +# Pour les conditions complexes, il vaut mieux utiliser l'expresssion `switch`: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` et `_` correspondent. + +# Le corps des fonctions, les déclarations et les assignements disposent d'un +# `switch` implicite, donc vous n'avez pas besoin de le réécrire: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. Compréhensions +######################################################################## + +# Comme en python, vous allez pouvoir utiliser les listes en compréhension, +# ce qui permet de générer rapidement et de manière élégante une liste de +# valeurs: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# `when` et `unless` peuvent être utilisés comme des filtres. + +# Cette technique fonctionne sur les objets de la même manière. Vous allez +# pouvoir générer l'ensemble de paires clé/valeur via la syntaxe suivante: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 4. Programmation orientée objet +######################################################################## + +# Bien que LiveScript soit un langage fonctionnel, il dispose d'intéressants +# outils pour la programmation objet. La syntaxe de déclaration d'une classe +# est héritée de CoffeeScript: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# En plus de l'héritage classique, vous pouvez utiliser autant de mixins +# que vous voulez pour votre classe. Les mixins sont juste des objets: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## Lectures complémentaires + +Il y a beaucoup plus de choses à dire sur LiveScript, mais ce guide devrait +suffire pour démarrer l'écriture de petites fonctionnalités. +Le [site officiel](http://livescript.net/) dispose de beaucoup d'information, +ainsi que d'un compilateur en ligne vous permettant de tester le langage! + +Jetez également un coup d'oeil à [prelude.ls](http://gkz.github.io/prelude-ls/), +et consultez le channel `#livescript` sur le réseau Freenode. diff --git a/fr-fr/markdown.html.markdown b/fr-fr/markdown.html.markdown index 29c0d65d..e5e7c73a 100644 --- a/fr-fr/markdown.html.markdown +++ b/fr-fr/markdown.html.markdown @@ -177,7 +177,7 @@ des syntaxes spécifiques --> \`\`\`ruby <!-- mais enlevez les backslashes quand vous faites ça, -gardez juste ```ruby ( ou nom de la synatxe correspondant à votre code )--> +gardez juste ```ruby ( ou nom de la syntaxe correspondant à votre code )--> def foobar puts "Hello world!" end diff --git a/git.html.markdown b/git.html.markdown index 4bbc58e7..bf8fce0c 100644 --- a/git.html.markdown +++ b/git.html.markdown @@ -462,6 +462,8 @@ $ git rm /pather/to/the/file/HelloWorld.c * [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) +* [Udemy Git Tutorial: A Comprehensive Guide](https://blog.udemy.com/git-tutorial-a-comprehensive-guide/) + * [git-scm - Video Tutorials](http://git-scm.com/videos) * [git-scm - Documentation](http://git-scm.com/docs) diff --git a/it-it/coffeescript-it.html.markdown b/it-it/coffeescript-it.html.markdown new file mode 100644 index 00000000..16eb9bd4 --- /dev/null +++ b/it-it/coffeescript-it.html.markdown @@ -0,0 +1,107 @@ +--- +language: coffeescript +contributors: + - ["Luca 'Kino' Maroni", "http://github.com/kino90"] + - ["Tenor Biel", "http://github.com/L8D"] + - ["Xavier Yao", "http://github.com/xavieryao"] +filename: coffeescript-it.coffee +lang: it-it +--- + +CoffeeScript è un piccolo linguaggio che compila direttamente nell'equivalente +JavaScript, non c'è nessuna interpretazione a runtime. Come possibile +successore di Javascript, CoffeeScript fa il suo meglio per restituire +un codice leggibile, ben stampato e performante in ogni ambiente JavaScript. + +Guarda anche [il sito di CoffeeScript](http://coffeescript.org/), che ha una +guida completa a CoffeeScript. + +```coffeescript +# CoffeeScript è un linguaggio hipster. +# Segue le mode di alcuni linguaggi moderni. +# Quindi i commenti sono come quelli di Ruby e Python, usano il cancelletto. + +### +I blocchi di commenti sono definiti con tre cancelletti, che vengono tradotti +direttamente in `/*` e `*/` nel codice JavaScript risultante. + +Prima di continuare devi conoscere la maggior parte +delle semantiche JavaScript. +### + +# Assegnamento: +numero = 42 #=> var numero = 42; +contrario = true #=> var contrario = true; + +# Condizioni: +numero = -42 if contrario #=> if(contrario) { numero = -42; } + +# Funzioni: +quadrato = (x) -> x * x #=> var quadrato = function(x) { return x * x; } + +riempi = (contenitore, liquido = "caffè") -> + "Sto riempiendo #{contenitore} con #{liquido}..." +#=>var riempi; +# +#riempi = function(contenitore, liquido) { +# if (liquido == null) { +# liquido = "caffè"; +# } +# return "Sto riempiendo " + contenitore + " con " + liquido + "..."; +#}; + +# Intervalli: +lista = [1..5] #=> var lista = [1, 2, 3, 4, 5]; + +# Oggetti: +matematica = + radice: Math.sqrt + quadrato: quadrato + cubo: (x) -> x * quadrato x +#=> var matematica = { +# "radice": Math.sqrt, +# "quadrato": quadrato, +# "cubo": function(x) { return x * quadrato(x); } +#} + +# Splats: +gara = (vincitore, partecipanti...) -> + print vincitore, partecipanti +#=>gara = function() { +# var partecipanti, vincitore; +# vincitore = arguments[0], partecipanti = 2 <= arguments.length ? __slice.call(arguments, 1) : []; +# return print(vincitore, partecipanti); +#}; + +# Esistenza: +alert "Lo sapevo!" if elvis? +#=> if(typeof elvis !== "undefined" && elvis !== null) { alert("Lo sapevo!"); } + +# Comprensione degli Array: +cubi = (matematica.cubo num for num in lista) +#=>cubi = (function() { +# var _i, _len, _results; +# _results = []; +# for (_i = 0, _len = lista.length; _i < _len; _i++) { +# num = lista[_i]; +# _results.push(matematica.cubo(num)); +# } +# return _results; +# })(); + +cibi = ['broccoli', 'spinaci', 'cioccolato'] +mangia cibo for cibo in cibi when cibo isnt 'cioccolato' +#=>cibi = ['broccoli', 'spinaci', 'cioccolato']; +# +#for (_k = 0, _len2 = cibi.length; _k < _len2; _k++) { +# cibo = cibi[_k]; +# if (cibo !== 'cioccolato') { +# mangia(cibo); +# } +#} +``` + +## Altre risorse + +- [Smooth CoffeeScript](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto](https://leanpub.com/coffeescript-ristretto/read) diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown new file mode 100644 index 00000000..f5d0c172 --- /dev/null +++ b/it-it/elixir-it.html.markdown @@ -0,0 +1,418 @@ +--- +language: elixir +contributors: + - ["Luca 'Kino' Maroni", "https://github.com/kino90"] + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] +filename: learnelixir-it.ex +lang: it-it +--- + +Elixir è un linguaggio funzionale moderno, costruito sulla VM Erlang. +È totalmente compatibile con Erlang, ma con una sintassi più standard +e molte altre funzionalità. + +```elixir + +# I commenti su una riga iniziano con un cancelletto. + +# Non esistono commenti multilinea, +# ma puoi concatenare più commenti. + +# Per usare la shell di elixir usa il comando `iex`. +# Compila i tuoi moduli con il comando `elixirc`. + +# Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato +# elixir correttamente. + +## --------------------------- +## -- Tipi di base +## --------------------------- + +# Numeri +3 # intero (Integer) +0x1F # intero +3.0 # decimale (Float) + +# Atomi, che sono literals, una costante con un nome. Iniziano con `:`. +:ciao # atomo (Atom) + +# Tuple che sono salvate in celle di memoria contigue. +{1,2,3} # tupla (Tuple) + +# Possiamo accedere ad un elemento di una tupla con la funzione `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Liste, che sono implementate come liste concatenate (o linked list). +[1,2,3] # lista (List) + +# Possiamo accedere alla testa (head) e alla coda (tail) delle liste così: +[testa | coda] = [1,2,3] +testa #=> 1 +coda #=> [2,3] + +# In Elixir, proprio come in Erlang, il simbolo `=` denota pattern matching e +# non un assegnamento. +# +# Questo significa che la parte sinistra (pattern) viene confrontata alla +# parte destra. +# +# Questo spiega il funzionamento dell'esempio dell'accesso alla lista di prima. + +# Un pattern match darà errore quando le parti non combaciano, ad esempio se +# le tuple hanno dimensione differente. +# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Ci sono anche i binari +<<1,2,3>> # binari (Binary) + +# Stringhe e liste di caratteri +"ciao" # stringa (String) +'ciao' # lista di caratteri (List) + +# Stringhe multilinea +""" +Sono una stringa +multi-linea. +""" +#=> "Sono una stringa\nmulti-linea.\n" + +# Le stringhe sono tutte codificate in UTF-8: +"cìaò" +#=> "cìaò" + +# le stringhe in realtà sono dei binari, e le liste di caratteri sono liste. +<<?a, ?b, ?c>> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` in elixir restituisce il valore ASCII della lettera `a` +?a #=> 97 + +# Per concatenare liste si usa `++`, per binari si usa `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'ciao ' ++ 'mondo' #=> 'ciao mondo' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"ciao " <> "mondo" #=> "ciao mondo" + +# Gli intervalli sono rappresentati come `inizio..fine` (estremi inclusi) +1..10 #=> 1..10 (Range) +minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli +[minore, maggiore] #=> [1, 10] + +## --------------------------- +## -- Operatori +## --------------------------- + +# Un po' di matematica +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In elixir l'operatore `/` restituisce sempre un decimale. + +# Per fare una divisione intera si usa `div` +div(10, 2) #=> 5 + +# Per ottenere il resto di una divisione si usa `rem` +rem(10, 3) #=> 1 + +# Ci sono anche gli operatori booleani: `or`, `and` e `not`. +# Questi operatori si aspettano un booleano come primo argomento. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir fornisce anche `||`, `&&` e `!` che accettano argomenti +# di qualsiasi tipo. +# Tutti i valori tranne `false` e `nil` saranno valutati come true. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Per i confronti abbiamo: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` e `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` e `!==` sono più rigidi quando si confrontano interi e decimali: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Possiamo anche confrontare tipi di dato diversi: +1 < :ciao #=> true + +# L'ordine generale è definito sotto: +# numeri < atomi < riferimenti < funzioni < porte < pid < tuple < liste +# < stringhe di bit + +# Per citare Joe Armstrong su questo: "L'ordine non è importante, +# ma è importante che sia definito un ordine." + +## --------------------------- +## -- Controllo di flusso +## --------------------------- + +# espressione `se` (`if`) +if false do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# c'è anche un `se non` (`unless`) +unless true do + "Questo non si vedrà mai" +else + "Questo sì" +end + +# Ti ricordi il pattern matching? +# Moltre strutture di controllo di flusso in elixir si basano su di esso. + +# `case` ci permette di confrontare un valore a diversi pattern: +case {:uno, :due} do + {:quattro, :cinque} -> + "Questo non farà match" + {:uno, x} -> + "Questo farà match e binderà `x` a `:due`" + _ -> + "Questo farà match con qualsiasi valore" +end + +# Solitamente si usa `_` se non si ha bisogno di utilizzare un valore. +# Ad esempio, se ci serve solo la testa di una lista: +[testa | _] = [1,2,3] +testa #=> 1 + +# Per aumentare la leggibilità possiamo usarlo in questo modo: +[testa | _coda] = [:a, :b, :c] +testa #=> :a + +# `cond` ci permette di verificare più condizioni allo stesso momento. +# Usa `cond` invece di innestare più espressioni `if`. +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + 1 + 2 == 3 -> + "Questa sì!" +end + +# È pratica comune mettere l'ultima condizione a `true`, che farà sempre match +cond do + 1 + 1 == 3 -> + "Questa stringa non si vedrà mai" + 2 * 5 == 12 -> + "Nemmeno questa" + true -> + "Questa sì! (essenzialmente funziona come un else)" +end + +# `try/catch` si usa per gestire i valori lanciati (throw), +# Supporta anche una clausola `after` che è invocata in ogni caso. +try do + throw(:ciao) +catch + message -> "Ho ricevuto #{message}." +after + IO.puts("Io sono la clausola 'after'.") +end +#=> Io sono la clausola 'after' +# "Ho ricevuto :ciao" + +## --------------------------- +## -- Moduli e Funzioni +## --------------------------- + +# Funzioni anonime (notare il punto) +quadrato = fn(x) -> x * x end +quadrato.(5) #=> 25 + +# Accettano anche guardie e condizioni multiple. +# le guardie ti permettono di perfezionare il tuo pattern matching, +# sono indicate dalla parola chiave `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir fornisce anche molte funzioni, disponibili nello scope corrente. +is_number(10) #=> true +is_list("ciao") #=> false +elem({1,2,3}, 0) #=> 1 + +# Puoi raggruppare delle funzioni all'interno di un modulo. +# All'interno di un modulo usa `def` per definire le tue funzioni. +defmodule Matematica do + def somma(a, b) do + a + b + end + + def quadrato(x) do + x * x + end +end + +Matematica.somma(1, 2) #=> 3 +Matematica.quadrato(3) #=> 9 + +# Per compilare il modulo 'Matematica' salvalo come `matematica.ex` e usa +# `elixirc`. +# nel tuo terminale: elixirc matematica.ex + +# All'interno di un modulo possiamo definire le funzioni con `def` e funzioni +# private con `defp`. +# Una funzione definita con `def` è disponibile per essere invocata anche da +# altri moduli, una funziona privata può essere invocata solo localmente. +defmodule MatematicaPrivata do + def somma(a, b) do + esegui_somma(a, b) + end + + defp esegui_somma(a, b) do + a + b + end +end + +MatematicaPrivata.somma(1, 2) #=> 3 +# MatematicaPrivata.esegui_somma(1, 2) #=> ** (UndefinedFunctionError) + +# Anche le dichiarazioni di funzione supportano guardie e condizioni multiple: +defmodule Geometria do + def area({:rettangolo, w, h}) do + w * h + end + + def area({:cerchio, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometria.area({:rettangolo, 2, 3}) #=> 6 +Geometria.area({:cerchio, 3}) #=> 28.25999999999999801048 +# Geometria.area({:cerchio, "non_un_numero"}) +#=> ** (FunctionClauseError) no function clause matching in Geometria.area/1 + +# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir +defmodule Ricorsione do + def somma_lista([testa | coda], accumulatore) do + somma_lista(coda, accumulatore + testa) + end + + def somma_lista([], accumulatore) do + accumulatore + end +end + +Ricorsione.somma_lista([1,2,3], 0) #=> 6 + +# I moduli di Elixir supportano attributi. Ci sono degli attributi incorporati +# e puoi anche aggiungerne di personalizzati. +defmodule Modulo do + @moduledoc """ + Questo è un attributo incorporato in un modulo di esempio. + """ + + @miei_dati 100 # Questo è un attributo personalizzato . + IO.inspect(@miei_dati) #=> 100 +end + +## --------------------------- +## -- Strutture ed Eccezioni +## --------------------------- + + +# Le Strutture (Structs) sono estensioni alle mappe che portano +# valori di default, garanzia alla compilazione e polimorfismo in Elixir. +defmodule Persona do + defstruct nome: nil, eta: 0, altezza: 0 +end + +luca = %Persona{ nome: "Luca", eta: 24, altezza: 185 } +#=> %Persona{eta: 24, altezza: 185, nome: "Luca"} + +# Legge al valore di 'nome' +luca.nome #=> "Luca" + +# Modifica il valore di eta +luca_invecchiato = %{ luca | eta: 25 } +#=> %Persona{eta: 25, altezza: 185, nome: "Luca"} + +# Il blocco `try` con la parola chiave `rescue` è usato per gestire le eccezioni +try do + raise "un errore" +rescue + RuntimeError -> "Salvato un errore di Runtime" + _error -> "Questo salverà da qualsiasi errore" +end + +# Tutte le eccezioni hanno un messaggio +try do + raise "un errore" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Concorrenza +## --------------------------- + +# Elixir si basa sul modello degli attori per la concorrenza. +# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir +# sono tre primitive: creare processi, inviare messaggi e ricevere messaggi. + +# Per creare un nuovo processo si usa la funzione `spawn`, che riceve una +# funzione come argomento. +f = fn -> 2 * 2 end #=> #Function<erl_eval.20.80484245> +spawn(f) #=> #PID<0.40.0> + +# `spawn` restituisce un pid (identificatore di processo). Puoi usare questo +# pid per inviare messaggi al processo. +# Per passare messaggi si usa l'operatore `send`. +# Perché tutto questo sia utile dobbiamo essere capaci di ricevere messaggi, +# oltre ad inviarli. Questo è realizzabile con `receive`: +defmodule Geometria do + def calcolo_area do + receive do + {:rettangolo, w, h} -> + IO.puts("Area = #{w * h}") + calcolo_area() + {:cerchio, r} -> + IO.puts("Area = #{3.14 * r * r}") + calcolo_area() + end + end +end + +# Compila il modulo e crea un processo che esegue `calcolo_area` nella shell +pid = spawn(fn -> Geometria.calcolo_area() end) #=> #PID<0.40.0> + +# Invia un messaggio a `pid` che farà match su un pattern nel blocco in receive +send pid, {:rettangolo, 2, 3} +#=> Area = 6 +# {:rettangolo,2,3} + +send pid, {:cerchio, 2} +#=> Area = 12.56000000000000049738 +# {:cerchio,2} + +# Anche la shell è un processo. Puoi usare `self` per ottenere il pid corrente +self() #=> #PID<0.27.0> +``` + +## Referenze + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org) +* [Documentazione Elixir](http://elixir-lang.org/docs/master/) +* ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas +* [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) di Fred Hebert +* ["Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) di Joe Armstrong diff --git a/make.html.markdown b/make.html.markdown new file mode 100644 index 00000000..75543dcd --- /dev/null +++ b/make.html.markdown @@ -0,0 +1,243 @@ +---
+language: make
+contributors:
+ - ["Robert Steed", "https://github.com/robochat"]
+filename: Makefile
+---
+
+A Makefile defines a graph of rules for creating a target (or targets).
+Its purpose is to do the minimum amount of work needed to update a
+target to the most recent version of the source. Famously written over a
+weekend by Stuart Feldman in 1976, it is still widely used (particularly
+on Unix) despite many competitors and criticisms.
+
+There are many varieties of make in existance, this article assumes that
+we are using GNU make which is the standard on Linux.
+
+```make
+
+# Comments can be written like this.
+
+# Files should be named Makefile and then be can run as `make <target>`.
+# Otherwise we use `make -f "filename" <target>`.
+
+# Warning - only use TABS to indent in Makefiles, never spaces!
+
+#-----------------------------------------------------------------------
+# Basics
+#-----------------------------------------------------------------------
+
+# A rule - this rule will only run if file0.txt doesn't exist.
+file0.txt:
+ echo "foo" > file0.txt
+ # Even comments in these 'recipe' sections get passed to the shell.
+ # Try `make file0.txt` or simply `make` - first rule is the default.
+
+
+# This rule will only run if file0.txt is newer than file1.txt.
+file1.txt: file0.txt
+ cat file0.txt > file1.txt
+ # use the same quoting rules as in the shell.
+ @cat file0.txt >> file1.txt
+ # @ stops the command from being echoed to stdout.
+ -@echo 'hello'
+ # - means that make will keep going in the case of an error.
+ # Try `make file1.txt` on the commandline.
+
+# A rule can have multiple targets and multiple prerequisites
+file2.txt file3.txt: file0.txt file1.txt
+ touch file2.txt
+ touch file3.txt
+
+# Make will complain about multiple recipes for the same rule. Empty
+# recipes don't count though and can be used to add new dependencies.
+
+#-----------------------------------------------------------------------
+# Phony Targets
+#-----------------------------------------------------------------------
+
+# A phony target. Any target that isn't a file.
+# It will never be up to date so make will always try to run it.
+all: maker process
+
+# We can declare things out of order.
+maker:
+ touch ex0.txt ex1.txt
+
+# Can avoid phony rules breaking when a real file has the same name by
+.PHONY: all maker process
+# This is a special target. There are several others.
+
+# A rule with a dependency on a phony target will always run
+ex0.txt ex1.txt: maker
+
+# Common phony targets are: all make clean install ...
+
+#-----------------------------------------------------------------------
+# Automatic Variables & Wildcards
+#-----------------------------------------------------------------------
+
+process: file*.txt #using a wildcard to match filenames
+ @echo $^ # $^ is a variable containing the list of prerequisites
+ @echo $@ # prints the target name
+ #(for multiple target rules, $@ is whichever caused the rule to run)
+ @echo $< # the first prerequisite listed
+ @echo $? # only the dependencies that are out of date
+ @echo $+ # all dependencies including duplicates (unlike normal)
+ #@echo $| # all of the 'order only' prerequisites
+
+# Even if we split up the rule dependency definitions, $^ will find them
+process: ex1.txt file0.txt
+# ex1.txt will be found but file0.txt will be deduplicated.
+
+#-----------------------------------------------------------------------
+# Patterns
+#-----------------------------------------------------------------------
+
+# Can teach make how to convert certain files into other files.
+
+%.png: %.svg
+ inkscape --export-png $^
+
+# Pattern rules will only do anything if make decides to create the \
+target.
+
+# Directory paths are normally ignored when matching pattern rules. But
+# make will try to use the most appropriate rule available.
+small/%.png: %.svg
+ inkscape --export-png --export-dpi 30 $^
+
+# make will use the last version for a pattern rule that it finds.
+%.png: %.svg
+ @echo this rule is chosen
+
+# However make will use the first pattern rule that can make the target
+%.png: %.ps
+ @echo this rule is not chosen if *.svg and *.ps are both present
+
+# make already has some pattern rules built-in. For instance, it knows
+# how to turn *.c files into *.o files.
+
+# Older makefiles might use suffix rules instead of pattern rules
+.png.ps:
+ @echo this rule is similar to a pattern rule.
+
+# Tell make about the suffix rule
+.SUFFIXES: .png
+
+#-----------------------------------------------------------------------
+# Variables
+#-----------------------------------------------------------------------
+# aka. macros
+
+# Variables are basically all string types
+
+name = Ted
+name2="Sarah"
+
+echo:
+ @echo $(name)
+ @echo ${name2}
+ @echo $name # This won't work, treated as $(n)ame.
+ @echo $(name3) # Unknown variables are treated as empty strings.
+
+# There are 4 places to set variables.
+# In order of priority from highest to lowest:
+# 1: commandline arguments
+# 2: Makefile
+# 3: shell enviroment variables - make imports these automatically.
+# 4: make has some predefined variables
+
+name4 ?= Jean
+# Only set the variable if enviroment variable is not already defined.
+
+override name5 = David
+# Stops commandline arguments from changing this variable.
+
+name4 +=grey
+# Append values to variable (includes a space).
+
+# Pattern-specific variable values (GNU extension).
+echo: name2 = Sara # True within the matching rule
+ # and also within its remade recursive dependencies
+ # (except it can break when your graph gets too complicated!)
+
+# Some variables defined automatically by make.
+echo_inbuilt:
+ echo $(CC)
+ echo ${CXX)}
+ echo $(FC)
+ echo ${CFLAGS)}
+ echo $(CPPFLAGS)
+ echo ${CXXFLAGS}
+ echo $(LDFLAGS)
+ echo ${LDLIBS}
+
+#-----------------------------------------------------------------------
+# Variables 2
+#-----------------------------------------------------------------------
+
+# The first type of variables are evaluated each time they are used.
+# This can be expensive, so a second type of variable exists which is
+# only evaluated once. (This is a GNU make extension)
+
+var := hello
+var2 ::= $(var) hello
+#:= and ::= are equivalent.
+
+# These variables are evaluated procedurely (in the order that they
+# appear), thus breaking with the rest of the language !
+
+# This doesn't work
+var3 ::= $(var4) and good luck
+var4 ::= good night
+
+#-----------------------------------------------------------------------
+# Functions
+#-----------------------------------------------------------------------
+
+# make has lots of functions available.
+
+sourcefiles = $(wildcard *.c */*.c)
+objectfiles = $(patsubst %.c,%.o,$(sourcefiles))
+
+# Format is $(func arg0,arg1,arg2...)
+
+# Some examples
+ls: * src/*
+ @echo $(filter %.txt, $^)
+ @echo $(notdir $^)
+ @echo $(join $(dir $^),$(notdir $^))
+
+#-----------------------------------------------------------------------
+# Directives
+#-----------------------------------------------------------------------
+
+# Include other makefiles, useful for platform specific code
+include foo.mk
+
+sport = tennis
+# Conditional compilation
+report:
+ifeq ($(sport),tennis)
+ @echo 'game, set, match'
+else
+ @echo "They think it's all over; it is now"
+endif
+
+# There are also ifneq, ifdef, ifndef
+
+foo = true
+
+ifdef $(foo)
+bar = 'hello'
+endif
+```
+
+
+### More Resources
+
++ [gnu make documentation](https://www.gnu.org/software/make/manual/)
++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/)
++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html)
+
diff --git a/perl6.html.markdown b/perl6.html.markdown index af545793..8d425f7d 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -213,7 +213,7 @@ say $x; #=> 52 # - `if` # Before talking about `if`, we need to know which values are "Truthy" # (represent True), and which are "Falsey" (or "Falsy") -- represent False. -# Only these values are Falsey: (), "", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: 0, (), {}, "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown new file mode 100644 index 00000000..cc07a2ec --- /dev/null +++ b/pt-br/perl-pt.html.markdown @@ -0,0 +1,166 @@ +--- +name: perl +category: language +language: perl +filename: learnperl-pt.pl +contributors: + - ["Korjavin Ivan", "http://github.com/korjavin"] +translators: + - ["Miguel Araújo", "https://github.com/miguelarauj1o"] +lang: pt-br +--- + +Perl 5 é, uma linguagem de programação altamente capaz, rica em recursos, com mais de 25 anos de desenvolvimento. + +Perl 5 roda em mais de 100 plataformas, de portáteis a mainframes e é adequada tanto para prototipagem rápida, quanto em projetos de desenvolvimento em grande escala. + +```perl +# Comentários de uma linha começam com um sinal de número. + +#### Tipos de variáveis em Perl + +# Variáveis iniciam com um sigilo, que é um símbolo que mostra o tipo. +# Um nome de variável válido começa com uma letra ou sublinhado, +# seguido por qualquer número de letras, números ou sublinhados. + +### Perl has three main variable types: $scalar, @array, e %hash. + +## Scalars +# Um scalar representa um valor único: +my $animal = "camelo"; +my $resposta = 42; + +# Valores scalar podem ser strings, inteiros ou números ponto-flutuantes e +# Perl vai automaticamente converter entre eles quando for preciso. + +## Arrays +# Um array representa uma lista de valores: +my @animais = ("camelo", "vaca", "boi"); +my @números = (23, 42, 69); +my @misturado = ("camelo", 42, 1.23); + +## Hashes +# Um hash representa um conjunto de pares chave/valor: + +my %fruta_cor = ("maçã", "vermelho", "banana", "amarelo"); + +# Você pode usar o espaço em branco e o operador "=>" para colocá-los de +# maneira mais agradável: + +my %fruta_cor = ( + maçã => "vermelho", + banana => "amarelo", +); + +# Scalars, arrays and hashes são documentados mais profundamentes em perldata. +# (perldoc perldata). + +# Mais tipos de dados complexos podem ser construídas utilizando referências, +# o que permite que você crie listas e hashes dentro de listas e hashes. + +#### Condicionais e construtores de iteração + +# Perl possui a maioria das construções condicionais e de iteração habituais. + +if ($var) { + ... +} elsif ($var eq 'bar') { + ... +} else { + ... +} + +unless (condição) { + ... +} +# Isto é fornecido como uma versão mais legível de "if (!condition)" + +# A forma Perlish pós-condição +print "Yow!" if $zippy; +print "Nós não temos nenhuma banana" unless $bananas; + +# while +while (condição) { + ... +} + +# for +for (my $i = 0; $i < $max; $i++) { + print "valor é $i"; +} + +for (my $i = 0; $i < @elements; $i++) { + print "Elemento atual é " . $elements[$i]; +} + +for my $element (@elements) { + print $element; +} + +# implícito + +for (@elements) { + print; +} + +#### Expressões regulares + +# O suporte a expressões regulares do Perl é ao mesmo tempo amplo e profundo, +# e é objeto de longa documentação em perlrequick, perlretut, e em outros +# lugares. No entanto, em suma: + +# Casamento simples +if (/foo/) { ... } # verdade se $_ contém "foo" +if ($a =~ /foo/) { ... } # verdade se $a contém "foo" + +# Substituição simples + +$a =~ s/foo/bar/; # substitui foo com bar em $a +$a =~ s/foo/bar/g; # substitui TODAS AS INSTÂNCIAS de foo com bar em $a + +#### Arquivos e I/O + +# Você pode abrir um arquivo para entrada ou saída usando a função "open()". + +open(my $in, "<", "input.txt") ou desistir "Não pode abrir input.txt: $!"; +open(my $out, ">", "output.txt") ou desistir "Não pode abrir output.txt: $!"; +open(my $log, ">>", "my.log") ou desistir "Não pode abrir my.log: $!"; + +# Você pode ler de um arquivo aberto usando o operador "<>". No contexto +# scalar, ele lê uma única linha do arquivo, e em contexto de lista lê o +# arquivo inteiro, atribuindo cada linha a um elemento da lista: + +my $linha = <$in>; +my @linhas = <$in>; + +#### Escrevendo subrotinas + +# Escrever subrotinas é fácil: + +sub logger { + my $mensagem = shift; + + open my $arquivo, ">>", "my.log" or die "Não poderia abrir my.log: $!"; + + print $arquivo $ensagem; +} + +# Agora nós podemos usar a subrotina como qualquer outra função construída: + +logger("Nós temos uma subrotina de log!"); +``` + +#### Usando módulos Perl + +Módulos Perl provê uma lista de recursos para lhe ajudar a evitar redesenhar +a roda, e tudo isso pode ser baixado do CPAN (http://www.cpan.org/). Um número +de módulos populares podem ser incluídos com a própria distribuição do Perl. + +perlfaq contém questões e respostas relacionadas a muitas tarefas comuns, e frequentemente provê sugestões para um bom números de módulos CPAN. + +#### Leitura Adicional + + - [perl-tutorial](http://perl-tutorial.org/) + - [Learn at www.perl.com](http://www.perl.org/learn.html) + - [perldoc](http://perldoc.perl.org/) + - and perl built-in : `perldoc perlintro` diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 8b292edd..d8a02d36 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -54,7 +54,7 @@ the community has moved to at least 1.9.2 or 1.9.3. ## Ruby Implementations The Ruby ecosystem enjoys many different implementations of Ruby, each with -unique strengths and states of compatability. To be clear, the different +unique strengths and states of compatibility. To be clear, the different implementations are written in different languages, but *they are all Ruby*. Each implementation has special hooks and extra features, but they all run normal Ruby files well. For instance, JRuby is written in Java, but you do diff --git a/rust.html.markdown b/rust.html.markdown index dd03acdd..4fbd6144 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -281,7 +281,7 @@ fn main() { println!("{}", var); // Unlike `box`, `var` can still be used println!("{}", *ref_var); // var = 5; // this would not compile because `var` is borrowed - // *ref_var = 6; // this would too, because `ref_var` is an immutable reference + // *ref_var = 6; // this would not too, because `ref_var` is an immutable reference // Mutable reference // While a value is mutably borrowed, it cannot be accessed at all. diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown new file mode 100644 index 00000000..41835e13 --- /dev/null +++ b/tr-tr/swift-tr.html.markdown @@ -0,0 +1,590 @@ +--- +language: swift +contributors: + - ["Özgür Şahin", "https://github.com/ozgurshn/"] +filename: learnswift.swift +--- + +Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. + +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. + +Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı. + +See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), which has a complete tutorial on Swift. + +Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var. + + + +```swift +// modülü import etme +import UIKit + +// +// MARK: Temeller +// + + +//XCode işaretlemelerle kodunuzu bölümlere ayırmanızı ve sağ üstteki metot + listesinde gruplama yapmanıza olanak sağlıyor +// MARK: Bölüm işareti +// TODO: Daha sonra yapılacak +// FIXME: Bu kodu düzelt + + +//Swift 2 de, println ve print metotları print komutunda birleştirildi. Print + otomatik olarak yeni satır ekliyor. +print("Merhaba dünya") // println print olarak kullanılıyor. +print("Merhaba dünya", appendNewLine: false) // yeni bir satır eklemeden yazar. + +// variables (var) değer atandıktan sonra değiştirilebilir. +// constants (let) değer atndıktan sonra değiştirilemez. + +var degiskenim = 42 +let øπΩ = "deger" // unicode degişken adları +let π = 3.1415926 +let convenience = "keyword" // bağlamsal değişken adı +let isim = "ahmet"; let soyad = "un" // farklı ifadeler noktalı virgül +kullanılarak ayrılabilir. +let `class` = "keyword" // rezerve edilmiş keywordler tek tırnak içerisine +alınarak değişken adı olarak kullanılabilir +let doubleOlduguBelli: Double = 70 +let intDegisken = 0007 // 7 +let largeIntDegisken = 77_000 // 77000 +let etiket = "birseyler " + String(degiskenim) // Cast etme +let piYazi = "Pi = \(π), Pi 2 = \(π * 2)" // String içerisine değiken yazdırma + + +// Builde özel değişkenler +// -D build ayarını kullanır. +#if false + print("yazılmadı") + let buildDegiskeni= 3 +#else + let buildDegiskeni = 7 +#endif +print("Build degiskeni: \(buildDegiskeni)") // Build degeri: 7 + +/* + Optionals Swift dilinde bazı değerleri veya yokluğu (None) bir değişkende + tutmanıza olanak sağlar. + + Swift'te her bir degişkeninin bir değeri olması gerektiğinden, nil değeri + bile Optional değer olarak saklanır. + + Optional<T> bir enum'dır. +*/ +var baziOptionalString: String? = "optional" // nil olabilir. +// yukarıdakiyle aynı ama ? bir postfix (sona eklenir) operatördür. (kolay +okunabilir) +var someOptionalString2: Optional<String> = "optional" + + +if baziOptionalString != nil { + // ben nil değilim + if baziOptionalString!.hasPrefix("opt") { + print("ön eki var") + } + + let bos = baziOptionalString?.isEmpty +} +baziOptionalString = nil + +// belirgin olarak acilan(unwrap) opsiyonel (optional) değer +var acilanString: String! = "Değer bekleniliyor" +//yukarıdakiyle aynı ama ! bir postfix operatördür (kolay okunabilir) +var acilanString2: ImplicitlyUnwrappedOptional<String> = "Değer bekleniliyor." + +if let baziOpsiyonelSabitString = baziOptionalString { + // eğer bir değeri varsa, nil değilse + if ! baziOpsiyonelSabitString("tamam") { + // ön eke sahip değil + } +} + +// Swift değişkenlerde herhangi bir tip saklanabilir. +// AnyObject == id +// Objective-C deki `id` den farklı olarak, AnyObject tüm değişkenlerle + çalışabilir (Class, Int, struct, etc) +var herhangiBirObject: AnyObject = 7 +herhangiBirObject = "Değer string olarak değişti, iyi bir yöntem değil ama mümkün" + +/* + Yorumlar buraya + + /* + İç içe yorum yazılması da mümkün + */ +*/ + +// +// MARK: Koleksiyonlar +// + +/* + Array ve Dictionary tipleri aslında structdırlar. Bu yüzden `let` ve `var` + ayrıca bu tipleri tanımlarken değişebilir(var) veya değişemez(let) + olduğunu belirtir. + +*/ + +// Diziler +var liste = ["balik", "su", "limon"] +liste[1] = "şişe su" +let bosDizi = [String]() // let == değiştirilemez +let bosDizi2 = Array<String>() // yukarıdakiyle aynı +var bosDegistirilebilirDizi = [String]() // var == değişebilir + + +// Dictionary +var meslekler = [ + "Kamil": "Kaptan", + "Ayse": "Analist" +] +meslekler["Cansu"] = "Halkla İlişkiler" +let bosDictionary = [String: Float]() // let == değiştirilemez +let bosDictionary2 = Dictionary<String, Float>() // yukarıdakiyle aynı +var bosDegistirilebirDictionary = [String: Float]() // var == değiştirilebilir + + +// +// MARK: Kontroller +// + +// for döngüsü (dizi) +let dizi = [1, 1, 2, 3, 5] +for deger in dizi { + if deger == 1 { + print("Bir!") + } else { + print("Bir degil!") + } +} + +// for döngüsü (dictionary) +var dict = ["one": 1, "two": 2] +for (key, value) in dict { + print("\(key): \(value)") +} + +// for döngüsü (aralık) +for i in -1...liste.count { + print(i) +} +liste[1...2] = ["et", "yogurt"] +// ..< kullanarak son elemanı çıkartabilirsiniz + +// while döngüsü +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while döngüsü +do { + print("merhaba") +} while 1 == 2 + +// Switch +// Çok güçlü, `if` ifadesenin daha kolay okunabilir hali olarak düşünün +// String, object örnekleri, ve primitif tipleri (Int, Double, vs) destekler. +let sebze = "kırmızı biber" +switch sebze { +case "sogan": + let sebzeYorumu = "Biraz da domates ekle" +case "domates", "salata": + let sebzeYorumu = "İyi bir sandviç olur" +case let lokalScopeDegeri where lokalScopeDegeri.hasSuffix("biber"): + let sebzeYorumu = "Acı bir \(lokalScopeDegeri)?" +default: // zorunludur (tüm olasılıkları yakalamak icin) + let sebzeYorumu = "Corbadaki herseyin tadı güzel" +} + + +// +// MARK: Fonksiyonlar +// + +// Fonksiyonlar first-class tiplerdir, yani başka fonksiyon içine konabilir +// ve parametre olarak geçirilebilirler. + +// Swift dökümanlarıylaa birlikte Fonksiyonlar (format as reStructedText) + +/** + selamlama işlemi + + :param: isim e isim + :param: gun e A gun + :returns: isim ve gunu iceren bir String +*/ +func selam(isim: String, gun: String) -> String { + return "Merhaba \(isim), bugün \(gun)." +} +selam("Can", "Salı") + +// fonksiyon parametre davranışı hariç yukarıdakine benzer +func selam2(#gerekliIsim: String, disParametreIsmi lokalParamtreIsmi: String) -> String { + return "Merhaba \(gerekliIsim), bugün \(lokalParamtreIsmi)" +} +selam2(gerekliIsim:"Can", disParametreIsmi: "Salı") + +// Bir tuple ile birden fazla deger dönen fonksiyon +func fiyatlariGetir() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} +let fiyatTuple = fiyatlariGetir() +let fiyat = fiyatTuple.2 // 3.79 +// _ (alt çizgi) kullanımı Tuple degerlerini veya diğer değerleri görmezden +gelir +let (_, fiyat1, _) = fiyatTuple // fiyat1 == 3.69 +print(fiyat1 == fiyatTuple.1) // true +print("Benzin fiyatı: \(fiyat)") + +// Çeşitli Argümanlar +func ayarla(sayilar: Int...) { + // its an array + let sayi = sayilar[0] + let argumanSAyisi = sayilar.count +} + +// fonksiyonu parametre olarak geçirme veya döndürme +func arttirmaIslemi() -> (Int -> Int) { + func birEkle(sayi: Int) -> Int { + return 1 + sayi + } + return birEkle +} +var arttir = arttirmaIslemi() +arttir(7) + +// referans geçirme +func yerDegistir(inout a: Int, inout b: Int) { + let tempA = a + a = b + b = tempA +} +var someIntA = 7 +var someIntB = 3 +yerDegistir(&someIntA, &someIntB) +print(someIntB) // 7 + + +// +// MARK: Closurelar +// +var sayilar = [1, 2, 6] + +// Fonksiyonlar özelleştirilmiş closurelardır. ({}) + +// Closure örneği. +// `->` parametrelerle dönüş tipini birbirinden ayırır +// `in` closure başlığını closure bodysinden ayırır. +sayilar.map({ + (sayi: Int) -> Int in + let sonuc = 3 * sayi + return sonuc +}) + +// eger tip biliniyorsa, yukarıdaki gibi, şöyle yapabiliriz +sayilar = sayilar.map({ sayi in 3 * sayi }) +// Hatta bunu +//sayilar = sayilar.map({ $0 * 3 }) + +print(sayilar) // [3, 6, 18] + +// Trailing closure +sayilar = sorted(sayilar) { $0 > $1 } + +print(sayilar) // [18, 6, 3] + +// Super kısa hali ise, < operatörü tipleri çıkartabildiği için + +sayilar = sorted(sayilar, < ) + +print(sayilar) // [3, 6, 18] + +// +// MARK: Yapılar +// + +// Structurelar ve sınıflar birçok aynı özelliğe sahiptir. +struct IsimTablosu { + let isimler = [String]() + + // Özelleştirilmiş dizi erişimi + subscript(index: Int) -> String { + return isimler[index] + } +} + +// Structurelar otomatik oluşturulmuş kurucu metoda sahiptir. +let isimTablosu = IsimTablosu(isimler: ["Ben", "Onlar"]) +let isim = isimTablosu[1] +print("İsim \(name)") // İsim Onlar + +// +// MARK: Sınıflar +// + +// Sınıflar, structurelar ve üyeleri 3 seviye erişime sahiptir. +// Bunlar: internal (default), public, private + +public class Sekil { + public func alaniGetir() -> Int { + return 0; + } +} + +// Sınıfın tüm değişkenleri ve metotları publictir. +// Eğer sadece veriyi yapılandırılmış bir objede +// saklamak istiyorsanız, `struct` kullanmalısınız. + +internal class Rect: Sekil { + var yanUzunluk: Int = 1 + + // Özelleştirilmiş getter ve setter propertyleri + private var cevre: Int { + get { + return 4 * yanUzunluk + } + set { + // `newValue ` setterlarda yeni değere erişimi sağlar + yanUzunluk = newValue / 4 + } + } + + // Bir değişkene geç atama(lazy load) yapmak + // altSekil getter cağrılana dek nil (oluşturulmamış) olarak kalır + lazy var altSekil = Rect(yanUzunluk: 4) + + // Eğer özelleştirilmiş getter ve setter a ihtiyacınız yoksa, + // ama bir değişkene get veya set yapıldıktan sonra bir işlem yapmak + // istiyorsanız, `willSet` ve `didSet` metotlarını kullanabilirsiniz + var identifier: String = "defaultID" { + // `willSet` argümanı yeni değer için değişkenin adı olacaktır. + willSet(someIdentifier) { + print(someIdentifier) + } + } + + init(yanUzunluk: Int) { + self. yanUzunluk = yanUzunluk + // super.init i her zaman özelleştirilmiş değerleri oluşturduktan sonra + çağırın + super.init() + } + + func kisalt() { + if yanUzunluk > 0 { + --yanUzunluk + } + } + + override func alaniGetir() -> Int { + return yanUzunluk * yanUzunluk + } +} + +// Basit `Kare` sınıfI `Rect` sınıfını extend ediyor. +class Kare: Rect { + convenience init() { + self.init(yanUzunluk: 5) + } +} + +var benimKarem = Kare() +print(m benimKarem.alaniGetir()) // 25 +benimKarem.kisalt() +print(benimKarem.yanUzunluk) // 4 + +// sınıf örneğini cast etme +let birSekil = benimKarem as Sekil + +// örnekleri karşılaştır, objeleri karşılaştıran == (equal to) ile aynı değil +if benimKarem === benimKarem { + print("Evet, bu benimKarem") +} + +// Opsiyonel init +class Daire: Sekil { + var yaricap: Int + override func alaniGetir() -> Int { + return 3 * yaricap * yaricap + } + + // Eğer init opsiyonelse (nil dönebilir) `init` den sonra soru işareti + // son eki ekle. + init?(yaricap: Int) { + self.yaricap = yaricap + super.init() + + if yaricap <= 0 { + return nil + } + } +} + +var benimDairem = Daire(radius: 1) +print(benimDairem?.alaniGetir()) // Optional(3) +print(benimDairem!. alaniGetir()) // 3 +var benimBosDairem = Daire(yaricap: -1) +print(benimBosDairem?. alaniGetir()) // "nil" +if let daire = benimBosDairem { + // benimBosDairem nil olduğu için çalışmayacak + print("circle is not nil") +} + + +// +// MARK: Enumlar +// + +// Enumlar opsiyonel olarak özel bir tip veya kendi tiplerinde olabilirler. +// Sınıflar gibi metotlar içerebilirler. + +enum Kart { + case Kupa, Maca, Sinek, Karo + func getIcon() -> String { + switch self { + case .Maca: return "♤" + case .Kupa: return "♡" + case .Karo: return "♢" + case .Sinek: return "♧" + } + } +} + +// Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz. +var kartTipi: Kart = .Kupa + +// Integer olmayan enumlar direk değer (rawValue) atama gerektirir. +enum KitapAdi: String { + case John = "John" + case Luke = "Luke" +} +print("Name: \(KitapAdi.John.rawValue)") + +// Değerlerle ilişkilendirilmiş Enum +enum Mobilya { + // Int ile ilişkilendirilmiş + case Masa(yukseklik: Int) + // String ve Int ile ilişkilendirilmiş + case Sandalye(String, Int) + + func aciklama() -> String { + switch self { + case .Masa(let yukseklik): + return "Masa boyu \(yukseklik) cm" + case .Sandalye(let marka, let yukseklik): + return "\(brand) marka sandalyenin boyu \(yukseklik) cm" + } + } +} + +var masa: Mobilya = .Masa(yukseklik: 80) +print(masa.aciklama()) // "Masa boyu 80 cm" +var sandalye = Mobilya.Sandalye("Foo", 40) +print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm" + + +// +// MARK: Protokoller +// + +// `protocol` onu kullanan tiplerin bazı özel değişkenleri, metotları, +// tip metotlarını,opertörleri ve alt indisleri (subscripts) içermesini +// zorunlu hale getirebilir. + +protocol SekilUretici { + var aktif: Bool { get set } + func sekilOlustur() -> Sekil +} + +// @objc ile tanımlanan protokoller, uygunluğu kontrol edebilmenizi sağlayacak +// şekilde opsiyonel fonksiyonlara izin verir +@objc protocol SekliDondur { + optional func sekillendirilmis() + optional func sekillendirilebilir() -> Bool +} + +class BenimSeklim: Rect { + var delegate: SekliDondur? + + func buyut() { + yanUzlunluk += 2 + + // Bir çalışma zamanı hatası("optional chaining") fırlatmak yerine nil + //değeri görmezden gelerek nil dönmek için opsiyonel değişken, metot veya + // altindisten sonra soru işareti koyabilirsiniz. + if let izinVeriyormu = self.delegate?.sekillendirilebilir?() { + // önce delegate i sonra metodu test edin + self.delegate?.sekillendirilmis?() + } + } +} + + +// +// MARK: Diğerleri +// + +// `extension`lar: Var olan tiplere ekstra özellikler ekleyin + +// Kare artık `Printable` protokolüne uyuyor. +extension Kare: Printable { + var description: String { + return "Alan: \(alaniGetir()) - ID: \(self.identifier)" + } +} + +print("Kare: \(benimKarem)") + +// Dahili tipleri de yeni özellikler ekleyebilirsiniz +extension Int { + var customProperty: String { + return "Bu sayı \(self)" + } + + func carp(num: Int) -> Int { + return num * self + } +} + +print(7.customProperty) // "Bu sayı 7" +print(14.carp(3)) // 42 + +// Genericler: Java ve C#'a benzer şekilde. `where` anahtar kelimesini +// kullanarak genericlerin özelliklerini belirleyin + +func indexiBul<T: Equatable>(dizi: [T], bulunacakDeger: T) -> Int? { + for (index, deger) in enumerate(dizi) { + if deger == bulunacakDeger { + return index + } + } + return nil +} +let bulunanIndex = indexiBul([1, 2, 3, 4], 3) +print(bulunanIndex == 2) // true + +// Operatorler: +// Özel operatorler şu karakterlerle başlayabilir: +// / = - + * % < > ! & | ^ . ~ +// veya +// Unicode math, symbol, arrow, dingbat, ve line/box karakterleri. +prefix operator !!! {} + +// Yan uzunluğu 3 katına çıkartan prefix operatörü +prefix func !!! (inout sekil: Kare) -> Kare { + sekil.YanUzunluk *= 3 + return sekil +} + +// güncel deger +print(benimKarem.YanUzunluk) // 4 + +// yan uzunluğu !!! operatorü kullanarak 3 katına çıkar +!!!benimKarem +print(benimKarem.YanUzunluk) // 12 +``` diff --git a/zh-cn/bash-cn.html.markdown b/zh-cn/bash-cn.html.markdown index 558d9110..d85e5b8f 100644 --- a/zh-cn/bash-cn.html.markdown +++ b/zh-cn/bash-cn.html.markdown @@ -258,7 +258,7 @@ help return help source help . -# 用 mam 指令阅读相关的 Bash 手册 +# 用 man 指令阅读相关的 Bash 手册 apropos bash man 1 bash man bash diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 3a461efe..49224085 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -239,7 +239,7 @@ func learnConcurrency() { go inc(0, c) // go is a statement that starts a new goroutine. go inc(10, c) go inc(-805, c) - // 从channel中独处结果并打印。 + // 从channel中读取结果并打印。 // 打印出什么东西是不可预知的。 fmt.Println(<-c, <-c, <-c) // channel在右边的时候,<-是读操作。 diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index b1143dac..b633714d 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -69,7 +69,7 @@ __此文本也是__ <!-- 如果你插入一个 HTML中的<br />标签,你可以在段末加入两个以上的空格, 然后另起一段。--> -此段落结尾有两个空格(选中以显示)。 +此段落结尾有两个空格(选中以显示)。 上文有一个 <br /> ! |