diff options
-rw-r--r-- | c++.html.markdown | 98 | ||||
-rw-r--r-- | c.html.markdown | 3 | ||||
-rw-r--r-- | elisp.html.markdown | 2 | ||||
-rw-r--r-- | es-es/powershell-es.html.markdown | 329 | ||||
-rw-r--r-- | fortran95.html.markdown | 452 | ||||
-rw-r--r-- | fr-fr/rust-fr.html.markdown | 319 | ||||
-rw-r--r-- | fsharp.html.markdown | 7 | ||||
-rw-r--r-- | it-it/rust-it.html.markdown | 321 | ||||
-rw-r--r-- | rust.html.markdown | 5 | ||||
-rw-r--r-- | scala.html.markdown | 60 | ||||
-rw-r--r-- | sv-se/json-sv.html.markdown | 32 | ||||
-rw-r--r-- | zh-cn/go-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/kotlin-cn.html.markdown | 346 | ||||
-rw-r--r-- | zh-cn/r-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-tw/bash-tw.html.markdown | 377 |
15 files changed, 2284 insertions, 71 deletions
diff --git a/c++.html.markdown b/c++.html.markdown index 290633f3..5dc1af59 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -808,8 +808,8 @@ void doSomethingWithAFile(const std::string& filename) // have default comparators, but you can override it. class Foo { public: - int j; - Foo(int a) : j(a) {} + int j; + Foo(int a) : j(a) {} }; struct compareFunction { bool operator()(const Foo& a, const Foo& b) const { @@ -948,7 +948,7 @@ f1 = f2; #include<tuple> -// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members , +// Conceptually, Tuples are similar to old data structures (C-like structs) but instead of having named data members, // its elements are accessed by their order in the tuple. // We start with constructing a tuple. @@ -958,10 +958,10 @@ const int maxN = 1e9; const int maxL = 15; auto second = make_tuple(maxN, maxL); -// printing elements of 'first' tuple +// Printing elements of 'first' tuple cout << get<0>(first) << " " << get<1>(first) << "\n"; //prints : 10 A -// printing elements of 'second' tuple +// Printing elements of 'second' tuple cout << get<0>(second) << " " << get<1>(second) << "\n"; // prints: 1000000000 15 // Unpacking tuple into variables @@ -989,43 +989,43 @@ cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' ///////////////////// -// CONTAINERS +// Containers ///////////////////// -// Containers or the Standard Template Library are some predefined templates -// They manages the storage space for its elements and provide -// member functions to access and manipulate them +// Containers or the Standard Template Library are some predefined templates. +// They manage the storage space for its elements and provide +// member functions to access and manipulate them. -// Few containers are as follows:- +// Few containers are as follows: -// Vectors (Dynamic arrays) +// Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time -#include<vector> // will include the header file for vector -vector< Data_Type > Vector_name; // used to initialize the vector -cin>>val; +#include<vector> +vector<Data_Type> Vector_name; // used to initialize the vector +cin >> val; Vector_name.push_back(val); // will push the value of variable into array -// To iterate through vector, we have 2 choices -// using normal looping +// To iterate through vector, we have 2 choices: +// Normal looping for(int i=0; i<Vector_name.size(); i++) // It will iterate through the vector from index '0' till last index -// Using Iterator +// Iterator vector<Data_Type>::iterator it; // initialize the iteartor for vector for(it=vector_name.begin(); it!=vector_name.end();++it) // For accessing the element of the vector // Operator [] -var= vector_name[index]; //will assign value at that index to var +var = vector_name[index]; // Will assign value at that index to var // Set -// Sets are containers that store unique elements following a specific order -// Very useful container to store unique values in sorted order -// without any other functions or code +// Sets are containers that store unique elements following a specific order. +// Set is a very useful container to store unique values in sorted order +// without any other functions or code. -#include<set> // Will include the header file for sets -set< int > ST; // Will initialize the set of int data type +#include<set> +set<int> ST; // Will initialize the set of int data type ST.insert(30); // Will insert the value 30 in set ST ST.insert(10); // Will insert the value 10 in set ST ST.insert(20); // Will insert the value 20 in set ST @@ -1037,47 +1037,47 @@ ST.insert(30); // Will insert the value 30 in set ST ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators -set< int >::iterator it; -for(it=ST.begin();it<ST.end();it++) -{ - cout<<*it<<endl; +set<int>::iterator it; +for(it=ST.begin();it<ST.end();it++) { + cout << *it << endl; } -// OUTPUT: +// Output: // 10 // 30 // To clear the complete container we use Container_name.clear() ST.clear(); -cout<<ST.size(); // will print the size of set ST -// OUTPUT: 0 +cout << ST.size(); // will print the size of set ST +// Output: 0 // NOTE: for duplicate elements we can use multiset -// MAP +// Map // Maps store elements formed by a combination of a key value -// and a mapped value, following a specific order +// and a mapped value, following a specific order. -#include<map> // Will include the header file for map -map< char, int >mymap; // Will initalize the map with key as char and value as int +#include<map> +map<char, int> mymap; // Will initalize the map with key as char and value as int -mymap.insert ( pair<char,int>('A',1) ); +mymap.insert(pair<char,int>('A',1)); // Will insert value 1 for key A -mymap.insert ( pair<char,int>('Z',26) ); +mymap.insert(pair<char,int>('Z',26)); // Will insert value 26 for key Z // To iterate map<char,int>::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) - std::cout << it->first << "->" << it->second <<'\n'; + std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 // Z->26 // To find the value correponsing to a key it = mymap.find('Z'); -cout<<it->second; +cout << it->second; + +// Output: 26 -// OUTPUT: 26 /////////////////////////////////// // Logical and Bitwise operators @@ -1087,17 +1087,17 @@ cout<<it->second; // Logical operators -// C++ uses Short - circuit evaluation for boolean expressions, i.e, the second argument is executed or +// C++ uses Short-circuit evaluation for boolean expressions, i.e, the second argument is executed or // evaluated only if the first argument does not suffice to determine the value of the expression true && false // Performs **logical and** to yield false true || false // Performs **logical or** to yield true -! true // Performs **logcical not** to yield +! true // Performs **logical not** to yield false // Instead of using symbols equivalent keywords can be used true and false // Performs **logical and** to yield false -true or false // Performs **logical or** to yield true -not true // Performs **logcical not** to yield +true or false // Performs **logical or** to yield true +not true // Performs **logical not** to yield false // Bitwise operators @@ -1108,20 +1108,20 @@ not true // Performs **logcical not** to yield // **>>** Right Shift Operator -// << shifts bits to the right +// >> shifts bits to the right 4 >> 1 // Shifts bits of 4 to right by 1 to give 2 -// x << n can be thought as x / 2^n +// x >> n can be thought as x / 2^n -~4 // Performs a bitwise not +~4 // Performs a bitwise not 4 | 3 // Performs bitwise or 4 & 3 // Performs bitwise and 4 ^ 3 // Performs bitwise xor // Equivalent keywords are -compl 4 // Performs a bitwise not -4 bitor 3 // Performs bitwise or +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or 4 bitand 3 // Performs bitwise and -4 xor 3 // Performs bitwise xor +4 xor 3 // Performs bitwise xor ``` diff --git a/c.html.markdown b/c.html.markdown index babf0954..92f07fe2 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -449,7 +449,8 @@ int main (int argc, char** argv) int size = 10; int *my_arr = malloc(sizeof(int) * size); // Add an element to the array - my_arr = realloc(my_arr, ++size); + size++; + my_arr = realloc(my_arr, sizeof(int) * size); my_arr[10] = 5; // Dereferencing memory that you haven't allocated gives diff --git a/elisp.html.markdown b/elisp.html.markdown index da86cab3..c88d97f0 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -194,7 +194,7 @@ filename: learn-emacs-lisp.el ;; And evaluate it: (greeting "you") -;; Some function are interactive: +;; Some functions are interactive: (read-from-minibuffer "Enter your name: ") ;; Evaluating this function returns what you entered at the prompt. diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown new file mode 100644 index 00000000..dd92eb97 --- /dev/null +++ b/es-es/powershell-es.html.markdown @@ -0,0 +1,329 @@ +--- +category: tool +tool: powershell +contributors: + - ["Wouter Van Schandevijl", "https://github.com/laoujin"] +translators: + - ["Alexander Salamanca", "https://github.com/alexitosrv"] +filename: LearnPowershell-es.ps1 +lang: es-es +--- + +PowerShell es el lenguaje de automatización y gestión de configuraciones de Windows hecho por Microsoft basado en .NET Framework. Desde Windows 7 en adelante, esos sistemas operativos incluyen un intérprete de PowerShell. +Casi todos los ejemplos a continuación pueden ser parte de un script o ejecutados directamente en la consola de PowerShell. + +Una diferencia clave con respecto a Bash es que en PowerShell casi todo son manipulaciones de objetos en vez de análisis sobre flujos de texto plano. + +[Leer más acá.](https://technet.microsoft.com/en-us/library/bb978526.aspx) (EN) + +Si no está seguro sobre el ambiente de ejecución en su sistema: + +``` +Get-ExecutionPolicy -List +Set-ExecutionPolicy AllSigned +# Otras opciones de políticas de ejecución son: +# - Restricted: Los scripts no correrán. +# - RemoteSigned: Los scripts que se hayan descargado sólo correrán si han sido firmados por un editor de confianza. +# - AllSigned: Los scripts requieren ser firmados por un editor de confianza. +# - Unrestricted: Ejecuta cualquier script. +help about_Execution_Policies # para obtener más ayuda sobre políticas de ejecución. + +# Versión instalada de PowerShell: +$PSVersionTable +``` + +Para obtener ayuda: + +``` +# Si necesita encontrar algún comando +Get-Command about_* # tiene por abreviación (o alias): gcm +Get-Command -Verb Add # lista todos los comandos que tienen por verbo 'Add' +Get-Alias ps +Get-Alias -Definition Get-Process + +Get-Help ps | less # alias: help +ps | Get-Member # alias: gm + +Show-Command Get-EventLog # Muestra un formulario para llenar los parámetros del comando Get-EventLog + +Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como admin) +``` + +Acá inicia el tutorial: + +``` +# Como ya lo notó, los comentarios empiezan con # + +# Ejemplo de un simple hola mundo: +echo Hola mundo! +# echo es el alias del comando Write-Output (a los comandos también se les dice cmdlets) +# La mayoría de los cmdlets y funciones siguen la convención de llamarse de la forma: Verbo-Sustantivo + +# Cada comando inicia en una nueva línea, o después de un punto y coma: +echo 'Esta es la primer línea'; echo 'Esta es la segunda' + +# La declaración de una variable se ve así: +$unaCadena ="Algún texto" +# O así: +$unNumero = 5 -as [double] +$unaLista = 1,2,3,4,5 +$unaCadena = $unaLista -join '--' # también existe el parámetro -split +$unaTablaHash = @{nom1='val1'; nom2='val2'} + +# Uso de variables: +echo $unaCadena +echo "Interpolación: $unaCadena" +echo "`$unaCadena tiene longitud de $($unaCadena.Length)" +echo '$unaCadena' +echo @" +Esta es una Here-String +$otraVariable +"@ +# Note que una ' (comilla simple) no expande las variables! +# Las Here-Strings también funcionan con comilla simple + +# Variables Automáticas: +# Hay algunas variables previamente definidas en el ambiente que le pueden servir, tales como +echo "Booleanos: $TRUE y $FALSE" +echo "Valor vacío: $NULL" +echo "Valor de retorno del último programa: $?" +echo "Código de salida del último programa en Windows: $LastExitCode" +echo "El último token en la última línea de la sesión activa: $$" +echo "El primer token: $^" +echo "PID del script: $PID" +echo "Ruta completa del directorio dónde está el script actual: $PSScriptRoot" +echo 'Ruta completa de script actual: ' + $MyInvocation.MyCommand.Path +echo "Ruta completa de directorio actual: $Pwd" +echo "Argumentos pasados a la invocación de una función, script o bloque de código: $PSBoundParameters" +echo "Argumentos no predefinidos: $($Args -join ', ')." +# Para saber más sobre variables automáticas: `help about_Automatic_Variables` + +# Para enlazar otro archivo (operador punto) +. .\otroNombreDeScript.ps1 + + +### Control de Flujo +# Tenemos la estructura de if como es usual: +if ($Edad -is [string]) { + echo 'Pero... si $Edad no puede ser una cadena de texto!' +} elseif ($Edad -lt 12 -and $Edad -gt 0) { + echo 'Niño (Menor de 12. Mayor que 0)' +} else { + echo 'Adulto' +} + +# Sentencias switch de PS son más poderosas comparadas con otros lenguajes +$val = "20" +switch($val) { + { $_ -eq 42 } { "La respuesta es 42"; break } + '20' { "Exactamente 20"; break } + { $_ -like 's*' } { "No distingue entre mayúsculas/minúsculas"; break } + { $_ -clike 's*'} { "clike, ceq, cne para ser diferenciar el caso entre mayúsculas/minúsculas"; break } + { $_ -notmatch '^.*$'} { "Emparejamiento de expresiones regulares. cnotmatch, cnotlike, ..."; break } + { 'x' -contains 'x'} { "FALSO! -contains es para listas!"; break } + default { "Otros" } +} + +# El for clásico +for($i = 1; $i -le 10; $i++) { + "Número de ciclo $i" +} +# O más corto +1..10 | % { "Número de ciclo $_" } + +# PowerShell también incluye +foreach ($var in 'valor1','valor2','valor3') { echo $var } +# while () {} +# do {} while () +# do {} until () + +# Manejo de excepciones +try {} catch {} finally {} +try {} catch [System.NullReferenceException] { + echo $_.Exception | Format-List -Force +} + + +### Proveedores +# Lista de archivos y directorios en la ubicación actual +ls # o el alias `dir` +cd ~ # ir al directorio principal del usuario + +Get-Alias ls # -> Get-ChildItem +# ¿¡Eh!? Estos cmdlets tienen nombres genéricos porque a diferencia de otros lenguajes de scripting, +# PowerShell no opera únicamente en el directorio actual. +cd HKCU: # se dirige a la rama HKEY_CURRENT_USER del registro de Windows + +# Para hacer un listado de todos los proveedores disponibles +Get-PSProvider + + +### Tuberías +# Los Cmdlets tienen parámetros que controlan su ejecución: +Get-ChildItem -Filter *.txt -Name # Se obtiene sólo el nombre de todos los archivos txt +# Sólo se necesita escribir caracteres de un parámetro hasta que deja de ser ambiguo +ls -fi *.txt -n # -f no se puede porque también existe -Force +# Use `Get-Help Get-ChildItem -Full` para un tratado más completo + +# Los results del cmdlet anterior se le pueden pasar como entrada al siguiente. +# `$_` representa el objeto actual en el objeto de tubería. +ls | Where-Object { $_.Name -match 'c' } | Export-CSV exportado.txt +ls | ? { $_.Name -match 'c' } | ConvertTo-HTML | Out-File exportado.html + +# Si se confunde con la tubería use `Get-Member` para revisar +# los métodos y propiedades de los objetos de la tubería: +ls | Get-Member +Get-Date | gm + +# ` es el caracter de continuación de línea. O termine la línea con un | +Get-Process | Sort-Object ID -Descending | Select-Object -First 10 Name,ID,VM ` + | Stop-Process -WhatIf + +Get-EventLog Application -After (Get-Date).AddHours(-2) | Format-List + +# Use % como una abreviación de ForEach-Object +(a,b,c) | ForEach-Object ` + -Begin { "Iniciando"; $counter = 0 } ` + -Process { "Procesando $_"; $counter++ } ` + -End { "Terminando: $counter" } + +# El siguiente comando ps (alias de Get-Process) devuelve una tabla con 3 columnas +# La tercera columan es el valor de memoria virtual en MB y usando 2 dígitos decimales +# Las columnas calculadas pueden escribirse más extensamente como: +# `@{name='lbl';expression={$_}` +ps | Format-Table ID,Name,@{n='VM(MB)';e={'{0:n2}' -f ($_.VM / 1MB)}} -autoSize + + +### Funciones +# El atributo [string] es opcional. +function foo([string]$nombre) { + echo "Hey $nombre, aquí tiene una función" +} + +# Llamando una función +foo "Diga mi nombre" + +# Funciones con parámetros nombrados, atributos de parámetros y documentación analizable +<# +.SYNOPSIS +Establecer un nuevo sitio web +.DESCRIPTION +Crea todo lo que su sitio necesite +.PARAMETER siteName +El nombre para el nuevo sitio web +.EXAMPLE +Crear-SitioWeb -Nombre SitioBonito -Po 5000 +Crear-SitioWeb SiteWithDefaultPort +Crear-SitioWeb nombreSitio 2000 # ERROR! No se pudo validar arguemento de puerto +('nombre1','nombre2') | Crear-SitioWeb -Verbose +#> +function Crear-SitioWeb() { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline=$true, Mandatory=$true)] + [Alias('nombre')] + [string]$nombreSitio, + [ValidateSet(3000,5000,8000)] + [int]$puerto = 3000 + ) + BEGIN { Write-Verbose 'Creando nuevo(s) sitio(s) web' } + PROCESS { echo "nombre: $nombreSitio, puerto: $puerto" } + END { Write-Verbose 'Sitio(s) web creado(s)' } +} + + +### Todo es .NET +# Una cadena PS es, de hecho, una cadena tipo System.String de .NET +# Todos los métodos y propiedades de .NET están disponibles +'cadena'.ToUpper().Replace('E', 'eee') +# O más powershellezco +'cadena'.ToUpper() -replace 'E', 'eee' + +# ¿No recuerda cómo es que se llama cierto método .NET? +'cadena' | gm + +# Sintaxis para ejecutar métodos .NET estáticos +[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') + +# Nótese que cualquier función que proviene de .NET Framework REQUIERE paréntesis para ser invocada +# al contrario de las funciones definidas desde PS, las cuales NO PUEDEN ser invocadas con paréntesis. +# Si se invoca una función/cmdlet de PS usando paréntesis, +# es equivalente a que le estuviera pasando un parámetro de tipo lista +$writer = New-Object System.IO.StreamWriter($ruta, $true) +$writer.Write([Environment]::NewLine) +$writer.Dispose() + +### Entrada/Salida +# Leyendo una variable +$Nombre = Read-Host "¿Cómo se llama?" +echo "¡Hola $Nombre!" +[int]$Edad = Read-Host "¿Cuál es su edad?" + +# Test-Path, Split-Path, Join-Path, Resolve-Path +# Get-Content filename # devuelve un string[] +# Set-Content, Add-Content, Clear-Content +Get-Command ConvertTo-*,ConvertFrom-* + + +### Material útil +# Actualizar la ruta de ejecuciones (PATH) +$env:PATH = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") + +# Encontrar Python en el path +$env:PATH.Split(";") | Where-Object { $_ -like "*python*"} + +# Cambiar el directorio de trabajo sin tener que memorizar la ruta anterior +Push-Location c:\temp # se cambia el directorio de trabajo a c:\temp +Pop-Location # revierte el cambio y se devuelve a donde estaba al principio +# Los aliases son : pushd y popd + +# Desbloquear un archivo después de descargarlo de Internet +Get-ChildItem -Recurse | Unblock-File + +# Abre Windows Explorer en la ruta actual (usando el alias ii de Invoke-Item) +ii . + +# Pulse cualquier tecla para salir +$host.UI.RawUI.ReadKey() +return + +# Para crear un acceso directo +$WshShell = New-Object -comObject WScript.Shell +$Shortcut = $WshShell.CreateShortcut($link) +$Shortcut.TargetPath = $file +$Shortcut.WorkingDirectory = Split-Path $file +$Shortcut.Save() +``` + + +Configurando el shell + +``` +# $Profile es la ruta completa para su `Microsoft.PowerShell_profile.ps1` +# Todo el código alojado allí será ejecutado cuando se ejecuta una nueva sesión de PS +if (-not (Test-Path $Profile)) { + New-Item -Type file -Path $Profile -Force + notepad $Profile +} +# Más información en: `help about_profiles` +# Para un shell más productivo, asegúrese de verifivar el proyecto PSReadLine descrito abajo +``` + +Proyectos interesantes (EN) + +* [Channel9](https://channel9.msdn.com/Search?term=powershell%20pipeline#ch9Search&lang-en=en) Tutoriales de PowerShell +* [PSGet](https://github.com/psget/psget) NuGet para PowerShell +* [PSReadLine](https://github.com/lzybkr/PSReadLine/) Una implementación inspirada en bash para PowerShell (¡Es tan buena que ahora viene con Windows10 por defecto!) +* [Posh-Git](https://github.com/dahlbyk/posh-git/) Un intérprete bonito de Git (¡Recomendado!) +* [PSake](https://github.com/psake/psake) Herramienta de automatización de compilaciones +* [Pester](https://github.com/pester/Pester) Framework de pruebas BDD +* [Jump-Location](https://github.com/tkellogg/Jump-Location) Powershell `cd` que lee su mente + + +Material no cubierto en esta guía + +* WMI: Windows Management Intrumentation (Get-CimInstance) +* Multitarea: Start-Job -scriptBlock {...}, +* Firmas de código +* Remoting (Enter-PSSession/Exit-PSSession; Invoke-Command) diff --git a/fortran95.html.markdown b/fortran95.html.markdown new file mode 100644 index 00000000..8479fef8 --- /dev/null +++ b/fortran95.html.markdown @@ -0,0 +1,452 @@ +--- +language: Fortran +contributors: + - ["Robert Steed", "https://github.com/robochat"] +filename: learnfortran.f95 +--- + +Fortran is one of the oldest computer languages. It was developed in the 1950s +by IBM for numeric calculations (Fortran is an abreviation of "Formula +Translation"). Despite its age, it is still used for high-performance computing +such as weather prediction. However, the language has changed considerably over +the years, although mostly maintaining backwards compatibility; well known +versions are FORTRAN 77, Fortran 90, Fortran 95, Fortran 2003, Fortran 2008 and +Fortran 2015. + +This overview will discuss the features of Fortran 95 since it is the most +widely implemented of the more recent specifications and the later versions are +largely similar (by comparison FORTRAN 77 is a very different language). + +```fortran + +! This is a comment. + + +program example !declare a program called example. + + ! Code can only exist inside programs, functions, subroutines or modules. + ! Using indentation is not required but it is recommended. + + + ! Declaring Variables + ! =================== + + ! All declarations must come before statements and expressions. + + implicit none !prevents dynamic declaration of variables (recommended!) + ! Implicit none must be redeclared in every function/program/module... + + ! IMPORTANT - Fortran is case insensitive. + real z + REAL Z2 + + real :: v,x ! WARNING: default initial values are compiler dependent! + real :: a = 3, b=2E12, c = 0.01 + integer :: i, j, k=1, m + real, parameter :: PI = 3.1415926535897931 !declare a constant. + logical :: y = .TRUE. , n = .FALSE. !boolean type. + complex :: w = (0,1) !sqrt(-1) + character (len=3) :: month !string of 3 characters. + + real :: array(6) !declare an array of 6 reals. + real, dimension(4) :: arrayb !another way to declare an array. + integer :: arrayc(-10:10) !an array with a custom index. + real :: array2d(3,2) !multidimensional array. + + ! The '::' separators are not always necessary but are recommended. + + ! many other variable attributes also exist: + real, pointer :: p !declare a pointer. + + integer, parameter :: LP = selected_real_kind(20) + real (kind = LP) :: d !long precision variable. + + ! WARNING: initialising variables during declaration causes problems + ! in functions since this automatically implies the 'save' attribute + ! whereby values are saved between function calls. In general, separate + ! declaration and initialisation code except for constants! + + + ! Strings + ! ======= + + character :: a_char = 'i' + character (len = 6) :: a_str = "qwerty" + character (len = 30) :: str_b + character (len = *), parameter :: a_long_str = "This is a long string." + !can have automatic counting of length using (len=*) but only for constants. + + str_b = a_str // " keyboard" !concatenate strings using // operator. + + + ! Assignment & Arithmetic + ! ======================= + + Z = 1 !assign to variable z declared above (case insensitive). + j = 10 + 2 - 3 + a = 11.54 / (2.3 * 3.1) + b = 2**3 !exponentiation + + + ! Control Flow Statements & Operators + ! =================================== + + ! Single-line if statement + if (z == a) b = 4 !condition always need surrounding parentheses. + + if (z /= a) then !z not equal to a + ! Other symbolic comparisons are < > <= >= == /= + b = 4 + else if (z .GT. a) then !z greater than a + ! Text equivalents to symbol operators are .LT. .GT. .LE. .GE. .EQ. .NE. + b = 6 + else if (z < a) then !'then' must be on this line. + b = 5 !execution block must be on a new line. + else + b = 10 + end if !end statement needs the 'if' (or can use 'endif'). + + + if (.NOT. (x < c .AND. v >= a .OR. z == z)) then !boolean operators. + inner: if (.TRUE.) then !can name if-construct. + b = 1 + endif inner !then must name endif statement. + endif + + + i = 20 + select case (i) + case (0) !case i == 0 + j=0 + case (1:10) !cases i is 1 to 10 inclusive. + j=1 + case (11:) !all cases where i>=11 + j=2 + case default + j=3 + end select + + + month = 'jan' + ! Condition can be integer, logical or character type. + ! Select constructions can also be named. + monthly: select case (month) + case ("jan") + j = 0 + case default + j = -1 + end select monthly + + + do i=2,10,2 !loops from 2 to 10 (inclusive) in increments of 2. + innerloop: do j=1,3 !loops can be named too. + exit !quits the loop. + end do innerloop + cycle !jump to next loop iteration. + enddo + + + ! Goto statement exists but it is heavily discouraged though. + goto 10 + stop 1 !stops code immediately (returning specified condition code). +10 j = 201 !this line is labeled as line 10 + + + ! Arrays + ! ====== + array = (/1,2,3,4,5,6/) + array = [1,2,3,4,5,6] !using Fortran 2003 notation. + arrayb = [10.2,3e3,0.41,4e-5] + array2d = reshape([1.0,2.0,3.0,4.0,5.0,6.0], [3,2]) + + ! Fortran array indexing starts from 1. + ! (by default but can be defined differently for specific arrays). + v = array(1) !take first element of array. + v = array2d(2,2) + + print *, array(3:5) !print all elements from 3rd to 5th (inclusive). + print *, array2d(1,:) !print first column of 2d array. + + array = array*3 + 2 !can apply mathematical expressions to arrays. + array = array*array !array operations occur element-wise. + !array = array*array2d !these arrays would not be compatible. + + ! There are many built-in functions that operate on arrays. + c = dot_product(array,array) !this is the dot product. + ! Use matmul() for matrix maths. + c = sum(array) + c = maxval(array) + print *, minloc(array) + c = size(array) + print *, shape(array) + m = count(array > 0) + + ! Loop over an array (could have used Product() function normally). + v = 1 + do i = 1, size(array) + v = v*array(i) + end do + + ! Conditionally execute element-wise assignments. + array = [1,2,3,4,5,6] + where (array > 3) + array = array + 1 + elsewhere (array == 2) + array = 1 + elsewhere + array = 0 + end where + + ! Implied-DO loops are a compact way to create arrays. + array = [ (i, i = 1,6) ] !creates an array of [1,2,3,4,5,6] + array = [ (i, i = 1,12,2) ] !creates an array of [1,3,5,7,9,11] + array = [ (i**2, i = 1,6) ] !creates an array of [1,4,9,16,25,36] + array = [ (4,5, i = 1,3) ] !creates an array of [4,5,4,5,4,5] + + + ! Input/Output + ! ============ + + print *, b !print the variable 'b' to the command line + + ! We can format our printed output. + print "(I6)", 320 !prints ' 320' + print "(I6.4)", 3 !prints ' 0003' + print "(F6.3)", 4.32 !prints ' 4.320' + + ! The letter indicates the expected type and the number afterwards gives + ! the number of characters to use for printing the value. + ! Letters can be I (integer), F (real), E (engineering format), + ! L (logical), A (characters) ... + print "(I3)", 3200 !print '***' since the number doesn't fit. + + ! we can have multiple format specifications. + print "(I5,F6.2,E6.2)", 120, 43.41, 43.41 + print "(3I5)", 10, 20, 30 !3 repeats of integers (field width = 5). + print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 !repeated grouping of formats. + + ! We can also read input from the terminal. + read *, v + read "(2F6.2)", v, x !read two numbers + + ! To read a file. + open(unit=11, file="records.txt", status="old") + ! The file is referred to by a 'unit number', an integer that you pick in + ! the range 9:99. Status can be one of {'old','replace','new'}. + read(unit=11, fmt="(3F10.2)") a, b, c + close(11) + + ! To write a file. + open(unit=12, file="records.txt", status="replace") + write(12, "(F10.2,F10.2,F10.2)") c, b, a + close(12) + + ! There are more features available than discussed here and alternative + ! variants due to backwards compatability with older Fortran versions. + + + ! Built-in Functions + ! ================== + + ! Fortran has around 200 functions/subroutines intrinsic to the language. + ! Examples - + call cpu_time(v) !sets 'v' to a time in seconds. + k = ior(i,j) !bitwise OR of 2 integers. + v = log10(x) !log base 10. + i = floor(b) !returns the closest integer less than or equal to x. + v = aimag(w) !imaginary part of a complex number. + + + ! Functions & Subroutines + ! ======================= + + ! A subroutine runs some code on some input values and can cause + ! side-effects or modify the input values. + + call routine(a,c,v) !subroutine call. + + ! A function takes a list of input parameters and returns a single value. + ! However the input parameters may still be modified and side effects + ! executed. + + m = func(3,2,k) !function call. + + ! Function calls can also be evoked within expressions. + Print *, func2(3,2,k) + + ! A pure function is a function that doesn't modify its input parameters + ! or cause any side-effects. + m = func3(3,2,k) + + +contains ! Zone for defining sub-programs internal to the program. + + ! Fortran has a couple of slightly different ways to define functions. + + integer function func(a,b,c) !a function returning an integer value. + implicit none !best to use implicit none in function definitions too. + integer :: a,b,c !type of input parameters defined inside the function. + if (a >= 2) then + func = a + b + c !the return variable defaults to the function name. + return !can return the current value from the function at any time. + endif + func = a + c + ! Don't need a return statement at the end of a function. + end function func + + + function func2(a,b,c) result(f) !return variable declared to be 'f'. + implicit none + integer, intent(in) :: a,b !can declare and enforce that variables + !are not modified by the function. + integer, intent(inout) :: c + integer :: f !function return type declared inside the function. + integer :: cnt = 0 !GOTCHA - initialisation implies variable is + !saved between function calls. + f = a + b - c + c = 4 !altering the value of an input variable. + cnt = cnt + 1 !count number of function calls. + end function func2 + + + pure function func3(a,b,c) !a pure function can have no side-effects. + implicit none + integer, intent(in) :: a,b,c + integer :: func3 + func3 = a*b*c + end function func3 + + + subroutine routine(d,e,f) + implicit none + real, intent(inout) :: f + real, intent(in) :: d,e + f = 2*d + 3*e + f + end subroutine routine + + +end program example ! End of Program Definition ----------------------- + + +! Functions and Subroutines declared externally to the program listing need +! to be declared to the program using an Interface declaration (even if they +! are in the same source file!) (see below). It is easier to define them within +! the 'contains' section of a module or program. + +elemental real function func4(a) result(res) +! An elemental function is a Pure function that takes a scalar input variable +! but can also be used on an array where it will be separately applied to all +! of the elements of an array and return a new array. + real, intent(in) :: a + res = a**2 + 1.0 +end function func4 + + +! Modules +! ======= + +! A module is a useful way to collect related declarations, functions and +! subroutines together for reusability. + +module fruit + real :: apple + real :: pear + real :: orange +end module fruit + + +module fruity + ! Declarations must be in the order: modules, interfaces, variables. + ! (can declare modules and interfaces in programs too). + + use fruit, only: apple, pear ! use apple and pear from fruit module. + implicit none !comes after module imports. + + private !make things private to the module (default is public). + ! Declare some variables/functions explicitly public. + public :: apple,mycar,create_mycar + ! Declare some variables/functions private to the module (redundant here). + private :: func4 + + ! Interfaces + ! ========== + ! Explicitly declare an external function/procedure within the module + ! (better in general to put functions/procedures in the 'contains' section). + interface + elemental real function func4(a) result(res) + real, intent(in) :: a + end function func4 + end interface + + ! Overloaded functions can be defined using named interfaces. + interface myabs + ! Can use 'module procedure' keyword to include functions already + ! defined within the module. + module procedure real_abs, complex_abs + end interface + + ! Derived Data Types + ! ================== + ! Can create custom structured data collections. + type car + character (len=100) :: model + real :: weight !(kg) + real :: dimensions(3) !i.e. length-width-height (metres). + character :: colour + end type car + + type(car) :: mycar !declare a variable of your custom type. + ! See create_mycar() routine for usage. + + ! Note: There are no executable statements in modules. + +contains + + subroutine create_mycar(mycar) + ! Demonstrates usage of a derived data type. + implicit none + type(car),intent(out) :: mycar + + ! Access type elements using '%' operator. + mycar%model = "Ford Prefect" + mycar%colour = 'r' + mycar%weight = 1400 + mycar%dimensions(1) = 5.0 !default indexing starts from 1! + mycar%dimensions(2) = 3.0 + mycar%dimensions(3) = 1.5 + + end subroutine + + real function real_abs(x) + real :: x + if (x<0) then + real_abs = -x + else + real_abs = x + end if + end function real_abs + + real function complex_abs(z) + complex :: z + ! long lines can be continued using the continuation character '&' + complex_abs = sqrt(real(z)**2 + & + aimag(z)**2) + end function complex_abs + + +end module fruity + +``` + +### More Resources + +For more information on Fortran: + ++ [wikipedia](https://en.wikipedia.org/wiki/Fortran) ++ [Fortran_95_language_features](https://en.wikipedia.org/wiki/Fortran_95_language_features) ++ [fortranwiki.org](http://fortranwiki.org) ++ [www.fortran90.org/](http://www.fortran90.org) ++ [list of Fortran 95 tutorials](http://www.dmoz.org/Computers/Programming/Languages/Fortran/FAQs%2C_Help%2C_and_Tutorials/Fortran_90_and_95/) ++ [Fortran wikibook](https://en.wikibooks.org/wiki/Fortran) ++ [Fortran resources](http://www.fortranplus.co.uk/resources/fortran_resources.pdf) ++ [Mistakes in Fortran 90 Programs That Might Surprise You](http://www.cs.rpi.edu/~szymansk/OOF90/bugs.html) diff --git a/fr-fr/rust-fr.html.markdown b/fr-fr/rust-fr.html.markdown new file mode 100644 index 00000000..0fa16075 --- /dev/null +++ b/fr-fr/rust-fr.html.markdown @@ -0,0 +1,319 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Ryan Rembert", "http://jrrembert.github.io"] +filename: learnrust-fr.rs +lang: fr-fr +--- + +Rust est un langage de programmation développé par Mozilla Research. Rust combine le contrôle de bas niveau sur la performance avec la commodité et la sécurité garanties de haut niveau. + +Il atteint ces objectifs sans avoir besoin d'un ramasse-miettes ou environnement d'exécution, ce qui rend possible l'utilisation de bibliothèques Rust comme une substitution directe pour C. + +La première version de Rust, 0.1, est sortie en janvier 2012 et a tellement évolué rapidement que jusqu'à récemment, l'utilisation de versions stables était déconseillée - à la place ce était conseillé d'utiliser les nightly builds. + +Le 15 mai 2015, Rust 1.0 a été libéré avec une garantie complète de compatibilité ascendante. Améliorations aux temps de compilation et d'autres aspects du compilateur sont actuellement disponibles dans la nightly builds. Rust a adopté un modèle de libération à bord du train avec les versions régulières toutes les six semaines. Rust 1.1 beta a été mis à la disposition dans le même temps de la libération de Rust 1.0. + +Bien que Rust soit un langage relativement bas niveau, Rust a quelques concepts fonctionnels qui se trouvent généralement dans les langues de niveau supérieur. Cela rend Rust non seulement rapide, mais aussi efficace et facile à coder. + +```rust +// Ceci est un commentaire. commentaires de ligne ressemblent à ceci ... +// Et prolonger plusieurs lignes comme celle-ci. + +/// Les commentaires de documentation ressemblent à ceci et à soutenir +/// la notation de démarques. +/// # Exemples +/// +/// ``` +/// let cinq = 5 +/// ``` + +/////////////// +// 1. Basics // +/////////////// + +// Les fonctions +// `I32` est le type 32 bits entiers signés +fn add2(x: i32, y: i32) -> i32 { + // Retour implicite (pas virgule) + x + y +} + +// Fonction principale +fn main() { + // Nombres // + + // Reliures immutable + let x: i32 = 1; + + // Entier suffixes/float + let y: I32 = 13i32; + let f: f64 = 1.3f64; + + // Type Inférence + // La plupart du temps, le compilateur Rust peut déduire le type de variable + // est, donc vous ne devez pas écrire une annotation de type explicite. + // Tout au long de ce tutoriel, les types sont explicitement annotées dans + // de nombreux endroits, mais seulement à des fins de démonstration. + // L'inférence de type peut gérer cela pour vous la plupart du temps. + let implicit_x = 1; + let implicit_f = 1,3; + + // Arithmétique + let somme = x + y + 13; + + // Variable Mutable + let mut mutable = 1; + let mutable = 4; + let mutable += 2; + + // Chaînes // + + // Littéraux chaîne + let x: &str = "Bonjour tout le monde!"; + + // Impression + println!("{} {}", f, x); // 1.3 Bonjour tout le monde + + // A `Chaîne` - une chaîne de tas alloué + let s: String = "Bonjour tout le monde".to_string(); + + // Une tranche de chaîne - une vue immutable dans une else chaîne. + // Ceci est essentiellement un pointeur immutable à une chaîne - il n'a pas + // contient effectivement le contenu d'une chaîne, juste un pointeur vers + // quelque chose qui fait(dans ce cas, `s`). + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // Bonjour monde Bonjour tout le monde + + // Vecteurs/tableau // + + // Un tableau de taille fixe + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // Un tableau dynamique(vecteur) + let mut vecteur: Vec<i32> = vec![1, 2, 3, 4]; + vecteur.push(5); + + // Une tranche - une vue immutable dans un vecteur ou un tableau. + // Ceci est un peu comme une tranche de chaîne, mais pour les vecteurs. + let tranche: &[i32] = &vecteur; + + // Utiliser `{:?}` pour imprimer quelque chose de débogage de style + println!("{:?} {:?}", vecteur, tranche); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuples // + + // Un tuple est un ensemble de valeurs de peut-être différents types. + // de taille fixe + let x:(i32, &str, f64) = (1, "bonjour", 3.4); + + // Déstructurante `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 bonjour 3.4 + + // indexation + println!("{}", x.1); // Bonjour + + ////////////// + // 2. Types // + ////////////// + + // Struct + struct Point { + x: i32, + y: i32, + } + + let origine: Point = Point { x: 0, y: 0 }; + + // Un struct avec des champs sans nom, appelé 'tuple struct'. + struct Point2(i32, i32); + + let origine2 = Point2(0, 0); + + // Basic C-like enum + enum Direction { + Àgauche, + Droite, + En_Haut, + Vers_Le_Bas, + } + + let en_haut = Direction::En_Haut; + + // Enum avec des champs + enum OptionnelI32 { + AnI32(I32), + Rien, + } + + let deux: OptionnelI32 = OptionnelI32::AnI32(2); + let rien = OptionnelI32::Rien; + + // Generics // + + struct Foo<T> { bar: T } + + // Ceci est défini dans la bibliothèque standard comme `Option`. + enum Optionnel<T> { + SomeVal(T), + NoVal, + } + + // Méthodes // + + impl<T> Foo<T> { + // Méthodes prennent un paramètre explicite `de self`. + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // Traits (connu sous le nom des interfaces ou des classes de types dans + // d'elses langues). + + trait Frobnicate<T> { + fn frobnicate(self) -> Option<T>; + } + + impl<T> Frobnicate<T> for Foo<T> { + fn frobnicate(self) -> Option<T> { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + ///////////////////////// + // 3. Motif correspondant // + ///////////////////////// + + let foo = OptionnelI32::AnI32(1); + match foo { + OptionnelI32::AnI32(n) => println!("Il est un i32: {}", n), + OptionnelI32::Rien => println!("Il n'y a rien!"), + } + + // Motif avancé correspondant + struct FooBar { x: i32, y: OptionnelI32 } + let bar = FooBar { x: 15, y: OptionnelI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionnelI32 :: AnI32(0)} => + println!("Les chiffres sont nuls!"), + FooBar { x: n, y: OptionnelI32 :: AnI32(m)} if n == m => + println!("Les chiffres sont les mêmes"), + FooBar { x: n, y: OptionnelI32 :: AnI32(m)} => + println!("Différents numéros: {} {}", n, m)!, + FooBar { x: _, y: OptionnelI32 :: Rien} => + println!("Le deuxième numéro est rien!"), + } + + ///////////////////// + // 4. Flux de contrôle // + ///////////////////// + + // `for` boucles / itération + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Ranges + for i in 0u32..10 { + print!("{}", i); + } + println!(""); + // imprime `0 1 2 3 4 5 6 7 8 9` + + // `if` + if 1 == 1 { + println!("Maths est travaille!"); + } else { + println!("Oh non ...!"); + } + + // `if` comme expression + let valeur = if true { + "bien" + } else { + "mal" + }; + + // `while` boucle + while 1 == 1 { + println!("L'univers fonctionne normalement."); + } + + // Boucle infinie + loop { + println!("Bonjour!"); + } + + ///////////////////////////////// + // 5. Sécurité & pointeurs mémoire // + ///////////////////////////////// + + // Pointeur occasion - une seule chose peut "posséder" pointeur à un moment. + // Cela signifie que lorsque le `Box` laisse son champ d'application, il + // peut être automatiquement libérée en toute sécurité. + let mut mien: Box<i32> = Box::new(3); + *mien = 5; // déréférencer + // Ici, `now_its_mine` prend possession de` mine`. En d'elses termes, + // `mien` est déplacé. + let mut now_its_mine = mien; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", de la mine); // Cela ne compile pas parce + // que `now_its_mine` possède maintenant le pointeur + + // Référence - un pointeur immutable qui fait référence à d'elses données. + // Quand une référence est prise à une valeur, nous disons que la valeur + // a été "emprunté". + // Même si une valeur est emprunté immutablement, il ne peut pas être + // muté ou déplacé. + // Un emprunt dure jusqu'à la fin de la portée, il a été créé. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // Contrairement `box`, `var` peut encore être utilisé + println!("{}", *ref_var); + // Var = 5; // Cela ne compile pas parce que `var` est emprunté. + // *ref_var = 6; // Ce ne serait pas non plus, parce que `ref_var` est une + // référence immutable. + + // Référence Mutable + // Même si une valeur est mutably emprunté, il ne peut pas être + // accessible à tous. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + // '*' est utilisé pour pointer vers le var2 mutably emprunté. + *ref_var2 += 2; + + println!("{}", * ref_var2); // 6, // var2 ne serait pas compiler. + // ref_var2 est de type &mut i32 donc stocke il référence à i32, + // pas la valeur. + // var2 = 2; // Cela ne compile pas parce que `var2` est emprunté. +} +``` + +## Autres lectures + +Il y a beaucoup plus à Rust -- ce est juste l'essentiel de Rust afin que vous puissiez comprendre +les choses les plus importantes. Pour en savoir plus sur Rust, lire [La Programmation Rust +Langue](http://doc.rust-lang.org/book/index.html) et etudier la +[/r/rust](http://reddit.com/r/rust) subreddit. Les gens sur le canal de #rust sur +irc.mozilla.org sont aussi toujours prêts à aider les nouveaux arrivants. + +Vous pouvez également essayer caractéristiques de Rust avec un compilateur en ligne sur le fonctionnaire +[Rust parc](http://play.rust-lang.org) ou sur la principale +[Site Rust](http://rust-lang.org). diff --git a/fsharp.html.markdown b/fsharp.html.markdown index e345201d..69f4eb60 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -175,7 +175,12 @@ module ListExamples = // list comprehensions (aka generators) let squares = [for i in 1..10 do yield i * i] - // prime number generator + // A prime number generator + // - this is using a short notation for the pattern matching syntax + // - (p::xs) is 'first :: tail' of the list, could also be written as p :: xs + // this means this matches 'p' (the first item in the list), and xs is the rest of the list + // this is called the 'cons pattern' + // - uses 'rec' keyword, which is necessary when using recursion let rec sieve = function | (p::xs) -> p :: sieve [ for x in xs do if x % p > 0 then yield x ] | [] -> [] diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown new file mode 100644 index 00000000..dd5005f2 --- /dev/null +++ b/it-it/rust-it.html.markdown @@ -0,0 +1,321 @@ +--- +language: rust +contributors: + - ["Carlo Milanesi", "http://github.com/carlomilanesi"] +filename: rust-it.html.markdown +--- + +Rust è un linguaggio di programmazione sviluppato da Mozilla Research. +Rust combina il controllo a basso livello sulle prestazioni con alcune comodità +ad alto livello e stringenti garanzie di sicurezza. + +Rust raggiunge questi obiettivi senza richiedere la garbage collection né una grossa +libreria di supporto run-time, rendendo così possibile l'uso di librerie scritte in Rust +come rimpiazzo di librerie scritte in C. + +La prima versione pubblica di Rust, la 0.1, è stata rilasciata nel gennaio 2012, e per 3 anni +lo sviluppo è proceduto così rapidamente che l'utilizzo delle versioni +stabili veniva scoraggiato, e piuttosto si consigliava di utilizzare le versioni notturne +(nightly build). + +Il 15 maggio 2015, la versione 1.0 di Rust è stata rilasciata con la garanzia +che nelle successive versioni 1.x non ci sarebbero state modifiche che avrebbero reso +incompatibile il codice scritto per tale versione. +Nelle nightly build sono attualmente disponibili migliorie al tempo di compilazione +e ad altri aspetti del compilatore. Rust ha adottato un modello di rilascio a scaglioni +con rilasci regolari ogni sei settimane. Per esempio, la versione 1.1 beta è stata resa +disponibile contestualmente al rilascio della versione stabile 1.0. + +Sebbene Rust sia un linguaggio di livello relativamente basso, Rust ha alcuni concetti +di programmazione funzionale che solitamente si trovano solo nei linguaggi di livello più alto. +Ciò rende Rust non solo veloce, ma anche facile ed comodo da usare. + +```rust +// I commenti che stanno su una sola riga sono fatti così... +/* ...mentre così sono fatti +i commenti che richiedono +più righe */ + +/////////////////// +// 1. Fondamenti // +/////////////////// + +// Funzioni +// `i32` è il tipo per gli interi a 32-bit con segno +fn add2(x: i32, y: i32) -> i32 { + // return implicito (senza punto-e-virgola) + x + y +} + +// Funzione "main" +fn main() { + // Numeri // + + // Binding (ossia "variabili") immutabili + let x: i32 = 1; + + // Suffissi intero/virgola mobile + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // Inferenza di tipo + // La maggior parte delle volte, il compilatore Rust può inferire + // di quale tipo sia l'espressione usata per inizializzare un binding, + // e quindi non è necessario specificare esplicitamente il tipo. + // In tutto questo tutorial, i tipi vengono specificati esplicitamente in molti posti, + // ma solo a scopo dimostrativo. La maggior parte delle volte se ne potrebbe + // fare a meno, grazie all'inferenza di tipo. + let implicito_x = 1; + let implicito_f = 1.3; + + // Aritmetica + let somma = x + y + 13; + + // Variabile mutevole + let mut mutevole = 1; + mutevole = 4; + mutevole += 2; + + // Stringhe // + + // Letterali di stringa + let x: &str = "Ciao mondo!"; + + // Stampa + println!("{} {}", f, x); // 1.3 Ciao mondo! + + // Una `String` – una stringa allocata nello heap + let s: String = "Ciao mondo".to_string(); + + // Uno slice (fetta) di stringa – una vista immutabile + // all'interno di un'altra stringa. + // Uno slice è una coppia immutabile di puntatori al buffer contenuto + // nella stringa - non contiene dei caratteri, solo dei puntatori a + // un buffer statico o a un buffer contenuto in un altro oggetto (in questo caso, `s`) + let s_slice: &str = &s; + + println!("{} - {}", s, s_slice); // Ciao mondo - Ciao mondo + + // Vettori/array // + + // Un array di lunghezza fissa + let quattro_int: [i32; 4] = [1, 2, 3, 4]; + + // Un array dinamico (vettore) + let mut vettore: Vec<i32> = vec![1, 2, 3, 4]; + vettore.push(5); + + // Uno slice – una vista immutabile all'interno di un vettore o di un array + // E' molto simile a uno slice di stringa, ma per i vettori + let slice: &[i32] = &vettore; + + // Usa `{:?}` per stampare qualcosa a scopo di debugging + println!("{:?} {:?}", vettore, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // Tuple // + + // Una tupla è un insieme ordinato di dimensione fissa di valori aventi tipi eventualmente diversi + let x: (i32, &str, f64) = (1, "ciao", 3.4); + + // Il `let` che destruttura + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 ciao 3.4 + + // Indicizzazione + println!("{}", x.1); // ciao + + ///////////// + // 2. Tipi // + ///////////// + + // Strutture + struct Point { + x: i32, + y: i32, + } + + let origine: Punto = Punto { x: 0, y: 0 }; + + // Ana struct con campi senza nome, chiamata ‘tuple struct’ + struct Punto2(i32, i32); + + let origine2 = Punto2(0, 0); + + // Enum basilare, analoga a quelle del linguaggio C + enum Direzione { + Sinistra, + Destra, + Su, + Giu, + } + + let su = Direzione::Su; + + // Enum con campi + enum OpzionaleI32 { + UnI32(i32), + Niente, + } + + let due: OpzionaleI32 = OpzionaleI32::UnI32(2); + let niente = OpzionaleI32::Niente; + + // Generici // + + struct Foo<T> { bar: T } + + // Questo è definito nella libreria standard come `Option` + enum Opzionale<T> { + QualcheValore(T), + NessunValore, + } + + // Metodi // + + impl<T> Foo<T> { + // I metodi di oggetto prendono un parametro `self` esplicito + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // I trait (tratti), noti come "interfacce" o "mixin" in altri linguaggi + + trait Maneggiamento<T> { + fn maneggia(self) -> Option<T>; + } + + impl<T> Maneggiamento<T> for Foo<T> { + fn maneggia(self) -> Option<T> { + Some(self.bar) + } + } + + let altro_foo = Foo { bar: 1 }; + println!("{:?}", altro_foo.maneggia()); // Some(1) + + ///////////////////////// + // 3. Pattern matching // + ///////////////////////// + + let foo = OpzionaleI32::UnI32(1); + match foo { + OpzionaleI32::UnI32(n) => println!("E' un i32: {}", n), + OpzionaleI32::Niente => println!("Non vale niente!"), + } + + // Pattern matching avanzato + struct FooBar { x: i32, y: OpzionaleI32 } + let bar = FooBar { x: 15, y: OpzionaleI32::UnI32(32) }; + + match bar { + FooBar { x: 0, y: OpzionaleI32::UnI32(0) } => + println!("I numeri valgono zero!"), + FooBar { x: n, y: OpzionaleI32::UnI32(m) } if n == m => + println!("I numeri sono identici"), + FooBar { x: n, y: OpzionaleI32::UnI32(m) } => + println!("Numeri diversi: {} {}", n, m), + FooBar { x: _, y: OpzionaleI32::Niente } => + println!("Il secondo numbero non vale niente!"), + } + + /////////////////////////////////////////// + // 4. Flusso di controllo (Control flow) // + /////////////////////////////////////////// + + // Ciclo/iterazione con `for` + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // Range + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // Stampa `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("La matematica funziona!"); + } else { + println!("Oh no..."); + } + + // `if` come espressione + let value = if true { + "bene" + } else { + "male" + }; + + // Ciclo `while` + while 1 == 1 { + println!("L'universo sta funzionando regolarmente."); + } + + // Ciclo infinito + loop { + println!("Ciao!"); + } + + ///////////////////////////////////////////////// + // 5. La sicurezza della memoria e i puntatori // + ///////////////////////////////////////////////// + + // Puntatore posseduto (owned) – solamente una cosa sola per volta può ‘possedere’ questo puntatore + // Ciò significa che quando il `Box` abbandona il suo scope, verrà automaticamente deallocato in sicurezza. + let mut mio: Box<i32> = Box::new(3); + *mio = 5; // dereference + // Qui, `adesso_e_mio` acquisisce la proprietà di `mio`. In altre parole, `mio` viene spostato. + let mut adesso_e_mio = mio; + *adesso_e_mio += 2; + + println!("{}", adesso_e_mio); // 7 + // println!("{}", mio); // questo non compilerebbe perché `adesso_e_mio` adesso possiede il puntatore + + // Riferimento (reference) – un puntatore immutabile che si riferisce ad altri dati + // Quando un riferimento viene preso a un valore, diciamo che quel valore + // è stato ‘preso in prestito’ (borrowed). + // Mentre un valore è preso in prestito immutabilmente, non può venire mutato né spostato. + // Un prestito dura fino alla fine dello scope in cui è stato creato. + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); // Diversamente da `box`, `var` può ancora essere usato + println!("{}", *ref_var); + // var = 5; // questo non compilerebbe, perché `var` è stato preso in prestito + // *ref_var = 6; // neanche questo, perché `ref_var` è un riferimento immutabile + + // Riferimento immutabile + // Mentre un valore è preso in presto mutevolmente, non può essere acceduto in nessun modo. + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; // '*' serve a puntare al binding var2, preso in presto mutevolmente + + println!("{}", *ref_var2); // 6 + // var2 non compilerebbe. ref_var2 è di tipo &mut i32, e quindi + // immagazzina un riferimento a un i32, e non il valore stesso. + // var2 = 2; // questo non compilerebbe, perché `var2` è stato preso in prestito +} +``` + +## Ulteriori letture + +C'è molto di più in Rust — questi sono solo i fondamenti di Rust, che servono a capire +le cose più importanti. + +Purtroppo c'è pochissima documentazione in italiano, tra cui: +(https://www.mozillaitalia.org/home/2015/05/30/primi-passi-con-rust/) + +Però ce n'è parecchia in inglese. Per saperne di più, leggi [The Rust Programming +Language](http://doc.rust-lang.org/book/index.html) e tieni d'occhio l'area di interesse di Reddit (subreddit) +[/r/rust](http://reddit.com/r/rust). + +Puoi anche provare a programmare in varie versioni di Rust usando il compilatore online al sito ufficiale +[Rust playpen](http://play.rust-lang.org). diff --git a/rust.html.markdown b/rust.html.markdown index 4aa9ca7c..f1b62ef4 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -88,9 +88,10 @@ fn main() { let s: String = "hello world".to_string(); // A string slice – an immutable view into another string - // This is basically an immutable pointer to a string – it doesn’t + // This is basically an immutable pair of pointers to a string – it doesn’t // actually contain the contents of a string, just a pointer to - // something that does (in this case, `s`) + // the begin and a pointer to the end of a string buffer, + // statically allocated or contained in another object (in this case, `s`) let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world diff --git a/scala.html.markdown b/scala.html.markdown index 7f5f0ec3..5e3ece2d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -12,22 +12,62 @@ Scala - the scalable language ```scala +///////////////////////////////////////////////// +// 0. Basics +///////////////////////////////////////////////// /* - Set yourself up: + Setup Scala: 1) Download Scala - http://www.scala-lang.org/downloads 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable - 3) Start a Scala REPL by running `scala`. You should see the prompt: - - scala> - - This is the so called REPL (Read-Eval-Print Loop). You may type any Scala - expression, and the result will be printed. We will explain what Scala files - look like further into this tutorial, but for now, let's start with some - basics. - */ +/* + Try the REPL + + Scala has a tool called the REPL (Read-Eval-Print Loop) that is anologus to + commandline interpreters in many other languages. You may type any Scala + expression, and the result will be evaluated and printed. + + The REPL is a very handy tool to test and verify code. Use it as you read + this tutorial to quickly explore concepts on your own. +*/ + +// Start a Scala REPL by running `scala`. You should see the prompt: +$ scala +scala> + +// By default each expression you type is saved as a new numbered value +scala> 2 + 2 +res0: Int = 4 + +// Default values can be reused. Note the value type displayed in the result.. +scala> res0 + 2 +res1: Int = 6 + +// Scala is a strongly typed language. You can use the REPL to check the type +// without evaluating an expression. +scala> :type (true, 2.0) +(Boolean, Double) + +// REPL sessions can be saved +scala> :save /sites/repl-test.scala + +// Files can be loaded into the REPL +scala> :load /sites/repl-test.scala +Loading /sites/repl-test.scala... +res2: Int = 4 +res3: Int = 6 + +// You can search your recent history +scala> :h? +1 2 + 2 +2 res0 + 2 +3 :save /sites/repl-test.scala +4 :load /sites/repl-test.scala +5 :h? + +// Now that you know how to play, let's learn a little scala... ///////////////////////////////////////////////// // 1. Basics diff --git a/sv-se/json-sv.html.markdown b/sv-se/json-sv.html.markdown index c2ee36dd..002aec2e 100644 --- a/sv-se/json-sv.html.markdown +++ b/sv-se/json-sv.html.markdown @@ -4,18 +4,30 @@ filename: learnjson-sv.json contributors: - ["Anna Harren", "https://github.com/iirelu"] - ["Marco Scannadinari", "https://github.com/marcoms"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Michael Neth", "https://github.com/infernocloud"] translators: - ["Lari Kovanen", "https://github.com/larkov"] + - ["Joakim Lahtinen", "https://github.com/VibyJocke"] lang: sv-se --- -Eftersom JSON är ett extremt lätt data-utbytes format så kommer detta -förmodligen att vara den lättaste "Learn X in Y Minutes" någonsin. +JSON är ett extremt enkelt datautbytesformat. Som [json.org](http://json.org) beskriver så är det lätt för människor att läsa och skriva, och för datorer att tolka och generera. -JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar -C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa -100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. +En bit av JSON måste representera antingen: +* En samling av namn/värde-par (`{ }`). I olika språk kan denna realiseras som ett objekt, struct, dictionary, hash-tabell, nyckellista eller en associativ array. +* En ordnad lista av värden (`[ ]`). I olika språk kan denna realiseras som en array, vektor, lista eller sekvens. +JSON i dess renaste form har inga kommentarer, men de flesta tolkarna accepterar C-stils (`//`, `/* */`) kommentarer. Vissa tolkar tolererar även komman efter sista elementet i en array, eller det sista attributet av ett objekt, men dessa bör undvikas för bättre kompabilitet. + +Detta dokument kommer dock att tillämpa 100% giltigt JSON. Lyckligtvis så är resten av dokumentet självförklarande. + +Följande datatyper stöds: +* Strängar: `"hello"`, `"\"A quote.\""`, `"\u0abe"`, `"Newline.\n"` +* Nummer: `23`, `0.11`, `12e10`, `3.141e-10`, `1.23e+4` +* Objekt: `{ "key": "value" }` +* Arrayer: `["Values"]` +* Övriga: `true`, `false`, `null` ```json { @@ -57,6 +69,16 @@ C-stils (`//`, `/* */`) kommentarer. Detta dokument kommer dock att tillämpa , "en kommentar till": "vad fint" }, + + + "blanksteg": "Spelar ingen roll.", + + + "det var kort": "Nu är du klar och kan allt vad JSON har att erbjuda." } ``` + +## Fortsatt läsning + +* [JSON.org](http://json.org/json-sv.html) Allt du kan tänkas vilja veta om JSON, och lite därtill. diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 49224085..fa4540a2 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -129,7 +129,7 @@ func learnFlowControl() { fmt.Println("told ya") } // 用go fmt 命令可以帮你格式化代码,所以不用怕被人吐槽代码风格了, - // 也不用容忍被人的代码风格。 + // 也不用容忍别人的代码风格。 if false { // pout } else { diff --git a/zh-cn/kotlin-cn.html.markdown b/zh-cn/kotlin-cn.html.markdown new file mode 100644 index 00000000..1fd12f5b --- /dev/null +++ b/zh-cn/kotlin-cn.html.markdown @@ -0,0 +1,346 @@ +--- +language: kotlin +contributors: + - ["S Webber", "https://github.com/s-webber"] +translators: + - ["Jimin Lu", "https://github.com/lujimin"] +filename: LearnKotlin-cn.kt +lang: zh-cn +--- + +Kotlin是一门适用于JVM、Android和浏览器的静态类型编程语言。它100%兼容Java。 +[了解更多。](https://kotlinlang.org/) + +```java +// 单行注释从 // 开始 +/* +多行注释看起来像这样。 +*/ + +// "package" 关键字的工作方式与Java相同。 +package com.learnxinyminutes.kotlin + +/* +Kotlin程序的入口点是一个"main"函数 +该函数传递一个包含任何命令行参数的数组。 +*/ +fun main(args: Array<String>) { + /* + 使用"var"或"val"来声明一个值。 + "val"声明的值不能被重新赋值,而"var"声明的值可以。 + */ + val fooVal = 10 // 以后我们不能再次给fooVal赋值 + var fooVar = 10 + fooVar = 20 // fooVar可以被再次赋值 + + /* + 在大多数情况下,Kotlin可以确定变量的类型是什么, + 所以我们不必要每次都去明确指定它。 + 我们可以像这样明确地声明一个变量的类型: + */ + val foo : Int = 7 + + /* + 可以采取和Java类似的方法来表示一个字符串。 + 用反斜杠来转义字符。 + */ + val fooString = "My String Is Here!"; + val barString = "Printing on a new line?\nNo Problem!"; + val bazString = "Do you want to add a tab?\tNo Problem!"; + println(fooString); + println(barString); + println(bazString); + + /* + 原始字符串用三重引号(""")来定义。 + 原始字符串可以包含换行符以及其他任何字符。 + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Hello, world!") +} +""" + println(fooRawString) + + /* + 字符串可以包含模板表达式。 + 模板表达式从一个美元符号($)开始。 + */ + val fooTemplateString = "$fooString has ${fooString.length} characters" + println(fooTemplateString) + + /* + 当某个变量的值可以为 null 的时候,我们必须被明确指定它是可为空的。 + 在变量声明处的类型后面加上?来标识它是可为空的。 + 我们可以用?.操作符来访问可为空的变量。 + 我们可以用?:操作符来指定一个在变量为空时使用的替代值。 + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + 使用"fun"关键字来声明一个函数。 + 函数的参数在函数名后面的括号内指定。 + 函数的参数可以设定一个默认值。 + 如果需要的话,函数的返回值类型可以在参数后面指定。 + */ + fun hello(name: String = "world") : String { + return "Hello, $name!" + } + println(hello("foo")) // => Hello, foo! + println(hello(name = "bar")) // => Hello, bar! + println(hello()) // => Hello, world! + + /* + 用"vararg"关键字来修饰一个函数的参数来允许可变参数传递给该函数 + */ + fun varargExample(vararg names: Int) { + println("Argument has ${names.size} elements") + } + varargExample() // => Argument has 0 elements + varargExample(1) // => Argument has 1 elements + varargExample(1, 2, 3) // => Argument has 3 elements + + /* + 当函数只包含一个单独的表达式时,大括号可以被省略。 + 函数体可以被指定在一个=符号后面。 + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // 如果返回值类型可以被推断,那么我们不需要指定它。 + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // 函数可以用函数作为参数并且可以返回函数。 + fun not(f: (Int) -> Boolean) : (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // 命名函数可以用::运算符被指定为参数。 + val notOdd = not(::odd) + val notEven = not(::even) + // 匿名函数可以被指定为参数。 + val notZero = not {n -> n == 0} + /* + 如果一个匿名函数只有一个参数 + 那么它的声明可以被省略(连同->)。 + 这个参数的名字是"it"。 + */ + val notPositive = not {it > 0} + for (i in 0..4) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + // "class"关键字用来声明类。 + class ExampleClass(val x: Int) { + fun memberFunction(y: Int) : Int { + return x + y + } + + infix fun infixMemberFunction(y: Int) : Int { + return x * y + } + } + /* + 我们调用构造方法来创建一个新的实例。 + 注意,Kotlin没有"new"关键字。 + */ + val fooExampleClass = ExampleClass(7) + // 可以使用一个点号来调用成员函数。 + println(fooExampleClass.memberFunction(4)) // => 11 + /* + 如果使用"infix"关键字来标记一个函数 + 那么可以使用中缀表示法来调用该函数。 + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + 数据类是创建只包含数据的类的一个简洁的方法。 + "hashCode"、"equals"和"toString"方法将被自动生成。 + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // 数据类有一个"copy"函数 + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // 对象可以被解构成为多个变量 + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // "with"函数类似于JavaScript中的"with"用法。 + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableDate = MutableDataClassExample(7, 4, 9) + with (fooMutableDate) { + x -= 2 + y += 2 + z-- + } + println(fooMutableDate) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + 我们可以使用"listOf"函数来创建一个list。 + 这个list是不可变的 - 元素不可以被添加或删除。 + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // 可以通过索引来访问list中的元素。 + println(fooList[1]) // => b + + // 可以使用"mutableListOf"函数来创建一个可变的list。 + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // 我们可以使用"setOf"函数来创建一个set。 + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // 我们可以使用"mapOf"函数来创建一个map。 + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // 可以通过键来访问map中的值。 + println(fooMap["a"]) // => 8 + + /* + 序列表示惰性求值集合。 + 我们可以使用"generateSequence"函数来创建一个序列。 + */ + val fooSequence = generateSequence(1, {it + 1}) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // 一个用序列来生成斐波那契数列的例子。 + fun fibonacciSequence() : Sequence<Long> { + var a = 0L + var b = 1L + + fun next() : Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + + // Kotlin为集合提供高阶函数。 + val z = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // 任何提供迭代器的都可以使用"for"循环。 + for (c in "hello") { + println(c) + } + + // "while"循环的用法和其他语言一样。 + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + // "when"可以用来替代"if-else if"链。 + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when"可以带参数。 + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when"可以作为一个函数,提供返回值。 + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + 我们可以通过使用"is"操作符来检查一个对象是否是某个类型的。 + 如果对象通过了类型检查那么它可以作为该类型使用而不需要强制转换它。 + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x自动转换为Boolean + return x + } else if (x is Int) { + // x自动转换为Int + return x > 0 + } else if (x is String) { + // x自动转换为String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Hello, world!")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + /* + 扩展是用来给一个类添加新的功能的。 + 它类似于C#的扩展方法。 + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! + + println(EnumExample.A) // => A + println(ObjectExample.hello()) // => hello +} + +// 枚举类和Java的枚举类型类似。 +enum class EnumExample { + A, B, C +} + +/* +"object"关键字用来创建单例对象。 +我们不能把它赋给一个变量,但我们可以通过它的名字引用它。 +这类似于Scala的单例对象。 +*/ +object ObjectExample { + fun hello() : String { + return "hello" + } +} + +``` + +### 进一步阅读 + +* [Kotlin教程](https://kotlinlang.org/docs/tutorials/) +* [在您的浏览器中使用Kotlin](http://try.kotlinlang.org/) +* [Kotlin资源列表](http://kotlin.link/) diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 0c46bc22..55a29b11 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -285,7 +285,7 @@ while (a > 4) { } # 记住,在 R 语言中 for / while 循环都很慢 -# 建议使用 apply()(我们一会介绍)来错做一串数据(比如一列或者一行数据) +# 建议使用 apply()(我们一会介绍)来操作一串数据(比如一列或者一行数据) # IF/ELSE diff --git a/zh-tw/bash-tw.html.markdown b/zh-tw/bash-tw.html.markdown new file mode 100644 index 00000000..78b39f2d --- /dev/null +++ b/zh-tw/bash-tw.html.markdown @@ -0,0 +1,377 @@ +--- +category: tool +tool: bash +contributors: + - ["Max Yankov", "https://github.com/golergka"] + - ["Darren Lin", "https://github.com/CogBear"] + - ["Alexandre Medeiros", "http://alemedeiros.sdf.org"] + - ["Denis Arh", "https://github.com/darh"] + - ["akirahirose", "https://twitter.com/akirahirose"] + - ["Anton Strömkvist", "http://lutic.org/"] + - ["Rahil Momin", "https://github.com/iamrahil"] + - ["Gregrory Kielian", "https://github.com/gskielian"] + - ["Etan Reisner", "https://github.com/deryni"] + - ["Jonathan Wang", "https://github.com/Jonathansw"] + - ["Leo Rudberg", "https://github.com/LOZORD"] + - ["Betsy Lorton", "https://github.com/schbetsy"] + - ["John Detter", "https://github.com/jdetter"] +translators: + - ["Jinchang Ye", "https://github.com/Alwayswithme"] + - ["Chunyang Xu", "https://github.com/XuChunyang"] + - ["Weihang Lo", "https://github.com/weihanglo"] +filename: LearnBash-tw.sh +lang: zh-tw +--- + +Bash 是一個爲 GNU 計劃編寫的 Unix shell,是 Linux 和 Mac OS X 下預設的 shell。 +以下大多數例子可以作爲腳本的一部分運行,也可直接在 shell 下互動執行。 + +[更多資訊](http://www.gnu.org/software/bash/manual/bashref.html) + +```bash +#!/bin/bash +# 腳本的第一行叫 shebang,用來告知系統如何執行該腳本: +# 參見: http://en.wikipedia.org/wiki/Shebang_(Unix) +# 如你所見,註釋以 # 開頭,shebang 也是註釋。 + +# 顯示 “Hello world!” +echo Hello world! + +# 每一句指令以換行或分號隔開: +echo 'This is the first line'; echo 'This is the second line' + +# 宣告一個變數: +Variable="Some string" + +# 下面是錯誤的做法: +Variable = "Some string" +# Bash 會把 Variable 當做一個指令,由於找不到該指令,因此這裡會報錯。 + +# 也不可以這樣: +Variable= 'Some string' +# Bash 會認爲 'Some string' 是一條指令,由於找不到該指令,這裡會再次報錯。 +# (這個例子中 'Variable=' 這部分會被當作僅對 'Some string' 起作用的賦值。) + +# 使用變數: +echo $Variable +echo "$Variable" +echo '$Variable' +# 當你賦值 (assign) 、匯出 (export),或者以其他方式使用變數時,變數名前不加 $。 +# 如果要使用變數的值, 則要加 $。 +# 注意: ' (單引號) 不會展開變數。 + +# 參數展開式 ${}: +echo ${Variable} +# 這是一個參數展開的簡單用法 +# 使用參數展開會得到該變數的值,也就是會「展開」或印出該值。 +# 在展開期間,可以修改該值或該參數。 +# 以下是修改參數展開式的範例: + +# 在變數內部進行字串代換 +echo ${Variable/Some/A} +# 會把 Variable 中首次出現的 "some" 替換成 “A”。 + +# 變數的截取 +Length=7 +echo ${Variable:0:Length} +# 這樣僅會返回變數值的前7個字元 + +# 變數的預設值 +echo ${Foo:-"DefaultValueIfFooIsMissingOrEmpty"} +# 對 null (Foo=) 和空字串 (Foo="") 起作用; 零(Foo=0)時返回0 +# 注意這僅返回預設值而不是改變變數的值 + +# 括號展開 { } +# 用以產生任意的字串 +echo {1..10} +echo {a..z} +# 這將會輸出該範圍內的起始值到最終值。 + +# 內建變數: +# 下面的內建變數很有用 +echo "Last program's return value: $?" +echo "Script's PID: $$" +echo "Number of arguments: $#" +echo "Scripts arguments: $@" +echo "Scripts arguments separated in different variables: $1 $2..." + +# 現在,我們知道變數如何使用與印出 +# 讓我們開始學習其他Bash基礎吧! + +# 使用 `pwd` 指令,可以得知當前工作目錄 +# `pwd` 意指 「印出工作目錄」(print working directory)。 +# 我們也可使用內建變數 `$PWD`。 +# 下列兩行指令等價: +echo "I'm in $(pwd)" # 執行 `pwd` 且將該值內插至輸出中 +echo "I'm in $PWD" # 直接內插 `$PWD` 變數 + +# 如果終端機上有太多輸出,`clear` 指令可以清除螢幕先前的輸出 +clear +# Ctrl-L 也有相同的效果 + +# 讀取輸入: +echo "What's your name?" +read Name # 這裡不需要宣告新變數 +echo Hello, $Name! + +# 一般 if 結構看起來像這樣: +# 'man test' 可查看更多的信息 +if [ $Name != $USER ] +then + echo "Your name isn't your username" +else + echo "Your name is your username" +fi + +# 注意: 如果 $Name 為空,bash會將該條件式解讀成: +if [ != USER ] +# 這是一個錯誤的語法 +# 所以,安全避免空變數的方法如下: +if [ "$Name" != $USER ] ... +# 如果 $Name 為空,該條件式將被視為: +if [ "" != $USER] +# 此條件式可正常運作 + + +# 根據上一個指令執行結果決定是否執行下一個指令 +echo "Always executed" || echo "Only executed if first command fails" +echo "Always executed" && echo "Only executed if first command does NOT fail" + +# 在 if 語句中使用 && 和 || 需要多對方括號 +if [ $Name == "Steve" ] && [ $Age -eq 15 ] +then + echo "This will run if $Name is Steve AND $Age is 15." +fi + +if [ $Name == "Daniya" ] || [ $Name == "Zach" ] +then + echo "This will run if $Name is Daniya OR Zach." +fi + +# 表達式的格式如下: +echo $(( 10 + 5 )) + +# 與其他程式語言不同的是,bash 運行時依賴上下文。比如,使用 ls 時,列出當前目錄。 +ls + +# 指令可以帶有選項: +ls -l # 列出文件和目錄的詳細信息 +ls -t # 以最後修改時間,對文件與目錄排序 +ls -R # 遞迴列出目錄與次目錄的內容 + +# 前一個指令的輸出可以當作後一個指令的輸入。grep 用來匹配字串。 +# 用下面的指令列出當前目錄下所有的 txt 文件: +ls -l | grep "\.txt" + +# 使用 `cat` 將檔案印出在標準輸出中: +cat file.txt + +# 使用 `cat` 讀取檔案 +Contents=$(cat file.txt) +echo "START OF FILE\n$Contents\nEND OF FILE" + +# 使用 `cp` 複製檔案或目錄,`cp` 會創建新版本的來源檔案/目錄 +# 所以,編輯副本不會影響到初始來源(反之亦然)。 +# 注意,如果目的地已存在該檔案/目錄,該檔案/目錄將會被覆寫 +cp srcFile.txt clone.txt +cp -r srcDirectory/ dst/ # 遞迴複製 + +# 如需在兩台電腦間交換檔案,請查看 `scp` 或 `sftp`。 +# `scp` 與 `cp` 相似。 +# `sftp` 則有更高的互動性(與 `ftp` 相似)。 + +# 使用 `mv` 來移動目錄與檔案。 +# `mv` 與 `cp` 相似,但會刪除來源。 +# `mv` 也可以用來重新命名檔案/目錄! +mv s0urc3.txt dst.txt + +# 由於 bash 運行時依賴當前目錄的上下文, +# 需要在其他目錄執行指令時,可使用 `cd` 改變當前目錄: +cd ~ # 到家目錄 +cd .. # 到上一層目錄 + # (^^例如, 從 /home/username/Downloads 到 /home/username) +cd /home/username/Documents # 到指定目錄 +cd ~/Documents/.. # 仍位於家目錄,不是嗎? + +# 使用子殼程式 (subshells) 在不同目錄間工作 +(echo "First, I'm here: $PWD") && (cd someDir; echo "Then, I'm here: $PWD") +pwd # 仍在第一個目錄 + +# 使用 `mkdir` 來建立新的目錄 +mkdir myNewDir +# 使用 `-p` 選項參數,將會自動創建路徑中不存在的目錄 +mkdir -p myNewDir/with/intermediate/directories + +# 將指令的輸出輸入重新導向(標準輸入、標準輸出、標準錯誤輸出)。 +# 從標準輸入讀取資料,直到 ^EOF$ (End-of-file),且將讀取的資料覆寫至hello.py +cat > hello.py << EOF +#!/usr/bin/env python +from __future__ import print_function +import sys +print("#stdout", file=sys.stdout) +print("#stderr", file=sys.stderr) +for line in sys.stdin: + print(line, file=sys.stdout) +EOF + +# 重新導向可以到標準輸出(stdout),標準輸入(stdin)和標準錯誤輸出(stderr)。 +python hello.py < "input.in" +python hello.py > "output.out" +python hello.py 2> "error.err" +python hello.py > "output-and-error.log" 2>&1 +python hello.py > /dev/null 2>&1 +# `>` 會覆蓋已存在的文件, `>>` 會以累加的方式輸出文件中。 +python hello.py >> "output.out" 2>> "error.err" + +# 覆蓋 output.out , 追加 error.err 並統計行數 +info bash 'Basic Shell Features' 'Redirections' > output.out 2>> error.err +wc -l output.out error.err + +# 運行指令並印出文件描述 (比如 /dev/fd/123) +# 具體可查看: man fd +echo <(echo "#helloworld") + +# 以 "#helloworld" 覆蓋 output.out: +cat > output.out <(echo "#helloworld") +echo "#helloworld" > output.out +echo "#helloworld" | cat > output.out +echo "#helloworld" | tee output.out >/dev/null + +# 清理臨時文件並顯示詳情(增加 '-i' 選項啓用互動模式) +# 警告: `rm` 指令無法復原 +rm -v output.out error.err output-and-error.log +rm -r tempDir/ # 遞迴刪除 + +# 一個指令可用 $( ) 嵌套在另一個指令內部: +# 以下的指令會印出當前目錄下的目錄和文件總數 +echo "There are $(ls | wc -l) items here." + +# 反引號 `` 起相同作用,但不允許嵌套 +# 優先使用 $( ). +echo "There are `ls | wc -l` items here." + +# Bash 的 case 語句與 Java 和 C++ 中的 switch 語句類似: +case "$Variable" in + # 列出需要匹配的字串 + 0) echo "There is a zero.";; + 1) echo "There is a one.";; + *) echo "It is not null.";; +esac + +# 循環遍歷給定的參數序列: +# 變數$Variable 的值會被印出 3 次。 +for Variable in {1..3} +do + echo "$Variable" +done + +# 或傳統的 “for循環” : +for ((a=1; a <= 3; a++)) +do + echo $a +done + +# 也可以用於文件 +# 用 cat 輸出 file1 和 file2 內容 +for Variable in file1 file2 +do + cat "$Variable" +done + +# 或作用於其他命令的輸出 +# 對 ls 輸出的文件執行 cat 指令。 +for Output in $(ls) +do + cat "$Output" +done + +# while 循環: +while [ true ] +do + echo "loop body here..." + break +done + +# 你也可以使用函數 +# 定義函數: +function foo () +{ + echo "Arguments work just like script arguments: $@" + echo "And: $1 $2..." + echo "This is a function" + return 0 +} + +# 更簡單的方法 +bar () +{ + echo "Another way to declare functions!" + return 0 +} + +# 呼叫函數 +foo "My name is" $Name + +# 有很多有用的指令需要學習: +# 打印 file.txt 的最後 10 行 +tail -n 10 file.txt +# 印出 file.txt 的前 10 行 +head -n 10 file.txt +# 將 file.txt 按行排序 +sort file.txt +# 報告或忽略重複的行,用選項 -d 印出重複的行 +uniq -d file.txt +# 打印每行中 ',' 之前內容 +cut -d ',' -f 1 file.txt +# 將 file.txt 文件所有 'okay' 替換爲 'great', (兼容正規表達式) +sed -i 's/okay/great/g' file.txt +# 將 file.txt 中匹配正則的行打印到標準輸出 +# 這裡印出以 "foo" 開頭, "bar" 結尾的行 +grep "^foo.*bar$" file.txt +# 使用選項 "-c" 統計行數 +grep -c "^foo.*bar$" file.txt +# 其他實用的選項參數 +grep -r "^foo.*bar$" someDir/ # 遞迴的 `grep` +grep -n "^foo.*bar$" file.txt # 顯示行數 +grep -rI "^foo.*bar$" someDir/ # 遞迴的 `grep`, 但忽略二進位檔案 +# 同樣的搜尋,再過濾包含「baz」的行 +grep "^foo.*bar$" file.txt | grep -v "baz" + +# 如果要搜尋字面上的字串而不是用正規表達式,使用 `fgrep` 或 `grep -F` +fgrep "foobar" file.txt + +# trap command allows you to execute a command when a signal is received by your script. +# `trap` 可以在一個script運行,接收到特定信號時,執行對應的指令 +# `trap` 接收到 `SIGHUP`、`SIGINT`、`SIGTERM` 信號時,會移除 $TEMP_FILE +trap "rm $TEMP_FILE; exit" SIGHUP SIGINT SIGTERM + +# `sudo` 可用於以superuser的身分執行指令 +$NAME1=$(whoami) +$NAME2=$(sudo whoami) +echo "Was $NAME1, then became more powerful $NAME2" + +# 以 bash 內建的 'help' 指令閱讀 Bash 內建文件: +help +help help +help for +help return +help source +help . + +# 用 man 指令閱讀相關的 Bash 手冊 +apropos bash +man 1 bash +man bash + +# 用 info 指令查閱命令的 info 文件 (info 中按 ? 顯示幫助信息) +apropos info | grep '^info.*(' +man info +info info +info 5 info + +# 閱讀 Bash 的 info 文件: +info bash +info bash 'Bash Features' +info bash 6 +info --apropos bash +``` |