mirror of
https://github.com/adambard/learnxinyminutes-docs.git
synced 2025-04-27 07:33:57 +00:00
t push origin masterMerge branch 'master' of github.com:adambard/learnxinyminutes-docs
This commit is contained in:
commit
1b95655b3c
@ -70,7 +70,7 @@ void main() {
|
||||
```
|
||||
|
||||
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,
|
||||
are passed to functions by value (i.e. copied) and classes are passed by reference. Furthermore,
|
||||
we can use templates to parameterize all of these on both types and values!
|
||||
|
||||
```c
|
||||
@ -218,7 +218,7 @@ void main() {
|
||||
// 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.
|
||||
// You can pass any 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);
|
||||
@ -228,7 +228,7 @@ void main() {
|
||||
```
|
||||
|
||||
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.
|
||||
That's thanks to a D innovation know as Uniform Function Call Syntax (UFCS).
|
||||
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)
|
||||
@ -238,21 +238,23 @@ 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!
|
||||
|
||||
```c
|
||||
// Let's say we want to populate a large array with the square root of all
|
||||
// consecutive integers starting from 1 (up until the size of the array), and we
|
||||
// want to do this concurrently taking advantage of as many cores as we have
|
||||
// available.
|
||||
|
||||
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.
|
||||
// Create your large array
|
||||
auto arr = new double[1_000_000];
|
||||
|
||||
// Use an index, and an array element by reference,
|
||||
// and just call parallel on the array!
|
||||
// Use an index, access every array element by reference (because we're
|
||||
// going to change each element) and just call parallel on the array!
|
||||
foreach(i, ref elem; parallel(arr)) {
|
||||
ref = sqrt(i + 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
@ -2,6 +2,7 @@
|
||||
language: elisp
|
||||
contributors:
|
||||
- ["Bastien Guerry", "http://bzg.fr"]
|
||||
- ["Saurabh Sandav", "http://github.com/SaurabhSandav"]
|
||||
filename: learn-emacs-lisp.el
|
||||
---
|
||||
|
||||
@ -26,7 +27,7 @@ filename: learn-emacs-lisp.el
|
||||
;;
|
||||
;; Going through this tutorial won't damage your computer unless
|
||||
;; you get so angry that you throw it on the floor. In that case,
|
||||
;; I hereby decline any responsability. Have fun!
|
||||
;; I hereby decline any responsibility. Have fun!
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;;
|
||||
|
@ -97,7 +97,7 @@ not False # => True
|
||||
None # => None
|
||||
|
||||
# No uses el símbolo de igualdad `==` para comparar objetos con None
|
||||
# Usa `is` en lugar de
|
||||
# Usa `is` en su lugar
|
||||
"etc" is None #=> False
|
||||
None is None #=> True
|
||||
|
||||
@ -383,7 +383,7 @@ def keyword_args(**kwargs):
|
||||
keyword_args(pie="grande", lago="ness") #=> {"pie": "grande", "lago": "ness"}
|
||||
|
||||
|
||||
# You can do both at once, if you like# Puedes hacer ambas a la vez si quieres
|
||||
# Puedes hacer ambas a la vez si quieres
|
||||
def todos_los_argumentos(*args, **kwargs):
|
||||
print args
|
||||
print kwargs
|
||||
@ -511,7 +511,7 @@ def duplicar_numeros(iterable):
|
||||
for i in iterable:
|
||||
yield i + i
|
||||
|
||||
# Un generador cera valores sobre la marcha.
|
||||
# Un generador crea valores sobre la marcha.
|
||||
# En vez de generar y retornar todos los valores de una vez, crea uno en cada iteración.
|
||||
# Esto significa que valores más grandes que 15 no serán procesados en 'duplicar_numeros'.
|
||||
# Fíjate que 'range' es un generador. Crear una lista 1-900000000 tomaría mucho tiempo en crearse.
|
||||
|
@ -29,7 +29,7 @@ Nadie los usa.
|
||||
Tu tampoco deberías
|
||||
=end
|
||||
|
||||
# Lo primero y principal: Todo es un objeto
|
||||
# En primer lugar: Todo es un objeto
|
||||
|
||||
# Los números son objetos
|
||||
|
||||
@ -128,7 +128,7 @@ ruta = '/mal/nombre/'
|
||||
|
||||
# Los símbolos (son objetos)
|
||||
# Los símbolos son inmutables, constantes reusables representadas internamente por un
|
||||
# valor entero. Son usalmente usados en vez de strings para expresar eficientemente
|
||||
# valor entero. Son normalmente usados en vez de strings para expresar eficientemente
|
||||
# valores específicos y significativos
|
||||
|
||||
:pendiente.class #=> Symbol
|
||||
@ -156,7 +156,7 @@ arreglo[0] #=> 1
|
||||
arreglo.first #=> 1
|
||||
arreglo[12] #=> nil
|
||||
|
||||
# Tal como la aritmética, el acceso como variable[índice]
|
||||
# Al igual que en aritmética, el acceso como variable[índice]
|
||||
# es sólo azúcar sintáctica
|
||||
# para llamar el método [] de un objeto
|
||||
arreglo.[] 0 #=> 1
|
||||
|
@ -190,7 +190,7 @@ end
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
-- A table can have a metatable that gives the table operator-overloadish
|
||||
-- behavior. Later we'll see how metatables support js-prototypey behaviour.
|
||||
-- behaviour. Later we'll see how metatables support js-prototypey behaviour.
|
||||
|
||||
f1 = {a = 1, b = 2} -- Represents the fraction a/b.
|
||||
f2 = {a = 2, b = 3}
|
||||
|
@ -73,7 +73,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891
|
||||
|
||||
% Calling functions can be done in either of two ways:
|
||||
% Standard function syntax:
|
||||
load('myFile.mat', 'y') % arguments within parantheses, spererated by commas
|
||||
load('myFile.mat', 'y') % arguments within parentheses, separated by commas
|
||||
% Command syntax:
|
||||
load myFile.mat y % no parentheses, and spaces instead of commas
|
||||
% Note the lack of quote marks in command form: inputs are always passed as
|
||||
@ -279,7 +279,7 @@ clf clear % clear current figure window, and reset most figure properties
|
||||
|
||||
% Properties can be set and changed through a figure handle.
|
||||
% You can save a handle to a figure when you create it.
|
||||
% The function gcf returns a handle to the current figure
|
||||
% The function get returns a handle to the current figure
|
||||
h = plot(x, y); % you can save a handle to a figure when you create it
|
||||
set(h, 'Color', 'r')
|
||||
% 'y' yellow; 'm' magenta, 'c' cyan, 'r' red, 'g' green, 'b' blue, 'w' white, 'k' black
|
||||
|
@ -18,7 +18,7 @@ lang: ru-ru
|
||||
% Пунктуационные знаки, используемые в Erlang:
|
||||
% Запятая (`,`) разделяет аргументы в вызовах функций, структурах данных и
|
||||
% образцах.
|
||||
% Точка (`.`) (с пробелом после них) разделяет функции и выражения в
|
||||
% Точка (`.`) (с пробелом после неё) разделяет функции и выражения в
|
||||
% оболочке.
|
||||
% Точка с запятой (`;`) разделяет выражения в следующих контекстах:
|
||||
% формулы функций, выражения `case`, `if`, `try..catch` и `receive`.
|
||||
|
195
ru-ru/perl-ru.html.markdown
Normal file
195
ru-ru/perl-ru.html.markdown
Normal file
@ -0,0 +1,195 @@
|
||||
---
|
||||
category: language
|
||||
language: perl
|
||||
filename: learnperl-ru.pl
|
||||
contributors:
|
||||
- ["Korjavin Ivan", "http://github.com/korjavin"]
|
||||
translators:
|
||||
- ["Elena Bolshakova", "http://github.com/liruoko"]
|
||||
lang: ru-ru
|
||||
---
|
||||
|
||||
Perl 5 -- высокоуровневый мощный язык с 25-летней историей.
|
||||
Особенно хорош для обработки разнообразных текстовых данных.
|
||||
|
||||
Perl 5 работает более чем на 100 платформах, от портативных устройств
|
||||
до мейнфреймов, и подходит как для быстрого прототипирования,
|
||||
так и для крупных проектов.
|
||||
|
||||
```perl
|
||||
# Комментарии начинаются с символа решетки.
|
||||
|
||||
|
||||
#### Типы переменных в Perl
|
||||
|
||||
# Скалярные переменные начинаются с знака доллара $.
|
||||
# Имя переменной состоит из букв, цифр и знаков подчеркивания,
|
||||
# начиная с буквы или подчеркивания.
|
||||
|
||||
### В Perl три основных типа переменных: скаляры, массивы, хеши.
|
||||
|
||||
## Скаляры
|
||||
# Скаляр хранит отдельное значение:
|
||||
my $animal = "camel";
|
||||
my $answer = 42;
|
||||
|
||||
# Скаляры могут быть строками, целыми и вещественными числами.
|
||||
# Когда требуется, Perl автоматически выполняет преобразования к нужному типу.
|
||||
|
||||
## Массивы
|
||||
# Массив хранит список значений:
|
||||
my @animals = ("camel", "llama", "owl");
|
||||
my @numbers = (23, 42, 69);
|
||||
my @mixed = ("camel", 42, 1.23);
|
||||
|
||||
|
||||
## Хеши
|
||||
# Хеш хранит набор пар ключ/значение:
|
||||
|
||||
my %fruit_color = ("apple", "red", "banana", "yellow");
|
||||
|
||||
# Можно использовать оператор "=>" для большей наглядности:
|
||||
|
||||
my %fruit_color = (
|
||||
apple => "red",
|
||||
banana => "yellow",
|
||||
);
|
||||
|
||||
# Важно: вставка и поиск в хеше выполняются за константное время,
|
||||
# независимо от его размера.
|
||||
|
||||
# Скаляры, массивы и хеши подробно описаны в разделе perldata
|
||||
# (perldoc perldata).
|
||||
|
||||
# Более сложные структуры данных можно получить, если использовать ссылки.
|
||||
# С помощью ссылок можно получить массив массивов хешей, в которых хранятся другие хеши.
|
||||
|
||||
#### Условные операторы и циклы
|
||||
|
||||
# В Perl есть большинсво привычных условных и циклических конструкций.
|
||||
|
||||
if ( $var ) {
|
||||
...
|
||||
} elsif ( $var eq 'bar' ) {
|
||||
...
|
||||
} else {
|
||||
...
|
||||
}
|
||||
|
||||
unless ( condition ) {
|
||||
...
|
||||
}
|
||||
# Это более читаемый вариант для "if (!condition)"
|
||||
|
||||
# Специфические Perl-овые пост-условия:
|
||||
print "Yow!" if $zippy;
|
||||
print "We have no bananas" unless $bananas;
|
||||
|
||||
# while
|
||||
while ( condition ) {
|
||||
...
|
||||
}
|
||||
|
||||
|
||||
# for, foreach
|
||||
for ($i = 0; $i <= $max; $i++) {
|
||||
...
|
||||
}
|
||||
|
||||
foreach (@array) {
|
||||
print "This element is $_\n";
|
||||
}
|
||||
|
||||
for my $el (@array) {
|
||||
print "This element is $el\n";
|
||||
}
|
||||
|
||||
#### Регулярные выражения
|
||||
|
||||
# Регулярные выражения занимают важное место в Perl-е,
|
||||
# и подробно описаны в разделах документации perlrequick, perlretut и других.
|
||||
# Вкратце:
|
||||
|
||||
# Сопоставление с образцом
|
||||
if (/foo/) { ... } # выполняется, если $_ содержит "foo"
|
||||
if ($a =~ /foo/) { ... } # выполняется, если $a содержит "foo"
|
||||
|
||||
# Простые замены
|
||||
|
||||
$a =~ s/foo/bar/; # заменяет foo на bar в строке $a
|
||||
$a =~ s/foo/bar/g; # заменяет ВСЕ ВХОЖДЕНИЯ foo на bar в строке $a
|
||||
|
||||
|
||||
#### Файлы и ввод-вывод
|
||||
|
||||
# Открыть файл на чтение или запись можно с помощью функции "open()".
|
||||
|
||||
open(my $in, "<", "input.txt") or die "Can't open input.txt: $!";
|
||||
open(my $out, ">", "output.txt") or die "Can't open output.txt: $!";
|
||||
open(my $log, ">>", "my.log") or die "Can't open my.log: $!";
|
||||
|
||||
# Читать из файлового дескриптора можно с помощью оператора "<>".
|
||||
# В скалярном контексте он читает одну строку из файла, в списковом --
|
||||
# читает сразу весь файл, сохраняя по одной строке в элементе массива:
|
||||
|
||||
my $line = <$in>;
|
||||
my @lines = <$in>;
|
||||
|
||||
#### Подпрограммы (функции)
|
||||
|
||||
# Объявить функцию просто:
|
||||
|
||||
sub logger {
|
||||
my $logmessage = shift;
|
||||
open my $logfile, ">>", "my.log" or die "Could not open my.log: $!";
|
||||
print $logfile $logmessage;
|
||||
}
|
||||
|
||||
# Теперь можно использовать эту функцию так же, как и встроенные:
|
||||
|
||||
logger("We have a logger subroutine!");
|
||||
```
|
||||
|
||||
#### Perl-модули
|
||||
|
||||
Perl-овые модули предоставляют широкий набор функциональности,
|
||||
так что вы можете не изобретать заново велосипеды, а просто скачать
|
||||
нужный модуль с CPAN (http://www.cpan.org/).
|
||||
Некоторое количество самых полезных модулей включено в стандартную
|
||||
поставку Perl.
|
||||
|
||||
Раздел документации perlfaq содержит вопросы и ответы о многих частых
|
||||
задачах, и часто предлагает подходящие CPAN-модули.
|
||||
|
||||
|
||||
#### Unicode
|
||||
|
||||
Вам наверняка понадобится работать с не-ASCII текстами.
|
||||
Добавьте эти прагмы в начало скрипта:
|
||||
|
||||
```perl
|
||||
use utf8;
|
||||
use open ':std' => ':utf8';
|
||||
```
|
||||
|
||||
Подробнее читайте в perldoc, разделы perlunicode и open.
|
||||
|
||||
|
||||
#### strict, warnings
|
||||
|
||||
Прагмы strict и warnings включают полезные проверки во время компиляции:
|
||||
|
||||
```perl
|
||||
use strict;
|
||||
use warnings;
|
||||
```
|
||||
|
||||
Подробнее смотрите perldoc strict и perldoc warnings.
|
||||
|
||||
|
||||
#### Смотрите также
|
||||
|
||||
- [perl-tutorial](http://perl-tutorial.org/)
|
||||
- [обучающий раздел на www.perl.com](http://www.perl.org/learn.html)
|
||||
- [perldoc в вебе](http://perldoc.perl.org/)
|
||||
- встроенная справка : `perldoc perlintro`
|
Loading…
Reference in New Issue
Block a user