From 041064416115985ef336babe6ef7dbac726327fa Mon Sep 17 00:00:00 2001 From: Jonathan Scott Duff Date: Fri, 24 Apr 2015 17:07:55 -0500 Subject: Add a link about parrot suspension --- perl6.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index b2d7d48c..bcf56800 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -7,11 +7,13 @@ contributors: - ["Nami-Doc", "http://github.com/Nami-Doc"] --- -Perl 6 is a highly capable, feature-rich programming language made for the -upcoming hundred years. +Perl 6 is a highly capable, feature-rich programming language made for at +least the next hundred years. -Perl 6 runs on [the Parrot VM](http://parrot.org/), the JVM -and [the MoarVM](http://moarvm.com). +The primary Perl 6 compiler is called [Rakudo](http://rakudo.org), which runs on +the JVM and [the MoarVM](http://moarvm.com) and +[prior to March 2015](http://pmthium.com/2015/02/suspending-rakudo-parrot/), +[the Parrot VM](http://parrot.org/). Meta-note : the triple pound signs are here to denote headlines, double paragraphs, and single notes. -- cgit v1.2.3 From 1cf3a8d797a25071470e6b529aa7db6a54f0b4ab Mon Sep 17 00:00:00 2001 From: Fabio Souto Date: Mon, 27 Apr 2015 17:03:00 +0200 Subject: Added missing section and fixes some typos --- es-es/python-es.html.markdown | 120 +++++++++++++++++++++++++++++++++--------- 1 file changed, 96 insertions(+), 24 deletions(-) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index f7a0ec02..4930eebc 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://ldinh.ca"] translators: - ["Camilo Garrido", "http://www.twitter.com/hirohope"] + - ["Fabio Souto", "http://fabiosouto.me"] lang: es-es filename: learnpython-es.py --- @@ -30,27 +31,47 @@ Nota: Este artículo aplica a Python 2.7 específicamente, pero debería ser apl # Tienes números 3 #=> 3 -# Matemática es lo que esperarías -1 + 1 #=> 2 -8 - 1 #=> 7 -10 * 2 #=> 20 -35 / 5 #=> 7 +# Evidentemente puedes realizar operaciones matemáticas +1 + 1 #=> 2 +8 - 1 #=> 7 +10 * 2 #=> 20 +35 / 5 #=> 7 # La división es un poco complicada. Es división entera y toma la parte entera # de los resultados automáticamente. -5 / 2 #=> 2 +5 / 2 #=> 2 # Para arreglar la división necesitamos aprender sobre 'floats' # (números de coma flotante). 2.0 # Esto es un 'float' -11.0 / 4.0 #=> 2.75 ahhh...mucho mejor +11.0 / 4.0 #=> 2.75 ahhh...mucho mejor + +# Resultado de la división de enteros truncada para positivos y negativos +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # funciona con números en coma flotante +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# El operador módulo devuelve el resto de una división entre enteros +7 % 3 # => 1 + +# Exponenciación (x elevado a y) +2**4 # => 16 # Refuerza la precedencia con paréntesis -(1 + 3) * 2 #=> 8 +(1 + 3) * 2 #=> 8 + +# Operadores booleanos +# Nota: "and" y "or" son sensibles a mayúsculas +True and False #=> False +False or True #=> True -# Valores 'boolean' (booleanos) son primitivos -True -False +# Podemos usar operadores booleanos con números enteros +0 and 2 #=> 0 +-5 or 0 #=> -5 +0 == False #=> True +2 == True #=> False +1 == True #=> True # Niega con 'not' not True #=> False @@ -90,7 +111,7 @@ not False #=> True # Una forma más reciente de formatear strings es el método 'format'. # Este método es la forma preferida "{0} pueden ser {1}".format("strings", "formateados") -# Puedes usar palabras claves si no quieres contar. +# Puedes usar palabras clave si no quieres contar. "{nombre} quiere comer {comida}".format(nombre="Bob", comida="lasaña") # None es un objeto @@ -107,8 +128,8 @@ None is None #=> True # None, 0, y strings/listas vacíos(as) todas se evalúan como False. # Todos los otros valores son True -0 == False #=> True -"" == False #=> True +bool(0) #=> False +bool("") #=> False #################################################### @@ -130,16 +151,16 @@ otra_variable # Levanta un error de nombre # 'if' puede ser usado como una expresión "yahoo!" if 3 > 2 else 2 #=> "yahoo!" -# Listas almacenan secuencias +# Las listas almacenan secuencias lista = [] # Puedes empezar con una lista prellenada otra_lista = [4, 5, 6] # Añadir cosas al final de una lista con 'append' -lista.append(1) #lista ahora es [1] -lista.append(2) #lista ahora es [1, 2] -lista.append(4) #lista ahora es [1, 2, 4] -lista.append(3) #lista ahora es [1, 2, 4, 3] +lista.append(1) # lista ahora es [1] +lista.append(2) # lista ahora es [1, 2] +lista.append(4) # lista ahora es [1, 2, 4] +lista.append(3) # lista ahora es [1, 2, 4, 3] # Remueve del final de la lista con 'pop' lista.pop() #=> 3 y lista ahora es [1, 2, 4] # Pongámoslo de vuelta @@ -173,11 +194,11 @@ lista.extend(otra_lista) # lista ahora es [1, 2, 3, 4, 5, 6] # Chequea la existencia en una lista con 1 in lista #=> True -# Examina el largo de una lista con 'len' +# Examina el tamaño de una lista con 'len' len(lista) #=> 6 -# Tuplas son como listas pero son inmutables. +# Las tuplas son como las listas, pero son inmutables. tupla = (1, 2, 3) tupla[0] #=> 1 tupla[0] = 3 # Levanta un error TypeError @@ -266,7 +287,7 @@ conjunto_lleno | otro_conjunto #=> {1, 2, 3, 4, 5, 6} # Hagamos sólo una variable una_variable = 5 -# Aquí está una declaración de un 'if'. ¡La indentación es significativa en Python! +# Aquí está una declaración de un 'if'. ¡La indentación es importante en Python! # imprime "una_variable es menor que 10" if una_variable > 10: print "una_variable es completamente mas grande que 10." @@ -400,12 +421,12 @@ class Humano(object): # Un atributo de clase es compartido por todas las instancias de esta clase especie = "H. sapiens" - # Constructor basico + # Constructor básico, se llama al instanciar la clase. def __init__(self, nombre): # Asigna el argumento al atributo nombre de la instancia self.nombre = nombre - # Un metodo de instancia. Todos los metodos toman self como primer argumento + # Un método de instancia. Todos los metodos toman self como primer argumento def decir(self, msg): return "%s: %s" % (self.nombre, msg) @@ -470,6 +491,56 @@ import math dir(math) +#################################################### +## 7. Avanzado +#################################################### + +# Los generadores permiten evaluación perezosa +def duplicar_numeros(iterable): + for i in iterable: + yield i + i + +# Un generador crea valores sobre la marcha +# En vez de generar y devolver todos los valores de una vez, crea un valor +# en cada iteración. En este ejemplo los valores mayores que 15 no serán +# procesados en duplicar_numeros. +# Nota: xrange es un generador que hace lo mismo que range. +# Crear una lista de 1 a 900000000 lleva mucho tiempo y ocupa mucho espacio. +# xrange crea un generador, mientras que range crea toda la lista. +# Añadimos un guion bajo a los nombres de variable que coinciden con palabras +# reservadas de python. +xrange_ = xrange(1, 900000000) + +# duplica todos los números hasta que encuentra un resultado >= 30 +for i in duplicar_numeros(xrange_): + print i + if i >= 30: + break + +# Decoradores +# en este ejemplo pedir rodea a hablar +# Si por_favor es True se cambiará el mensaje. +from functools import wraps + + +def pedir(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, por_favor = target_function(*args, **kwargs) + if por_favor: + return "{} {}".format(msg, "¡Por favor! Soy pobre :(") + return msg + + return wrapper + + +@pedir +def hablar(por_favor=False): + msg = "¿Me puedes comprar una cerveza?" + return msg, por_favor + +print hablar() # ¿Me puedes comprar una cerveza? +print hablar(por_favor=True) # ¿Me puedes comprar una cerveza? ¡Por favor! Soy pobre :( ``` ## ¿Listo para más? @@ -481,6 +552,7 @@ dir(math) * [The Official Docs](http://docs.python.org/2.6/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) +* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Encuadernados -- cgit v1.2.3 From 95e0a50cc44a46561069d538fb5a89a4e1edea99 Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Thu, 26 Feb 2015 17:40:57 +0300 Subject: [objective-c/ru] Updating Objective-C guide --- ru-ru/objective-c-ru.html.markdown | 654 ++++++++++++++++++++++++++++++++----- 1 file changed, 578 insertions(+), 76 deletions(-) diff --git a/ru-ru/objective-c-ru.html.markdown b/ru-ru/objective-c-ru.html.markdown index 3246de82..ddff2e5c 100644 --- a/ru-ru/objective-c-ru.html.markdown +++ b/ru-ru/objective-c-ru.html.markdown @@ -1,106 +1,171 @@ --- language: Objective-C -filename: LearnObjectiveC.m +filename: LearnObjectiveC-ru.m contributors: - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - ["Yannick Loriot", "https://github.com/YannickL"] + - ["Levi Bostian", "https://github.com/levibostian"] translators: - ["Evlogy Sutormin", "http://evlogii.com"] + - ["Dmitry Bessonov", "https://github.com/TheDmitry"] lang: ru-ru --- -Objective-C — компилируемый объектно-ориентированный язык программирования, используемый корпорацией Apple, -построенный на основе языка Си и парадигм Smalltalk. -В частности, объектная модель построена в стиле Smalltalk — то есть объектам посылаются сообщения. +Objective-C — основной язык программирования, используемый корпорацией Apple +для операционных систем OS X и iOS и их соответствующих фреймворках Cocoa и +Cocoa Touch. +Он является объектно-ориентированным языком программирования общего назначения, +который добавляет обмен сообщениями в Smalltalk-стиле к языку программирования C. ```objective_c -// Однострочный комментарий +// Однострочные комментарии начинаются с // /* -Многострочный -комментарий +Так выглядят многострочные комментарии */ -// Импорт файлов фреймворка Foundation с помощью #import +// Импорт заголовочных файлов фреймворка Foundation с помощью #import +// Используйте <>, чтобы импортировать глобальные файлы (обычно фреймворки) +// Используйте "", чтобы импортировать локальные файлы (из проекта) #import #import "MyClass.h" -// Точка входа в программу это функция main, -// которая возвращает целый тип integer +// Если вы включили модули для iOS >= 7.0 или OS X >= 10.9 проектов в +// Xcode 5, вы можете импортировать фреймворки подобным образом: +@import Foundation; + +// Точка входа в программу - это функция main, +// которая возвращает целый тип int main (int argc, const char * argv[]) { - // Создание autorelease pool для управления памятью + // Создание autorelease pool для управления памятью в программе NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - + // В место этого воспользуйтесь @autoreleasepool, если вы используете + // автоматический подсчет ссылок (ARC) + @autoreleasepool { + // Используйте NSLog для печати в консоль - NSLog(@"Hello World!"); // Напечатает строку "Hello World!" + NSLog(@"Привет Мир!"); // Напечатает строку "Привет Мир!" /////////////////////////////////////// // Типы и переменные /////////////////////////////////////// - // Простое объявление + // Объявление простых типов int myPrimitive1 = 1; long myPrimitive2 = 234554664565; + // Объявление объектов // Помещайте * в начало названия объекта для строго типизированного объявления MyClass *myObject1 = nil; // Строгая типизация id myObject2 = nil; // Слабая типизация - - NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // %@ – это объект - // 'description' это общий для всех объектов метод вывода данных + // 'description' - это общий для всех объектов метод вывода данных + NSLog(@"%@ and %@", myObject1, [myObject2 description]); // напечатает "(null) and (null)" // Строка - NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // напечатает "Hello World!" + NSString *worldString = @"Мир"; + NSLog(@"Привет %@!", worldString); // напечатает "Привет Мир!" + // NSMutableString - это изменяемая версия NSString-объекта + NSMutableString *mutableString = [NSMutableString stringWithString:@"Привет"]; + [mutableString appendString:@" Мир!"]; + NSLog(@"%@", mutableString); // напечатает => "Привет Мир!" // Символьные литералы NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; + char theLetterZ = [theLetterZNumber charValue]; // или 'Z' NSLog(@"%c", theLetterZ); - // Целочисленный литералы + // Целочисленные литералы NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; + int fortyTwo = [fortyTwoNumber intValue]; // или '42' NSLog(@"%i", fortyTwo); // Беззнаковый целочисленный литерал NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; // или 42 NSLog(@"%u", fortyTwoUnsigned); NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; // или 42 NSLog(@"%hi", fortyTwoShort); + NSNumber *fortyOneShortNumber = [NSNumber numberWithShort:41]; + unsigned short fortyOneUnsigned = [fortyOneShortNumber unsignedShortValue]; // или 41 + NSLog(@"%u", fortyOneUnsigned); + NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; + long fortyTwoLong = [fortyTwoLongNumber longValue]; // или 42 NSLog(@"%li", fortyTwoLong); + + NSNumber *fiftyThreeLongNumber = @53L; + unsigned long fiftyThreeUnsigned = [fiftyThreeLongNumber unsignedLongValue]; // или 53 + NSLog(@"%lu", fiftyThreeUnsigned); // Вещественный литерал NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); + float piFloat = [piFloatNumber floatValue]; // или 3.141592654f + NSLog(@"%f", piFloat); // напечатает 3.141592654 + NSLog(@"%5.2f", piFloat); // напечатает " 3.14" NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; + double piDouble = [piDoubleNumber doubleValue]; // или 3.1415926535 NSLog(@"%f", piDouble); - + NSLog(@"%4.2f", piDouble); // напечатает "3.14" + + // NSDecimalNumber - это класс с фиксированной точкой, который является + // более точным, чем float или double + NSDecimalNumber *oneDecNum = [NSDecimalNumber decimalNumberWithString:@"10.99"]; + NSDecimalNumber *twoDecNum = [NSDecimalNumber decimalNumberWithString:@"5.002"]; + // NSDecimalNumber не способен использовать стандартные +, -, *, / операторы, + // поэтому он предоставляет свои собственные: + [oneDecNum decimalNumberByAdding:twoDecNum]; + [oneDecNum decimalNumberBySubtracting:twoDecNum]; + [oneDecNum decimalNumberByMultiplyingBy:twoDecNum]; + [oneDecNum decimalNumberByDividingBy:twoDecNum]; + NSLog(@"%@", oneDecNum); // напечатает "10.99", т.к. NSDecimalNumber - изменяемый + // BOOL (булевый) литерал NSNumber *yesNumber = @YES; NSNumber *noNumber = @NO; - + // или + BOOL yesBool = YES; + BOOL noBool = NO; + NSLog(@"%i", yesBool); // напечатает 1 + // Массив + // Может содержать различные типы данных, но должен быть объектом Objective-C NSArray *anArray = @[@1, @2, @3, @4]; NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // Print "Third number = 3" + NSLog(@"Третье число = %@", thirdNumber); // Напечатает "Третье число = 3" + // NSMutableArray - это изменяемая версия NSArray, допускающая вам изменять + // элементы в массиве и расширять или сокращать массив. + // Удобный, но не эффективный как NSArray. + NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:2]; + [mutableArray addObject:@"Привет"]; + [mutableArray addObject:@"Мир"]; + [mutableArray removeObjectAtIndex:0]; + NSLog(@"%@", [mutableArray objectAtIndex:0]); // напечатает "Мир" // Словарь - NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; - NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Object = %@", valueObject); // Напечатает "Object = (null)" - + NSDictionary *aDictionary = @{ @"ключ1" : @"значение1", @"ключ2" : @"значение2" }; + NSObject *valueObject = aDictionary[@"Ключ"]; + NSLog(@"Объект = %@", valueObject); // Напечатает "Объект = (null)" + // NSMutableDictionary тоже доступен, как изменяемый словарь + NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:2]; + [mutableDictionary setObject:@"значение1" forKey:@"ключ1"]; + [mutableDictionary setObject:@"значение2" forKey:@"ключ2"]; + [mutableDictionary removeObjectForKey:@"ключ1"]; + + // Множество + NSSet *set = [NSSet setWithObjects:@"Привет", @"Привет", @"Мир", nil]; + NSLog(@"%@", set); // напечатает {(Hello, World)} (порядок может отличаться) + // NSMutableSet тоже доступен, как изменяемое множество + NSMutableSet *mutableSet = [NSMutableSet setWithCapacity:2]; + [mutableSet addObject:@"Привет"]; + [mutableSet addObject:@"Привет"]; + NSLog(@"%@", mutableSet); // напечатает => {(Привет)} + /////////////////////////////////////// // Операторы /////////////////////////////////////// @@ -124,13 +189,13 @@ int main (int argc, const char * argv[]) // Условный оператор if (NO) { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } else if (0) { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } else { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } // Ветвление с множественным выбором @@ -138,15 +203,15 @@ int main (int argc, const char * argv[]) { case 0: { - NSLog(@"I am never run"); + NSLog(@"Я никогда не выполнюсь"); } break; case 1: { - NSLog(@"I am also never run"); + NSLog(@"Я тоже никогда не выполнюсь"); } break; default: { - NSLog(@"I print"); + NSLog(@"Я напечатаюсь"); } break; } @@ -170,7 +235,7 @@ int main (int argc, const char * argv[]) // "2," // "3," - // // Цикл просмотра + // Цикл просмотра NSArray *values = @[@0, @1, @2, @3]; for (NSNumber *value in values) { @@ -180,20 +245,32 @@ int main (int argc, const char * argv[]) // "2," // "3," + // Цикл for для объектов. Может использоваться с любым объектом Objective-C + for (id item in values) { + NSLog(@"%@,", item); + } // напечатает => "0," + // "1," + // "2," + // "3," + // Обработка исключений @try { // Ваше исключение здесь @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"File Not Found on System" userInfo:nil]; + reason:@"Файл не найден в системе" userInfo:nil]; } @catch (NSException * e) { - NSLog(@"Exception: %@", e); + NSLog(@"Исключение: %@", e); } @finally { - NSLog(@"Finally"); - } // => напечатает "Exception: File Not Found on System" - // "Finally" + NSLog(@"В конце отводится время для очистки."); + } // => напечатает "Исключение: Файл не найден в системе" + // "В конце отводится время для очистки." + + // NSError - это полезные объекты для аргументов функции, чтобы заполнить их + // пользовательскими ошибками. + NSError *error = [NSError errorWithDomain:@"Неправильный эл. адрес." code:4 userInfo:nil]; /////////////////////////////////////// // Объекты @@ -203,13 +280,16 @@ int main (int argc, const char * argv[]) // Объект не является полнофункциональным пока обе части не выполнятся. MyClass *myObject = [[MyClass alloc] init]; - // В Objective-C можель ООП базируется на передаче сообщений. + // В Objective-C модель ООП базируется на передаче сообщений. // В Objective-C Вы не просто вызваете метод; вы посылаете сообщение. - [myObject instanceMethodWithParameter:@"Steve Jobs"]; + [myObject instanceMethodWithParameter:@"Стив Джобс"]; // Очищайте память, перед завершением работы программы. [pool drain]; + // Конец @autoreleasepool + } + // Конец программы. return 0; } @@ -222,63 +302,144 @@ int main (int argc, const char * argv[]) // Синтаксис объявления: // @interface ИмяКласса : ИмяКлассаРодителя <ИмплементируемыеПротоколы> // { -// Объявление переменных; +// тип имя; <= Объявление переменных; // } +// @property тип имя; <= объявление свойств // -/+ (тип) Объявление метода(ов). // @end - - -@interface MyClass : NSObject +@interface MyClass : NSObject // NSObject - это базовый класс в Objective-C. { - int count; - id data; + // Объявления экземпляров переменных (может существовать в файлах интерфейса или реализвации) + int count; // По умолчанию защищенный доступ. + @private id data; // Приватный доступ (Намного удобнее объявлять в файле реализации) NSString *name; } -// При объявлении свойств сразу генерируются геттер и сеттер -@property int count; -@property (copy) NSString *name; // Скопировать объект в ходе присвоения. -@property (readonly) id data; // Генерация только геттера +// Удобное обозначение для переменных с открытым (public) доступом +// автоматически генерируется сеттер-метод +// По умолчанию название сеттер-метода начинается с 'set' с последующим именем +// переменной из @property +@property int propInt; // Имя сеттер-метода = 'setPropInt' +@property (copy) id copyId; // (copy) => Скопировать объект в ходе присвоения. +// (readonly) => Не позволяет установить значение вне @interface +@property (readonly) NSString *roString; // Используйте @synthesize + // в @implementation, чтобы создать аксессор +// Вы можете настроить геттер и сеттер имена вместо используемого 'set'-имени по умолчанию: +@property (getter=lengthGet, setter=lengthSet:) int length; // Методы -+/- (return type)methodSignature:(Parameter Type *)parameterName; ++/- (возвращаемый тип)сигнатураМетода:(Параметр типа *)имяПараметра; // + для методов класса + (NSString *)classMethod; ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight; -// - для метода объекта +// - для методов объекта - (NSString *)instanceMethodWithParameter:(NSString *)string; - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; -@end +// Методы-конструктор с аргументом: +- (id)initWithDistance:(int)defaultDistance; +// В Objective-C имена методов очень описательные. Всегда имена методов соответствуют своим аргументам + +@end // Устанавливает конец интерфейса (interface) + + +// Чтобы обратиться к открытым (public) переменным из файла реализации, @property генерирует сеттер-метод +// автоматически. Название метода - это 'set' с последующим именем переменной из @property: +MyClass *myClass = [[MyClass alloc] init]; // создает экземпляр объекта класса MyClass +[myClass setCount:10]; +NSLog(@"%d", [myClass count]); // напечатает => 10 +// Или используйте свой геттер и сеттер методы, которые определены в @interface: +[myClass lengthSet:32]; +NSLog(@"%i", [myClass lengthGet]); // напечатает => 32 +// Для удобства вы можете использовать точечную нотацию, +// чтобы установить и получить доступ к переменным объекта: +myClass.count = 45; +NSLog(@"%i", myClass.count); // напечатает => 45 + +// Вызов методов класса: +NSString *classMethodString = [MyClass classMethod]; +MyClass *classFromName = [MyClass myClassFromName:@"Привет"]; + +// Вызов методов экземпляра: +MyClass *myClass = [[MyClass alloc] init]; // Создает экземпляр объекта MyClass +NSString *stringFromInstanceMethod = [myClass instanceMethodWithParameter:@"Привет"]; + +// Селекторы +// Это способ динамически представить методы. Используйте для вызова методов класса, передайте методы +// через функции, чтобы сказать другим классам, что они должны вызвать их и сохранить методы +// как переменные +// SEL - это тип данных. @selector() вернет селектор из предоставленного имени метода +// methodAParameterAsString:andAParameterAsNumber: - это название метода в MyClass +SEL selectorVar = @selector(methodAParameterAsString:andAParameterAsNumber:); +if ([myClass respondsToSelector:selectorVar]) { // Проверяет содержит ли класс метод + // Необходимо установить все аргументы метода в один объект, что отправить его в performSelector-функцию + NSArray *arguments = [NSArray arrayWithObjects:@"Привет", @4, nil]; + [myClass performSelector:selectorVar withObject:arguments]; // Вызывает метод +} else { + // NSStringFromSelector() вернет NSString название метода полученного селектором + NSLog(@"MyClass не содержит метод: %@", NSStringFromSelector(selectedVar)); +} // Имплементируйте методы в файле МойКласс.m: +@implementation MyClass { + long distance; // Переменная экземпляра с закрытым (private) доступом + NSNumber height; +} -@implementation MyClass +// To access a public variable from the interface file, use '_' followed by variable name: +_count = 5; // References "int count" from MyClass interface +// Access variables defined in implementation file: +distance = 18; // References "long distance" from MyClass implementation +// To use @property variable in implementation, use @synthesize to create accessor variable: +@synthesize roString = _roString; // _roString available now in @implementation + +// Called before calling any class methods or instantiating any objects ++ (void)initialize +{ + if (self == [MyClass class]) { + distance = 0; + } +} // Вызывается при высвобождении памяти под объектом - (void)dealloc { + [height release]; // Если не используется ARC, убедитесь в освобождении переменных объекта класса + [super dealloc]; // and call parent class dealloc } -// Конструкторы – это способ осздания объектов класса. -// Это обычный конструктор вызываемый при создании объекта клсааа. +// Конструкторы – это способ создания объектов класса. +// Это конструктор по умолчанию, который вызывается, когда объект инициализируется. - (id)init { - if ((self = [super init])) + if ((self = [super init])) // 'super' используется для того, чтобы обратиться к методам родительского класса { - self.count = 1; + self.count = 1; // 'self' используется для вызова самого себя } return self; } +// Можно создать конструкторы, которые содержат аргументы: +- (id)initWithDistance:(int)defaultDistance +{ + distance = defaultDistance; + return self; +} + (NSString *)classMethod { return [[self alloc] init]; } ++ (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight +{ + height = defaultHeight; + return [[self alloc] init]; +} + - (NSString *)instanceMethodWithParameter:(NSString *)string { - return @"New string"; + return @"Новая строка"; } - (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number @@ -286,23 +447,364 @@ int main (int argc, const char * argv[]) return @42; } +// Objective-C не содержит объявление приватных методов, но вы можете имитировать их. +// Чтобы сымитировать приватный метод, создайте метод в @implementation, но не в @interface. +- (NSNumber *)secretPrivateMethod { + return @72; +} +[self secretPrivateMethod]; // Вызывает приватный метод + // Методы объявленные в МyProtocol (см. далее) - (void)myProtocolMethod { - // имплементация + // операторы } +@end // Устанавливает конец реализации (implementation) + +/////////////////////////////////////// +// Категории +/////////////////////////////////////// +// Категория - это группа методов предназначенные для того, чтобы расширить класс. Они позволяют вам добавить новые методы +// к существующему классу для организационных целей. Это не стоит путать с подклассами. +// Подклассы предназначены для ИЗМЕНЕНИЯ функциональности объекта пока как категории ДОБАВЛЯЮТ +// функциональность в объект. +// Категории позволяют вам: +// -- Добавлять методы в существующий класс для организационных целей. +// -- Допускает вам расширять объекты Objective-C классов (напр.: NSString) добавить ваши собственные методы. +// -- Добавляет возможность создать защищенные и закрытые методы классов. +// ПРИМЕЧАНИЕ: Не переопределяйте методы базового класса в категории даже если у вас есть возможность это сделать +// to. Переопределение методов может привести к ошибкам компиляции позднее между различными категориями и это +// нарушает цель категорий, чтобы добавлять только функциональность. Вместо этого подклассы переопределяют методы. + +// Здесь простой базовый класс Car. +@interface Car : NSObject + +@property NSString *make; +@property NSString *color; + +- (void)turnOn; +- (void)accelerate; + @end -/* - * Протокол объявляет методы которые должны быть имплементированы - * Протокол не является классом. Он просто определяет интерфейс, - * который должен быть имплементирован. - */ +// И реализация базового класса Car: +#import "Car.h" + +@implementation Car + +@synthesize make = _make; +@synthesize color = _color; + +- (void)turnOn { + NSLog(@"Машина заведена."); +} +- (void)accelerate { + NSLog(@"Ускорение."); +} -@protocol MyProtocol - - (void)myProtocolMethod; @end + +// Теперь, если мы хотели создать грузовой объект, мы должны вместо создания подкласса класса Car, как это будет +// изменять функциональность Car чтобы вести себя подобно грузовику. Но давайте посмотрим, если мы хотим только добавить +// функциональность в существующий Car. Хороший пример должен быть чистить автомобиль. Итак мы создадим +// категорию для добавления его очистительных методов: +// @interface ИмяФайла: Car+Clean.h (ИмяБазовогоКласса+ИмяКатегории.h) +#import "Car.h" // Убедитесь в том, что базовый класс импортирован для расширения. + +@interface Car (Clean) // Имя категории внутри (), следующие после имени базового класса. + +- (void)washWindows; // Названия новых методов, которые мы добавляем в наш объект Car. +- (void)wax; + +@end + +// @implementation имя файла: Car+Clean.m (ИмяБазовогоКласса+ИмяКатегории.m) +#import "Car+Clean.h" // Импортируйте Очистку файл @interface категории. + +@implementation Car (Clean) + +- (void)washWindows { + NSLog(@"Окна промыли."); +} +- (void)wax { + NSLog(@"Воском натерли."); +} + +@end + +// Любой экземпляр объекта Car имеет возможность воспользоваться категорией. Все, что нужно сделать, это импортировать ее: +#import "Car+Clean.h" // Импортировать как множество различных категорий, как вы хотите использовать. +#import "Car.h" // Кроме того, необходимо импортировать базовый класс для использования его оригинальные функциональные возможности. + +int main (int argc, const char * argv[]) { + @autoreleasepool { + Car *mustang = [[Car alloc] init]; + mustang.color = @"Красный"; + mustang.make = @"Форд"; + + [mustang turnOn]; // Используйте методы из базового класса Car. + [mustang washWindows]; // Используйте методы категории Clean из класса Car. + } + return 0; +} + +// Objective-C не поддерживает объявление защищенных методов, но вы можете имитировать их. +// Создайте категорию, содержащую все защищенные методы, затем импортируйте ее только в +// @implementation-файле класса, относящегося к классу Car: +@interface Car (Protected) // Наименование категории с помощью 'Protected' +// дает знать, что методы защищенные. + +- (void)lockCar; // Здесь перечисляются методы, которые должны быть созданы +// только с помощью объектов класса Car. + +@end +// Чтобы воспользоваться защищенными методами, импортируйте категорию, затем реализуйте методы: +#import "Car+Protected.h" // Запомните, делайте импорт только в файле с @implementation. + +@implementation Car + +- (void)lockCar { + NSLog(@"Машина закрыта."); // Экземпляры класса Car не могут использовать +// метод lockCar, потому что он объявлен не в @interface. +} + +@end + +/////////////////////////////////////// +// Расширения +/////////////////////////////////////// +// Расширения позволяют вам переопределять атрибуты свойств и методов +// с открытым доступом в @interface. +// @interface имя файла: Shape.h +@interface Shape : NSObject // Расширение базового класса Shape переопределяет + // свои поля ниже. + +@property (readonly) NSNumber *numOfSides; + +- (int)getNumOfSides; + +@end +// Вы можете переопределить numOfSides-переменную или getNumOfSides-метод +// Внесение изменений с помощью расширения делается следующим образом: +// @implementation имя файла: Shape.m +#import "Shape.h" +// Расширения "живут" в том же файле, где и @implementation класса. +@interface Shape () // После имени базового класса скобки () объявляют расширение. + +@property (copy) NSNumber *numOfSides; // Делает numOfSides-свойство + // копирующим (copy) вместо свойства только для чтения (readonly). +-(NSNumber)getNumOfSides; // Изменяет метод getNumOfSides так, + // чтобы он возвращал объект NSNumber вместо типа int. +-(void)privateMethod; // Вы также можете создать новый закрытый метод + // внутри расширения. + +@end +// Главный @implementation: +@implementation Shape + +@synthesize numOfSides = _numOfSides; + +-(NSNumber)getNumOfSides { // Все операторы внутри расширения + // должны быть в @implementation. + return _numOfSides; +} +-(void)privateMethod { + NSLog(@"Закрытый метод созданный с помощью расширения."); + NSLog(@"Экземпляр Shape не может вызвать этот метод."); +} + +@end + +/////////////////////////////////////// +// Протоколы +/////////////////////////////////////// +// Протокол объявляет методы, которые могут быть реализованы с помощью +// любого класса. Протоколы сами по себе не являются классами. Они просто +// определяют интерфейс, который должен быть реализован другими объектами. +// @protocol имя файла: "CarUtilities.h" +@protocol CarUtilities // => Имя другого протокола, +// который включен в этот протокол. + @property BOOL engineOn; // Адаптирующий класс должен определить +// все @synthesize для @property и + - (void)turnOnEngine; // определить все методы. +@end +// Ниже пример класса, реализующий протокол. +#import "CarUtilities.h" // Импорт файла с @protocol. + +@interface Car : NSObject // Внутри <> имя протокола +// Здесь вам не нужно указывать @property или имена методов для CarUtilities. +// Они нужны только для @implementation. +- (void)turnOnEngineWithUtilities:(id )car; // Вы также можете +// указать тип протоколов. +@end +// В @implementation нужно реализовать все @property и методы для протокола. +@implementation Car : NSObject + +@synthesize engineOn = _engineOn; // Создайте @synthesize-оператор +// для "@property engineOn". + +- (void)turnOnEngine { // Реализуйте turnOnEngine как вам угодно. Протоколы +// не определят, + _engineOn = YES; // как вам реализовать метод, он только требует, +// чтобы вы реализовали его. +} +// Вы можете использовать протокол как данные, если вы знаете, что он реализует +// методы и переменные. +- (void)turnOnEngineWithCarUtilities:(id )objectOfSomeKind { + [objectOfSomeKind engineOn]; // У вас есть доступ к переменным объекта + [objectOfSomeKind turnOnEngine]; // и методам. + [objectOfSomeKind engineOn]; // Может или не может быть значение YES. Класс +// реализует как нужно. +} + +@end +// Экземпляры класса Car сейчас имеют доступ к протоколу. +Car *carInstance = [[Car alloc] init]; +[carInstance setEngineOn:NO]; +[carInstance turnOnEngine]; +if ([carInstance engineOn]) { + NSLog(@"Двигатель запущен."); // напечатает => "Двигатель запущен." +} +// Убедитись в том, что объект типа 'id' реализует протокол перед вызовом методов протокола: +if ([myClass conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Не работает, т.к. класс MyClass не реализует протокол CarUtilities."); +} else if ([carInstance conformsToProtocol:@protocol(CarUtilities)]) { + NSLog(@"Работает как класс Car, который реализует протокол CarUtilities."); +} +// Категории тоже могут реализовать протоколы: +// @interface Car (CarCategory) +// Вы можете реализовать много протоколов: +// @interface Car : NSObject +// ЗАМЕЧАНИЕ: Если два или более протоколов полагаются друг на друга, +// убедитесь, что они ранее объявлены: +#import "Brother.h" + +@protocol Brother; // Оператор раннего объявления. Без него компилятор +// выдаст ошибку. + +@protocol Sister + +- (void)beNiceToBrother:(id )brother; + +@end + +// Рассмотрите проблему, где протокол Sister полагается на протокол Brother, +// а Brother полагается на Sister. +#import "Sister.h" + +@protocol Sister; // Эти строки предотвращают рекурсию, решая этим проблему. + +@protocol Brother + +- (void)beNiceToSister:(id )sister; + +@end + + +/////////////////////////////////////// +// Блоки +/////////////////////////////////////// +// Блоки - это операторы кода, наподобие функции, которую возможно использовать +// как данные. +// Ниже простой блок с целочисленным аргументом, и возвращает аргумент плюс 4. +int (^addUp)(int n); // Объявите переменную, чтобы сохранить блок. +void (^noParameterBlockVar)(void); // Пример объявления блока-переменной +// без аргументов. +// Блоки имею доступ к переменным в той же области видимости. Но переменные +// будут только для чтения, и значения переданных в блок станут значением +// переменной, когда блок создастся. +int outsideVar = 17; // Если мы редактируем outsideVar после объявления addUp, +// outsideVar остается равным 17. +__block long mutableVar = 3; // __block делают переменные перезаписываемыми +// в блоках, в отличие от outsideVar. +addUp = ^(int n) { // Удалите (int n) в блоке, чтобы не принимать +// какие-либо параметры. + NSLog(@"Вы можете иметь столько строк в блоке, сколько вы хотели."); + NSSet *blockSet; // Также вы можете объявить локальные переменные. + mutableVar = 32; // Присвоить новое значение к __block-переменной. + return n + outsideVar; // Необязательный оператор возврата. +} +int addUp = add(10 + 16); // Вызывает блок кода с аргументами. +// Блоки часто используются как аргументы функции, чтобы позже их вызвать, или +// как функции обратного вызова (callbacks). +@implementation BlockExample : NSObject + +- (void)runBlock:(void (^)(NSString))block { + NSLog(@"В аргументе блок ничего не возвращает и принимает NSString-объект."); + block(@"Аргумент передан блоку на исполнение."); // Вызов блока. +} + +@end + + +/////////////////////////////////////// +// Управление памятью +/////////////////////////////////////// +/* +Для каждого объекта, используемого в приложении, должна быть выделена память +для таких объектов. Когда приложение прекращает использование объекта, память +должна быть освобождена, чтобы гарантировать эффективность приложения. +Objective-C не использует сборщик мусора, а вместо этого применяет подсчет ссылок. +Пока существует по крайней мере одна ссылка на объект (также называется +"владение" объектом), то объект будет доступен к использованию (еще известно +как "право владения"). + +Когда экземпляр владеет объектом, его ссылка увеличивается на один. Когда +объекта освобождается, счетчик ссылки уменьшается на один. Когда счетчик ссылки +равен нулю, объект удаляется из памяти. + +Над всеми объектами взаимодействуют, следуя паттерну: +(1) создание объекта, (2) использование объекта, (3) затем освобождение объекта из памяти. +*/ + +MyClass *classVar = [MyClass alloc]; // 'alloc' устанавливает счетчик ссылки +// объекта classVar на 1 и возвращает указатель на объект. +[classVar release]; // Уменьшает счетчик ссылки объекта classVar +// 'retain' заявляет право собственности на существующий экземпляр объекта +// и увеличивает счетчик ссылки. Затем вернет указатель на объект. +MyClass *newVar = [classVar retain]; // Если classVar освободится, объект +// останется в памяти, потому что newVar - владелец +[classVar autorelease]; // Удалит право на владение объектом +// в конце @autoreleasepool блока. Вернет указатель на объект. + +// @property может использовать 'retain' и 'assign' тоже для маленького +// удобного определения +@property (retain) MyClass *instance; // Освободит старое значение и сохранит +// одно новое (строгая ссылка) +@property (assign) NSSet *set; // Укажет на новое значение +// без сохранения/освобождения старого значения (слабая ссылка) + +// Автоматический подсчет ссылок (ARC) +// Управление памятью может быть трудным, поэтому в Xcode 4.2 и iOS 4 введен +// автоматический подсчет ссылок (ARC). +// ARC - это особенность компилятора, который помещает "retain", "release" +// и "autorelease" автоматически за вас тогда, когда используется ARC, +// вам не нужно больше обращаться к "retain", "relase" или "autorelease" +MyClass *arcMyClass = [[MyClass alloc] init]; +// ... код, использующий объект arcMyClass +// Без ARC, вам нужно было бы вызвать: [arcMyClass release] после того, как вы +// завершите работу с объектом arcMyClass. Но с ARC, +// теперь этого не нужно делать. Он будет помещать release-вызов за вас + +// Что касается 'assign' и 'retain' @property атрибутов, в ARC вы должны +// использовать 'weak' и 'strong' +@property (weak) MyClass *weakVar; // 'weak' не принимает право на владение +// объектом. Если исходный счетчик ссылки экземпляра обнуляется, +// weakVar-свойство автоматически примет значение nil, +// во избежание падения приложения +@property (strong) MyClass *strongVar; // 'strong' принимает право на владение +// объектом. Гарантирует, что объект останится в памяти для использования + +// Для обычных переменных (не объявленных с помощью @property), используйте +// следующий способ: +__strong NSString *strongString; // По умолчанию. Переменная сохраняется в памяти, +// пока она не покинет область видимости +__weak NSSet *weakSet; // Слабая ссылка на существующий объект. Когда существующий +// объект освобождается, weakSet принимает nil +__unsafe_unretained NSArray *unsafeArray; // Похож на __weak, но unsafeArray +// не принимает nil, когда существующий объект освобождается + ``` ## На почитать -- cgit v1.2.3 From 1989c6773a2c8dd35c16fdabaa2464db4e79f7fc Mon Sep 17 00:00:00 2001 From: TheDmitry Date: Fri, 27 Mar 2015 12:36:14 +0300 Subject: [brainfuck/ru] Updating brainfuck guide --- ru-ru/brainfuck-ru.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ru-ru/brainfuck-ru.html.markdown b/ru-ru/brainfuck-ru.html.markdown index 500ac010..fcee185f 100644 --- a/ru-ru/brainfuck-ru.html.markdown +++ b/ru-ru/brainfuck-ru.html.markdown @@ -11,6 +11,8 @@ lang: ru-ru Brainfuck (пишется маленькими буквами, кроме начала предложения) - это очень маленький Тьюринг-полный язык программирования лишь с 8 командами. +Вы можете испытать brainfuck в вашем браузере с помощью [brainfuck-визуализатора](http://fatiherikli.github.io/brainfuck-visualizer/). + ``` Любой символ, кроме "><+-.,[]", игнорируется, за исключением кавычек. -- cgit v1.2.3 From 68b05bcc518064dab26c5098ea369a71bb9b5d8e Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 17 Jun 2015 23:25:16 +0200 Subject: Fix adambard/learnxinyminutes-site#12 --- it-it/c++-it.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/it-it/c++-it.html.markdown b/it-it/c++-it.html.markdown index 4f5ac8a2..e7e1d89e 100644 --- a/it-it/c++-it.html.markdown +++ b/it-it/c++-it.html.markdown @@ -1,6 +1,6 @@ --- language: c++ -filename: learncpp.cpp +filename: learncpp-it.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From ad344ac7c68ecbfa55f5d7d50bc8b3e7c162f14b Mon Sep 17 00:00:00 2001 From: Esption Date: Wed, 17 Jun 2015 18:35:32 -0500 Subject: Rust: Change '&*' to '&' --- rust.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 17f7dc90..fbfa4cdf 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -84,7 +84,7 @@ fn main() { // This is basically an immutable pointer to a string – it doesn’t // actually contain the contents of a string, just a pointer to // something that does (in this case, `s`) - let s_slice: &str = &*s; + let s_slice: &str = &s; println!("{} {}", s, s_slice); // hello world hello world @@ -99,7 +99,7 @@ fn main() { // A slice – an immutable view into a vector or array // This is much like a string slice, but for vectors - let slice: &[i32] = &*vector; + let slice: &[i32] = &vector; // Use `{:?}` to print something debug-style println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] -- cgit v1.2.3 From 6b109e1460e11cb1030f4832ee67e89283cc6808 Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Thu, 18 Jun 2015 22:20:30 +0800 Subject: cp original file to zh-cn/ --- zh-cn/groovy-cn.html.markdown | 427 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 427 insertions(+) create mode 100644 zh-cn/groovy-cn.html.markdown diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown new file mode 100644 index 00000000..519f36ce --- /dev/null +++ b/zh-cn/groovy-cn.html.markdown @@ -0,0 +1,427 @@ +--- +language: Groovy +filename: learngroovy.groovy +contributors: + - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] +filename: learngroovy.groovy +--- + +Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) + +```groovy + +/* + Set yourself up: + + 1) Install GVM - http://gvmtool.net/ + 2) Install Groovy: gvm install groovy + 3) Start the groovy console by typing: groovyConsole + +*/ + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Hello World +println "Hello world!" + +/* + Variables: + + You can assign values to variables for later use +*/ + +def x = 1 +println x + +x = new java.util.Date() +println x + +x = -3.1499392 +println x + +x = false +println x + +x = "Groovy!" +println x + +/* + Collections and maps +*/ + +//Creating an empty list +def technologies = [] + +/*** Adding a elements to the list ***/ + +// As with Java +technologies.add("Grails") + +// Left shift adds, and returns the list +technologies << "Groovy" + +// Add multiple elements +technologies.addAll(["Gradle","Griffon"]) + +/*** Removing elements from the list ***/ + +// As with Java +technologies.remove("Griffon") + +// Subtraction works also +technologies = technologies - 'Grails' + +/*** Iterating Lists ***/ + +// Iterate over elements of a list +technologies.each { println "Technology: $it"} +technologies.eachWithIndex { it, i -> println "$i: $it"} + +/*** Checking List contents ***/ + +//Evaluate if a list contains element(s) (boolean) +contained = technologies.contains( 'Groovy' ) + +// Or +contained = 'Groovy' in technologies + +// Check for multiple contents +technologies.containsAll(['Groovy','Grails']) + +/*** Sorting Lists ***/ + +// Sort a list (mutates original list) +technologies.sort() + +// To sort without mutating original, you can do: +sortedTechnologies = technologies.sort( false ) + +/*** Manipulating Lists ***/ + +//Replace all elements in the list +Collections.replaceAll(technologies, 'Gradle', 'gradle') + +//Shuffle a list +Collections.shuffle(technologies, new Random()) + +//Clear a list +technologies.clear() + +//Creating an empty map +def devMap = [:] + +//Add values +devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +devMap.put('lastName','Perez') + +//Iterate over elements of a map +devMap.each { println "$it.key: $it.value" } +devMap.eachWithIndex { it, i -> println "$i: $it"} + +//Evaluate if a map contains a key +assert devMap.containsKey('name') + +//Evaluate if a map contains a value +assert devMap.containsValue('Roberto') + +//Get the keys of a map +println devMap.keySet() + +//Get the values of a map +println devMap.values() + +/* + Groovy Beans + + GroovyBeans are JavaBeans but using a much simpler syntax + + When Groovy is compiled to bytecode, the following rules are used. + + * If the name is declared with an access modifier (public, private or + protected) then a field is generated. + + * A name declared with no access modifier generates a private field with + public getter and setter (i.e. a property). + + * If a property is declared final the private field is created final and no + setter is generated. + + * You can declare a property and also declare your own getter or setter. + + * You can declare a property and a field of the same name, the property will + use that field then. + + * If you want a private or protected property you have to provide your own + getter and setter which must be declared private or protected. + + * If you access a property from within the class the property is defined in + at compile time with implicit or explicit this (for example this.foo, or + simply foo), Groovy will access the field directly instead of going though + the getter and setter. + + * If you access a property that does not exist using the explicit or + implicit foo, then Groovy will access the property through the meta class, + which may fail at runtime. + +*/ + +class Foo { + // read only property + final String name = "Roberto" + + // read only property with public getter and protected setter + String language + protected void setLanguage(String language) { this.language = language } + + // dynamically typed property + def lastName +} + +/* + Logical Branching and Looping +*/ + +//Groovy supports the usual if - else syntax +def x = 3 + +if(x==1) { + println "One" +} else if(x==2) { + println "Two" +} else { + println "X greater than Two" +} + +//Groovy also supports the ternary operator: +def y = 10 +def x = (y > 1) ? "worked" : "failed" +assert x == "worked" + +//For loop +//Iterate over a range +def x = 0 +for (i in 0 .. 30) { + x += i +} + +//Iterate over a list +x = 0 +for( i in [5,3,2,1] ) { + x += i +} + +//Iterate over an array +array = (0..20).toArray() +x = 0 +for (i in array) { + x += i +} + +//Iterate over a map +def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] +x = 0 +for ( e in map ) { + x += e.value +} + +/* + Operators + + Operator Overloading for a list of the common operators that Groovy supports: + http://www.groovy-lang.org/operators.html#Operator-Overloading + + Helpful groovy operators +*/ +//Spread operator: invoke an action on all items of an aggregate object. +def technologies = ['Groovy','Grails','Gradle'] +technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() } + +//Safe navigation operator: used to avoid a NullPointerException. +def user = User.get(1) +def username = user?.username + + +/* + Closures + A Groovy Closure is like a "code block" or a method pointer. It is a piece of + code that is defined and then executed at a later point. + + More info at: http://www.groovy-lang.org/closures.html +*/ +//Example: +def clos = { println "Hello World!" } + +println "Executing the Closure:" +clos() + +//Passing parameters to a closure +def sum = { a, b -> println a+b } +sum(2,4) + +//Closures may refer to variables not listed in their parameter list. +def x = 5 +def multiplyBy = { num -> num * x } +println multiplyBy(10) + +// If you have a Closure that takes a single argument, you may omit the +// parameter definition of the Closure +def clos = { print it } +clos( "hi" ) + +/* + Groovy can memorize closure results [1][2][3] +*/ +def cl = {a, b -> + sleep(3000) // simulate some time consuming processing + a + b +} + +mem = cl.memoize() + +def callClosure(a, b) { + def start = System.currentTimeMillis() + mem(a, b) + println "Inputs(a = $a, b = $b) - took ${System.currentTimeMillis() - start} msecs." +} + +callClosure(1, 2) +callClosure(1, 2) +callClosure(2, 3) +callClosure(2, 3) +callClosure(3, 4) +callClosure(3, 4) +callClosure(1, 2) +callClosure(2, 3) +callClosure(3, 4) + +/* + Expando + + The Expando class is a dynamic bean so we can add properties and we can add + closures as methods to an instance of this class + + http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html +*/ + def user = new Expando(name:"Roberto") + assert 'Roberto' == user.name + + user.lastName = 'Pérez' + assert 'Pérez' == user.lastName + + user.showInfo = { out -> + out << "Name: $name" + out << ", Last name: $lastName" + } + + def sw = new StringWriter() + println user.showInfo(sw) + + +/* + Metaprogramming (MOP) +*/ + +//Using ExpandoMetaClass to add behaviour +String.metaClass.testAdd = { + println "we added this" +} + +String x = "test" +x?.testAdd() + +//Intercepting method calls +class Test implements GroovyInterceptable { + def sum(Integer x, Integer y) { x + y } + + def invokeMethod(String name, args) { + System.out.println "Invoke method $name with args: $args" + } +} + +def test = new Test() +test?.sum(2,3) +test?.multiply(2,3) + +//Groovy supports propertyMissing for dealing with property resolution attempts. +class Foo { + def propertyMissing(String name) { name } +} +def f = new Foo() + +assertEquals "boo", f.boo + +/* + TypeChecked and CompileStatic + Groovy, by nature, is and will always be a dynamic language but it supports + typechecked and compilestatic + + More info: http://www.infoq.com/articles/new-groovy-20 +*/ +//TypeChecked +import groovy.transform.TypeChecked + +void testMethod() {} + +@TypeChecked +void test() { + testMeethod() + + def name = "Roberto" + + println naameee + +} + +//Another example: +import groovy.transform.TypeChecked + +@TypeChecked +Integer test() { + Integer num = "1" + + Integer[] numbers = [1,2,3,4] + + Date date = numbers[1] + + return "Test" + +} + +//CompileStatic example: +import groovy.transform.CompileStatic + +@CompileStatic +int sum(int x, int y) { + x + y +} + +assert sum(2,5) == 7 + + +``` + +## Further resources + +[Groovy documentation](http://www.groovy-lang.org/documentation.html) + +[Groovy web console](http://groovyconsole.appspot.com/) + +Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) + +## Books + +* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) + +* [Groovy in Action] (http://manning.com/koenig2/) + +* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) + +[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ +[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize +[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html + + + -- cgit v1.2.3 From 021c80723e3b28d81c852b6fd58b6ec9e34670ff Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Fri, 19 Jun 2015 10:58:39 +0800 Subject: zh-cn translation for groovy --- zh-cn/groovy-cn.html.markdown | 203 ++++++++++++++++++++---------------------- 1 file changed, 98 insertions(+), 105 deletions(-) diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index 519f36ce..ccd48a4c 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -1,36 +1,38 @@ --- language: Groovy -filename: learngroovy.groovy +filename: learngroovy-cn.groovy contributors: - ["Roberto Pérez Alcolea", "http://github.com/rpalcolea"] -filename: learngroovy.groovy +translators: + - ["Todd Gao", "http://github.com/7c00"] +lang: zh-cn --- -Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) +Groovy - Java平台的动态语言。[了解更多。](http://www.groovy-lang.org/) ```groovy /* - Set yourself up: + 安装: - 1) Install GVM - http://gvmtool.net/ - 2) Install Groovy: gvm install groovy - 3) Start the groovy console by typing: groovyConsole + 1) 安装 GVM - http://gvmtool.net/ + 2) 安装 Groovy: gvm install groovy + 3) 启动 groovy 控制台,键入: groovyConsole */ -// Single line comments start with two forward slashes +// 双斜线开始的是单行注释 /* -Multi line comments look like this. +像这样的是多行注释 */ // Hello World println "Hello world!" /* - Variables: + 变量: - You can assign values to variables for later use + 可以给变量赋值,稍后再用 */ def x = 1 @@ -49,142 +51,137 @@ x = "Groovy!" println x /* - Collections and maps + 集合和map */ -//Creating an empty list +//创建一个空的列表 def technologies = [] -/*** Adding a elements to the list ***/ +/*** 往列表中增加一个元素 ***/ -// As with Java +// 和Java一样 technologies.add("Grails") -// Left shift adds, and returns the list +// 左移添加,返回该列表 technologies << "Groovy" -// Add multiple elements +// 增加多个元素 technologies.addAll(["Gradle","Griffon"]) -/*** Removing elements from the list ***/ +/*** 从列表中删除元素 ***/ -// As with Java +// 和Java一样 technologies.remove("Griffon") -// Subtraction works also +// 减法也行 technologies = technologies - 'Grails' -/*** Iterating Lists ***/ +/*** 遍历列表 ***/ -// Iterate over elements of a list +// 遍历列表中的元素 technologies.each { println "Technology: $it"} technologies.eachWithIndex { it, i -> println "$i: $it"} -/*** Checking List contents ***/ +/*** 检查列表内容 ***/ -//Evaluate if a list contains element(s) (boolean) +//判断列表是否包含某元素,返回boolean contained = technologies.contains( 'Groovy' ) -// Or +// 或 contained = 'Groovy' in technologies -// Check for multiple contents +// 检查多个元素 technologies.containsAll(['Groovy','Grails']) -/*** Sorting Lists ***/ +/*** 排序列表 ***/ -// Sort a list (mutates original list) +// 排序列表(修改原列表) technologies.sort() -// To sort without mutating original, you can do: +// 要想不修改原列表,可以这样: sortedTechnologies = technologies.sort( false ) -/*** Manipulating Lists ***/ +/*** 操作列表 ***/ -//Replace all elements in the list +//替换列表元素 Collections.replaceAll(technologies, 'Gradle', 'gradle') -//Shuffle a list +//打乱列表 Collections.shuffle(technologies, new Random()) -//Clear a list +//清空列表 technologies.clear() -//Creating an empty map +//创建空的map def devMap = [:] -//Add values +//增加值 devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] devMap.put('lastName','Perez') -//Iterate over elements of a map +//遍历map元素 devMap.each { println "$it.key: $it.value" } devMap.eachWithIndex { it, i -> println "$i: $it"} -//Evaluate if a map contains a key +//判断map是否包含某键 assert devMap.containsKey('name') -//Evaluate if a map contains a value +//判断map是否包含某值 assert devMap.containsValue('Roberto') -//Get the keys of a map +//取得map所有的键 println devMap.keySet() -//Get the values of a map +//取得map所有的值 println devMap.values() /* Groovy Beans - GroovyBeans are JavaBeans but using a much simpler syntax + GroovyBeans 是 JavaBeans,但使用了更简单的语法 - When Groovy is compiled to bytecode, the following rules are used. + Groovy 被编译为字节码时,遵循下列规则。 - * If the name is declared with an access modifier (public, private or - protected) then a field is generated. + * 如果一个名字声明时带有访问修饰符(public, private, 或者 protected), + 则会生成一个字段(field)。 - * A name declared with no access modifier generates a private field with - public getter and setter (i.e. a property). + * 名字声明时没有访问修饰符,则会生成一个带有public getter和setter的 + private字段,即属性(property)。 - * If a property is declared final the private field is created final and no - setter is generated. + * 如果一个属性声明为final,则会创建一个final的private字段,但不会生成setter。 - * You can declare a property and also declare your own getter or setter. + * 可以声明一个属性的同时定义自己的getter和setter。 - * You can declare a property and a field of the same name, the property will - use that field then. + * 可以声明具有相同名字的属性和字段,该属性会使用该字段。 - * If you want a private or protected property you have to provide your own - getter and setter which must be declared private or protected. + * 如果要定义private或protected属性,必须提供声明为private或protected的getter + 和setter。 - * If you access a property from within the class the property is defined in - at compile time with implicit or explicit this (for example this.foo, or - simply foo), Groovy will access the field directly instead of going though - the getter and setter. + * 如果使用显式或隐式的 this(例如 this.foo, 或者 foo)访问类的在编译时定义的属性, + Groovy会直接访问对应字段,而不是使用getter或者setter - * If you access a property that does not exist using the explicit or - implicit foo, then Groovy will access the property through the meta class, - which may fail at runtime. + * 如果使用显式或隐式的 foo 访问一个不存在的属性,Groovy会通过元类(meta class) + 访问它,这可能导致运行时错误。 */ class Foo { - // read only property + // 只读属性 final String name = "Roberto" - // read only property with public getter and protected setter + // 只读属性,有public getter和protected setter String language protected void setLanguage(String language) { this.language = language } - // dynamically typed property + // 动态类型属性 def lastName } /* - Logical Branching and Looping + 逻辑分支和循环 */ -//Groovy supports the usual if - else syntax +//Groovy支持常见的if - else语法 def x = 3 if(x==1) { @@ -195,32 +192,32 @@ if(x==1) { println "X greater than Two" } -//Groovy also supports the ternary operator: +//Groovy也支持三元运算符 def y = 10 def x = (y > 1) ? "worked" : "failed" assert x == "worked" -//For loop -//Iterate over a range +//for循环 +//使用区间(range)遍历 def x = 0 for (i in 0 .. 30) { x += i } -//Iterate over a list +//遍历列表 x = 0 for( i in [5,3,2,1] ) { x += i } -//Iterate over an array +//遍历数组 array = (0..20).toArray() x = 0 for (i in array) { x += i } -//Iterate over a map +//遍历map def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] x = 0 for ( e in map ) { @@ -228,54 +225,52 @@ for ( e in map ) { } /* - Operators + 运算符 - Operator Overloading for a list of the common operators that Groovy supports: + Groovy中下列运算符支持重载: http://www.groovy-lang.org/operators.html#Operator-Overloading - Helpful groovy operators + 实用的groovy运算符 */ -//Spread operator: invoke an action on all items of an aggregate object. +//展开(spread)运算符:对聚合对象的所有元素施加操作 def technologies = ['Groovy','Grails','Gradle'] -technologies*.toUpperCase() // = to technologies.collect { it?.toUpperCase() } +technologies*.toUpperCase() // 相当于 technologies.collect { it?.toUpperCase() } -//Safe navigation operator: used to avoid a NullPointerException. +//安全导航(safe navigation)运算符:用来避免NullPointerException def user = User.get(1) def username = user?.username /* - Closures - A Groovy Closure is like a "code block" or a method pointer. It is a piece of - code that is defined and then executed at a later point. + 闭包 + Groovy闭包好比代码块或者方法指针,它是一段定义稍后执行的代码。 - More info at: http://www.groovy-lang.org/closures.html + 更多信息见:http://www.groovy-lang.org/closures.html */ -//Example: +//例子: def clos = { println "Hello World!" } println "Executing the Closure:" clos() -//Passing parameters to a closure +//传参数给闭包 def sum = { a, b -> println a+b } sum(2,4) -//Closures may refer to variables not listed in their parameter list. +//闭包可以引用参数列表以外的变量 def x = 5 def multiplyBy = { num -> num * x } println multiplyBy(10) -// If you have a Closure that takes a single argument, you may omit the -// parameter definition of the Closure +// 只有一个参数的闭包可以省略参数的定义 def clos = { print it } clos( "hi" ) /* - Groovy can memorize closure results [1][2][3] + Groovy可以记忆闭包结果 [1][2][3] */ def cl = {a, b -> - sleep(3000) // simulate some time consuming processing + sleep(3000) // 模拟费时操作 a + b } @@ -300,8 +295,7 @@ callClosure(3, 4) /* Expando - The Expando class is a dynamic bean so we can add properties and we can add - closures as methods to an instance of this class + Expando类是一种动态bean类,可以给它的实例添加属性和添加闭包作为方法 http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html */ @@ -321,10 +315,10 @@ callClosure(3, 4) /* - Metaprogramming (MOP) + 元编程(MOP) */ -//Using ExpandoMetaClass to add behaviour +//使用ExpandoMetaClass增加行为 String.metaClass.testAdd = { println "we added this" } @@ -332,7 +326,7 @@ String.metaClass.testAdd = { String x = "test" x?.testAdd() -//Intercepting method calls +//方法调用注入 class Test implements GroovyInterceptable { def sum(Integer x, Integer y) { x + y } @@ -345,7 +339,7 @@ def test = new Test() test?.sum(2,3) test?.multiply(2,3) -//Groovy supports propertyMissing for dealing with property resolution attempts. +//Groovy支持propertyMissing,来处理属性解析尝试 class Foo { def propertyMissing(String name) { name } } @@ -354,13 +348,12 @@ def f = new Foo() assertEquals "boo", f.boo /* - TypeChecked and CompileStatic - Groovy, by nature, is and will always be a dynamic language but it supports - typechecked and compilestatic + 类型检查和静态编译 + Groovy天生是并将永远是一门静态语言,但也支持类型检查和静态编译 - More info: http://www.infoq.com/articles/new-groovy-20 + 更多: http://www.infoq.com/articles/new-groovy-20 */ -//TypeChecked +//类型检查 import groovy.transform.TypeChecked void testMethod() {} @@ -375,7 +368,7 @@ void test() { } -//Another example: +//另一例子 import groovy.transform.TypeChecked @TypeChecked @@ -390,7 +383,7 @@ Integer test() { } -//CompileStatic example: +//静态编译例子 import groovy.transform.CompileStatic @CompileStatic @@ -403,15 +396,15 @@ assert sum(2,5) == 7 ``` -## Further resources +## 进阶资源 -[Groovy documentation](http://www.groovy-lang.org/documentation.html) +[Groovy文档](http://www.groovy-lang.org/documentation.html) [Groovy web console](http://groovyconsole.appspot.com/) -Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) +加入[Groovy用户组](http://www.groovy-lang.org/usergroups.html) -## Books +## 图书 * [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) -- cgit v1.2.3 From a6a498efab8b3ed2e8062a97e0fd47fb181b98f4 Mon Sep 17 00:00:00 2001 From: Todd Gao Date: Fri, 19 Jun 2015 12:16:41 +0800 Subject: update Chinese translation --- zh-cn/groovy-cn.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index ccd48a4c..562a0284 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -32,7 +32,7 @@ println "Hello world!" /* 变量: - 可以给变量赋值,稍后再用 + 可以给变量赋值,以便稍后使用 */ def x = 1 @@ -51,7 +51,7 @@ x = "Groovy!" println x /* - 集合和map + 集合和映射 */ //创建一个空的列表 @@ -73,7 +73,7 @@ technologies.addAll(["Gradle","Griffon"]) // 和Java一样 technologies.remove("Griffon") -// 减法也行 +// 减号也行 technologies = technologies - 'Grails' /*** 遍历列表 ***/ @@ -93,7 +93,7 @@ contained = 'Groovy' in technologies // 检查多个元素 technologies.containsAll(['Groovy','Grails']) -/*** 排序列表 ***/ +/*** 列表排序 ***/ // 排序列表(修改原列表) technologies.sort() @@ -101,7 +101,7 @@ technologies.sort() // 要想不修改原列表,可以这样: sortedTechnologies = technologies.sort( false ) -/*** 操作列表 ***/ +/*** 列表操作 ***/ //替换列表元素 Collections.replaceAll(technologies, 'Gradle', 'gradle') @@ -112,27 +112,27 @@ Collections.shuffle(technologies, new Random()) //清空列表 technologies.clear() -//创建空的map +//创建空的映射 def devMap = [:] //增加值 devMap = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] devMap.put('lastName','Perez') -//遍历map元素 +//遍历映射元素 devMap.each { println "$it.key: $it.value" } devMap.eachWithIndex { it, i -> println "$i: $it"} -//判断map是否包含某键 +//判断映射是否包含某键 assert devMap.containsKey('name') -//判断map是否包含某值 +//判断映射是否包含某值 assert devMap.containsValue('Roberto') -//取得map所有的键 +//取得映射所有的键 println devMap.keySet() -//取得map所有的值 +//取得映射所有的值 println devMap.values() /* @@ -217,7 +217,7 @@ for (i in array) { x += i } -//遍历map +//遍历映射 def map = ['name':'Roberto', 'framework':'Grails', 'language':'Groovy'] x = 0 for ( e in map ) { @@ -227,7 +227,7 @@ for ( e in map ) { /* 运算符 - Groovy中下列运算符支持重载: + 在Groovy中以下常用运算符支持重载: http://www.groovy-lang.org/operators.html#Operator-Overloading 实用的groovy运算符 @@ -243,7 +243,7 @@ def username = user?.username /* 闭包 - Groovy闭包好比代码块或者方法指针,它是一段定义稍后执行的代码。 + Groovy闭包好比代码块或者方法指针,它是一段代码定义,可以以后执行。 更多信息见:http://www.groovy-lang.org/closures.html */ @@ -326,7 +326,7 @@ String.metaClass.testAdd = { String x = "test" x?.testAdd() -//方法调用注入 +//拦截方法调用 class Test implements GroovyInterceptable { def sum(Integer x, Integer y) { x + y } @@ -349,7 +349,7 @@ assertEquals "boo", f.boo /* 类型检查和静态编译 - Groovy天生是并将永远是一门静态语言,但也支持类型检查和静态编译 + Groovy天生是并将永远是一门动态语言,但也支持类型检查和静态编译 更多: http://www.infoq.com/articles/new-groovy-20 */ -- cgit v1.2.3 From e4931ee126a23a851c6a2ab474e84996e1b28f3e Mon Sep 17 00:00:00 2001 From: Ahmad Fatoum Date: Fri, 19 Jun 2015 23:11:38 +0200 Subject: Fixed misinfo regarding sigils also # is more commonly called number sign than number symbol. --- perl.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/perl.html.markdown b/perl.html.markdown index 3c0699ad..4e172406 100644 --- a/perl.html.markdown +++ b/perl.html.markdown @@ -12,16 +12,16 @@ Perl 5 is a highly capable, feature-rich programming language with over 25 years Perl 5 runs on over 100 platforms from portables to mainframes and is suitable for both rapid prototyping and large scale development projects. ```perl -# Single line comments start with a number symbol. +# Single line comments start with a number sign. #### Perl variable types -# Variables begin with the $ symbol. +# Variables begin with a sigil, which is a symbol showing the type. # A valid variable name starts with a letter or underscore, # followed by any number of letters, numbers, or underscores. -### Perl has three main variable types: scalars, arrays, and hashes. +### Perl has three main variable types: $scalar, @array, and %hash. ## Scalars # A scalar represents a single value: -- cgit v1.2.3 From 8d22be8f85339a73f4dcf09be4feefe1be9156b9 Mon Sep 17 00:00:00 2001 From: Michael Simpson Date: Mon, 22 Jun 2015 16:03:24 -0400 Subject: Remove in-development from Rust's description Now that Rust is stable at 1.0 saying "in-development" might not be appropriate any more. --- rust.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index fbfa4cdf..dd03acdd 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnrust.rs --- -Rust is an in-development programming language developed by Mozilla Research. +Rust is a programming language developed by Mozilla Research. Rust combines low-level control over performance with high-level convenience and safety guarantees. -- cgit v1.2.3 From 5e2eed46b23130353122c5bf80be2f3aa2f656bb Mon Sep 17 00:00:00 2001 From: Christian Schlensker Date: Wed, 24 Jun 2015 10:50:39 -0700 Subject: Fix typo in elixer --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index fb5f183a..c8599838 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -195,7 +195,7 @@ cond do "But I will" end -# It is common to see the last condition equal to `true`, which will always match. +# It is common to set the last condition equal to `true`, which will always match. cond do 1 + 1 == 3 -> "I will never be seen" -- cgit v1.2.3 From ed8f34eb3337bd78e2dca23be34746d01272f1ae Mon Sep 17 00:00:00 2001 From: ven Date: Sat, 27 Jun 2015 16:07:21 +0200 Subject: fix typo, resolves #1156 --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index 44ad333c..de7d2f25 100644 --- a/perl6.html.markdown +++ b/perl6.html.markdown @@ -1044,7 +1044,7 @@ postcircumfix:<{ }>(%h, $key, :delete); # (you can call operators like that) # *everything* -- with great power comes great responsibility) ## Meta operators ! -# Oh boy, get ready. Get ready, because we're dwelving deep +# Oh boy, get ready. Get ready, because we're delving deep # into the rabbit's hole, and you probably won't want to go # back to other languages after reading that. # (I'm guessing you don't want to already at that point). -- cgit v1.2.3 From 9f17872f21bc3a43a1023325414802c2e4467534 Mon Sep 17 00:00:00 2001 From: Leonardo Diez Date: Fri, 3 Jul 2015 11:34:26 +0200 Subject: Update git-es.html.markdown --- es-es/git-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index 5c9d3378..73853a9d 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -38,7 +38,7 @@ uno o varios archivos, a lo largo del tiempo. * Se puede trabajar sin conexion. * Colaborar con otros es sencillo!. * Derivar, Crear ramas del proyecto (aka: Branching) es facil!. -* Combinar (aka: Marging) +* Combinar (aka: Merging) * Git es rapido. * Git es flexible. -- cgit v1.2.3 From 92096a65ed309e84439f84f7b410a044386a2959 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 08:35:31 -0600 Subject: python/en - added two resources --- python.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index ace3f794..354fd9a1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -630,10 +630,12 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [Python Module of the Week](http://pymotw.com/2/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) +* [Real Python](https://realpython.com/) -- cgit v1.2.3 From 55f9ff0654f6489aa53e3a799af2dd462fa9c5c8 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 08:36:51 -0600 Subject: python/en - added two resources --- python3.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/python3.html.markdown b/python3.html.markdown index a112912f..9369a3ad 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -645,15 +645,16 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) - * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) +* [Real Python](https://realpython.com/) -- cgit v1.2.3 From c6caa7664c53d8decb2076987f601a7c99fd6951 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 21:12:12 -0600 Subject: Update python.html.markdown --- python.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 354fd9a1..b89fe57d 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -637,5 +637,3 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -* [Real Python](https://realpython.com/) - -- cgit v1.2.3 From 5b66758d761afceb797ae0f21d5c99351d29361e Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 21:12:58 -0600 Subject: Update python3.html.markdown --- python3.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 9369a3ad..dd57bf58 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -656,5 +656,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) * [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -* [Real Python](https://realpython.com/) - -- cgit v1.2.3 From 8544847845c0405e54acadf5125edc0554d73b75 Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 6 Jul 2015 10:40:05 +0200 Subject: change haskell's operator `$` description wording for #1161 --- haskell.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6a64442f..369b1b20 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -209,14 +209,15 @@ foo 5 -- 75 -- the expression on its right is applied as the parameter to the function on its left. -- before -(even (fib 7)) -- false - --- after -even . fib $ 7 -- false +even (fib 7) -- false -- equivalently even $ fib 7 -- false +-- composing functions +even . fib $ 7 -- false + + ---------------------------------------------------- -- 5. Type signatures ---------------------------------------------------- -- cgit v1.2.3 From abcb4e25de06ce4b295b1999fd251d76f60d5fc5 Mon Sep 17 00:00:00 2001 From: Guangming Mao Date: Wed, 8 Jul 2015 20:51:09 +0800 Subject: rust/zh Add chinese translation for rust --- zh-cn/rust-cn.html.markdown | 296 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 zh-cn/rust-cn.html.markdown diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown new file mode 100644 index 00000000..f50c1566 --- /dev/null +++ b/zh-cn/rust-cn.html.markdown @@ -0,0 +1,296 @@ +--- +language: rust +contributors: + - ["P1start", "http://p1start.github.io/"] +translators: + - ["Guangming Mao", "http://maogm.com"] +filename: learnrust-cn.rs +lang: zh-cn +--- + +Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制和高级语言的便利性和安全保障结合在了一起。 + +而 Rust 并不需要一个垃圾回收器或者运行时即可实现这个目的,这使得 Rust 库可以成为一种 C 语言的替代品。 + +Rust 第一版(0.1 版)发布于 2012 年 1 月,3 年以来一直在紧锣密鼓地迭代。 +因为更新太频繁,一般建议使用每夜构建版而不是稳定版,直到最近 1.0 版本的发布。 + +2015 年 3 月 15 日,Rust 1.0 发布,完美向后兼容,最新的每夜构建版提供了缩短编译时间等新特性。 +Rust 采用了持续迭代模型,每 6 周一个发布版。Rust 1.1 beta 版在 1.0 发布时同时发布。 + +尽管 Rust 相对来说是一门底层语言,它提供了一些常见于高级语言的函数式编程的特性。这让 Rust 不仅高效,并且易用。 + +```rust +// 这是注释,单行注释... +/* ...这是多行注释 */ + +/////////////// +// 1. 基础 // +/////////////// + +// 函数 (Functions) +// `i32` 是有符号 32 位整数类型(32-bit signed integers) +fn add2(x: i32, y: i32) -> i32 { + // 隐式返回 (不要分号) + x + y +} + +// 主函数(Main function) +fn main() { + // 数字 (Numbers) // + + // 不可变绑定 + let x: i32 = 1; + + // 整形/浮点型数 后缀 + let y: i32 = 13i32; + let f: f64 = 1.3f64; + + // 类型推导 + // 大部分时间,Rust 编译器会推导变量类型,所以不必把类型显式写出来。 + // 这个教程里面很多地方都显式写了类型,但是只是为了示范。 + // 绝大部分时间可以交给类型推导。 + let implicit_x = 1; + let implicit_f = 1.3; + + // 算术运算 + let sum = x + y + 13; + + // 可变变量 + let mut mutable = 1; + mutable = 4; + mutable += 2; + + // 字符串 (Strings) // + + // 字符串字面量 + let x: &str = "hello world!"; + + // 输出 + println!("{} {}", f, x); // 1.3 hello world + + // 一个 `String` – 在堆上分配空间的字符串 + let s: String = "hello world".to_string(); + + // 字符串分片(slice) - 另一个字符串的不可变视图 + // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何类容,只是一个指向某个东西的指针 + // 比如这里就是 `s` + let s_slice: &str = &s; + + println!("{} {}", s, s_slice); // hello world hello world + + // 数组 (Vectors/arrays) // + + // 长度固定的数组 (array) + let four_ints: [i32; 4] = [1, 2, 3, 4]; + + // 变长数组 (vector) + let mut vector: Vec = vec![1, 2, 3, 4]; + vector.push(5); + + // 分片 - 某个数组(vector/array)的不可变视图 + // 和字符串分片基本一样,只不过是针对数组的 + let slice: &[i32] = &vector; + + // 使用 `{:?}` 按调试样式输出 + println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] + + // 元组 (Tuples) // + + // 元组是固定大小的一组值,可以是不同类型 + let x: (i32, &str, f64) = (1, "hello", 3.4); + + // 解构 `let` + let (a, b, c) = x; + println!("{} {} {}", a, b, c); // 1 hello 3.4 + + // 索引 + println!("{}", x.1); // hello + + ////////////// + // 2. 类型 (Type) // + ////////////// + + // 结构体(Sturct) + struct Point { + x: i32, + y: i32, + } + + let origin: Point = Point { x: 0, y: 0 }; + + // 匿名成员结构体,又叫“元组结构体”(‘tuple struct’) + struct Point2(i32, i32); + + let origin2 = Point2(0, 0); + + // 基础的 C 风格枚举类型(enum) + enum Direction { + Left, + Right, + Up, + Down, + } + + let up = Direction::Up; + + // 有成员的枚举类型 + enum OptionalI32 { + AnI32(i32), + Nothing, + } + + let two: OptionalI32 = OptionalI32::AnI32(2); + let nothing = OptionalI32::Nothing; + + // 泛型 (Generics) // + + struct Foo { bar: T } + + // 这个在标准库里面有实现,叫 `Option` + enum Optional { + SomeVal(T), + NoVal, + } + + // 方法 (Methods) // + + impl Foo { + // 方法需要一个显式的 `self` 参数 + fn get_bar(self) -> T { + self.bar + } + } + + let a_foo = Foo { bar: 1 }; + println!("{}", a_foo.get_bar()); // 1 + + // 接口(Traits) (其他语言里叫 interfaces 或 typeclasses) // + + trait Frobnicate { + fn frobnicate(self) -> Option; + } + + impl Frobnicate for Foo { + fn frobnicate(self) -> Option { + Some(self.bar) + } + } + + let another_foo = Foo { bar: 1 }; + println!("{:?}", another_foo.frobnicate()); // Some(1) + + /////////////////////////////////// + // 3. 模板匹配 (Pattern matching) // + /////////////////////////////////// + + let foo = OptionalI32::AnI32(1); + match foo { + OptionalI32::AnI32(n) => println!("it’s an i32: {}", n), + OptionalI32::Nothing => println!("it’s nothing!"), + } + + // 高级模板匹配 + struct FooBar { x: i32, y: OptionalI32 } + let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; + + match bar { + FooBar { x: 0, y: OptionalI32::AnI32(0) } => + println!("The numbers are zero!"), + FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m => + println!("The numbers are the same"), + FooBar { x: n, y: OptionalI32::AnI32(m) } => + println!("Different numbers: {} {}", n, m), + FooBar { x: _, y: OptionalI32::Nothing } => + println!("The second number is Nothing!"), + } + + /////////////////////////////// + // 4. 条件控制 (Control flow) // + /////////////////////////////// + + // `for` 循环 + let array = [1, 2, 3]; + for i in array.iter() { + println!("{}", i); + } + + // 区间 (Ranges) + for i in 0u32..10 { + print!("{} ", i); + } + println!(""); + // 输出 `0 1 2 3 4 5 6 7 8 9 ` + + // `if` + if 1 == 1 { + println!("Maths is working!"); + } else { + println!("Oh no..."); + } + + // `if` 可以当表达式 + let value = if true { + "good" + } else { + "bad" + }; + + // `while` 循环 + while 1 == 1 { + println!("The universe is operating normally."); + } + + // 无限循环 + loop { + println!("Hello!"); + } + + //////////////////////////////////////////////// + // 5. 内存安全和指针 (Memory safety & pointers) // + //////////////////////////////////////////////// + + // 独占指针 (Owned pointer) - 同一时刻只能有一个对象能“拥有”这个指针 + // 意味着 `Box` 离开他的作用域后,会被安全的释放 + let mut mine: Box = Box::new(3); + *mine = 5; // 解引用 + // `now_its_mine` 获取了 `mine` 的所有权。换句话说,`mine` 移动 (move) 了 + let mut now_its_mine = mine; + *now_its_mine += 2; + + println!("{}", now_its_mine); // 7 + // println!("{}", mine); // 编译报错,因为现在 `now_its_mine` 独占那个指针 + + // 引用 (Reference) – 引用其他数据的不可变指针 + // 当引用指向某个值,我们称为“借用”这个值,因为是被不可变的借用,所以不能被修改,也不能移动 + // 借用一直持续到生命周期结束,即离开作用域 + let mut var = 4; + var = 3; + let ref_var: &i32 = &var; + + println!("{}", var); //不像 `box`, `var` 还可以继续使用 + println!("{}", *ref_var); + // var = 5; // 编译报错,因为 `var` 被借用了 + // *ref_var = 6; // 编译报错,因为 `ref_var` 是不可变引用 + + // 可变引用 (Mutable reference) + // 当一个变量被可变地借用时,也不可使用 + let mut var2 = 4; + let ref_var2: &mut i32 = &mut var2; + *ref_var2 += 2; + + println!("{}", *ref_var2); // 6 + // var2 = 2; // 编译报错,因为 `var2` 被借用了 +} +``` + +## 更深入的资料 + +Rust 还有很多很多其他类容 - 这只是 Rust 最基础的东西,帮助你了解 Rust 里面最重要的东西。 +如果想深入学习 Rust,可以去阅读 +[The Rust Programming Language](http://doc.rust-lang.org/book/index.html) +或者上 reddit [/r/rust](http://reddit.com/r/rust) 订阅。 +同时 irc.mozilla.org 的 #rust 频道上的小伙伴们也非常欢迎新来的朋友。 + +你可以在这个在线编译器 [Rust playpen](http://play.rust-lang.org) 上尝试 Rust 的一些特性 +或者上[官方网站](http://rust-lang.org). -- cgit v1.2.3 From 56171326c725f70cfdec99d8086d9c5dc8d1a211 Mon Sep 17 00:00:00 2001 From: = <=> Date: Sun, 12 Jul 2015 16:17:23 -0700 Subject: added chapel.html.markdown, performed a first pass at the tutorial, and the beginning readme of the tutorial. Currently missing topics [ reduction, scal, non-loop tuple expansion, whole array/partial array assignment] --- chapel.html.markdown | 722 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 722 insertions(+) create mode 100644 chapel.html.markdown diff --git a/chapel.html.markdown b/chapel.html.markdown new file mode 100644 index 00000000..a17222b9 --- /dev/null +++ b/chapel.html.markdown @@ -0,0 +1,722 @@ +--- +language: chapel +filename: learnchapel.chpl +contributors: + - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola.com/"] +lang: en +--- +What is Chapel? +=============== +You can read all about chapel at [Cray's official Chapel website](chapel.cray.com). +In short, Chapel is an open-source, high-productivity, parallel-programming language in development +at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. + +Chapel is currently in-development so there are occasional hiccups with +performance and language features, which is why you should write as much Chapel + +Your input, questions, and discoveries are important to us! +----------------------------------------------------------- +The more information you give the Chapel development team about issues you encounter with the language, +the better the language gets. +Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) +There is also a #chapel-developers hosted at chat.freenode.net. + +If you're really interested in the cutting edge compiler or contributing to the project, +the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) +under the Apache v2.0 license + +Installing the Compiler +----------------------- +Chapel can be built and installed on your average 'nix machine (and cygwin). +Download the latest release version from https://github.com/chapel-lang/chapel/releases/ +and its as easy as +1. ```tar -xvf chapel-1.11.0.tar.gz``` +2. ```cd chapel-1.11.0``` +3. ```make``` +4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + +You will need to ```source util/setchplenv.*``` from the chapel directory every +time your terminal starts so its suggested that you drop that command in a script +that will get executed on startup (like .bashrc). + + +Chapel is easily installed with Brew for OS X +1. ```brew update``` +2. ```brew install chapel``` + +Who is this tutorial for? +------------------------- +This tutorial is for people who want to learn the ropes of chapel without having to +hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations +differ between one another. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. +Refer to the [language specification](http://chapel.cray.com/language.html) +and the [library-documentation](http://chapel.cray.com/docs/latest/) for more details. + +Occasionally check here back to see if more topics have been added. + +```chapel +// Comments are C-family style +// one line comment +/* + multi-line comment +*/ + +// Basic printing +write( "Hello, " ); +writeln( "World!" ); +// write and writeln can take a list of things to print. +// each thing is printed right next to each other, so include your spacing! +writeln( "There are ", 3, " commas (\",\") in this line of code" ); +// Different output channels +stdout.writeln( "This goes to standard output (just like plain writeln() does)"); +stderr.writeln( "This goes to standard error" ); + +// Variables +// Variables dont have to be explicitly as long as the compiler can figure +// out the type that it will hold. +var myVar = 10; // 10 is an int, so myVar is implicitly an int +myVar = -10; +// var anError; // compile time error, dont know what type anError should be. + +// We can (and should) explicitly type things +var mySecondVar: real; // define mySecondVar as a real +var myThirdVar: real = -1.234; +mySecondVar = myThirdVar; + +// There are a number of basic types. +var myInt: int = -1000; // signed ints +var myUint: uint = 1234; // unsigned ints +var myReal: real = 9.876; // floating point numbers +var myImag: imag = 5.0i; // imaginary numbers +var myCplx: complex = 10 + 9i; // complex numbers +myCplx = myInt + myImag ; // another way to form complex numbers +var myBool: bool = false; // booleans +var myStr: string = "Some string..."; // strings + +// Some types can have sizes +var my8Int: int(8) = 10; // 8 bit (one byte) sized int; +var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real + +// Typecasting +var intFromReal = myReal : int; +// could also explicitly type intFromReal +// var intFromReal: int = myReal : int; + +// Operators +// Math operators +var a: int, thisInt = 1234, thatInt = 5678; +a = thisInt + thatInt; // Addition +a = thisInt * thatInt; // Multiplication +a = thisInt - thatInt; // Subtraction +a = thisInt / thatInt; // division +a = thisInt ** thatInt; // exponentiation +a = thisInt % thatInt; // remainder (modulo) + +// Logical Operators +var b: bool, thisBool = false, thatBool = true; +b = thisBool && thatBool; // logical and +b = thisBool || thatBool; // logical or +b = !thisBool; // logical negation + +// Relational Operators +b = thisInt > thatInt; // greater-than +b = thisInt >= thatInt; // greater-than-or-equal-to +b = thisInt < a && a <= thatInt; // less-than, and, less-than-or-equal-to +b = thisInt != thatInt; // not-equal-to +b = thisInt == thatInt; // equal-to + +// Bitwise operations +a = thisInt << 10; // left-bit-shift by 10 bits; +a = thatInt >> 5; // right-bit-shift by 5 bits; +a = ~thisInt; // bitwise-negation +a = thisInt ^ thatInt; // bitwise exclusive-or + +// Compound assignment operations +a += thisInt; // addition-equals ( a = a + thisInt;) +a *= thatInt; // times-equals ( a = a * thatInt; ) +b &&= thatBool; // logical-and-equals ( b = b && thatBool; ) +a <<= 3; // left-bit-shift-equals ( a = a << 10; ) +// and so on... +// Unlike other C family languages there are no +// pre/post-increment/decrement operators like +// ++j, --j, j++, j-- + + +// Swap operator +var temp_this = thisInt; +var temp_that = thatInt; +thisInt <=> thatInt; // Swap the values of thisInt and thatInt +writeln( (temp_this == thatInt) && (temp_that == thisInt) ); + +// We can also define operator overloads, +// which we'll cover with procedures. + +// Tuples +// tuples can be of the same type +var sameTup: 2*int = (10,-1); +// or different types +var diffTup: (int,real,complex) = (5, 1.928, myCplx); +// Accessed using array bracket notation +// However, tuples are all 1-indexed +writeln( "(", sameTup[1], ",", sameTup[2], ")" ); +writeln( diffTup ); +// Tuples can also be written into. +diffTup[1] = -1; +// Can also be used to easily write a collection of variables +// as is common in debugging +writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); + +// Type aliasing +type chroma = int; // type of a single hue +type RGBColor = 3*chroma; // type representing a full color +var black: RGBColor = ( 0,0,0 ); +var white: RGBColor = ( 255, 255, 255 ); + + + +// If-Then statements +// if-thens dont require parentheses around the condition +// as they do in C (however, we will use them) +// and a single line body can use the 'then' keyword instead of braces +// and else statements can be written similarly +// (but we're only going to show it once). +if 10 < 100 then + writeln( "All is well" ); + +if -1 < 1 then + writeln( "Continuing to believe reality" ); +else + writeln( "Send mathematician, something's wrong" ); + + +if ( 10 > 100 ) { + writeln( "Universe broken. Please reboot universe." ); +} + +if ( a % 2 == 0 ) { + writeln( a, " is even." ); +} else { + writeln( a, " is odd." ); +} + +if ( a % 3 == 0 ) { + writeln( a, " is even divisible by 3." ); +} else if ( a % 3 == 1 ){ + writeln( a, " is divided by 3 with a remainder of 1." ); +} else { + writeln( b, " is divided by 3 with a remainder of 2." ); +} + +// Ternary: if-then-else in a statement +var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; + +// Select statements +// Select statements are much like switch statements in other languages +// However, Select statements dont cascade like in C or Java +var inputOption = "anOption"; +select( inputOption ){ + when "anOption" do writeln( "Chose 'anOption'" ); + when "otherOption" { + writeln( "Chose 'otherOption'" ); + writeln( "Which has a body" ); + } + otherwise { + writeln( "Any other Input" ); + writeln( "the otherwise case doesn't need a do if the body is one line" ); + writeln( "Oh, and when statements dont cascade like the case statements" ); + writeln( "of other languages" ); + } +} + +// Loops +// While Loops +// While loops and Do-While loops are basically the same in every language. + +var j: int = 1; +var jSum: int = 0; +while( j <= 1000 ){ + jSum += j; + j += 1; // there are no ++j, --j, j++, j--, operators +} +writeln( jSum ); + +// basic Do-While loop +do{ + jSum += j; + j += 1; +}while( j <= 10000 ); +writeln( jSum ); + +// For loops +// For loops are much like those in python in that they iterate over a range. +// ranges themselves are types, and can be stuffed into variables +// (more about that later) + +for i in 1..10 do write( i , ", ") ; +writeln(); + +var iSum: int = 0; +for i in 1..1000 { + iSum += i; +} +writeln( iSum ); + +for x in 1..10 { + for y in 1..10 { + write( (x,y), "\t" ); + } + writeln(); +} + +// Ranges and Domains +// For-loops and arrays both use ranges and domains to +// define an index set that can be iterated over. +// Ranges are single dimensional +// Domains can be multi-dimensional and represent indicies +// of different types as well. +// They are types, and can be assigned into variables; +var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 + +// Ranges can be strided using the 'by' operator. +// Note: the stridable=true is only necessary if we type the variable +var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 + +// The end point of a range can be determined using the count (#) operator +var rangeCount: range = -5..#12; // range from -5 to 6 + +// Can mix operators +var rangeCountBy: range(stridable=true) = -5..#12 by 2; // -5, -3, -1, 1, 3, 5 +writeln( rangeCountBy ); + +// Can query properties of the range +// Print the first index, last index, number of indices, +// stride, and ask if 2 is include in the range +writeln( ( rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, + rangeCountBy.stride, rangeCountBy.member( 2 ) ) ); + +for i in rangeCountBy{ + write( i, if i == rangeCountBy.last then "\n" else ", " ); +} + +// domains are similarly defined using range notation +var domain1to10: domain(1) = {1..10}; // domain from 1..10; +var twoDimensions: domain(2) = {-2..2,0..2}; // domain over two dimensions + +// Can iterate over the indices as tuples +for idx in twoDimensions do + write( idx , ", "); +writeln(); + +// Or can deconstruct the tuple +for (x,y) in twoDimensions { + write( (x,y), ", " ); +} +writeln(); + +// Associative domains act like sets +var intSet: domain(int); // empty set of ints +intSet += 1; +intSet += 2; +intSet += 3; +intSet += 1; // redundant add 1 +intSet -= 3; // remove 3 +writeln( intSet ); + + +// Arrays +// Array are similar to those of other languages. +// Their sizes are defined using ranges and domains. +// that represent their indices, but we'll touch more on those later +var intArray: [1..10] int; // array of integers defined using range literal + +// Accessed using bracket notation +for i in 1..10 do + intArray[i] = -i; +writeln( intArray ); +// we cannot access intArray[0] because it exists outside +// of the index set we defined (1..10) +// intArray[11] is illegal for the same reason. + +var realDomain: domain(2) = {1..5,1..7}; +var realArray: [realDomain] real; +// similarly we could have done: +// var realArray: [1..5,1..7] real; + +for i in 1..5 { + // use the range from 2nd dimension of the domain + for j in realDomain.dim(2) { + realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list + var idx: 2*int = (i,j); // note: 'index' is a keyword + realArray[idx] = - realArray[(i,j)]; // index using tuples + } +} + +// arrays have domains as members that we can iterate over +for idx in realArray.domain { // idx is, again, a 2*int tuple + realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list +} + +writeln( realArray ); + +// can also iterate over the values of an array +var rSum: real = 0; +for value in realArray { + rSum += value; // read a value + value = rSum; // write a value +} +writeln( rSum, "\n", realArray ); + +// Using associative domains we can create associative arrays (dictionaries) +var dictDomain: domain(string) = { "one", "two" }; +var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; +dict["three"] = 3; +writeln( dict ); + + +// Procedures +// Chapel procedures have similar syntax to other languages functions. + +proc fibonacci( n : int ) : int { + if ( n == 0 || n == 1 ) then return n; + return fibonacci( n-1 ) + fibonacci( n-2 ); +} + +// input parameters can be untyped +proc doublePrint( thing ): void { + write( thing, " ", thing, "\n"); +} + +// return type can be inferred (as long as the compiler can figure it out) +proc addThree( n ) { + return n + 3; +} + +doublePrint( addThree( fibonacci( 20 ) ) ); + +// Can also take unlimited number of parameters +proc maxOf( x ...?k ) { + // x refers to a tuple of one type, with k elements + var maximum = x[1]; + for i in 2..k do maximum = if (maximum < x[i]) then x[i] else maximum; + return maximum; +} +writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); + +// the ? operator is called the query operator, and is used to take +// undetermined values (like tuple and array sizes, and generic types). + +// Taking arrays as parameters. +// The query operator is used to determine the domain of A. +// this is important to define the return type (if you wanted to) +proc invertArray( A: [?D] int ): [D] int{ + for a in A do a = -a; + return A; +} + +writeln( invertArray( intArray ) ); + +// Procedures can have default parameter values, and +// the parameters can be named in the call, even out of order +proc defaultsProc( x: int, y: real = 1.2634 ): (int,real){ + return (x,y); +} + +writeln( defaultsProc( 10 ) ); +writeln( defaultsProc( x=11 ) ); +writeln( defaultsProc( x=12, y=5.432 ) ); +writeln( defaultsProc( y=9.876, x=13 ) ); + +// Generic procedures can still retain type +// Here we define a procedure that takes two arguments +// of the same type, yet we dont define what that type is. +proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { + select( valueType ){ + when int do writeln( arg1, " and ", arg2, " are ints" ); + when real do writeln( arg1, " and ", arg2, " are reals" ); + otherwise writeln( arg1, " and ", arg2, " are somethings!" ); + } +} + +genericProc( 1, 2 ); +genericProc( 1.2, 2.3 ); +genericProc( 1.0+2.0i, 3.0+4.0i ); + +// We can also enforce a form of polymorphism with the 'where' clause +// This allows the compiler to decide which function to use. +// Note: that means that all information needs to be known at compile +// time. Hence, we use params here to assert that the arguments must +// be known at compile time. +proc whereProc( param N : int ): void + where ( N > 0 ) { + writeln( "N is greater than 0" ); +} + +proc whereProc( param N : int ): void + where ( N < 0 ) { + writeln( "N is less than 0" ); +} + +whereProc( 10 ); +whereProc( -1 ); +// whereProc( 0 ) would result in a compiler error because there +// are no functions that satisfy the where clause's condition. +// We could have defined a whereProc without a where clause that would +// then have been called. + +// Operator definitions are through procedures as well +// we can define the unary operators: +// + - ! ~ +// and the binary operators: +// + - * / % ** == <= >= < > << >> & | ˆ by +// += -= *= /= %= **= &= |= ˆ= <<= >>= <=> + +// boolean exclusive or operator +proc ^( left : bool, right : bool ): bool { + return (left || right) && !( left && right ); +} + +writeln( true ^ true ); +writeln( false ^ true ); +writeln( true ^ false ); +writeln( false ^ false ); + +// Define a * operator on any two types. +proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ + return (left, right ); +} + +writeln( 1 * "a" ); // uses our * operator +writeln( 1 * 2 ); // uses the original * operator + +/* +Note: You could break everything if you + get careless with your overloads. +This here will break everything. Dont do it. +proc +( left: int, right: int ): int{ + return left - right; +} +*/ + +// Classes +class MyClass { + // Member variables + var memberInt : int; + var memberBool : bool = true; + + // Classes have default constructors that dont need to be coded (see below) + // Our explicitly defined constructor + proc MyClass( val : real ){ + this.memberInt = ceil( val ): int; + } + + // Our explicitly defined destructor + proc ~MyClass( ){ + writeln( "MyClass Destructor called ", (this.memberInt, this.memberBool) ); + } + + // Class methods + proc setMemberInt( val: int ){ + this.memberInt = val; + } + + proc setMemberBool( val: bool ){ + this.memberBool = val; + } + + proc getMemberInt( ): int{ + return this.memberInt; + } + + proc getMemberBool(): bool { + return this.memberBool; + } + +} + +// Construct using default constructor, using default values +var myObject = new MyClass( 10 ); + myObject = new MyClass( memberInt = 10 ); // equivalent +writeln( myObject.getMemberInt() ); +// ... using our values +var myDiffObject = new MyClass( -1, true ); + myDiffObject = new MyClass( memberInt = -1, + memberBool = false ); // equivalent +writeln( (myDiffObject.getMemberInt(), myDiffObject.getMemberBool() )); + +// Construct using written constructor +var myOtherObject = new MyClass( 1.95 ); + myOtherObject = new MyClass( val = 1.95 ); // equivalent +writeln( myOtherObject.getMemberInt() ); + +// We can define an operator on our class as well but +// the definition has to be outside the class definition +proc +( A : MyClass, B : MyClass) : MyClass { + return new MyClass( memberInt = A.getMemberInt() + B.getMemberInt(), + memberBool = A.getMemberBool() || B.getMemberBool() ); +} + +var plusObject = myObject + myDiffObject; +writeln( (plusObject.getMemberInt(), plusObject.getMemberBool() ) ); + +// destruction +delete myObject; +delete myDiffObject; +delete myOtherObject; +delete plusObject; + +// Classes can inherit from one or more parent classes +class MyChildClass : MyClass { + var memberComplex: complex; +} + +// Generic Classes +class GenericClass { + type classType; + var classDomain: domain(1); + var classArray: [classDomain] classType; + + // Explicit constructor + proc GenericClass( type classType, elements : int ){ + this.classDomain = {1..#elements}; + } + + // Copy constructor + // Note: We still have to put the the type as an argument, but we can + // default to the type of the other object using the query (?) operator + // Further, we can take advantage of this to allow our copy constructor + // to copy classes of different types + proc GenericClass( other : GenericClass(?otherType), + type classType = otherType ) { + this.classDomain = other.classDomain; + // Copy and cast + [ idx in this.classDomain ] this[ idx ] = other[ idx ] : classType; + } + + // Define bracket notation on a GenericClass object + // i.e. objVar[ i ] or objVar( i ) + proc this( i : int ) ref : classType { + return this.classArray[ i ]; + } + + // Define an iterator for the class. + // i.e. for i in objVar do .... + iter these() ref : classType { + for i in this.classDomain do + yield this[i]; + } + +} + +var realList = new GenericClass( real, 10 ); +// We can assign to the array in the object using the bracket notation +for i in realList.classDomain do realList[i] = i + 1.0; +// We can iterate over a +for value in realList do write( value, ", " ); +writeln(); + +// Make a copy of realList using the copy constructor +var copyList = new GenericClass( realList ); +for value in copyList do write( value, ", " ); +writeln(); + +// make a copy of realList and change the type, also using the copy constructor +var copyNewTypeList = new GenericClass( realList, int ); +for value in copyNewTypeList do write( value, ", " ); +writeln(); + + +// Tasks +// A task is some work that will be done separately from +// the current task, and (if there are any available) in its own thread. + +// a synch statement will ensure that the progress of the +// main task will not progress until the children have synced back up. +sync { +// a begin statement will spin the body off into one new task + begin { + var a = 0; + for i in 1..1000 do a += 1; + writeln( "Done: ", a); + } + writeln( "spun off a task!"); +} +writeln( "Back together" ); + +proc printFibb( n: int ){ + writeln( "fibonacci(",n,") = ", fibonacci( n ) ); +} + +// a cobegin statement will spin each +// statement of the body into one new task +cobegin { + printFibb( 20 ); + printFibb( 10 ); + printFibb( 5 ); + { + // this is a nested statement body and thus is a single statement + // to the parent statement and is executed by a single task + writeln( "this gets" ); + writeln( "executed as" ); + writeln( "a whole" ); + } +} +// Notice here that the prints may happen in any order. + +// Coforall loop will create a new task for EACH iteration +// NOTE! coforall should be used only for creating tasks! +// Using it to iterating over an array or something like that is very a bad idea! + +var num_tasks = 10; // Number of tasks we want +coforall taskID in 1..#num_tasks { + writeln( "Hello from task# ", taskID ); +} +// Again we see that prints happen in any order. + +// forall loops are another parallel loop, but only create a smaller number +// of tasks, specifically dataParTasksPerLocale number of task (more later) +forall i in 1..100 { + write( i, ", "); +} +writeln(); +// Here we see that there are sections that are in order, followed by +// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ) +// this is because each task is taking on a chunk of the range 1..10 +// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens +// in parallel. +// Your results may depend on your machine and configuration + +// For both the forall and coforall loops, the execution of the parent task +// will not continue until all the children sync up. + +// forall loops are particularly useful for parallel iteration over arrays +// Lets run an experiment to see how much faster a parallel loop is +use Time; // Import the Time module to use Timer objects +var timer: Timer; +var myBigArray: [{1..4000,1..4000}] real; // large array we will write into +// Serial Experiment +timer.start(); // start timer +for (x,y) in myBigArray.domain { // serial iteration + myBigArray[x,y] = (x:real) / (y:real); +} +timer.stop(); // stop timer +writeln( "Serial: ", timer.elapsed() ); // print elapsed time +timer.clear(); // clear timer for parallel loop + +// Parallel Experiment +timer.start(); // start timer +forall (x,y) in myBigArray.domain { // parallel iteration + myBigArray[x,y] = (x:real) / (y:real); +} +timer.stop(); // stop timer +writeln( "Parallel: ", timer.elapsed() ); // print elapsed time +timer.clear(); +// you may have noticed that (depending on how many cores you have) that +// the parallel loop went faster than the serial loop + +// A succinct way of writing a forall loop over an array: +[ val in myBigArray ] val = 1 / val; // iterate over values +// or +[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies + +``` \ No newline at end of file -- cgit v1.2.3 From 3ad75a4fb79e819a1ea5b2ab74bbfbb2c59c17fd Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:40:32 -0700 Subject: Minor fix removed .com from my (ian bertolacci) website link --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index a17222b9..df9c1a44 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -2,7 +2,7 @@ language: chapel filename: learnchapel.chpl contributors: - - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola.com/"] + - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] lang: en --- What is Chapel? @@ -719,4 +719,4 @@ timer.clear(); // or [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies -``` \ No newline at end of file +``` -- cgit v1.2.3 From 2ba9af4b85de0a2214d3c4de0f1509440a41adef Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:43:42 -0700 Subject: Header modified Found an unfinished sentence, fixed it. --- chapel.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index df9c1a44..01826a9c 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -11,11 +11,10 @@ You can read all about chapel at [Cray's official Chapel website](chapel.cray.co In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Chapel is currently in-development so there are occasional hiccups with -performance and language features, which is why you should write as much Chapel - Your input, questions, and discoveries are important to us! ----------------------------------------------------------- +Chapel is currently in-development so there are occasional hiccups with +performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) @@ -39,7 +38,6 @@ You will need to ```source util/setchplenv.*``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). - Chapel is easily installed with Brew for OS X 1. ```brew update``` 2. ```brew install chapel``` -- cgit v1.2.3 From cbbb833445e0e2b6223ce1c30943ed92ebc87ad7 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:45:18 -0700 Subject: List formatting Lists needed a space before numbers to actually become html list formatted. --- chapel.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 01826a9c..9005b05f 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -29,18 +29,18 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). Download the latest release version from https://github.com/chapel-lang/chapel/releases/ and its as easy as -1. ```tar -xvf chapel-1.11.0.tar.gz``` -2. ```cd chapel-1.11.0``` -3. ```make``` -4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + 1. ```tar -xvf chapel-1.11.0.tar.gz``` + 2. ```cd chapel-1.11.0``` + 3. ```make``` + 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` You will need to ```source util/setchplenv.*``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X -1. ```brew update``` -2. ```brew install chapel``` + 1. ```brew update``` + 2. ```brew install chapel``` Who is this tutorial for? ------------------------- -- cgit v1.2.3 From 7ff3bd31d86009aec4d14292b2cbd02a3352e70f Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:48:34 -0700 Subject: Link and header fix 1. put latest release url under the text [download the latest ....] 2. changed '... important to us!' to '... important to the developers!' so not to confuse the us (chapel dev team) with the tutorial people (learnxinyminutes) --- chapel.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 9005b05f..db566454 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -11,8 +11,8 @@ You can read all about chapel at [Cray's official Chapel website](chapel.cray.co In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Your input, questions, and discoveries are important to us! ------------------------------------------------------------ +Your input, questions, and discoveries are important to the developers! +----------------------------------------------------------------------- Chapel is currently in-development so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter with the language, @@ -27,7 +27,7 @@ under the Apache v2.0 license Installing the Compiler ----------------------- Chapel can be built and installed on your average 'nix machine (and cygwin). -Download the latest release version from https://github.com/chapel-lang/chapel/releases/ +[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as 1. ```tar -xvf chapel-1.11.0.tar.gz``` 2. ```cd chapel-1.11.0``` -- cgit v1.2.3 From 70a5440d4c4575dfe07495cadc9aa48f1d85d016 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:49:49 -0700 Subject: Bad Link fix fixed a link that was suppose to go to the chapel.cray.com site, but did not. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index db566454..90b64854 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -7,7 +7,7 @@ lang: en --- What is Chapel? =============== -You can read all about chapel at [Cray's official Chapel website](chapel.cray.com). +You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -- cgit v1.2.3 From 28f2817ac36e6fd85bff29e8dcda71f452d4b97e Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 12 Jul 2015 16:50:55 -0700 Subject: removed hyphen removed hyphen from library-documentation --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 90b64854..1c5bcc15 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -49,7 +49,7 @@ hear about what fiber mixture the ropes are, or how they were braided, or how th differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) -and the [library-documentation](http://chapel.cray.com/docs/latest/) for more details. +and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check here back to see if more topics have been added. -- cgit v1.2.3 From 7bdcbc834e25c89a4ae59ac6282e82e75f6f7fb6 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Mon, 13 Jul 2015 16:42:46 -0700 Subject: removed IRC node. That node refers to people developing in the compiler, no developers using the language --- chapel.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 1c5bcc15..3e6c7bb6 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -18,7 +18,6 @@ performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) -There is also a #chapel-developers hosted at chat.freenode.net. If you're really interested in the cutting edge compiler or contributing to the project, the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) -- cgit v1.2.3 From 2a41844229c841894b58f64b1841802e24483803 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 07:40:53 -0700 Subject: changed some wording in header. added tuple expansion --- chapel.html.markdown | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 3e6c7bb6..3563e4c1 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -17,11 +17,10 @@ Chapel is currently in-development so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. -Feel free to email the team and other developers through the sourceforge email lists at [sourceforge](https://sourceforge.net/p/chapel/mailman) +Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). -If you're really interested in the cutting edge compiler or contributing to the project, -the git repository for Chapel is open-source at [github](https://github.com/chapel-lang/chapel) -under the Apache v2.0 license +If you're really interested in the development of the compiler or contributing to the project, +[check out the master Github repository](https://github.com/chapel-lang/chapel). Installing the Compiler ----------------------- @@ -33,7 +32,7 @@ and its as easy as 3. ```make``` 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` -You will need to ```source util/setchplenv.*``` from the chapel directory every +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). @@ -160,10 +159,14 @@ writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); // Tuples can also be written into. diffTup[1] = -1; -// Can also be used to easily write a collection of variables -// as is common in debugging +// you can expand tuples as well +var (tupInt, tupReal, tupCplx) = diffTup; +writeln( diffTup == (tupInt, tupReal, tupCplx) ); +// Can also be used to easily write a collection of +// variables as a list (common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); + // Type aliasing type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color -- cgit v1.2.3 From df0cd1395db5178aabc68bf17d48a8278f16d749 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:30:09 -0700 Subject: numerous slight modifications, and additions. Notable: added const, param, config --- chapel.html.markdown | 197 +++++++++++++++++++++++++++------------------------ 1 file changed, 103 insertions(+), 94 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 3563e4c1..6382f75a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -8,15 +8,12 @@ lang: en What is Chapel? =============== You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). -In short, Chapel is an open-source, high-productivity, parallel-programming language in development -at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. +In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- -Chapel is currently in-development so there are occasional hiccups with -performance and language features. -The more information you give the Chapel development team about issues you encounter with the language, -the better the language gets. +Chapel is currently in-development so there are occasional hiccups with performance and language features. +The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). If you're really interested in the development of the compiler or contributing to the project, @@ -32,9 +29,7 @@ and its as easy as 3. ```make``` 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` -You will need to ```source util/setchplenv.EXT``` from the chapel directory every -time your terminal starts so its suggested that you drop that command in a script -that will get executed on startup (like .bashrc). +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X 1. ```brew update``` @@ -42,12 +37,9 @@ Chapel is easily installed with Brew for OS X Who is this tutorial for? ------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to -hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations -differ between one another. +This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) -and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check here back to see if more topics have been added. @@ -69,11 +61,11 @@ stdout.writeln( "This goes to standard output (just like plain writeln() does)") stderr.writeln( "This goes to standard error" ); // Variables -// Variables dont have to be explicitly as long as the compiler can figure -// out the type that it will hold. +// Variables dont have to be explicitly typed as long as +// the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; -// var anError; // compile time error, dont know what type anError should be. +// var anError; // this would be a compile time error. // We can (and should) explicitly type things var mySecondVar: real; // define mySecondVar as a real @@ -96,10 +88,26 @@ var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real // Typecasting var intFromReal = myReal : int; -// could also explicitly type intFromReal -// var intFromReal: int = myReal : int; +var intFromReal2: int = myReal : int; + +// consts are constants, they cannot be changed after set in runtime +const almostPi: real = 11.0/7.0; +// params are constants whose value must be known statically at compile time +// Like consts, they cannot be changed during runtime +param compileTimeConst: int = 16; + +// The config modifier allows values to be set at the command line +// and is much easier that the usual getOpts debacle +// config vars and consts can be changed through the command line at run time +config var varCmdLineArg: int = -123; +config const constCmdLineArg: int = 777; +// set with --VarName=Value or --VarName Value at run time + +// config params can be set at compile time +config param paramCmdLineArg: bool = false; +writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); +//set config with --set paramCmdLineArg=value at compile time -// Operators // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition @@ -138,12 +146,11 @@ a <<= 3; // left-bit-shift-equals ( a = a << 10; ) // pre/post-increment/decrement operators like // ++j, --j, j++, j-- - // Swap operator -var temp_this = thisInt; -var temp_that = thatInt; +var old_this = thisInt; +var old_that = thatInt; thisInt <=> thatInt; // Swap the values of thisInt and thatInt -writeln( (temp_this == thatInt) && (temp_that == thisInt) ); +writeln( (old_this == thatInt) && (old_that == thisInt) ); // We can also define operator overloads, // which we'll cover with procedures. @@ -162,13 +169,13 @@ diffTup[1] = -1; // you can expand tuples as well var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); -// Can also be used to easily write a collection of -// variables as a list (common in debugging) +// Can also be used to easily write a collection +// of variables as a list (common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); // Type aliasing -type chroma = int; // type of a single hue +type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); @@ -176,11 +183,11 @@ var white: RGBColor = ( 255, 255, 255 ); // If-Then statements -// if-thens dont require parentheses around the condition +// if-thens dont require parentheses around the condition // as they do in C (however, we will use them) -// and a single line body can use the 'then' keyword instead of braces -// and else statements can be written similarly -// (but we're only going to show it once). +// A single line body can use the 'then' keyword instead of +// braces and else statements can be written similarly + if 10 < 100 then writeln( "All is well" ); @@ -211,7 +218,6 @@ if ( a % 3 == 0 ) { // Ternary: if-then-else in a statement var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; -// Select statements // Select statements are much like switch statements in other languages // However, Select statements dont cascade like in C or Java var inputOption = "anOption"; @@ -229,10 +235,7 @@ select( inputOption ){ } } -// Loops -// While Loops // While loops and Do-While loops are basically the same in every language. - var j: int = 1; var jSum: int = 0; while( j <= 1000 ){ @@ -248,11 +251,10 @@ do{ }while( j <= 10000 ); writeln( jSum ); -// For loops + // For loops are much like those in python in that they iterate over a range. -// ranges themselves are types, and can be stuffed into variables +// Ranges themselves are types, and can be stuffed into variables // (more about that later) - for i in 1..10 do write( i , ", ") ; writeln(); @@ -273,14 +275,23 @@ for x in 1..10 { // For-loops and arrays both use ranges and domains to // define an index set that can be iterated over. // Ranges are single dimensional -// Domains can be multi-dimensional and represent indicies -// of different types as well. +// Domains can be multi-dimensional and can +// represent indicies of different types as well. // They are types, and can be assigned into variables; var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 +var range2to11 = 2..11; // 2, 3, 4, ..., 11 + +//ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... +var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 +// Note: the range(boundedType= ... ) is only +// necessary if we explicitly type the variable // Ranges can be strided using the 'by' operator. -// Note: the stridable=true is only necessary if we type the variable var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 +var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 +// Note: the range(stridable=true) is only +// necessary if we explicitly type the variable // The end point of a range can be determined using the count (#) operator var rangeCount: range = -5..#12; // range from -5 to 6 @@ -299,9 +310,11 @@ for i in rangeCountBy{ write( i, if i == rangeCountBy.last then "\n" else ", " ); } -// domains are similarly defined using range notation -var domain1to10: domain(1) = {1..10}; // domain from 1..10; -var twoDimensions: domain(2) = {-2..2,0..2}; // domain over two dimensions +// Rectangular domains are similarly defined using range notation +var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; +var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges +var thirdDim: range = 1..16; +var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable // Can iterate over the indices as tuples for idx in twoDimensions do @@ -310,38 +323,37 @@ writeln(); // Or can deconstruct the tuple for (x,y) in twoDimensions { - write( (x,y), ", " ); + write( "(", x, ", ", y, ")", ", " ); } writeln(); // Associative domains act like sets -var intSet: domain(int); // empty set of ints -intSet += 1; -intSet += 2; -intSet += 3; -intSet += 1; // redundant add 1 -intSet -= 3; // remove 3 -writeln( intSet ); +var stringSet: domain(string); // empty set of strings +stringSet += "a"; +stringSet += "b"; +stringSet += "c"; +stringSet += "a"; // redundant add "a" +stringSet -= "c"; // remove "c" +writeln( stringSet ); -// Arrays // Array are similar to those of other languages. -// Their sizes are defined using ranges and domains. -// that represent their indices, but we'll touch more on those later -var intArray: [1..10] int; // array of integers defined using range literal +// Their sizes are defined using domains that represent their indices +var intArray: [1..10] int; +var intArray2: [{1..10}] int; //equivalent // Accessed using bracket notation for i in 1..10 do intArray[i] = -i; writeln( intArray ); // we cannot access intArray[0] because it exists outside -// of the index set we defined (1..10) +// of the index set, {1..10}, we defined it to have // intArray[11] is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; -// similarly we could have done: -// var realArray: [1..5,1..7] real; +var realArray2: [1..5,1..7] real; // equivalent +var realArray3: [{1..5,1..7}] real; // equivalent for i in 1..5 { // use the range from 2nd dimension of the domain @@ -353,7 +365,7 @@ for i in 1..5 { } // arrays have domains as members that we can iterate over -for idx in realArray.domain { // idx is, again, a 2*int tuple +for idx in realArray.domain { // again, idx is a 2*int tuple realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list } @@ -373,16 +385,13 @@ var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; writeln( dict ); - -// Procedures // Chapel procedures have similar syntax to other languages functions. - proc fibonacci( n : int ) : int { - if ( n == 0 || n == 1 ) then return n; + if ( n <= 1 ) then return n; return fibonacci( n-1 ) + fibonacci( n-2 ); } -// input parameters can be untyped +// input parameters can be untyped (a generic procedure) proc doublePrint( thing ): void { write( thing, " ", thing, "\n"); } @@ -394,7 +403,7 @@ proc addThree( n ) { doublePrint( addThree( fibonacci( 20 ) ) ); -// Can also take unlimited number of parameters +// Can also take 'unlimited' number of parameters proc maxOf( x ...?k ) { // x refers to a tuple of one type, with k elements var maximum = x[1]; @@ -404,7 +413,7 @@ proc maxOf( x ...?k ) { writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); // the ? operator is called the query operator, and is used to take -// undetermined values (like tuple and array sizes, and generic types). +// undetermined values (like tuple or array sizes, and generic types). // Taking arrays as parameters. // The query operator is used to determine the domain of A. @@ -427,9 +436,9 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// Generic procedures can still retain type -// Here we define a procedure that takes two arguments -// of the same type, yet we dont define what that type is. +// We can query the type of arguments to make safer generic procedures +// Here we define a procedure that takes two arguments of +// the same type, yet we dont define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { select( valueType ){ when int do writeln( arg1, " and ", arg2, " are ints" ); @@ -481,24 +490,24 @@ writeln( false ^ true ); writeln( true ^ false ); writeln( false ^ false ); -// Define a * operator on any two types. +// Define a * operator on any two types that returns a tupe of those types proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } writeln( 1 * "a" ); // uses our * operator -writeln( 1 * 2 ); // uses the original * operator +writeln( 1 * 2 ); // uses the original * operator /* -Note: You could break everything if you - get careless with your overloads. -This here will break everything. Dont do it. +Note: You could break everything if you get careless with your overloads. +This here will break everything. Don't do it. proc +( left: int, right: int ): int{ return left - right; } */ -// Classes +// Classes are similar to those in C++ and Java. +// They currently lack privatization class MyClass { // Member variables var memberInt : int; @@ -541,8 +550,8 @@ writeln( myObject.getMemberInt() ); // ... using our values var myDiffObject = new MyClass( -1, true ); myDiffObject = new MyClass( memberInt = -1, - memberBool = false ); // equivalent -writeln( (myDiffObject.getMemberInt(), myDiffObject.getMemberBool() )); + memberBool = true ); // equivalent +writeln( myDiffObject ); // Construct using written constructor var myOtherObject = new MyClass( 1.95 ); @@ -557,7 +566,7 @@ proc +( A : MyClass, B : MyClass) : MyClass { } var plusObject = myObject + myDiffObject; -writeln( (plusObject.getMemberInt(), plusObject.getMemberBool() ) ); +writeln( plusObject ); // destruction delete myObject; @@ -609,9 +618,11 @@ class GenericClass { } var realList = new GenericClass( real, 10 ); -// We can assign to the array in the object using the bracket notation +// We can assign to the member array of the object using the bracket +// notation that we defined ( proc this( i: int ){ ... } ) for i in realList.classDomain do realList[i] = i + 1.0; -// We can iterate over a +// We can iterate over the values in our list with the iterator +// we defined ( iter these(){ ... } ) for value in realList do write( value, ", " ); writeln(); @@ -626,11 +637,10 @@ for value in copyNewTypeList do write( value, ", " ); writeln(); -// Tasks -// A task is some work that will be done separately from -// the current task, and (if there are any available) in its own thread. +// A task is some work that will be done separately from the current +// task, and (if there are any available) in its own thread. -// a synch statement will ensure that the progress of the +// a sync statement will ensure that the progress of the // main task will not progress until the children have synced back up. sync { // a begin statement will spin the body off into one new task @@ -661,20 +671,19 @@ cobegin { writeln( "a whole" ); } } -// Notice here that the prints may happen in any order. +// Notice here that the prints from each statement may happen in any order. // Coforall loop will create a new task for EACH iteration -// NOTE! coforall should be used only for creating tasks! -// Using it to iterating over an array or something like that is very a bad idea! - var num_tasks = 10; // Number of tasks we want coforall taskID in 1..#num_tasks { writeln( "Hello from task# ", taskID ); } // Again we see that prints happen in any order. +// NOTE! coforall should be used only for creating tasks! +// Using it to iterating over a structure is very a bad idea! // forall loops are another parallel loop, but only create a smaller number -// of tasks, specifically dataParTasksPerLocale number of task (more later) +// of tasks, specifically --dataParTasksPerLocale=number of task forall i in 1..100 { write( i, ", "); } @@ -715,8 +724,8 @@ timer.clear(); // the parallel loop went faster than the serial loop // A succinct way of writing a forall loop over an array: -[ val in myBigArray ] val = 1 / val; // iterate over values -// or -[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; // iterate over indicies - +// iterate over values +[ val in myBigArray ] val = 1 / val; +// or iterate over indicies +[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` -- cgit v1.2.3 From 6a6673b1540eda903981bdaccc844a5fc802a216 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Tue, 14 Jul 2015 17:32:00 -0700 Subject: Fixed almost pi 22/7ths is closer to pi than 11/7ths. Almost twice as close! --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 6382f75a..fd01b0f2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -91,7 +91,7 @@ var intFromReal = myReal : int; var intFromReal2: int = myReal : int; // consts are constants, they cannot be changed after set in runtime -const almostPi: real = 11.0/7.0; +const almostPi: real = 22.0/7.0; // params are constants whose value must be known statically at compile time // Like consts, they cannot be changed during runtime param compileTimeConst: int = 16; -- cgit v1.2.3 From e8b259f4c6fa71cea3ba9d0f65469b2a5eb56da6 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:44:55 -0700 Subject: Moved majority of header to bottom. Less preachy? --- chapel.html.markdown | 77 +++++++++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 34 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index fd01b0f2..799d32c3 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -5,43 +5,11 @@ contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] lang: en --- -What is Chapel? -=============== + You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. -Your input, questions, and discoveries are important to the developers! ------------------------------------------------------------------------ -Chapel is currently in-development so there are occasional hiccups with performance and language features. -The more information you give the Chapel development team about issues you encounter with the language, the better the language gets. -Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). - -If you're really interested in the development of the compiler or contributing to the project, -[check out the master Github repository](https://github.com/chapel-lang/chapel). - -Installing the Compiler ------------------------ -Chapel can be built and installed on your average 'nix machine (and cygwin). -[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` - -You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). - -Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` - -Who is this tutorial for? -------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. -It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. - -Occasionally check here back to see if more topics have been added. +More information and support can be found at the bottom of this document. ```chapel // Comments are C-family style @@ -729,3 +697,44 @@ timer.clear(); // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` +Who is this tutorial for? +------------------------- +This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. +It won't teach you how to develop amazingly performant code, and it's not exhaustive. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. + +Occasionally check back here and on the Chapel site to see if more topics have been added or more tutorials created. + +Your input, questions, and discoveries are important to the developers! +----------------------------------------------------------------------- +The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. +The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. +Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). + +If you're really interested in the development of the compiler or contributing to the project, +[check out the master Github repository](https://github.com/chapel-lang/chapel). +It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0). + +Installing the Compiler +----------------------- +Chapel can be built and installed on your average 'nix machine (and cygwin). +[Download the latest release version](https://github.com/chapel-lang/chapel/releases/) +and its as easy as + 1. ```tar -xvf chapel-1.11.0.tar.gz``` + 2. ```cd chapel-1.11.0``` + 3. ```make``` + 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + +You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). + +Chapel is easily installed with Brew for OS X + 1. ```brew update``` + 2. ```brew install chapel``` + +Compiling Code +-------------- +Builds like other compilers +```chpl myFile.chpl -o myExe`` + +A notable argument: + * ``--fast``: enables a number of optimizations and disables array bounds checks. Only enable when application is stable. -- cgit v1.2.3 From 343ae6ca1bd908aedfabe1dad948e4efff449628 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 17:49:59 -0700 Subject: Almost last update. Small changes to wording --- chapel.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 799d32c3..5633214a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -703,7 +703,7 @@ This tutorial is for people who want to learn the ropes of chapel without having It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. -Occasionally check back here and on the Chapel site to see if more topics have been added or more tutorials created. +Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- @@ -734,7 +734,7 @@ Chapel is easily installed with Brew for OS X Compiling Code -------------- Builds like other compilers -```chpl myFile.chpl -o myExe`` +```chpl myFile.chpl -o myExe``` A notable argument: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Only enable when application is stable. + * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 2e7ebaa3b940ec9de04f2266138abca58becaf30 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 18:40:53 -0700 Subject: A number of edits. Some cosmetic. Added iterators, argument/return intents --- chapel.html.markdown | 129 ++++++++++++++++++++++++++++++++++----------------- 1 file changed, 87 insertions(+), 42 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 5633214a..ecbab2a2 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -28,7 +28,6 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" ); stdout.writeln( "This goes to standard output (just like plain writeln() does)"); stderr.writeln( "This goes to standard error" ); -// Variables // Variables dont have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int @@ -123,39 +122,31 @@ writeln( (old_this == thatInt) && (old_that == thisInt) ); // We can also define operator overloads, // which we'll cover with procedures. -// Tuples -// tuples can be of the same type +// Tuples can be of the same type var sameTup: 2*int = (10,-1); +var sameTup2 = (11, -6); // or different types var diffTup: (int,real,complex) = (5, 1.928, myCplx); +var diffTupe2 = ( 7, 5.64, 6.0+1.5i ); // Accessed using array bracket notation // However, tuples are all 1-indexed writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); // Tuples can also be written into. diffTup[1] = -1; -// you can expand tuples as well +// Can expand tuple values into their own variables var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); -// Can also be used to easily write a collection -// of variables as a list (common in debugging) +// Useful for writing a list of variables ( as is common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); - // Type aliasing type chroma = int; // type of a single hue type RGBColor = 3*chroma; // type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); - - -// If-Then statements -// if-thens dont require parentheses around the condition -// as they do in C (however, we will use them) -// A single line body can use the 'then' keyword instead of -// braces and else statements can be written similarly - +// if-then-else works just like any other C-family language if 10 < 100 then writeln( "All is well" ); @@ -164,7 +155,6 @@ if -1 < 1 then else writeln( "Send mathematician, something's wrong" ); - if ( 10 > 100 ) { writeln( "Universe broken. Please reboot universe." ); } @@ -219,7 +209,6 @@ do{ }while( j <= 10000 ); writeln( jSum ); - // For loops are much like those in python in that they iterate over a range. // Ranges themselves are types, and can be stuffed into variables // (more about that later) @@ -245,9 +234,11 @@ for x in 1..10 { // Ranges are single dimensional // Domains can be multi-dimensional and can // represent indicies of different types as well. -// They are types, and can be assigned into variables; -var range1to10: range = 1..10; // // 1, 2, 3, ... , 10 +// They are first-class citizen types, and can be assigned into variables +var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 +var rangeThistoThat: range = thisInt..thatInt; // using variables +var rangeEmpty: range = 100..-100 ; // this is a valid, but empty range //ranges can be unbounded var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... @@ -257,10 +248,12 @@ var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 // Ranges can be strided using the 'by' operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 -var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 // Note: the range(stridable=true) is only // necessary if we explicitly type the variable +// Use by to create a reverse range +var reverse2to10by2 = 10..2 by -2; // 10, 8, 6, 4, 2 + // The end point of a range can be determined using the count (#) operator var rangeCount: range = -5..#12; // range from -5 to 6 @@ -278,7 +271,7 @@ for i in rangeCountBy{ write( i, if i == rangeCountBy.last then "\n" else ", " ); } -// Rectangular domains are similarly defined using range notation +// Rectangular domains are defined using the same range syntax var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges var thirdDim: range = 1..16; @@ -324,8 +317,7 @@ var realArray2: [1..5,1..7] real; // equivalent var realArray3: [{1..5,1..7}] real; // equivalent for i in 1..5 { - // use the range from 2nd dimension of the domain - for j in realDomain.dim(2) { + for j in realDomain.dim(2) { // only use the 2nd dimension of the domain realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list var idx: 2*int = (i,j); // note: 'index' is a keyword realArray[idx] = - realArray[(i,j)]; // index using tuples @@ -351,7 +343,7 @@ writeln( rSum, "\n", realArray ); var dictDomain: domain(string) = { "one", "two" }; var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; -writeln( dict ); +for key in dictDomain do writeln( dict[key] ); // Chapel procedures have similar syntax to other languages functions. proc fibonacci( n : int ) : int { @@ -404,7 +396,40 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// We can query the type of arguments to make safer generic procedures +// intent modifiers on the arguments convey how +// those arguments are passed to the procedure +// in: copy arg in, but not out +// out: copy arg out, but not in +// inout: copy arg in, copy arg out +// ref: pass arg by reference +proc intentsProc( in inarg, out outarg, inout inoutarg, ref refarg ){ + writeln( "Inside Before: ", (inarg, outarg, inoutarg, refarg) ); + inarg = inarg + 100; + outarg = outarg + 100; + inoutarg = inoutarg + 100; + refarg = refarg + 100; + writeln( "Inside After: ", (inarg, outarg, inoutarg, refarg) ); +} + +var inVar: int = 1; +var outVar: int = 2; +var inoutVar: int = 3; +var refVar: int = 4; +writeln( "Outside Before: ", (inVar, outVar, inoutVar, refVar) ); +intentsProc( inVar, outVar, inoutVar, refVar ); +writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); + +// Similarly we can define intents on the return type +proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { + var array: [1..#elems] int; + for idx in array.domain do array[idx] = startNumber + idx; + return array; +} +writeln( makeArray( 10, -1 ) ); +// this makes more practical sense for class methods where references to +// elements in a data-structure are returned via a method or iterator + +// We can query the type of arguments to generic procedures // Here we define a procedure that takes two arguments of // the same type, yet we dont define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { @@ -421,9 +446,8 @@ genericProc( 1.0+2.0i, 3.0+4.0i ); // We can also enforce a form of polymorphism with the 'where' clause // This allows the compiler to decide which function to use. -// Note: that means that all information needs to be known at compile -// time. Hence, we use params here to assert that the arguments must -// be known at compile time. +// Note: that means that all information needs to be known at compile time. +// The param modifier on the arg is used to enforce this constraint. proc whereProc( param N : int ): void where ( N > 0 ) { writeln( "N is greater than 0" ); @@ -474,6 +498,25 @@ proc +( left: int, right: int ): int{ } */ +// iterators are a close cousin to the procedure. +// However, instead of returning a single value, +// iterators yield many values to a loop. +// This is useful when a complicated set or order of iterations is needed but +// allows the code defining the iterations to be separate from the loop body. +iter oddsThenEvens( N: int ): int { + for i in 1..N by 2 { + yield i; // yield values instead of returning. + } + + for i in 2..N by 2 { + yield i; + } +} + +for i in oddsThenEvens( 10 ) do write( i, ", " ); +writeln(); + + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -567,16 +610,18 @@ class GenericClass { type classType = otherType ) { this.classDomain = other.classDomain; // Copy and cast - [ idx in this.classDomain ] this[ idx ] = other[ idx ] : classType; + for idx in this.classDomain do this[ idx ] = other[ idx ] : classType; } - // Define bracket notation on a GenericClass object + // Define bracket notation on a GenericClass + // object so it can behave like a normal array // i.e. objVar[ i ] or objVar( i ) proc this( i : int ) ref : classType { return this.classArray[ i ]; } - // Define an iterator for the class. + // Define an iterator for the class to + // yield values from the array to a loop // i.e. for i in objVar do .... iter these() ref : classType { for i in this.classDomain do @@ -604,19 +649,20 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln(); +// Parallelism +// In other languages, parallelism is typically this is done with +// complicated libraries and strange class structure hierarchies. +// Chapel has it baked right into the language. -// A task is some work that will be done separately from the current -// task, and (if there are any available) in its own thread. - +// A begin statement will spin the body of that statement off into one new task. // a sync statement will ensure that the progress of the // main task will not progress until the children have synced back up. sync { -// a begin statement will spin the body off into one new task - begin { + begin { // start of new task's body var a = 0; for i in 1..1000 do a += 1; writeln( "Done: ", a); - } + } // end of new tasks body writeln( "spun off a task!"); } writeln( "Back together" ); @@ -625,12 +671,11 @@ proc printFibb( n: int ){ writeln( "fibonacci(",n,") = ", fibonacci( n ) ); } -// a cobegin statement will spin each -// statement of the body into one new task +// a cobegin statement will spin each statement of the body into one new task cobegin { - printFibb( 20 ); - printFibb( 10 ); - printFibb( 5 ); + printFibb( 20 ); // new task + printFibb( 10 ); // new task + printFibb( 5 ); // new task { // this is a nested statement body and thus is a single statement // to the parent statement and is executed by a single task -- cgit v1.2.3 From 7640ea4a306b979912d63d646864da824103c082 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Tue, 14 Jul 2015 19:07:59 -0700 Subject: Some rewriting, hopefully the last commit before pull request --- chapel.html.markdown | 276 +++++++++++++++++++++++++++------------------------ 1 file changed, 145 insertions(+), 131 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index ecbab2a2..8b41dc32 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -25,29 +25,30 @@ writeln( "World!" ); // each thing is printed right next to each other, so include your spacing! writeln( "There are ", 3, " commas (\",\") in this line of code" ); // Different output channels -stdout.writeln( "This goes to standard output (just like plain writeln() does)"); +stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); stderr.writeln( "This goes to standard error" ); // Variables dont have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; +var mySecondVar = myVar; // var anError; // this would be a compile time error. // We can (and should) explicitly type things -var mySecondVar: real; // define mySecondVar as a real -var myThirdVar: real = -1.234; -mySecondVar = myThirdVar; +var myThirdVar: real; // define mySecondVar as a real +var myFourthVar: real = -1.234; +myThirdVar = myFourthVar; // There are a number of basic types. -var myInt: int = -1000; // signed ints -var myUint: uint = 1234; // unsigned ints -var myReal: real = 9.876; // floating point numbers -var myImag: imag = 5.0i; // imaginary numbers -var myCplx: complex = 10 + 9i; // complex numbers -myCplx = myInt + myImag ; // another way to form complex numbers -var myBool: bool = false; // booleans -var myStr: string = "Some string..."; // strings +var myInt: int = -1000; // Signed ints +var myUint: uint = 1234; // Unsigned ints +var myReal: real = 9.876; // Floating point numbers +var myImag: imag = 5.0i; // Imaginary numbers +var myCplx: complex = 10 + 9i; // Complex numbers +myCplx = myInt + myImag ; // Another way to form complex numbers +var myBool: bool = false; // Booleans +var myStr: string = "Some string..."; // Strings // Some types can have sizes var my8Int: int(8) = 10; // 8 bit (one byte) sized int; @@ -59,6 +60,7 @@ var intFromReal2: int = myReal : int; // consts are constants, they cannot be changed after set in runtime const almostPi: real = 22.0/7.0; + // params are constants whose value must be known statically at compile time // Like consts, they cannot be changed during runtime param compileTimeConst: int = 16; @@ -68,47 +70,47 @@ param compileTimeConst: int = 16; // config vars and consts can be changed through the command line at run time config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; -// set with --VarName=Value or --VarName Value at run time +// Set with --VarName=Value or --VarName Value at run time // config params can be set at compile time config param paramCmdLineArg: bool = false; writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); -//set config with --set paramCmdLineArg=value at compile time +// Set config with --set paramCmdLineArg=value at compile time // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition a = thisInt * thatInt; // Multiplication a = thisInt - thatInt; // Subtraction -a = thisInt / thatInt; // division -a = thisInt ** thatInt; // exponentiation -a = thisInt % thatInt; // remainder (modulo) +a = thisInt / thatInt; // Division +a = thisInt ** thatInt; // Exponentiation +a = thisInt % thatInt; // Remainder (modulo) // Logical Operators var b: bool, thisBool = false, thatBool = true; -b = thisBool && thatBool; // logical and -b = thisBool || thatBool; // logical or -b = !thisBool; // logical negation +b = thisBool && thatBool; // Logical and +b = thisBool || thatBool; // Logical or +b = !thisBool; // Logical negation // Relational Operators -b = thisInt > thatInt; // greater-than -b = thisInt >= thatInt; // greater-than-or-equal-to -b = thisInt < a && a <= thatInt; // less-than, and, less-than-or-equal-to -b = thisInt != thatInt; // not-equal-to -b = thisInt == thatInt; // equal-to +b = thisInt > thatInt; // Greater-than +b = thisInt >= thatInt; // Greater-than-or-equal-to +b = thisInt < a && a <= thatInt; // Less-than, and, less-than-or-equal-to +b = thisInt != thatInt; // Not-equal-to +b = thisInt == thatInt; // Equal-to // Bitwise operations -a = thisInt << 10; // left-bit-shift by 10 bits; -a = thatInt >> 5; // right-bit-shift by 5 bits; -a = ~thisInt; // bitwise-negation -a = thisInt ^ thatInt; // bitwise exclusive-or +a = thisInt << 10; // Left-bit-shift by 10 bits; +a = thatInt >> 5; // Right-bit-shift by 5 bits; +a = ~thisInt; // Bitwise-negation +a = thisInt ^ thatInt; // Bitwise exclusive-or // Compound assignment operations -a += thisInt; // addition-equals ( a = a + thisInt;) -a *= thatInt; // times-equals ( a = a * thatInt; ) -b &&= thatBool; // logical-and-equals ( b = b && thatBool; ) -a <<= 3; // left-bit-shift-equals ( a = a << 10; ) -// and so on... +a += thisInt; // Addition-equals ( a = a + thisInt;) +a *= thatInt; // Times-equals ( a = a * thatInt; ) +b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) +a <<= 3; // LEft-bit-shift-equals ( a = a << 10; ) +// and many, many more. // Unlike other C family languages there are no // pre/post-increment/decrement operators like // ++j, --j, j++, j-- @@ -119,8 +121,7 @@ var old_that = thatInt; thisInt <=> thatInt; // Swap the values of thisInt and thatInt writeln( (old_this == thatInt) && (old_that == thisInt) ); -// We can also define operator overloads, -// which we'll cover with procedures. +// Operator overloads can also be defined, as we'll see with procedures // Tuples can be of the same type var sameTup: 2*int = (10,-1); @@ -128,25 +129,29 @@ var sameTup2 = (11, -6); // or different types var diffTup: (int,real,complex) = (5, 1.928, myCplx); var diffTupe2 = ( 7, 5.64, 6.0+1.5i ); + // Accessed using array bracket notation // However, tuples are all 1-indexed writeln( "(", sameTup[1], ",", sameTup[2], ")" ); writeln( diffTup ); + // Tuples can also be written into. diffTup[1] = -1; + // Can expand tuple values into their own variables var (tupInt, tupReal, tupCplx) = diffTup; writeln( diffTup == (tupInt, tupReal, tupCplx) ); + // Useful for writing a list of variables ( as is common in debugging) writeln( (a,b,thisInt,thatInt,thisBool,thatBool) ); // Type aliasing -type chroma = int; // type of a single hue -type RGBColor = 3*chroma; // type representing a full color +type chroma = int; // Type of a single hue +type RGBColor = 3*chroma; // Type representing a full color var black: RGBColor = ( 0,0,0 ); var white: RGBColor = ( 255, 255, 255 ); -// if-then-else works just like any other C-family language +// If-then-else works just like any other C-family language if 10 < 100 then writeln( "All is well" ); @@ -193,16 +198,16 @@ select( inputOption ){ } } -// While loops and Do-While loops are basically the same in every language. +// While and Do-While loops are basically the same in every language. var j: int = 1; var jSum: int = 0; while( j <= 1000 ){ jSum += j; - j += 1; // there are no ++j, --j, j++, j--, operators + j += 1; } writeln( jSum ); -// basic Do-While loop +// Do-While loop do{ jSum += j; j += 1; @@ -213,7 +218,7 @@ writeln( jSum ); // Ranges themselves are types, and can be stuffed into variables // (more about that later) for i in 1..10 do write( i , ", ") ; -writeln(); +writeln( ); var iSum: int = 0; for i in 1..1000 { @@ -225,7 +230,7 @@ for x in 1..10 { for y in 1..10 { write( (x,y), "\t" ); } - writeln(); + writeln( ); } // Ranges and Domains @@ -238,14 +243,16 @@ for x in 1..10 { var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 var rangeThistoThat: range = thisInt..thatInt; // using variables -var rangeEmpty: range = 100..-100 ; // this is a valid, but empty range +var rangeEmpty: range = 100..-100 ; // this is valid but contains no indices -//ranges can be unbounded -var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... -var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 +// Ranges can be unbounded +var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; +// 1, 2, 3, 4, 5, ... // Note: the range(boundedType= ... ) is only // necessary if we explicitly type the variable +var rangeNegInfto1 = ..1; // ..., -4, -3, -2, -1, 0, 1 + // Ranges can be strided using the 'by' operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 // Note: the range(stridable=true) is only @@ -280,24 +287,23 @@ var threeDims: domain(3) = {thirdDim, 1..10, 5..10}; // using a range variable // Can iterate over the indices as tuples for idx in twoDimensions do write( idx , ", "); -writeln(); +writeln( ); -// Or can deconstruct the tuple +// or can deconstruct the tuple for (x,y) in twoDimensions { write( "(", x, ", ", y, ")", ", " ); } -writeln(); +writeln( ); // Associative domains act like sets var stringSet: domain(string); // empty set of strings stringSet += "a"; stringSet += "b"; stringSet += "c"; -stringSet += "a"; // redundant add "a" -stringSet -= "c"; // remove "c" +stringSet += "a"; // Redundant add "a" +stringSet -= "c"; // Remove "c" writeln( stringSet ); - // Array are similar to those of other languages. // Their sizes are defined using domains that represent their indices var intArray: [1..10] int; @@ -307,35 +313,35 @@ var intArray2: [{1..10}] int; //equivalent for i in 1..10 do intArray[i] = -i; writeln( intArray ); -// we cannot access intArray[0] because it exists outside -// of the index set, {1..10}, we defined it to have +// We cannot access intArray[0] because it exists outside +// of the index set, {1..10}, we defined it to have. // intArray[11] is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; -var realArray2: [1..5,1..7] real; // equivalent -var realArray3: [{1..5,1..7}] real; // equivalent +var realArray2: [1..5,1..7] real; // Equivalent +var realArray3: [{1..5,1..7}] real; // Equivalent for i in 1..5 { - for j in realDomain.dim(2) { // only use the 2nd dimension of the domain - realArray[i,j] = -1.61803 * i + 0.5 * j; // access using index list - var idx: 2*int = (i,j); // note: 'index' is a keyword - realArray[idx] = - realArray[(i,j)]; // index using tuples + for j in realDomain.dim(2) { // Only use the 2nd dimension of the domain + realArray[i,j] = -1.61803 * i + 0.5 * j; // Access using index list + var idx: 2*int = (i,j); // Note: 'index' is a keyword + realArray[idx] = - realArray[(i,j)]; // Index using tuples } } -// arrays have domains as members that we can iterate over -for idx in realArray.domain { // again, idx is a 2*int tuple - realArray[idx] = 1 / realArray[idx[1],idx[2]]; // access by tuple and list +// Arrays have domains as members that we can iterate over +for idx in realArray.domain { // Again, idx is a 2*int tuple + realArray[idx] = 1 / realArray[idx[1],idx[2]]; // Access by tuple and list } writeln( realArray ); -// can also iterate over the values of an array +// Can also iterate over the values of an array var rSum: real = 0; for value in realArray { - rSum += value; // read a value - value = rSum; // write a value + rSum += value; // Read a value + value = rSum; // Write a value } writeln( rSum, "\n", realArray ); @@ -351,12 +357,12 @@ proc fibonacci( n : int ) : int { return fibonacci( n-1 ) + fibonacci( n-2 ); } -// input parameters can be untyped (a generic procedure) +// Input parameters can be untyped (a generic procedure) proc doublePrint( thing ): void { write( thing, " ", thing, "\n"); } -// return type can be inferred (as long as the compiler can figure it out) +// Return type can be inferred (as long as the compiler can figure it out) proc addThree( n ) { return n + 3; } @@ -372,12 +378,12 @@ proc maxOf( x ...?k ) { } writeln( maxOf( 1, -10, 189, -9071982, 5, 17, 20001, 42 ) ); -// the ? operator is called the query operator, and is used to take +// The ? operator is called the query operator, and is used to take // undetermined values (like tuple or array sizes, and generic types). // Taking arrays as parameters. // The query operator is used to determine the domain of A. -// this is important to define the return type (if you wanted to) +// This is important to define the return type (if you wanted to) proc invertArray( A: [?D] int ): [D] int{ for a in A do a = -a; return A; @@ -396,7 +402,7 @@ writeln( defaultsProc( x=11 ) ); writeln( defaultsProc( x=12, y=5.432 ) ); writeln( defaultsProc( y=9.876, x=13 ) ); -// intent modifiers on the arguments convey how +// Intent modifiers on the arguments convey how // those arguments are passed to the procedure // in: copy arg in, but not out // out: copy arg out, but not in @@ -426,7 +432,7 @@ proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { return array; } writeln( makeArray( 10, -1 ) ); -// this makes more practical sense for class methods where references to +// This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator // We can query the type of arguments to generic procedures @@ -462,17 +468,17 @@ whereProc( 10 ); whereProc( -1 ); // whereProc( 0 ) would result in a compiler error because there // are no functions that satisfy the where clause's condition. -// We could have defined a whereProc without a where clause that would -// then have been called. +// We could have defined a whereProc without a where clause that would then have +// served as a catch all for all the other cases (of which there is only one). -// Operator definitions are through procedures as well -// we can define the unary operators: +// Operator definitions are through procedures as well. +// We can define the unary operators: // + - ! ~ // and the binary operators: // + - * / % ** == <= >= < > << >> & | ˆ by // += -= *= /= %= **= &= |= ˆ= <<= >>= <=> -// boolean exclusive or operator +// Boolean exclusive or operator proc ^( left : bool, right : bool ): bool { return (left || right) && !( left && right ); } @@ -487,8 +493,8 @@ proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } -writeln( 1 * "a" ); // uses our * operator -writeln( 1 * 2 ); // uses the original * operator +writeln( 1 * "a" ); // Uses our * operator +writeln( 1 * 2 ); // Uses the default * operator /* Note: You could break everything if you get careless with your overloads. @@ -498,24 +504,21 @@ proc +( left: int, right: int ): int{ } */ -// iterators are a close cousin to the procedure. +// Iterators are a sisters to the procedure, and almost +// everything about procedures also applies to iterators // However, instead of returning a single value, // iterators yield many values to a loop. // This is useful when a complicated set or order of iterations is needed but // allows the code defining the iterations to be separate from the loop body. iter oddsThenEvens( N: int ): int { - for i in 1..N by 2 { + for i in 1..N by 2 do yield i; // yield values instead of returning. - } - - for i in 2..N by 2 { + for i in 2..N by 2 do yield i; - } } for i in oddsThenEvens( 10 ) do write( i, ", " ); -writeln(); - +writeln( ); // Classes are similar to those in C++ and Java. // They currently lack privatization @@ -548,7 +551,7 @@ class MyClass { return this.memberInt; } - proc getMemberBool(): bool { + proc getMemberBool( ): bool { return this.memberBool; } @@ -556,30 +559,30 @@ class MyClass { // Construct using default constructor, using default values var myObject = new MyClass( 10 ); - myObject = new MyClass( memberInt = 10 ); // equivalent -writeln( myObject.getMemberInt() ); + myObject = new MyClass( memberInt = 10 ); // Equivalent +writeln( myObject.getMemberInt( ) ); // ... using our values var myDiffObject = new MyClass( -1, true ); myDiffObject = new MyClass( memberInt = -1, - memberBool = true ); // equivalent + memberBool = true ); // Equivalent writeln( myDiffObject ); // Construct using written constructor var myOtherObject = new MyClass( 1.95 ); - myOtherObject = new MyClass( val = 1.95 ); // equivalent -writeln( myOtherObject.getMemberInt() ); + myOtherObject = new MyClass( val = 1.95 ); // Equivalent +writeln( myOtherObject.getMemberInt( ) ); // We can define an operator on our class as well but // the definition has to be outside the class definition proc +( A : MyClass, B : MyClass) : MyClass { - return new MyClass( memberInt = A.getMemberInt() + B.getMemberInt(), - memberBool = A.getMemberBool() || B.getMemberBool() ); + return new MyClass( memberInt = A.getMemberInt( ) + B.getMemberInt( ), + memberBool = A.getMemberBool( ) || B.getMemberBool( ) ); } var plusObject = myObject + myDiffObject; writeln( plusObject ); -// destruction +// Destruction delete myObject; delete myDiffObject; delete myOtherObject; @@ -620,10 +623,10 @@ class GenericClass { return this.classArray[ i ]; } - // Define an iterator for the class to - // yield values from the array to a loop + // Define an implicit iterator for the class + // to yield values from the array to a loop // i.e. for i in objVar do .... - iter these() ref : classType { + iter these( ) ref : classType { for i in this.classDomain do yield this[i]; } @@ -635,19 +638,19 @@ var realList = new GenericClass( real, 10 ); // notation that we defined ( proc this( i: int ){ ... } ) for i in realList.classDomain do realList[i] = i + 1.0; // We can iterate over the values in our list with the iterator -// we defined ( iter these(){ ... } ) +// we defined ( iter these( ){ ... } ) for value in realList do write( value, ", " ); -writeln(); +writeln( ); // Make a copy of realList using the copy constructor var copyList = new GenericClass( realList ); for value in copyList do write( value, ", " ); -writeln(); +writeln( ); -// make a copy of realList and change the type, also using the copy constructor +// Make a copy of realList and change the type, also using the copy constructor var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); -writeln(); +writeln( ); // Parallelism // In other languages, parallelism is typically this is done with @@ -655,14 +658,14 @@ writeln(); // Chapel has it baked right into the language. // A begin statement will spin the body of that statement off into one new task. -// a sync statement will ensure that the progress of the -// main task will not progress until the children have synced back up. +// A sync statement will ensure that the progress of the main +// task will not progress until the children have synced back up. sync { - begin { // start of new task's body + begin { // Start of new task's body var a = 0; for i in 1..1000 do a += 1; writeln( "Done: ", a); - } // end of new tasks body + } // End of new tasks body writeln( "spun off a task!"); } writeln( "Back together" ); @@ -671,13 +674,13 @@ proc printFibb( n: int ){ writeln( "fibonacci(",n,") = ", fibonacci( n ) ); } -// a cobegin statement will spin each statement of the body into one new task +// A cobegin statement will spin each statement of the body into one new task cobegin { printFibb( 20 ); // new task printFibb( 10 ); // new task printFibb( 5 ); // new task { - // this is a nested statement body and thus is a single statement + // This is a nested statement body and thus is a single statement // to the parent statement and is executed by a single task writeln( "this gets" ); writeln( "executed as" ); @@ -700,41 +703,41 @@ coforall taskID in 1..#num_tasks { forall i in 1..100 { write( i, ", "); } -writeln(); +writeln( ); // Here we see that there are sections that are in order, followed by -// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ) -// this is because each task is taking on a chunk of the range 1..10 +// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). +// This is because each task is taking on a chunk of the range 1..10 // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens // in parallel. // Your results may depend on your machine and configuration -// For both the forall and coforall loops, the execution of the parent task -// will not continue until all the children sync up. +// For both the forall and coforall loops, the execution of the +// parent task will not continue until all the children sync up. -// forall loops are particularly useful for parallel iteration over arrays +// forall loops are particularly useful for parallel iteration over arrays. // Lets run an experiment to see how much faster a parallel loop is use Time; // Import the Time module to use Timer objects var timer: Timer; -var myBigArray: [{1..4000,1..4000}] real; // large array we will write into +var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into // Serial Experiment -timer.start(); // start timer -for (x,y) in myBigArray.domain { // serial iteration +timer.start( ); // Start timer +for (x,y) in myBigArray.domain { // Serial iteration myBigArray[x,y] = (x:real) / (y:real); } -timer.stop(); // stop timer -writeln( "Serial: ", timer.elapsed() ); // print elapsed time -timer.clear(); // clear timer for parallel loop +timer.stop( ); // Stop timer +writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time +timer.clear( ); // Clear timer for parallel loop // Parallel Experiment -timer.start(); // start timer -forall (x,y) in myBigArray.domain { // parallel iteration +timer.start( ); // start timer +forall (x,y) in myBigArray.domain { // Parallel iteration myBigArray[x,y] = (x:real) / (y:real); } -timer.stop(); // stop timer -writeln( "Parallel: ", timer.elapsed() ); // print elapsed time -timer.clear(); -// you may have noticed that (depending on how many cores you have) that -// the parallel loop went faster than the serial loop +timer.stop( ); // Stop timer +writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time +timer.clear( ); +// You may have noticed that (depending on how many cores you have) +// that the parallel loop went faster than the serial loop // A succinct way of writing a forall loop over an array: // iterate over values @@ -750,6 +753,17 @@ Refer to the [language specification](http://chapel.cray.com/language.html) and Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. +### What this tutorial is lacking: + * Modules and standard modules + * Synchronize and atomic variables + * Multiple Locales (distributed memory system) + * proc main(){ ... } + * Records + * Whole/sliced array assignment + * Reductions and scans + * Range and domain slicing + * Parallel iterators + Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. -- cgit v1.2.3 From d6f8b8e629b0eb043710864566f894c0ce5f871c Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Tue, 14 Jul 2015 19:09:10 -0700 Subject: Codify proc() main lacking note --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 8b41dc32..2cd55a66 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -757,7 +757,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * Modules and standard modules * Synchronize and atomic variables * Multiple Locales (distributed memory system) - * proc main(){ ... } + * ```proc main(){ ... }``` * Records * Whole/sliced array assignment * Reductions and scans -- cgit v1.2.3 From cf26b05a233950c4ae30e0915b6892399c7f0151 Mon Sep 17 00:00:00 2001 From: Guangming Mao Date: Wed, 15 Jul 2015 16:01:37 +0800 Subject: Refine some sentences and fix some typos --- zh-cn/rust-cn.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zh-cn/rust-cn.html.markdown b/zh-cn/rust-cn.html.markdown index f50c1566..17a897df 100644 --- a/zh-cn/rust-cn.html.markdown +++ b/zh-cn/rust-cn.html.markdown @@ -8,7 +8,7 @@ filename: learnrust-cn.rs lang: zh-cn --- -Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制和高级语言的便利性和安全保障结合在了一起。 +Rust 是由 Mozilla 研究院开发的编程语言。Rust 将底层的性能控制与高级语言的便利性和安全保障结合在了一起。 而 Rust 并不需要一个垃圾回收器或者运行时即可实现这个目的,这使得 Rust 库可以成为一种 C 语言的替代品。 @@ -73,7 +73,7 @@ fn main() { let s: String = "hello world".to_string(); // 字符串分片(slice) - 另一个字符串的不可变视图 - // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何类容,只是一个指向某个东西的指针 + // 基本上就是指向一个字符串的不可变指针,它不包含字符串里任何内容,只是一个指向某个东西的指针 // 比如这里就是 `s` let s_slice: &str = &s; @@ -181,7 +181,7 @@ fn main() { println!("{:?}", another_foo.frobnicate()); // Some(1) /////////////////////////////////// - // 3. 模板匹配 (Pattern matching) // + // 3. 模式匹配 (Pattern matching) // /////////////////////////////////// let foo = OptionalI32::AnI32(1); @@ -190,7 +190,7 @@ fn main() { OptionalI32::Nothing => println!("it’s nothing!"), } - // 高级模板匹配 + // 高级模式匹配 struct FooBar { x: i32, y: OptionalI32 } let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) }; @@ -206,7 +206,7 @@ fn main() { } /////////////////////////////// - // 4. 条件控制 (Control flow) // + // 4. 流程控制 (Control flow) // /////////////////////////////// // `for` 循环 @@ -251,7 +251,7 @@ fn main() { //////////////////////////////////////////////// // 独占指针 (Owned pointer) - 同一时刻只能有一个对象能“拥有”这个指针 - // 意味着 `Box` 离开他的作用域后,会被安全的释放 + // 意味着 `Box` 离开他的作用域后,会被安全地释放 let mut mine: Box = Box::new(3); *mine = 5; // 解引用 // `now_its_mine` 获取了 `mine` 的所有权。换句话说,`mine` 移动 (move) 了 @@ -286,8 +286,8 @@ fn main() { ## 更深入的资料 -Rust 还有很多很多其他类容 - 这只是 Rust 最基础的东西,帮助你了解 Rust 里面最重要的东西。 -如果想深入学习 Rust,可以去阅读 +Rust 还有很多很多其他内容 - 这只是 Rust 最基本的功能,帮助你了解 Rust 里面最重要的东西。 +如果想深入学习 Rust,可以去读 [The Rust Programming Language](http://doc.rust-lang.org/book/index.html) 或者上 reddit [/r/rust](http://reddit.com/r/rust) 订阅。 同时 irc.mozilla.org 的 #rust 频道上的小伙伴们也非常欢迎新来的朋友。 -- cgit v1.2.3 From 37257b592275a5ddb41d7e1d6545aa039b1a35c3 Mon Sep 17 00:00:00 2001 From: "ian.bertolacci" Date: Wed, 15 Jul 2015 12:08:15 -0700 Subject: epiphany on ref returns. lead to better example of ref returns and then also a description of ref vars --- chapel.html.markdown | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 8b41dc32..77efbf5a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -77,6 +77,15 @@ config param paramCmdLineArg: bool = false; writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); // Set config with --set paramCmdLineArg=value at compile time +// refs operate much like a reference in C++ +var actual = 10; +ref refToActual = actual; // refToActual refers to actual +writeln( actual, " == ", refToActual ); // prints the same value +actual = -123; // modify actual (which refToActual refers to) +writeln( actual, " == ", refToActual ); // prints the same value +refToActual = 99999999; // modify what refToActual refers to (which is actual) +writeln( actual, " == ", refToActual ); // prints the same value + // Math operators var a: int, thisInt = 1234, thatInt = 5678; a = thisInt + thatInt; // Addition @@ -426,12 +435,19 @@ intentsProc( inVar, outVar, inoutVar, refVar ); writeln( "Outside After: ", (inVar, outVar, inoutVar, refVar) ); // Similarly we can define intents on the return type -proc makeArray( elems: int, startNumber: int ) ref : [1..#elems] int { - var array: [1..#elems] int; - for idx in array.domain do array[idx] = startNumber + idx; - return array; -} -writeln( makeArray( 10, -1 ) ); +// refElement returns a reference to an element of array +proc refElement( array : [?D] ?T, idx ) ref : T { + return array[ idx ]; // returns a reference to +} + +var myChangingArray : [1..5] int = [1,2,3,4,5]; +writeln( myChangingArray ); +// Store reference to element in ref variable +ref refToElem = refElement( myChangingArray, 5 ); +writeln( refToElem ); +refToElem = -2; // modify reference which modifies actual value in array +writeln( refToElem ); +writeln( myChangingArray ); // This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator -- cgit v1.2.3 From 90c27c72cfbd1fc2fa4b5700a5e08efc6c3ed874 Mon Sep 17 00:00:00 2001 From: Kado Date: Thu, 16 Jul 2015 18:43:13 +0300 Subject: Update matlab.html.markdown --- matlab.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/matlab.html.markdown b/matlab.html.markdown index 9de41275..00f4c53a 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -43,7 +43,7 @@ edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window profile on % turns on the code profiler -profile of % turns off the code profiler +profile off % turns off the code profiler profile viewer % Open profiler help command % Displays documentation for command in Command Window -- cgit v1.2.3 From d995a0ae2792b3e6acc832438b84e9fed570d0e4 Mon Sep 17 00:00:00 2001 From: Mark Miller <725mrm@gmail.com> Date: Thu, 16 Jul 2015 16:45:25 -0500 Subject: Changed %s formatting to {n} style. If line 117 is accurate, then {n} style string formatting is the preferred style, and it should be reflected in the examples. --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index b89fe57d..3b233f7f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -327,8 +327,8 @@ prints: mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: - # You can use % to interpolate formatted strings - print "%s is a mammal" % animal + # You can use {0} to interpolate formatted strings. (See above.) + print "{0} is a mammal".format(animal) """ "range(number)" returns a list of numbers @@ -387,7 +387,7 @@ else: # Optional clause to the try/except block. Must follow all except blocks # Use "def" to create new functions def add(x, y): - print "x is %s and y is %s" % (x, y) + print "x is {0} and y is {1}".format(x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -497,7 +497,7 @@ class Human(object): # An instance method. All methods take "self" as the first argument def say(self, msg): - return "%s: %s" % (self.name, msg) + return "{0}: {1}".format(self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument -- cgit v1.2.3 From c22acdf8bd8750b664393422e1e00d4055f69e31 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Fri, 17 Jul 2015 14:45:18 +0900 Subject: Update chapel.html.markdown Make sure nothing breaks (too badly) --- chapel.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4d6d648..d4ce4dfa 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -3,7 +3,6 @@ language: chapel filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] -lang: en --- You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). @@ -11,7 +10,7 @@ In short, Chapel is an open-source, high-productivity, parallel-programming lang More information and support can be found at the bottom of this document. -```chapel +```c // Comments are C-family style // one line comment /* -- cgit v1.2.3 From 4edb920f518327325d092f76a99f901821f35c76 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:09:21 -0700 Subject: capitalization and attempt to fix lists --- chapel.html.markdown | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4ce4dfa..f308d1d8 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,11 +1,11 @@ --- -language: chapel +language: Chapel filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- -You can read all about chapel at [Cray's official Chapel website](http://chapel.cray.com). +You can read all about Chapel at [Cray's official Chapel website](http://chapel.cray.com). In short, Chapel is an open-source, high-productivity, parallel-programming language in development at Cray Inc., and is designed to run on multi-core PCs as well as multi-kilocore supercomputers. More information and support can be found at the bottom of this document. @@ -762,7 +762,7 @@ timer.clear( ); ``` Who is this tutorial for? ------------------------- -This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. +This tutorial is for people who want to learn the ropes of Chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. @@ -793,22 +793,27 @@ Installing the Compiler ----------------------- Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) -and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` +and its as easy as + +1. ```tar -xvf chapel-1.11.0.tar.gz``` + +2. ```cd chapel-1.11.0``` + +3. ```make``` + +4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` + +1. ```brew update``` + +2. ```brew install chapel``` Compiling Code -------------- Builds like other compilers ```chpl myFile.chpl -o myExe``` -A notable argument: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. +A notable argument, ``--fast`` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 4ae7b4921979998152c828a2b70576258a1f1468 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:13:51 -0700 Subject: Changed bash examples from block code Bash examples were in block code form (triple tick), should have been in inline mode (single tic) --- chapel.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index f308d1d8..5a0c3920 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -795,25 +795,25 @@ Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as -1. ```tar -xvf chapel-1.11.0.tar.gz``` +`tar -xvf chapel-1.11.0.tar.gz` -2. ```cd chapel-1.11.0``` +`cd chapel-1.11.0` -3. ```make``` +`make` -4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` +`source util/setchplenv.bash # or .sh or .csh or .fish` -You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). +You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X -1. ```brew update``` +`brew update` -2. ```brew install chapel``` +`brew install chapel` Compiling Code -------------- Builds like other compilers -```chpl myFile.chpl -o myExe``` +`chpl myFile.chpl -o myExe` -A notable argument, ``--fast`` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. +A notable argument, `--fast` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From 77c4ddb522881b4975bff0e6b34e46566336e266 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:15:29 -0700 Subject: Put lists back in Pretty sure what was causing the 'back end' error was my bad markdown skills --- chapel.html.markdown | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 5a0c3920..c6c4a191 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -794,26 +794,21 @@ Installing the Compiler Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as - -`tar -xvf chapel-1.11.0.tar.gz` - -`cd chapel-1.11.0` - -`make` - -`source util/setchplenv.bash # or .sh or .csh or .fish` + 1. `tar -xvf chapel-1.11.0.tar.gz` + 2. `cd chapel-1.11.0` + 3. `make` + 4. `source util/setchplenv.bash # or .sh or .csh or .fish` You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - -`brew update` - -`brew install chapel` + 1. `brew update` + 2. `brew install chapel` Compiling Code -------------- Builds like other compilers + `chpl myFile.chpl -o myExe` A notable argument, `--fast` enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From e7fe0b267a4c11136f4703493206d5862fa0fb76 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:24:16 -0700 Subject: Spellcheck --- chapel.html.markdown | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c6c4a191..b03aee7b 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -117,7 +117,7 @@ a = thisInt ^ thatInt; // Bitwise exclusive-or a += thisInt; // Addition-equals ( a = a + thisInt;) a *= thatInt; // Times-equals ( a = a * thatInt; ) b &&= thatBool; // Logical-and-equals ( b = b && thatBool; ) -a <<= 3; // LEft-bit-shift-equals ( a = a << 10; ) +a <<= 3; // Left-bit-shift-equals ( a = a << 10; ) // and many, many more. // Unlike other C family languages there are no // pre/post-increment/decrement operators like @@ -190,7 +190,7 @@ if ( a % 3 == 0 ) { var maximum = if ( thisInt < thatInt ) then thatInt else thisInt; // Select statements are much like switch statements in other languages -// However, Select statements dont cascade like in C or Java +// However, Select statements don't cascade like in C or Java var inputOption = "anOption"; select( inputOption ){ when "anOption" do writeln( "Chose 'anOption'" ); @@ -201,8 +201,6 @@ select( inputOption ){ otherwise { writeln( "Any other Input" ); writeln( "the otherwise case doesn't need a do if the body is one line" ); - writeln( "Oh, and when statements dont cascade like the case statements" ); - writeln( "of other languages" ); } } @@ -246,7 +244,7 @@ for x in 1..10 { // define an index set that can be iterated over. // Ranges are single dimensional // Domains can be multi-dimensional and can -// represent indicies of different types as well. +// represent indices of different types as well. // They are first-class citizen types, and can be assigned into variables var range1to10: range = 1..10; // 1, 2, 3, ..., 10 var range2to11 = 2..11; // 2, 3, 4, ..., 11 @@ -452,7 +450,7 @@ writeln( myChangingArray ); // We can query the type of arguments to generic procedures // Here we define a procedure that takes two arguments of -// the same type, yet we dont define what that type is. +// the same type, yet we don't define what that type is. proc genericProc( arg1 : ?valueType, arg2 : valueType ): void { select( valueType ){ when int do writeln( arg1, " and ", arg2, " are ints" ); @@ -620,10 +618,10 @@ class GenericClass { } // Copy constructor - // Note: We still have to put the the type as an argument, but we can + // Note: We still have to put the type as an argument, but we can // default to the type of the other object using the query (?) operator // Further, we can take advantage of this to allow our copy constructor - // to copy classes of different types + // to copy classes of different types and cast on the fly proc GenericClass( other : GenericClass(?otherType), type classType = otherType ) { this.classDomain = other.classDomain; -- cgit v1.2.3 From 6a54bca6ee74486b6eddadec17b6fc7f0c8bf43b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Fri, 17 Jul 2015 10:31:32 -0700 Subject: Capitalization, Chapel Directory. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index b03aee7b..fb54d5a1 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -797,7 +797,7 @@ and its as easy as 3. `make` 4. `source util/setchplenv.bash # or .sh or .csh or .fish` -You will need to `source util/setchplenv.EXT` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). +You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X 1. `brew update` -- cgit v1.2.3 From 71f87d44fd4aae061e0c9d1b52a202a1be4fc332 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 18 Jul 2015 09:21:14 +0900 Subject: More line breaks Fix formatting in places --- chapel.html.markdown | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d4ce4dfa..ec46a083 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -760,8 +760,10 @@ timer.clear( ); // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; ``` + Who is this tutorial for? ------------------------- + This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. @@ -769,6 +771,7 @@ Refer to the [language specification](http://chapel.cray.com/language.html) and Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. ### What this tutorial is lacking: + * Modules and standard modules * Synchronize and atomic variables * Multiple Locales (distributed memory system) @@ -781,6 +784,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to Your input, questions, and discoveries are important to the developers! ----------------------------------------------------------------------- + The Chapel language is still in-development (version 1.11.0), so there are occasional hiccups with performance and language features. The more information you give the Chapel development team about issues you encounter or features you would like to see, the better the language becomes. Feel free to email the team and other developers through the [sourceforge email lists](https://sourceforge.net/p/chapel/mailman). @@ -791,9 +795,11 @@ It is under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0) Installing the Compiler ----------------------- + Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as + 1. ```tar -xvf chapel-1.11.0.tar.gz``` 2. ```cd chapel-1.11.0``` 3. ```make``` @@ -802,13 +808,17 @@ and its as easy as You will need to ```source util/setchplenv.EXT``` from the chapel directory every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X + 1. ```brew update``` 2. ```brew install chapel``` Compiling Code -------------- -Builds like other compilers + +Builds like other compilers: + ```chpl myFile.chpl -o myExe``` A notable argument: + * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. -- cgit v1.2.3 From bad5266d05485cd61ab1aa0884180ab78738cd9b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sat, 18 Jul 2015 14:16:08 -0700 Subject: Slight modifications. --- chapel.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index c97a5f2b..7ac73bbb 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,6 +1,6 @@ --- language: Chapel -filename: learnchapel.chpl +filename: learnChapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- @@ -27,7 +27,7 @@ writeln( "There are ", 3, " commas (\",\") in this line of code" ); stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); stderr.writeln( "This goes to standard error" ); -// Variables dont have to be explicitly typed as long as +// Variables don't have to be explicitly typed as long as // the compiler can figure out the type that it will hold. var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; @@ -540,7 +540,7 @@ class MyClass { var memberInt : int; var memberBool : bool = true; - // Classes have default constructors that dont need to be coded (see below) + // Classes have default constructors that don't need to be coded (see below) // Our explicitly defined constructor proc MyClass( val : real ){ this.memberInt = ceil( val ): int; @@ -771,7 +771,7 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: * Modules and standard modules - * Synchronize and atomic variables + * Synchronize variables and atomic operations * Multiple Locales (distributed memory system) * ```proc main(){ ... }``` * Records -- cgit v1.2.3 From fe0c14b8ad0f04b1d493fa6612a14d6cc7a48650 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 19 Jul 2015 16:01:04 -0700 Subject: De-capitalization Changed language name and filename back to lower case 'chapel' in keeping with previous name to avoid possible site breakage. --- chapel.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 7ac73bbb..53e9747c 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -1,6 +1,6 @@ --- -language: Chapel -filename: learnChapel.chpl +language: chapel +filename: learnchapel.chpl contributors: - ["Ian J. Bertolacci", "http://www.cs.colostate.edu/~ibertola/"] --- -- cgit v1.2.3 From 155bf5d0a285de2c4dec4033c8e9c20f6a42072b Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 19 Jul 2015 19:59:30 -0700 Subject: Added sync, single, and atomic vars. --- chapel.html.markdown | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 77 insertions(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 7ac73bbb..4f857775 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -757,6 +757,83 @@ timer.clear( ); [ val in myBigArray ] val = 1 / val; // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + +proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } +} + +// sync vars have two states: empty and full. +// If you read an empty variable or write a full variable, you are waited +// until the variable is full or empty again +var someSyncVar$: sync int; // varName$ is a convention not a law. +sync { + begin { + writeln( "Waiting to read" ); + var read_sync = someSyncVar$; + writeln( "value is ", read_sync ); + } + + begin { + writeln( "Writing in..." ); + countdown( 3 ); + someSyncVar$ = 123; + } +} + +// single vars can only be written once. A read on an unwritten single results +// in a wait, but when the variable has a value it can be read indefinitely +var someSingleVar$: single int; // varName$ is a convention not a law. +sync { + begin { + writeln( "Waiting to read" ); + for i in 1..5 { + var read_single = someSingleVar$; + writeln( i,"th time around an the value is ", read_single ); + } + } + + begin { + writeln( "Writing in..." ); + countdown( 3 ); + someSingleVar$ = 5; // first and only write ever. + } +} + +// atomic variables can be of type bool, int, uint, and real of any size. +var uranium: atomic int; +uranium.write( 238 ); // atomically write a variable +writeln( uranium.read() ); // atomically read a variable +// operations are described as functions, you could define your own operators. +uranium.sub( 3 ); // atomically subtract a variable +writeln( uranium.read() ); +var replaceWith = 239; +var was = uranium.exchange( replaceWith ); +writeln( "uranium was ", was, " but is now ", replaceWith ); +var isEqualTo = 235; +if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); +} else { + writeln( "uranium was not equal to ", isEqualTo, + " value stays the same... whatever it was" ); +} + +sync { + begin { + writeln( "Waiting to for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Uranium was set (by someone) to ", isEqualTo ); + } + + begin { + writeln( "Waiting to write uranium to ", isEqualTo ); + countdown( 3 ); + uranium.write( isEqualTo ); + } +} ``` Who is this tutorial for? @@ -771,7 +848,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: * Modules and standard modules - * Synchronize variables and atomic operations * Multiple Locales (distributed memory system) * ```proc main(){ ... }``` * Records -- cgit v1.2.3 From bcc84f9c768041b7f260907d4432e12658b76626 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 08:09:28 -0700 Subject: Explained atomics, moved atomics first Felt the need to add in an explanation about atomics, then felt that (because atomics are common in language and in theory) it should go before sync and single vars. Should I explain sync and single? --- chapel.html.markdown | 69 +++++++++++++++++++++++++++------------------------- 1 file changed, 36 insertions(+), 33 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 6fe7c1b0..bbbf50e8 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -765,6 +765,42 @@ proc countdown( seconds: int ){ } } +// Atomic variables, common to many languages, are ones whose operations +// occur uninterupted. Multiple threads can both modify atomic variables +// and can know that their values are safe. +// Chapel atomic variables can be of type bool, int, uint, and real. +var uranium: atomic int; +uranium.write( 238 ); // atomically write a variable +writeln( uranium.read() ); // atomically read a variable +// operations are described as functions, you could define your own operators. +uranium.sub( 3 ); // atomically subtract a variable +writeln( uranium.read() ); +var replaceWith = 239; +var was = uranium.exchange( replaceWith ); +writeln( "uranium was ", was, " but is now ", replaceWith ); +var isEqualTo = 235; +if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); +} else { + writeln( "uranium was not equal to ", isEqualTo, + " value stays the same... whatever it was" ); +} + +sync { + begin { + writeln( "Waiting to for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Uranium was set (by someone) to ", isEqualTo ); + } + + begin { + writeln( "Waiting to write uranium to ", isEqualTo ); + countdown( 3 ); + uranium.write( isEqualTo ); + } +} + // sync vars have two states: empty and full. // If you read an empty variable or write a full variable, you are waited // until the variable is full or empty again @@ -801,39 +837,6 @@ sync { someSingleVar$ = 5; // first and only write ever. } } - -// atomic variables can be of type bool, int, uint, and real of any size. -var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable -writeln( uranium.read() ); // atomically read a variable -// operations are described as functions, you could define your own operators. -uranium.sub( 3 ); // atomically subtract a variable -writeln( uranium.read() ); -var replaceWith = 239; -var was = uranium.exchange( replaceWith ); -writeln( "uranium was ", was, " but is now ", replaceWith ); -var isEqualTo = 235; -if uranium.compareExchange( isEqualTo, replaceWith ) { - writeln( "uranium was equal to ", isEqualTo, - " so replaced value with ", replaceWith ); -} else { - writeln( "uranium was not equal to ", isEqualTo, - " value stays the same... whatever it was" ); -} - -sync { - begin { - writeln( "Waiting to for uranium to be ", isEqualTo ); - uranium.waitFor( isEqualTo ); - writeln( "Uranium was set (by someone) to ", isEqualTo ); - } - - begin { - writeln( "Waiting to write uranium to ", isEqualTo ); - countdown( 3 ); - uranium.write( isEqualTo ); - } -} ``` Who is this tutorial for? -- cgit v1.2.3 From d2d98a381047d30e0355a8dacd0fdbe1188345c0 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 08:17:01 -0700 Subject: Spelling error Tupe -> Tuple --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index bbbf50e8..9ce184c0 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -501,7 +501,7 @@ writeln( false ^ true ); writeln( true ^ false ); writeln( false ^ false ); -// Define a * operator on any two types that returns a tupe of those types +// Define a * operator on any two types that returns a tuple of those types proc *( left : ?ltype, right : ?rtype): ( ltype, rtype ){ return (left, right ); } -- cgit v1.2.3 From 2936ca4c69f7b96dfbe7f67de0ebcad910395ba1 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 12:59:35 -0700 Subject: Erroneous comment removed "define mySecondVar as a real" unnecessary and incorrect. --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 9ce184c0..4cbc5a4b 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -35,7 +35,7 @@ var mySecondVar = myVar; // var anError; // this would be a compile time error. // We can (and should) explicitly type things -var myThirdVar: real; // define mySecondVar as a real +var myThirdVar: real; var myFourthVar: real = -1.234; myThirdVar = myFourthVar; -- cgit v1.2.3 From d35d9d213c3ce3ba1bb53aef896898d87e213d58 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 13:01:25 -0700 Subject: Word error that -> than --- chapel.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 4cbc5a4b..b124f54a 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -65,7 +65,7 @@ const almostPi: real = 22.0/7.0; param compileTimeConst: int = 16; // The config modifier allows values to be set at the command line -// and is much easier that the usual getOpts debacle +// and is much easier than the usual getOpts debacle // config vars and consts can be changed through the command line at run time config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; -- cgit v1.2.3 From 77daaef8ed6d2fed88405cf038d4e5f0b82dc1ef Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Mon, 20 Jul 2015 13:07:23 -0700 Subject: config param changeup changed some of the wording of the param config example. Namely put the comment immediately below the example. Also added --set to the noteable arguments list. Also changed "compile(?: )?time" to "compile-time" --- chapel.html.markdown | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index b124f54a..520f959d 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -32,7 +32,7 @@ stderr.writeln( "This goes to standard error" ); var myVar = 10; // 10 is an int, so myVar is implicitly an int myVar = -10; var mySecondVar = myVar; -// var anError; // this would be a compile time error. +// var anError; // this would be a compile-time error. // We can (and should) explicitly type things var myThirdVar: real; @@ -57,11 +57,11 @@ var my64Real: real(64) = 1.516; // 64 bit (8 bytes) sized real var intFromReal = myReal : int; var intFromReal2: int = myReal : int; -// consts are constants, they cannot be changed after set in runtime +// consts are constants, they cannot be changed after set in runtime. const almostPi: real = 22.0/7.0; -// params are constants whose value must be known statically at compile time -// Like consts, they cannot be changed during runtime +// params are constants whose value must be known statically at compile-time +// Their value cannot be changed. param compileTimeConst: int = 16; // The config modifier allows values to be set at the command line @@ -71,10 +71,10 @@ config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; // Set with --VarName=Value or --VarName Value at run time -// config params can be set at compile time +// config params can be set/changed at compile-time config param paramCmdLineArg: bool = false; +// Set config with --set paramCmdLineArg=value at compile-time writeln( varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg ); -// Set config with --set paramCmdLineArg=value at compile time // refs operate much like a reference in C++ var actual = 10; @@ -465,7 +465,7 @@ genericProc( 1.0+2.0i, 3.0+4.0i ); // We can also enforce a form of polymorphism with the 'where' clause // This allows the compiler to decide which function to use. -// Note: that means that all information needs to be known at compile time. +// Note: that means that all information needs to be known at compile-time. // The param modifier on the arg is used to enforce this constraint. proc whereProc( param N : int ): void where ( N > 0 ) { @@ -896,6 +896,7 @@ Builds like other compilers: ```chpl myFile.chpl -o myExe``` -A notable argument: +Notable arguments: * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. + * ```--set =```: set config param to at compile-time -- cgit v1.2.3 From 3332ce43bb73dcb850250847c6cffdc396338d5e Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Wed, 22 Jul 2015 19:08:22 -0700 Subject: added scans and reductions --- chapel.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/chapel.html.markdown b/chapel.html.markdown index 520f959d..e058bde9 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -837,6 +837,25 @@ sync { someSingleVar$ = 5; // first and only write ever. } } + +// we can define the operations + * & | ^ && || min max minloc maxloc +// over an entire array using scans and reductions +// Reductions apply the operation over the entire array and +// result in a single value +var listOfValues: [1..10] int = [456,354,15,57,36,45,15,8,678,2]; +var sumOfValues = + reduce listOfValues; +var maxValue = max reduce listOfValues; // give just max value +// gives max value and index of the max value +var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); +writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); + +// Scans apply the operation incrementally and return an array of the +// value of the operation at that index as it progressed through the +// array from array.domain.low to array.domain.high +var runningSumOfValues = + scan listOfValues; +var maxScan = max scan listOfValues; +writeln( runningSumOfValues ); +writeln( maxScan ); ``` Who is this tutorial for? -- cgit v1.2.3 From 8a968db2bc0f596e2e9d865b73d909b02ff774d6 Mon Sep 17 00:00:00 2001 From: Al Sweigart Date: Thu, 23 Jul 2015 11:24:40 -0700 Subject: Added links to the free book "Automate the Boring Stuff with Python" to the "Free Online" section. --- python.html.markdown | 1 + python3.html.markdown | 1 + 2 files changed, 2 insertions(+) diff --git a/python.html.markdown b/python.html.markdown index 3b233f7f..88e0deb1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -624,6 +624,7 @@ print say(say_please=True) # Can you buy me a beer? Please! I am poor :( ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [The Official Docs](http://docs.python.org/2.6/) diff --git a/python3.html.markdown b/python3.html.markdown index dd57bf58..36298566 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -642,6 +642,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) * [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) -- cgit v1.2.3 From ac2dfe7dc782cf1663944c0de48f6bbe810a56d8 Mon Sep 17 00:00:00 2001 From: Genki Marshall Date: Fri, 24 Jul 2015 13:21:01 -0700 Subject: [python3/en] Use `next()` instead of `__next__()` Fixes issue #1148. The reasoning is well explained by the issue. One can also refer to the docs [0], showing it is more idiomatic to use `next()`. [0]: https://www.python.org/dev/peps/pep-3114/ #double-underscore-methods-and-built-in-functions --- python3.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/python3.html.markdown b/python3.html.markdown index 36298566..9d965fb1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -394,15 +394,15 @@ our_iterable[1] # Raises a TypeError our_iterator = iter(our_iterable) # Our iterator is an object that can remember the state as we traverse through it. -# We get the next object by calling the __next__ function. -our_iterator.__next__() #=> "one" +# We get the next object with "next()". +next(our_iterator) #=> "one" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# It maintains state as we iterate. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. list(filled_dict.keys()) #=> Returns ["one", "two", "three"] -- cgit v1.2.3 From c2f85b27b5620054bb0306ee4730cefff60ad87c Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sat, 1 Aug 2015 17:02:51 -0700 Subject: added count-down mutex example. Cleaned up some of the reductions and scans prints --- chapel.html.markdown | 88 ++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 65 insertions(+), 23 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index e058bde9..0d1d38dc 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -533,6 +533,12 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); +// The 'zippered' iterator is an iterator that takes two or more iterators that +// have the same number of iterations and zips them together into one stream + // Ranges have implicit iterators +for (odd, even) in zip( 1..#10 by 2, 2..#10 by 2 ) do + writeln( (odd, even) ); + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -569,7 +575,7 @@ class MyClass { } } - + // Construct using default constructor, using default values var myObject = new MyClass( 10 ); myObject = new MyClass( memberInt = 10 ); // Equivalent @@ -732,6 +738,7 @@ writeln( ); use Time; // Import the Time module to use Timer objects var timer: Timer; var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into + // Serial Experiment timer.start( ); // Start timer for (x,y) in myBigArray.domain { // Serial iteration @@ -754,7 +761,8 @@ timer.clear( ); // A succinct way of writing a forall loop over an array: // iterate over values -[ val in myBigArray ] val = 1 / val; +[ val in myBigArray ] val = 1 / val; + // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; @@ -770,32 +778,35 @@ proc countdown( seconds: int ){ // and can know that their values are safe. // Chapel atomic variables can be of type bool, int, uint, and real. var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable +uranium.write( 238 ); // atomically write a variable writeln( uranium.read() ); // atomically read a variable + // operations are described as functions, you could define your own operators. uranium.sub( 3 ); // atomically subtract a variable writeln( uranium.read() ); + var replaceWith = 239; var was = uranium.exchange( replaceWith ); writeln( "uranium was ", was, " but is now ", replaceWith ); + var isEqualTo = 235; if uranium.compareExchange( isEqualTo, replaceWith ) { writeln( "uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith ); } else { writeln( "uranium was not equal to ", isEqualTo, - " value stays the same... whatever it was" ); + " so value stays the same... whatever it was" ); } sync { - begin { - writeln( "Waiting to for uranium to be ", isEqualTo ); + begin { // Reader task + writeln( "Reader: waiting for uranium to be ", isEqualTo ); uranium.waitFor( isEqualTo ); - writeln( "Uranium was set (by someone) to ", isEqualTo ); + writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); } - begin { - writeln( "Waiting to write uranium to ", isEqualTo ); + begin { // Writer task + writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); countdown( 3 ); uranium.write( isEqualTo ); } @@ -806,14 +817,14 @@ sync { // until the variable is full or empty again var someSyncVar$: sync int; // varName$ is a convention not a law. sync { - begin { - writeln( "Waiting to read" ); + begin { // Reader task + writeln( "Reader: waiting to read." ); var read_sync = someSyncVar$; writeln( "value is ", read_sync ); } - begin { - writeln( "Writing in..." ); + begin { // Writer task + writeln( "Writer: will write in..." ); countdown( 3 ); someSyncVar$ = 123; } @@ -823,30 +834,62 @@ sync { // in a wait, but when the variable has a value it can be read indefinitely var someSingleVar$: single int; // varName$ is a convention not a law. sync { - begin { - writeln( "Waiting to read" ); + begin { // Reader task + writeln( "Reader: waiting to read." ); for i in 1..5 { var read_single = someSingleVar$; - writeln( i,"th time around an the value is ", read_single ); + writeln( "Reader: iteration ", i,", and the value is ", read_single ); } } - begin { - writeln( "Writing in..." ); + begin { // Writer task + writeln( "Writer: will write in..." ); countdown( 3 ); someSingleVar$ = 5; // first and only write ever. } } +// Heres an example of using atomics and a synch variable to create a +// count-down mutex (also known as a multiplexer) +var count: atomic int; // our counter +var lock$: sync bool; // the mutex lock + +count.write( 2 ); // Only let two tasks in at a time. +lock$.writeXF( true ); // Set lock$ to full (unlocked) +// Note: The value doesnt actually matter, just the state +// (full:unlocked / empty:locked) +// Also, writeXF() fills (F) the sync var regardless of its state (X) + +coforall task in 1..#5 { // Generate tasks + // Create a barrier + do{ + lock$; // Read lock$ (wait) + }while count.read() < 1; // Keep waiting until a spot opens up + + count.sub(1); // decrement the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + + // Actual 'work' + writeln( "Task #", task, " doing work." ); + sleep( 2 ); + + count.add( 1 ); // Increment the counter + lock$.writeXF( true ); // Set lock$ to full (signal) +} + // we can define the operations + * & | ^ && || min max minloc maxloc // over an entire array using scans and reductions // Reductions apply the operation over the entire array and // result in a single value -var listOfValues: [1..10] int = [456,354,15,57,36,45,15,8,678,2]; +var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; var sumOfValues = + reduce listOfValues; -var maxValue = max reduce listOfValues; // give just max value -// gives max value and index of the max value -var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); +var maxValue = max reduce listOfValues; // 'max' give just max value + +// 'maxloc' gives max value and index of the max value +// Note: We have to zip the array and domain together with the zip iterator +var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + listOfValues.domain); + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); // Scans apply the operation incrementally and return an array of the @@ -874,7 +917,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * ```proc main(){ ... }``` * Records * Whole/sliced array assignment - * Reductions and scans * Range and domain slicing * Parallel iterators -- cgit v1.2.3 From 919f255a58d7af0a65d0fbf9b5232317ec20db28 Mon Sep 17 00:00:00 2001 From: Thiago van Dieten Date: Sun, 2 Aug 2015 12:58:23 +0300 Subject: Fix 'filename' collision between csharp{,-tr}.html.markdown Both were set to LearnCSharp.cs, so the live site has been serving the Turkish version for English. --- tr-tr/csharp-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 7755ed44..a68026a5 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -8,7 +8,7 @@ contributors: translators: - ["Melih Mucuk", "http://melihmucuk.com"] lang: tr-tr -filename: LearnCSharp.cs +filename: LearnCSharp-tr.cs --- -- cgit v1.2.3 From 11ca1012e402bbc51f70283c4e20ee8bf31deb7f Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 14:35:41 -0700 Subject: Clarified some wording on the zipper iterator. Changed the example to something more simple and informative. --- chapel.html.markdown | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 0d1d38dc..cfde0454 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -533,11 +533,13 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); -// The 'zippered' iterator is an iterator that takes two or more iterators that -// have the same number of iterations and zips them together into one stream - // Ranges have implicit iterators -for (odd, even) in zip( 1..#10 by 2, 2..#10 by 2 ) do - writeln( (odd, even) ); +// We can zipper together two or more iterators (who have the same number +// of iterations) using zip() to create a single zipped iterator, where each +// iteration of the zipped iterator yields a tuple of one value yielded +// from each iterator. + // Ranges have implicit iterators +for (positive, negative) in zip( 1..5, -5..-1) do + writeln( (positive, negative) ); // Classes are similar to those in C++ and Java. // They currently lack privatization -- cgit v1.2.3 From b27d5268227f8812c894a217a08fd8c6221d1797 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 15:37:01 -0700 Subject: Added modules and main() Worth noting that this will change the diff of the parallel section quite a bit, since they became the body of the main procedure. Thus each line in intented. --- chapel.html.markdown | 462 ++++++++++++++++++++++++++++----------------------- 1 file changed, 258 insertions(+), 204 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index cfde0454..d8783728 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -673,234 +673,288 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln( ); -// Parallelism -// In other languages, parallelism is typically this is done with -// complicated libraries and strange class structure hierarchies. -// Chapel has it baked right into the language. - -// A begin statement will spin the body of that statement off into one new task. -// A sync statement will ensure that the progress of the main -// task will not progress until the children have synced back up. -sync { - begin { // Start of new task's body - var a = 0; - for i in 1..1000 do a += 1; - writeln( "Done: ", a); - } // End of new tasks body - writeln( "spun off a task!"); -} -writeln( "Back together" ); -proc printFibb( n: int ){ - writeln( "fibonacci(",n,") = ", fibonacci( n ) ); -} +// Modules are Chapel's way of managing name spaces. +// The files containing these modules do not need to be named after the modules +// (as is with Java), but files implicitly name modules. +// In this case, this file implicitly names the 'learnchapel' module -// A cobegin statement will spin each statement of the body into one new task -cobegin { - printFibb( 20 ); // new task - printFibb( 10 ); // new task - printFibb( 5 ); // new task - { - // This is a nested statement body and thus is a single statement - // to the parent statement and is executed by a single task - writeln( "this gets" ); - writeln( "executed as" ); - writeln( "a whole" ); +module OurModule { + // We can use modules inside of other modules. + use Time; + + // We'll use this a procedure in the parallelism section. + proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } + } + + // Submodule of Ourmodule + // It is possible to create arbitrarily deep module nests. + module ChildModule { + proc foo(){ + writeln( "ChildModule.foo()"); + } } -} -// Notice here that the prints from each statement may happen in any order. - -// Coforall loop will create a new task for EACH iteration -var num_tasks = 10; // Number of tasks we want -coforall taskID in 1..#num_tasks { - writeln( "Hello from task# ", taskID ); -} -// Again we see that prints happen in any order. -// NOTE! coforall should be used only for creating tasks! -// Using it to iterating over a structure is very a bad idea! - -// forall loops are another parallel loop, but only create a smaller number -// of tasks, specifically --dataParTasksPerLocale=number of task -forall i in 1..100 { - write( i, ", "); -} -writeln( ); -// Here we see that there are sections that are in order, followed by -// a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). -// This is because each task is taking on a chunk of the range 1..10 -// (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens -// in parallel. -// Your results may depend on your machine and configuration - -// For both the forall and coforall loops, the execution of the -// parent task will not continue until all the children sync up. - -// forall loops are particularly useful for parallel iteration over arrays. -// Lets run an experiment to see how much faster a parallel loop is -use Time; // Import the Time module to use Timer objects -var timer: Timer; -var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into - -// Serial Experiment -timer.start( ); // Start timer -for (x,y) in myBigArray.domain { // Serial iteration - myBigArray[x,y] = (x:real) / (y:real); -} -timer.stop( ); // Stop timer -writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time -timer.clear( ); // Clear timer for parallel loop - -// Parallel Experiment -timer.start( ); // start timer -forall (x,y) in myBigArray.domain { // Parallel iteration - myBigArray[x,y] = (x:real) / (y:real); -} -timer.stop( ); // Stop timer -writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time -timer.clear( ); -// You may have noticed that (depending on how many cores you have) -// that the parallel loop went faster than the serial loop - -// A succinct way of writing a forall loop over an array: -// iterate over values -[ val in myBigArray ] val = 1 / val; - -// or iterate over indicies -[ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; - -proc countdown( seconds: int ){ - for i in 1..seconds by -1 { - writeln( i ); - sleep( 1 ); + + module SiblingModule { + proc foo(){ + writeln( "SiblingModule.foo()" ); + } } -} +} // end OurModule + +// Using OurModule also uses all the modules it uses. +// Since OurModule uses Time, we also use time. +use OurModule; + +// At this point we have not used ChildModule or SiblingModule so their symbols +// (i.e. foo ) are not available to us. +// However, the module names are, and we can explicitly call foo() through them. +SiblingModule.foo(); // Calls SiblingModule.foo() + +// Super explicit naming. +OurModule.ChildModule.foo(); // Calls ChildModule.foo() + +use ChildModule; +foo(); // Less explicit call on ChildModule.foo() + +// We can declare a main procedure +// Note: all the code above main still gets executed. +proc main(){ + + // Parallelism + // In other languages, parallelism is typically this is done with + // complicated libraries and strange class structure hierarchies. + // Chapel has it baked right into the language. + + // A begin statement will spin the body of that statement off + // into one new task. + // A sync statement will ensure that the progress of the main + // task will not progress until the children have synced back up. + sync { + begin { // Start of new task's body + var a = 0; + for i in 1..1000 do a += 1; + writeln( "Done: ", a); + } // End of new tasks body + writeln( "spun off a task!"); + } + writeln( "Back together" ); -// Atomic variables, common to many languages, are ones whose operations -// occur uninterupted. Multiple threads can both modify atomic variables -// and can know that their values are safe. -// Chapel atomic variables can be of type bool, int, uint, and real. -var uranium: atomic int; -uranium.write( 238 ); // atomically write a variable -writeln( uranium.read() ); // atomically read a variable - -// operations are described as functions, you could define your own operators. -uranium.sub( 3 ); // atomically subtract a variable -writeln( uranium.read() ); - -var replaceWith = 239; -var was = uranium.exchange( replaceWith ); -writeln( "uranium was ", was, " but is now ", replaceWith ); - -var isEqualTo = 235; -if uranium.compareExchange( isEqualTo, replaceWith ) { - writeln( "uranium was equal to ", isEqualTo, - " so replaced value with ", replaceWith ); -} else { - writeln( "uranium was not equal to ", isEqualTo, - " so value stays the same... whatever it was" ); -} + proc printFibb( n: int ){ + writeln( "fibonacci(",n,") = ", fibonacci( n ) ); + } -sync { - begin { // Reader task - writeln( "Reader: waiting for uranium to be ", isEqualTo ); - uranium.waitFor( isEqualTo ); - writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); + // A cobegin statement will spin each statement of the body into one new task + cobegin { + printFibb( 20 ); // new task + printFibb( 10 ); // new task + printFibb( 5 ); // new task + { + // This is a nested statement body and thus is a single statement + // to the parent statement and is executed by a single task + writeln( "this gets" ); + writeln( "executed as" ); + writeln( "a whole" ); + } } + // Notice here that the prints from each statement may happen in any order. - begin { // Writer task - writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); - countdown( 3 ); - uranium.write( isEqualTo ); + // Coforall loop will create a new task for EACH iteration + var num_tasks = 10; // Number of tasks we want + coforall taskID in 1..#num_tasks { + writeln( "Hello from task# ", taskID ); + } + // Again we see that prints happen in any order. + // NOTE! coforall should be used only for creating tasks! + // Using it to iterating over a structure is very a bad idea! + + // forall loops are another parallel loop, but only create a smaller number + // of tasks, specifically --dataParTasksPerLocale=number of task + forall i in 1..100 { + write( i, ", "); + } + writeln( ); + // Here we see that there are sections that are in order, followed by + // a section that would not follow ( e.g. 1, 2, 3, 7, 8, 9, 4, 5, 6, ). + // This is because each task is taking on a chunk of the range 1..10 + // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens + // in parallel. + // Your results may depend on your machine and configuration + + // For both the forall and coforall loops, the execution of the + // parent task will not continue until all the children sync up. + + // forall loops are particularly useful for parallel iteration over arrays. + // Lets run an experiment to see how much faster a parallel loop is + use Time; // Import the Time module to use Timer objects + var timer: Timer; + var myBigArray: [{1..4000,1..4000}] real; // Large array we will write into + + // Serial Experiment + timer.start( ); // Start timer + for (x,y) in myBigArray.domain { // Serial iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Serial: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); // Clear timer for parallel loop + + // Parallel Experiment + timer.start( ); // start timer + forall (x,y) in myBigArray.domain { // Parallel iteration + myBigArray[x,y] = (x:real) / (y:real); + } + timer.stop( ); // Stop timer + writeln( "Parallel: ", timer.elapsed( ) ); // Print elapsed time + timer.clear( ); + // You may have noticed that (depending on how many cores you have) + // that the parallel loop went faster than the serial loop + + // A succinct way of writing a forall loop over an array: + // iterate over values + [ val in myBigArray ] val = 1 / val; + + // or iterate over indicies + [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + + proc countdown( seconds: int ){ + for i in 1..seconds by -1 { + writeln( i ); + sleep( 1 ); + } } -} -// sync vars have two states: empty and full. -// If you read an empty variable or write a full variable, you are waited -// until the variable is full or empty again -var someSyncVar$: sync int; // varName$ is a convention not a law. -sync { - begin { // Reader task - writeln( "Reader: waiting to read." ); - var read_sync = someSyncVar$; - writeln( "value is ", read_sync ); + // Atomic variables, common to many languages, are ones whose operations + // occur uninterupted. Multiple threads can both modify atomic variables + // and can know that their values are safe. + // Chapel atomic variables can be of type bool, int, uint, and real. + var uranium: atomic int; + uranium.write( 238 ); // atomically write a variable + writeln( uranium.read() ); // atomically read a variable + + // operations are described as functions, you could define your own operators. + uranium.sub( 3 ); // atomically subtract a variable + writeln( uranium.read() ); + + var replaceWith = 239; + var was = uranium.exchange( replaceWith ); + writeln( "uranium was ", was, " but is now ", replaceWith ); + + var isEqualTo = 235; + if uranium.compareExchange( isEqualTo, replaceWith ) { + writeln( "uranium was equal to ", isEqualTo, + " so replaced value with ", replaceWith ); + } else { + writeln( "uranium was not equal to ", isEqualTo, + " so value stays the same... whatever it was" ); } - begin { // Writer task - writeln( "Writer: will write in..." ); - countdown( 3 ); - someSyncVar$ = 123; + sync { + begin { // Reader task + writeln( "Reader: waiting for uranium to be ", isEqualTo ); + uranium.waitFor( isEqualTo ); + writeln( "Reader: uranium was set (by someone) to ", isEqualTo ); + } + + begin { // Writer task + writeln( "Writer: will set uranium to the value ", isEqualTo, " in..." ); + countdown( 3 ); + uranium.write( isEqualTo ); + } } -} -// single vars can only be written once. A read on an unwritten single results -// in a wait, but when the variable has a value it can be read indefinitely -var someSingleVar$: single int; // varName$ is a convention not a law. -sync { - begin { // Reader task - writeln( "Reader: waiting to read." ); - for i in 1..5 { - var read_single = someSingleVar$; - writeln( "Reader: iteration ", i,", and the value is ", read_single ); + // sync vars have two states: empty and full. + // If you read an empty variable or write a full variable, you are waited + // until the variable is full or empty again + var someSyncVar$: sync int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + var read_sync = someSyncVar$; + writeln( "value is ", read_sync ); + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSyncVar$ = 123; } } - begin { // Writer task - writeln( "Writer: will write in..." ); - countdown( 3 ); - someSingleVar$ = 5; // first and only write ever. + // single vars can only be written once. A read on an unwritten single results + // in a wait, but when the variable has a value it can be read indefinitely + var someSingleVar$: single int; // varName$ is a convention not a law. + sync { + begin { // Reader task + writeln( "Reader: waiting to read." ); + for i in 1..5 { + var read_single = someSingleVar$; + writeln( "Reader: iteration ", i,", and the value is ", read_single ); + } + } + + begin { // Writer task + writeln( "Writer: will write in..." ); + countdown( 3 ); + someSingleVar$ = 5; // first and only write ever. + } } -} -// Heres an example of using atomics and a synch variable to create a -// count-down mutex (also known as a multiplexer) -var count: atomic int; // our counter -var lock$: sync bool; // the mutex lock - -count.write( 2 ); // Only let two tasks in at a time. -lock$.writeXF( true ); // Set lock$ to full (unlocked) -// Note: The value doesnt actually matter, just the state -// (full:unlocked / empty:locked) -// Also, writeXF() fills (F) the sync var regardless of its state (X) - -coforall task in 1..#5 { // Generate tasks - // Create a barrier - do{ - lock$; // Read lock$ (wait) - }while count.read() < 1; // Keep waiting until a spot opens up + // Heres an example of using atomics and a synch variable to create a + // count-down mutex (also known as a multiplexer) + var count: atomic int; // our counter + var lock$: sync bool; // the mutex lock + + count.write( 2 ); // Only let two tasks in at a time. + lock$.writeXF( true ); // Set lock$ to full (unlocked) + // Note: The value doesnt actually matter, just the state + // (full:unlocked / empty:locked) + // Also, writeXF() fills (F) the sync var regardless of its state (X) + + coforall task in 1..#5 { // Generate tasks + // Create a barrier + do{ + lock$; // Read lock$ (wait) + }while count.read() < 1; // Keep waiting until a spot opens up - count.sub(1); // decrement the counter - lock$.writeXF( true ); // Set lock$ to full (signal) + count.sub(1); // decrement the counter + lock$.writeXF( true ); // Set lock$ to full (signal) - // Actual 'work' - writeln( "Task #", task, " doing work." ); - sleep( 2 ); + // Actual 'work' + writeln( "Task #", task, " doing work." ); + sleep( 2 ); - count.add( 1 ); // Increment the counter - lock$.writeXF( true ); // Set lock$ to full (signal) -} + count.add( 1 ); // Increment the counter + lock$.writeXF( true ); // Set lock$ to full (signal) + } -// we can define the operations + * & | ^ && || min max minloc maxloc -// over an entire array using scans and reductions -// Reductions apply the operation over the entire array and -// result in a single value -var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; -var sumOfValues = + reduce listOfValues; -var maxValue = max reduce listOfValues; // 'max' give just max value - -// 'maxloc' gives max value and index of the max value -// Note: We have to zip the array and domain together with the zip iterator -var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, - listOfValues.domain); + // we can define the operations + * & | ^ && || min max minloc maxloc + // over an entire array using scans and reductions + // Reductions apply the operation over the entire array and + // result in a single value + var listOfValues: [1..10] int = [15,57,354,36,45,15,456,8,678,2]; + var sumOfValues = + reduce listOfValues; + var maxValue = max reduce listOfValues; // 'max' give just max value + + // 'maxloc' gives max value and index of the max value + // Note: We have to zip the array and domain together with the zip iterator + var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, + listOfValues.domain); -writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); - -// Scans apply the operation incrementally and return an array of the -// value of the operation at that index as it progressed through the -// array from array.domain.low to array.domain.high -var runningSumOfValues = + scan listOfValues; -var maxScan = max scan listOfValues; -writeln( runningSumOfValues ); -writeln( maxScan ); + writeln( (sumOfValues, maxValue, idxOfMax, listOfValues[ idxOfMax ] ) ); + + // Scans apply the operation incrementally and return an array of the + // value of the operation at that index as it progressed through the + // array from array.domain.low to array.domain.high + var runningSumOfValues = + scan listOfValues; + var maxScan = max scan listOfValues; + writeln( runningSumOfValues ); + writeln( maxScan ); +} ``` Who is this tutorial for? -- cgit v1.2.3 From 27cc82076214e68d9d93c90aafe5ae567fe78892 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 15:44:16 -0700 Subject: Uniform tics, noteable arguments addition. Changed all N-tics for preformatted/code text into single tics if that code was sinle line (i.e. bash commands, compiler arguments) Added --main-module, --module-dir to Notable arguments section. Realized that the text was disappering, so changed it to ``. Need to confirm it success. --- chapel.html.markdown | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index d8783728..14bbe9f5 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -968,9 +968,8 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to ### What this tutorial is lacking: - * Modules and standard modules + * Exposition of the standard modules * Multiple Locales (distributed memory system) - * ```proc main(){ ... }``` * Records * Whole/sliced array assignment * Range and domain slicing @@ -994,26 +993,28 @@ Chapel can be built and installed on your average 'nix machine (and cygwin). [Download the latest release version](https://github.com/chapel-lang/chapel/releases/) and its as easy as - 1. ```tar -xvf chapel-1.11.0.tar.gz``` - 2. ```cd chapel-1.11.0``` - 3. ```make``` - 4. ```source util/setchplenv.bash # or .sh or .csh or .fish``` + 1. `tar -xvf chapel-1.11.0.tar.gz` + 2. `cd chapel-1.11.0` + 3. `make` + 4. `source util/setchplenv.bash # or .sh or .csh or .fish` You will need to `source util/setchplenv.EXT` from within the Chapel directory (`$CHPL_HOME`) every time your terminal starts so its suggested that you drop that command in a script that will get executed on startup (like .bashrc). Chapel is easily installed with Brew for OS X - 1. ```brew update``` - 2. ```brew install chapel``` + 1. `brew update` + 2. `brew install chapel` Compiling Code -------------- Builds like other compilers: -```chpl myFile.chpl -o myExe``` +`chpl myFile.chpl -o myExe` Notable arguments: - * ``--fast``: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. - * ```--set =```: set config param to at compile-time + * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. + * `--set =`: set config param `` to `` at compile-time. + * `--main-module `: use the main() procedure found in the module `` as the executable's main. + * `--module-dir `: includes ` Date: Sun, 2 Aug 2015 15:53:19 -0700 Subject: Small corrections. Removed duplicate countDown. Weird leftover words from parallelism statemet General corrections so spelling capitalization --- chapel.html.markdown | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 14bbe9f5..a4bcfb9f 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -683,7 +683,7 @@ module OurModule { // We can use modules inside of other modules. use Time; - // We'll use this a procedure in the parallelism section. + // We'll use this procedure in the parallelism section. proc countdown( seconds: int ){ for i in 1..seconds by -1 { writeln( i ); @@ -691,7 +691,7 @@ module OurModule { } } - // Submodule of Ourmodule + // Submodules of OurModule // It is possible to create arbitrarily deep module nests. module ChildModule { proc foo(){ @@ -726,7 +726,7 @@ foo(); // Less explicit call on ChildModule.foo() proc main(){ // Parallelism - // In other languages, parallelism is typically this is done with + // In other languages, parallelism is typically done with // complicated libraries and strange class structure hierarchies. // Chapel has it baked right into the language. @@ -821,13 +821,6 @@ proc main(){ // or iterate over indicies [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; - proc countdown( seconds: int ){ - for i in 1..seconds by -1 { - writeln( i ); - sleep( 1 ); - } - } - // Atomic variables, common to many languages, are ones whose operations // occur uninterupted. Multiple threads can both modify atomic variables // and can know that their values are safe. -- cgit v1.2.3 From 4f6ae05392504f63b5ddd5c23d81700bf6aa1b7a Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Sun, 2 Aug 2015 16:05:19 -0700 Subject: Small changes no.2 --- chapel.html.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index a4bcfb9f..33bdc21d 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -673,15 +673,14 @@ var copyNewTypeList = new GenericClass( realList, int ); for value in copyNewTypeList do write( value, ", " ); writeln( ); - // Modules are Chapel's way of managing name spaces. // The files containing these modules do not need to be named after the modules -// (as is with Java), but files implicitly name modules. +// (as in Java), but files implicitly name modules. // In this case, this file implicitly names the 'learnchapel' module module OurModule { // We can use modules inside of other modules. - use Time; + use Time; // Time is one of the standard modules. // We'll use this procedure in the parallelism section. proc countdown( seconds: int ){ @@ -947,7 +946,7 @@ proc main(){ var maxScan = max scan listOfValues; writeln( runningSumOfValues ); writeln( maxScan ); -} +} // end main() ``` Who is this tutorial for? @@ -1010,4 +1009,4 @@ Notable arguments: * `--fast`: enables a number of optimizations and disables array bounds checks. Should only enable when application is stable. * `--set =`: set config param `` to `` at compile-time. * `--main-module `: use the main() procedure found in the module `` as the executable's main. - * `--module-dir `: includes ``: includes `` in the module search path. \ No newline at end of file -- cgit v1.2.3 From 496b11f8ce33f38fc1e29c23ee8c4261a811b967 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:47:02 +0700 Subject: scala: consistent style, language correction --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e6638121..12441af9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -16,15 +16,16 @@ Scala - the scalable language Set yourself up: 1) Download Scala - http://www.scala-lang.org/downloads - 2) unzip/untar in your favourite location and put the bin subdir on the path - 3) Start a scala REPL by typing scala. You should see the prompt: + 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 valid - Scala expression into it, 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. + 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. + */ -- cgit v1.2.3 From 9ddf69a14da14c0d29abb5a18b4d2dfd5a39c7b2 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:48:28 +0700 Subject: scala: language correction --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 12441af9..4121dc9b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -5,6 +5,7 @@ contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] filename: learn.scala --- @@ -33,10 +34,10 @@ Scala - the scalable language // 1. Basics ///////////////////////////////////////////////// -// Single line comments start with two forward slashes +// Single-line comments start with two forward slashes /* - Multi line comments, as you can already see from above, look like this. + Multi-line comments, as you can already see from above, look like this. */ // Printing, and forcing a new line on the next print -- cgit v1.2.3 From 8c06438ec9aec991b78bbd49d2343dc820da7669 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:15 +0700 Subject: scala: correct format --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 4121dc9b..03d80043 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) print("Hello world") // Declaring values is done using either var or val. -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -- cgit v1.2.3 From 5b683b34ddb313b8981f360c4a6b54cfbc3af396 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:54 +0700 Subject: scala: easier-to-look comment --- scala.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 03d80043..0bd1a56d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -51,9 +51,9 @@ print("Hello world") // val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 -x = 20 // error: reassignment to val +x = 20 // error: reassignment to val var y = 10 -y = 20 // y is now 20 +y = 20 // y is now 20 /* Scala is a statically typed language, yet note that in the above declarations, @@ -73,17 +73,17 @@ true false // Boolean operations -!true // false -!false // true +!true // false +!false // true true == false // false -10 > 5 // true +10 > 5 // true // Math is as per usual -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 -6 / 4 // 1 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 6.0 / 4 // 1.5 -- cgit v1.2.3 From dbdde5134b4c5777467a81c8fdf2128cb44edacc Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:50:32 +0700 Subject: scala: clearer comments --- scala.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 0bd1a56d..8d93169b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,12 +122,12 @@ s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." -s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" -f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. -- cgit v1.2.3 From efb338608b3b6e5af3652e71aa7fb85bdf5917b9 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:38 +0700 Subject: scala: consistent code format --- scala.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 8d93169b..62af31b6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -173,8 +173,8 @@ def sq(x: Int) = x * x // Compiler can guess return type is Int // Functions can have default parameters: def addWithDefault(x: Int, y: Int = 5) = x + y -addWithDefault(1, 2) // => 3 -addWithDefault(1) // => 6 +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 // Anonymous functions look like this: @@ -195,8 +195,8 @@ sq(10) // => 100 val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) -addOne(5) // => 6 -weirdSum(2, 4) // => 16 +addOne(5) // => 6 +weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most @@ -206,9 +206,9 @@ weirdSum(2, 4) // => 16 def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of foo! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonFunc } anonFunc(x) // This line is the return value of foo } @@ -361,7 +361,7 @@ class Dog(br: String) { val mydog = new Dog("greyhound") println(mydog.breed) // => "greyhound" -println(mydog.bark) // => "Woof, woof!" +println(mydog.bark) // => "Woof, woof!" // The "object" keyword creates a type AND a singleton instance of it. It is @@ -543,8 +543,8 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) // By itself, implicit keyword doesn't change the behavior of the value, so // above values can be used as usual. -myImplicitInt + 2 // => 102 -myImplicitFunction("Pitbull").breed // => "Golden Pitbull" +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" // The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit @@ -572,8 +572,8 @@ def foo[T : C] = ... // implicit conversion of type A => B, where A is the type of obj, and B has a // method called "method", that conversion is applied. So having // myImplicitFunction above in scope, we can say: -"Retriever".breed // => "Golden Retriever" -"Sheperd".bark // => "Woof, woof!" +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" // Here the String is first converted to Dog using our function above, and then // the appropriate method is called. This is an extremely powerful feature, but -- cgit v1.2.3 From 7c02089687eaee9c1fe9b1db3ab0674153077f56 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:59 +0700 Subject: scala: consistent code format --- scala.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 62af31b6..35042ebe 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -220,19 +220,19 @@ def foo(x: Int): Int = { 1 to 5 val r = 1 to 5 -r.foreach( println ) +r.foreach(println) r foreach println // NB: Scala is quite lenient when it comes to dots and brackets - study the // rules separately. This helps write DSLs and APIs that read like English -(5 to 1 by -1) foreach ( println ) +(5 to 1 by -1) foreach (println) // A while loops var i = 0 -while (i < 10) { println("i " + i); i+=1 } +while (i < 10) { println("i " + i); i += 1 } -while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? +while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why? i // Show the value of i. Note that while is a loop in the classical sense - // it executes sequentially while changing the loop variable. while is very @@ -241,19 +241,19 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10") x += 1 } while (x < 10) // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. -def showNumbersInRange(a:Int, b:Int):Unit = { +def showNumbersInRange(a:Int, b:Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } -showNumbersInRange(1,14) +showNumbersInRange(1, 14) // Conditionals @@ -307,13 +307,13 @@ s(1) (a, 2, "three") // Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) +val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10,3) // The function divideInts gives you the result and the remainder +divideInts(10, 3) // The function divideInts gives you the result and the remainder // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10,3) +val d = divideInts(10, 3) d._1 @@ -416,8 +416,8 @@ val otherGeorge = george.copy(phoneNumber = "9876") def matchPerson(person: Person): String = person match { // Then you specify the patterns: case Person("George", number) => "We found George! His number is " + number - case Person("Kate", number) => "We found Kate! Her number is " + number - case Person(name, number) => "We matched someone : " + name + ", phone : " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } val email = "(.*)@(.*)".r // Define a regex for the next example. @@ -448,7 +448,7 @@ def matchEverything(obj: Any): String = obj match { case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" // You can nest patterns: - case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } // In fact, you can pattern match any object with an "unapply" method. This @@ -495,7 +495,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, age:Int) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -596,7 +596,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable.{ List => ImmutableList } +import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From 513235c4754f87e64e5d564bb53ec643ce9333df Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:56:11 +0700 Subject: scala: clearer further resources (itemized) --- scala.html.markdown | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 35042ebe..10db5f78 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -631,13 +631,8 @@ writer.close() ## Further resources -[Scala for the impatient](http://horstmann.com/scala/) - -[Twitter Scala school](http://twitter.github.io/scala_school/) - -[The scala documentation](http://docs.scala-lang.org/) - -[Try Scala in your browser](http://scalatutorials.com/tour/) - -Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) - +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From d61ad107759c99de3dd32dc848086c16dbb14f15 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:58:36 +0700 Subject: scala: consistent code format --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 10db5f78..c482752d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -178,7 +178,7 @@ addWithDefault(1) // => 6 // Anonymous functions look like this: -(x:Int) => x * x +(x: Int) => x * x // Unlike defs, even the input type of anonymous functions can be omitted if the // context makes it clear. Notice the type "Int => Int" which means a function @@ -248,7 +248,7 @@ do { // Tail recursion is an idiomatic way of doing recurring things in Scala. // Recursive functions need an explicit return type, the compiler can't infer it. // Here it's Unit. -def showNumbersInRange(a:Int, b:Int): Unit = { +def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) -- cgit v1.2.3 From c4558c47eaf08d7a1d22789f1b0a38c23260fd18 Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:05:22 -0400 Subject: Println deprecated in Swift 2 --- swift.html.markdown | 56 +++++++++++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index ffc57e69..8e83a0b3 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,7 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -println("Hello, world") +// In Swift 2, println and print were combined into one print method. +print("Hello, world") // standard print +print("Hello, world", appendNewLine: true) // appending a new line // variables (var) value can change after being set // constants (let) value can NOT be changed after being set @@ -46,12 +48,12 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // String interpolation // Build Specific values // uses -D build configuration #if false - println("Not printed") + print("Not printed") let buildValue = 3 #else let buildValue = 7 #endif -println("Build value: \(buildValue)") // Build value: 7 +print("Build value: \(buildValue)") // Build value: 7 /* Optionals are a Swift language feature that allows you to store a `Some` or @@ -69,7 +71,7 @@ var someOptionalString2: Optional = "optional" if someOptionalString != nil { // I am not nil if someOptionalString!.hasPrefix("opt") { - println("has the prefix") + print("has the prefix") } let empty = someOptionalString?.isEmpty @@ -138,21 +140,21 @@ var emptyMutableDictionary = [String: Float]() // var == mutable let myArray = [1, 1, 2, 3, 5] for value in myArray { if value == 1 { - println("One!") + print("One!") } else { - println("Not one!") + print("Not one!") } } // for loop (dictionary) var dict = ["one": 1, "two": 2] for (key, value) in dict { - println("\(key): \(value)") + print("\(key): \(value)") } // for loop (range) for i in -1...shoppingList.count { - println(i) + print(i) } shoppingList[1...2] = ["steak", "peacons"] // use ..< to exclude the last number @@ -165,7 +167,7 @@ while i < 1000 { // do-while loop do { - println("hello") + print("hello") } while 1 == 2 // Switch @@ -222,8 +224,8 @@ let pricesTuple = getGasPrices() let price = pricesTuple.2 // 3.79 // Ignore Tuple (or other) values by using _ (underscore) let (_, price1, _) = pricesTuple // price1 == 3.69 -println(price1 == pricesTuple.1) // true -println("Gas price: \(price)") +print(price1 == pricesTuple.1) // true +print("Gas price: \(price)") // Variadic Args func setup(numbers: Int...) { @@ -251,7 +253,7 @@ func swapTwoInts(inout a: Int, inout b: Int) { var someIntA = 7 var someIntB = 3 swapTwoInts(&someIntA, &someIntB) -println(someIntB) // 7 +print(someIntB) // 7 // @@ -305,7 +307,7 @@ struct NamesTable { // Structures have an auto-generated (implicit) designated initializer let namesTable = NamesTable(names: ["Me", "Them"]) let name = namesTable[1] -println("Name is \(name)") // Name is Them +print("Name is \(name)") // Name is Them // // MARK: Classes @@ -386,7 +388,7 @@ let aShape = mySquare as Shape // compare instances, not the same as == which compares objects (equal to) if mySquare === mySquare { - println("Yep, it's mySquare") + print("Yep, it's mySquare") } // Optional init @@ -409,13 +411,13 @@ class Circle: Shape { } var myCircle = Circle(radius: 1) -println(myCircle?.getArea()) // Optional(3) -println(myCircle!.getArea()) // 3 +print(myCircle?.getArea()) // Optional(3) +print(myCircle!.getArea()) // 3 var myEmptyCircle = Circle(radius: -1) -println(myEmptyCircle?.getArea()) // "nil" +print(myEmptyCircle?.getArea()) // "nil" if let circle = myEmptyCircle { // will not execute since myEmptyCircle is nil - println("circle is not nil") + print("circle is not nil") } @@ -447,7 +449,7 @@ enum BookName: String { case John = "John" case Luke = "Luke" } -println("Name: \(BookName.John.rawValue)") +print("Name: \(BookName.John.rawValue)") // Enum with associated Values enum Furniture { @@ -467,9 +469,9 @@ enum Furniture { } var desk: Furniture = .Desk(height: 80) -println(desk.description()) // "Desk with 80 cm" +print(desk.description()) // "Desk with 80 cm" var chair = Furniture.Chair("Foo", 40) -println(chair.description()) // "Chair of Foo with 40 cm" +print(chair.description()) // "Chair of Foo with 40 cm" // @@ -522,7 +524,7 @@ extension Square: Printable { } } -println("Square: \(mySquare)") +print("Square: \(mySquare)") // You can also extend built-in types extension Int { @@ -535,8 +537,8 @@ extension Int { } } -println(7.customProperty) // "This is 7" -println(14.multiplyBy(3)) // 42 +print(7.customProperty) // "This is 7" +print(14.multiplyBy(3)) // 42 // Generics: Similar to Java and C#. Use the `where` keyword to specify the // requirements of the generics. @@ -550,7 +552,7 @@ func findIndex(array: [T], valueToFind: T) -> Int? { return nil } let foundAtIndex = findIndex([1, 2, 3, 4], 3) -println(foundAtIndex == 2) // true +print(foundAtIndex == 2) // true // Operators: // Custom operators can start with the characters: @@ -566,9 +568,9 @@ prefix func !!! (inout shape: Square) -> Square { } // current value -println(mySquare.sideLength) // 4 +print(mySquare.sideLength) // 4 // change side length using custom !!! operator, increases size by 3 !!!mySquare -println(mySquare.sideLength) // 12 +print(mySquare.sideLength) // 12 ``` -- cgit v1.2.3 From 775ac3b8595f80dd3229b7974672cf71d642d94f Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:10:10 -0400 Subject: Updated print description on Swift --- swift.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/swift.html.markdown b/swift.html.markdown index 8e83a0b3..5ea8da6b 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -26,9 +26,9 @@ import UIKit // TODO: Do something soon // FIXME: Fix this code -// In Swift 2, println and print were combined into one print method. -print("Hello, world") // standard print -print("Hello, world", appendNewLine: true) // appending a new line +// In Swift 2, println and print were combined into one print method. Print automatically appends a new line. +print("Hello, world") // println is now print +print("Hello, world", appendNewLine: false) // printing without appending a newline // variables (var) value can change after being set // constants (let) value can NOT be changed after being set -- cgit v1.2.3 From d17d41a02b5eb67b0b28a9708cfa5640e17325ef Mon Sep 17 00:00:00 2001 From: Anthony Nguyen Date: Mon, 3 Aug 2015 23:11:44 -0400 Subject: Println deprecated in Swift 2, added name --- swift.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/swift.html.markdown b/swift.html.markdown index 5ea8da6b..509c9d2f 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Grant Timmerman", "http://github.com/grant"] - ["Christopher Bess", "http://github.com/cbess"] - ["Joey Huang", "http://github.com/kamidox"] + - ["Anthony Nguyen", "http://github.com/anthonyn60"] filename: learnswift.swift --- -- cgit v1.2.3 From f27ed65af631279845b9871635e2118eba863ea1 Mon Sep 17 00:00:00 2001 From: billpcs Date: Wed, 5 Aug 2015 16:40:37 +0300 Subject: added the translations --- el-gr/racket-gr.html.markdown | 746 ++++++++++++++++++++++++++++++++++++++++++ el-gr/scala-gr.html.markdown | 690 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 1436 insertions(+) create mode 100644 el-gr/racket-gr.html.markdown create mode 100644 el-gr/scala-gr.html.markdown diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown new file mode 100644 index 00000000..6a3f99ef --- /dev/null +++ b/el-gr/racket-gr.html.markdown @@ -0,0 +1,746 @@ +---σ +language: racket +filename: learnracket.rkt +contributors: + - ["th3rac25", "https://github.com/voila"] + - ["Eli Barzilay", "https://github.com/elibarzilay"] + - ["Gustavo Schmidt", "https://github.com/gustavoschmidt"] + - ["Duong H. Nguyen", "https://github.com/cmpitg"] + - ["Keyan Zhang", "https://github.com/keyanzhang"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +--- + +Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. + +Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3rac25) or th3rac25 [at] [google's email service] + + +```racket +#lang racket ; ορίζει την γλώσσα που χρησιμοποιόυμε + +;;; Σχόλια + +;; Τα σχόλια μιας γραμμής ξεκινούν με ερωτηματικό + +#| Τα σχόλια ολόκληρου μπλόκ + μπορούν να εκτείνονται σε πολλές γραμμές και... + #| + μπορούν να είναι εμφωλευμένα! + |# +|# + +;; Τα σχόλια S-expression (εκφράσεις S) comments απορρίπτουν την +;; έκφραση που ακολουθεί, δυνατότητα που είναι χρήσιμη για να +;; κάνουμε σχόλια κάποιες εκφράσεις κατα τη διάρκεια του debugging + +#; (αυτή η έκφραση δεν θα εκτελεστεί) + +;; (Αν δεν καταλαβαίνεται τι είναι οι εκφράσεις , περιμένετε... Θα το μάθουμε +;; πολύ συντομα!) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 1. Πρωτογενείς τύποι μεταβλητών και τελεστές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Αριθμοί +9999999999999999999999 ; ακέραιοι +#b111 ; δυαδικοί => 7 +#o111 ; οκταδικοί => 73 +#x111 ; δεκαεξαδικοί => 273 +3.14 ; πραγματικοί +6.02e+23 +1/2 ; ρητοί +1+2i ; μιγαδικοί + +;; Οι μορφή των συναρτήσεων είναι (f x y z) +;; όπου το f είναι η συνάρτηση και τα x y z +;; είναι οι όροι που η συνάρτηση δέχεται +;; ως ορίσματα. Αν θέλουμε να δημιουργήσουμε +;; μια λίστα στην κυριολεξία απο δίαφορα δεδομένα, +;; χρησιμοποιούμε το ' για να το εμποδίσουμε απο το να +;; αξιολογηθεί σαν έκφραση. Για παράδειγμα: +'(+ 1 2) ; => Παραμένει (+ 1 2) και δεν γίνεται η πράξη +;; Τώρα , ας κάνουμε μερικές πράξεις +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(quotient 5 2) ; => 2 +(remainder 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(exact->inexact 1/3) ; => 0.3333333333333333 +(+ 1+2i 2-3i) ; => 3-1i + +;;; Λογικές μεταβλητές +#t ; για το true +#f ; για το false +(not #t) ; => #f +(and 0 #f (error "doesn't get here")) ; => #f +(or #f 0 (error "doesn't get here")) ; => 0 + +;;; Χαρακτήρες +#\A ; => #\A +#\λ ; => #\λ +#\u03BB ; => #\λ + +;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής +"Foo\tbar\41\x21\u0021\a\r\n" ; συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, + ; σε Unicode +"λx:(μα.α→α).xx" ; μπορούν να υπάρχουν και Unicode χαρακτήρες + +;; Μπορούμε να εννώσουμε αλφαριθμητικά! +(string-append "Hello " "world!") ; => "Hello world!" + +;; Ένα αλφαριθμητικό μπορούμε να το χρησιμοπιησουμε +;; όπως και μια λίστα απο χαρακτήρες +(string-ref "Apple" 0) ; => #\A ;; Παίρνουμε το πρώτο στοιχείο + +;; Η συνάρτηση format μπορεί να χρησιμοποιηθεί για +;; να μορφοποιήσουμε αλφαριθμητικά +(format "~a can be ~a" "strings" "formatted") ;; => "strings can be formatted" + +;; Η εκτύπωση είναι εύκολη. +(printf "I'm Racket. Nice to meet you!\n") + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 2. Μεταβλητές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; You can create a variable using define +;; a variable name can use any character except: ()[]{}",'`;#|\ +(define some-var 5) +some-var ; => 5 + +;; You can also use unicode characters +(define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? + ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. +(⊆ (set 3 2) (set 1 2 3)) ; => #t + +;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ +(printf name) +;; θα πάρουμε το παρακάτω μήνυμα +;name: undefined; +; cannot reference undefined identifier +; context...: + +;; Η τοπική δέσμευση : `me' δευσμεύεται με το "Bob" μόνο μέσα στο (let ...) +(let ([me "Bob"]) + "Alice" + me) ; => "Bob" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Δομές και συλλογές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δομές +(struct dog (name breed age)) +(define my-pet + (dog "lassie" "collie" 5)) +my-pet ; => # +(dog? my-pet) ; => #t +(dog-name my-pet) ; => "lassie" + +;;; Ζεύγη (αμετάβλητα) +;; Η δεσμευμένη λέξη `cons' δημιουργεί ζεύγη, +;; και το `car' και το `cdr' εξάγουν το πρώτο και +;; το δεύτερο στοιχείο αντίστοιχα. +(cons 1 2) ; => '(1 . 2) +(car (cons 1 2)) ; => 1 +(cdr (cons 1 2)) ; => 2 + +;;; Λίστες + +;; Οι λίστες είναι linked-list δομές δεδομένων, +;; που έχουν δημιουργηθεί απο ζευγάρια 'cons' +;; και τελειώνουν με 'null' (ή αλλιώς '()) για να +;; δηλώσουν ότι αυτό είναι το τέλος της λίστας +(cons 1 (cons 2 (cons 3 null))) ; => '(1 2 3) +;; Η δεσμευμένη λέξη 'list' είναι ένας εναλλακτικός +;; (και σαφώς πιο βολικός) τρόπος για να δημιουργούμε +;; λίστες +(list 1 2 3) ; => '(1 2 3) +;; αλλά και χρησιμοποιώντας ένα μονό εισαγωγικό το +;; το αποτέλεσμα είναι και πάλι το ίδιο +'(1 2 3) ; => '(1 2 3) + +;; Μπορούμε και πάλι όμως να χρησιμοποιούμε το 'cons' για να +;; προσθέσουμε ένα στοιχείο στην αρχή της λίστας +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;; Μπορούμε να χρησιμοποιούμε το 'append' για να προσθέτουμε +;; στοιχεία στο τέλος μιας λίστας. Το στοιχείο αυτό μπορεί +;; και να είναι ολόκληρη λίστα! +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;; Οι λίστες στην Racket είναι πολύ βασικές , οπότε υπάρχουν πολλές +;; δυνατές λειτουργίες για αυτές. Παρακάτω είναι μερικά παραδείγματα: +(map add1 '(1 2 3)) ; => '(2 3 4) +(map + '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(filter even? '(1 2 3 4)) ; => '(2 4) +(count even? '(1 2 3 4)) ; => 2 +(take '(1 2 3 4) 2) ; => '(1 2) +(drop '(1 2 3 4) 2) ; => '(3 4) + +;;; Διανύσματα + +;; Τα διανύσματα είναι πίνακες σταθερού μήκους +#(1 2 3) ; => '#(1 2 3) + +;; Χρησιμοποιύμε το `vector-append' για να προσθέσουμε διανύσματα +(vector-append #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + +;;; Σύνολα + +;; Δημιουργούμε ένα σύνολο απο μία λίστα +(list->set '(1 2 3 1 2 3 3 2 1 3 2 1)) ; => (set 1 2 3) + +;; Προσθέτουμε έναν αριθμό στο σύνολο χρησιμοποιώντας το `set-add' +(set-add (set 1 2 3) 4) ; => (set 1 2 3 4) + +;; Αφαιρούμε με το `set-remove' +(set-remove (set 1 2 3) 1) ; => (set 2 3) + +;; Βλέπουμε αν υπάρχει ένας αριθμός στο σύνολο με το `set-member?' +(set-member? (set 1 2 3) 1) ; => #t +(set-member? (set 1 2 3) 4) ; => #f + +;;; Πίνακες κατακερματισμού + +;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού +(define m (hash 'a 1 'b 2 'c 3)) + +;; Παίρνουμε μια τιμή απο τον πίνακα +(hash-ref m 'a) ; => 1 + +;; Άν ζητήσουμε μια τιμή που δέν υπάρχει παίρνουμε μία εξαίρεση +; (hash-ref m 'd) => no value found for key + +;; Μπορούμε να δώσουμε μια default τιμή για τα κλειδιά που λείπουν +(hash-ref m 'd 0) ; => 0 + + +;; Χρησιμοποιούμε το 'hash-set' για να επεκτείνουμε +;; ένα πίνακα κατακερματισμού +(define m2 (hash-set m 'd 4)) +m2 ; => '#hash((b . 2) (a . 1) (d . 4) (c . 3)) + +;; Θυμηθείτε ! Αυτοί οι πίνακες κατακερματισμού +;; είναι αμετάβλητοι! +m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' + +;; Χρησιμοποιούμε το `hash-remove' για να αφαιρέσουμε +;; κλειδία +(hash-remove m 'a) ; => '#hash((b . 2) (c . 3)) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 3. Συναρτήσεις +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το `lambda' για να δημιουργήσουμε συναρτήσεις. +;; Μια συνάρτηση πάντα επιστρέφει την τιμή της τελευταίας της έκφρασης +(lambda () "Hello World") ; => # +;; Μπορούμε επίσης να χρησιμοποιήσουμε το `λ' +(λ () "Hello World") ; => Ίδια συνάρτηση + +;; Χρησιμοποιύμε τις παρενθέσεις για να καλέσουμε όλες τις συναρτήσεις +;; συμπεριλαμβανομένων και των εκφράσεων 'λάμδα' +((lambda () "Hello World")) ; => "Hello World" +((λ () "Hello World")) ; => "Hello World" + +;; Εκχωρούμε σε μια μετάβλητη την συνάρτηση +(define hello-world (lambda () "Hello World")) +(hello-world) ; => "Hello World" + +;; Μπορούμε αυτό να το κάνουμε συντομότερο χρησιμοποιώντας +;; το λεγόμενο syntactic sugar : +(define (hello-world2) "Hello World") + +;; Το () στο παραπάνω είναι η λίστα από τα ορίσματα για την συνάρτηση + +(define hello + (lambda (name) + (string-append "Hello " name))) +(hello "Steve") ; => "Hello Steve" +;; ... ή ισοδύναμα, χρησιμοποιώντας sugared ορισμό: +(define (hello2 name) + (string-append "Hello " name)) + +;; Μπορούμε να έχουμε συναρτήσεις με πολλές μεταβλητές χρησιμοποιώντας +;; το `case-lambda' +(define hello3 + (case-lambda + [() "Hello World"] + [(name) (string-append "Hello " name)])) +(hello3 "Jake") ; => "Hello Jake" +(hello3) ; => "Hello World" +;; ... ή να ορίσουμε προαιρετικά ορίσματα με μια έκφραση προκαθορισμένης τιμής +(define (hello4 [name "World"]) + (string-append "Hello " name)) + +;; Οι συναρτήσεις μπορούν να πακετάρουν επιπλέον +;; ορίσματα μέσα σε μια λίστα +(define (count-args . args) + (format "You passed ~a args: ~a" (length args) args)) +(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)" +;; ... ή με unsugared μορφή `lambda': +(define count-args2 + (lambda args + (format "You passed ~a args: ~a" (length args) args))) + +;; Μπορούμε να εμπλέξουμε κανονικά και πακεταρισμένα ορίσματα +(define (hello-count name . args) + (format "Hello ~a, you passed ~a extra args" name (length args))) +(hello-count "Finn" 1 2 3) +; => "Hello Finn, you passed 3 extra args" +;; ... και unsugared: +(define hello-count2 + (lambda (name . args) + (format "Hello ~a, you passed ~a extra args" name (length args)))) + +;; Και με λέξεις κλειδία +(define (hello-k #:name [name "World"] #:greeting [g "Hello"] . args) + (format "~a ~a, ~a extra args" g name (length args))) +(hello-k) ; => "Hello World, 0 extra args" +(hello-k 1 2 3) ; => "Hello World, 3 extra args" +(hello-k #:greeting "Hi") ; => "Hi World, 0 extra args" +(hello-k #:name "Finn" #:greeting "Hey") ; => "Hey Finn, 0 extra args" +(hello-k 1 2 3 #:greeting "Hi" #:name "Finn" 4 5 6) + ; => "Hi Finn, 6 extra args" + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 4. Ισότητα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; για αριθμούς χρησιμοποιούμε το `=' +(= 3 3.0) ; => #t +(= 2 1) ; => #f + +;; Το `eq?' επιστρέφει #t αν δύο 2 ορίσματα αναφέρονται στο +;; ίδιο αντικείμενο (στη μνήμη),αλλιώς επιστρέφει #f. +;; Με άλλα λόγια, είναι απλή σύγκριση δεικτών. +(eq? '() '()) ; => #t, αφού υπάρχει μόνο μια άδεια λίστα στη μνήμη +(let ([x '()] [y '()]) + (eq? x y)) ; => #t, το ίδιο με πάνω + +(eq? (list 3) (list 3)) ; => #f +(let ([x (list 3)] [y (list 3)]) + (eq? x y)) ; => #f — δεν είναι η ίδια λίστα στην μνήμη! + +(let* ([x (list 3)] [y x]) + (eq? x y)) ; => #t, Αφού το x και το y τώρα δείχνουν στην ίδια θέση + +(eq? 'yes 'yes) ; => #t +(eq? 'yes 'no) ; => #f + +(eq? 3 3) ; => #t — να είστε προσεκτικοί εδώ + ; Είναι προτιμότερο να χρησιμοποιείτε `=' για την + ; σύγκριση αριθμών. +(eq? 3 3.0) ; => #f + +(eq? (expt 2 100) (expt 2 100)) ; => #f +(eq? (integer->char 955) (integer->char 955)) ; => #f + +(eq? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `eqv?' υποστηρίζει την σύκριση αριθμών αλλα και χαρακτήρων +;; Για άλλα ήδη μεταβλητών το `eqv?' και το `eq?' επιστρέφουν το ίδιο. +(eqv? 3 3.0) ; => #f +(eqv? (expt 2 100) (expt 2 100)) ; => #t +(eqv? (integer->char 955) (integer->char 955)) ; => #t + +(eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f + +;; Το `equal?' υποστηρίζει την σύγκριση των παρακάτω τύπων μεταβλητών: +;; `equal?' supports the comparison of the following datatypes: +;; αλφαριθμητικά, αλφαριθμητικά από bytes, μεταβλητά ζεύγη , διανύσματα, +;; πίνακες κατακερματισμού και δομές. +;; Για άλλα ήδη τύπων μεταβλητών το `equal?' και το `eqv?' επιστρέφουν το +;; ίδιο αποτέλεσμα. +(equal? 3 3.0) ; => #f +(equal? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #t +(equal? (list 3) (list 3)) ; => #t + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 5. Έλεχγος Ροής +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;;; Συνθήκες (conditionals) + +(if #t ; έκφραση ελέχγου + "this is true" ; έκφραση then + "this is false") ; έκφραση else +; => "this is true" + + +;; Στα conditionals, όλες οι μη #f τιμές θεωρούνται ως #t +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(Groucho Zeppo) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'yep + +;; Οι αλυσίδες `cond' είναι σειρές από ελέγχους για να +;; επιλεγεί ένα αποτέλεσμα +(cond [(> 2 2) (error "wrong!")] + [(< 2 2) (error "wrong again!")] + [else 'ok]) ; => 'ok + +;;; Αντιστοίχιση μοτίβων + +(define (fizzbuzz? n) + (match (list (remainder n 3) (remainder n 5)) + [(list 0 0) 'fizzbuzz] + [(list 0 _) 'fizz] + [(list _ 0) 'buzz] + [_ #f])) + +(fizzbuzz? 15) ; => 'fizzbuzz +(fizzbuzz? 37) ; => #f + +;;; Βρόχοι + +;; Οι επαναλήψεις μπορούν να γίνουν μέσω αναδρομής +(define (loop i) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) +(loop 5) ; => i=5, i=6, ... + +;; Παρομοίως με τη χρήση 'let' +(let loop ((i 0)) + (when (< i 10) + (printf "i=~a\n" i) + (loop (add1 i)))) ; => i=0, i=1, ... + + +;; Θα δείτε παρακάτω πως να προσθέσουμε μια νέα μορφή επανάληψης +;; αλλά η Racket έχει ήδη πολύ ευέλικτη μορφή για τους βρόχους +(for ([i 10]) + (printf "i=~a\n" i)) ; => i=0, i=1, ... +(for ([i (in-range 5 10)]) + (printf "i=~a\n" i)) ; => i=5, i=6, ... + +;;; +;;; Επανάληψη μέσα σε ακολουθίες: +;; Το `for' επιτρέπει την επενάληψη μέσα σε πολλά +;; άλλα ήδη από ακολουθίες: Λίστες, διανύσματα, +;; αλφαριθμητικά, σύνολα κτλ.. + +;;allows iteration over many other kinds of sequences: +;; lists, vectors, strings, sets, hash tables, etc... + +(for ([i (in-list '(l i s t))]) + (displayln i)) + +(for ([i (in-vector #(v e c t o r))]) + (displayln i)) + +(for ([i (in-string "string")]) + (displayln i)) + +(for ([i (in-set (set 'x 'y 'z))]) + (displayln i)) + +(for ([(k v) (in-hash (hash 'a 1 'b 2 'c 3 ))]) + (printf "key:~a value:~a\n" k v)) + +;;; Πιο περίπλοκες επαναλήψεις + +;; Παράλληλη σάρωση σε πολλαπλές ακολουθίες +;; (σταματά στην πιο σύντομη) +(for ([i 10] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x 1:y 2:z + +;; Εμφολευμένοι βρόχοι +(for* ([i 2] [j '(x y z)]) (printf "~a:~a\n" i j)) +; => 0:x, 0:y, 0:z, 1:x, 1:y, 1:z + +;; Συνθήκες +(for ([i 1000] + #:when (> i 5) + #:unless (odd? i) + #:break (> i 10)) + (printf "i=~a\n" i)) +; => i=6, i=8, i=10 + +;;; Σάρωση σε λίστες +;; Παρόμοιο με τους βρόχους 'for', απλά συλλέγουμε τα αποτελέσματα + +(for/list ([i '(1 2 3)]) + (add1 i)) ; => '(2 3 4) + +(for/list ([i '(1 2 3)] #:when (even? i)) + i) ; => '(2) + +(for/list ([i 10] [j '(x y z)]) + (list i j)) ; => '((0 x) (1 y) (2 z)) + +(for/list ([i 1000] #:when (> i 5) #:unless (odd? i) #:break (> i 10)) + i) ; => '(6 8 10) + +(for/hash ([i '(1 2 3)]) + (values i (number->string i))) +; => '#hash((1 . "1") (2 . "2") (3 . "3")) + +;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε +;; τιμές από τους βρόχους +(for/sum ([i 10]) (* i i)) ; => 285 +(for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 +(for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t +(for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t +;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιύμε +;; το 'for/fold' +(for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 +;; Αυτό συχνά μπορεί να αντικαταστήσει τους κοινούς +;; προστακτικούς βρόχους (imperative loops) + +;;; Εξαιρέσεις + +;; Για να πιάσουμε τις εξαιρέσεις χρησιμοποιούμε το +;; `with-handlers' +(with-handlers ([exn:fail? (lambda (exn) 999)]) + (+ 1 "2")) ; => 999 +(with-handlers ([exn:break? (lambda (exn) "no time")]) + (sleep 3) + "phew") ; => "phew", αλλά αν γίνει το break => "no time" + +;; Χρησιμοποιούμε το 'raise' για να άρουμε μια εξαίρεση +;; ή οποιαδήποτε άλλη τιμή +(with-handlers ([number? ; πιάνουμε αριθμητικές τιμές + identity]) ; και τις επιστρέφουμε σαν απλές τιμές + (+ 1 (raise 2))) ; => 2 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 6. Αλλαγή τιμών +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Χρησιμοποιούμε το 'set!' για να θέσουμε μια νέα τιμή +;; σε μια ήδη υπάρχουσα μεταβλητή +(define n 5) +(set! n (add1 n)) +n ; => 6 + +;; Χρησιμοποιούμε τα boxes για να δηλώσουμε ρητά ότι μια μεταβητή +;; θα είναι mutable (θα μπορεί να αλλάξη η τιμή της) +;; Αυτό είναι παρόμοιο με τους pointers σε άλλες γλώσσες +(define n* (box 5)) +(set-box! n* (add1 (unbox n*))) +(unbox n*) ; => 6 + + +;; Πολλοί τύποι μεταβλητών στη Racket είναι αμετάβλητοι πχ τα ζεύγη, οι +;; λίστες κτλ. Άλλοι υπάρχουν και σε μεταβλητή και σε αμετάβλητη μορφή +;; πχ αλφαριθμητικά, διανύσματα κτλ +(define vec (vector 2 2 3 4)) +(define wall (make-vector 100 'bottle-of-beer)) +;; Χρησιμοποιούμε το 'vector-set!' για να ανεώσουμε κάποια +;; συγκεκριμένη θέση +(vector-set! vec 0 1) +(vector-set! wall 99 'down) +vec ; => #(1 2 3 4) + + +;; Έτσι δημιουργούμε ένα άδειο μεταβλητό πίνακα κατακερματισμού +;; και τον χειριζόμαστε κατάλληλα +(define m3 (make-hash)) +(hash-set! m3 'a 1) +(hash-set! m3 'b 2) +(hash-set! m3 'c 3) +(hash-ref m3 'a) ; => 1 +(hash-ref m3 'd 0) ; => 0 +(hash-remove! m3 'a) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 7. Ενότητες (modules) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + + +;; Οι ενότητες μας επιτρέπουν να οργανώνουμε τον κώδικα σε πολλαπλά +;; αρχεία και επαναχρησιμοποιούμενες βιβλιοθήκες +;; Εδώ χρησιμοποιούμε υπο-ενότητες, εμφωλευμένες μέσα σε μια +;; άλλη ενότητα που δημιουργεί αυτό το κείμενο(ξεκινώντας από +;; την γραμμή '#lang' ) +(module cake racket/base ; ορίζουμε μια ενότητα 'cake' βασισμένο στο + ; racket/base + + (provide print-cake) ; συνάρτηση που εξάγεται από την ενότητα + + (define (print-cake n) + (show " ~a " n #\.) + (show " .-~a-. " n #\|) + (show " | ~a | " n #\space) + (show "---~a---" n #\-)) + + (define (show fmt n ch) ; εσωτερική συνάρτηση + (printf fmt (make-string n ch)) + (newline))) + +;; Χρησιμοποιομε το 'require' για να πάρουμε όλα τα +;; παρεχόμενα ονόματα από μία ενότητα +(require 'cake) ; το ' είναι για τοπική υποενότητα +(print-cake 3) +; (show "~a" 1 #\A) ; => error, το `show' δεν έχει εξαχθεί + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 8. Κλάσεις και αντικείμενα +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Δημιουργούμε μια κλάση fish% (- συνήθως χρησιμοποιούμε +;; το % στο όνομα μιας κλάσης ) +(define fish% + (class object% + (init size) ; initialization argument + (super-new) ; superclass initialization + ;; Field + (define current-size size) + ;; Public methods + (define/public (get-size) + current-size) + (define/public (grow amt) + (set! current-size (+ amt current-size))) + (define/public (eat other-fish) + (grow (send other-fish get-size))))) + +;; Δημιουργούμε ένα instance του fish% +(define charlie + (new fish% [size 10])) + +;; Χρησιμοποιούμε το 'send' για να καλέσουμε +;; τις μεθόδους ενός αντικειμένου +(send charlie get-size) ; => 10 +(send charlie grow 6) +(send charlie get-size) ; => 16 + +;; Το `fish%' είναι μία τιμή "πρώτης κλάσης" +;; `fish%' is a plain "first class" value, με το οποίο μπορούμε να +;; κάνουμε προσμείξεις +(define (add-color c%) + (class c% + (init color) + (super-new) + (define my-color color) + (define/public (get-color) my-color))) +(define colored-fish% (add-color fish%)) +(define charlie2 (new colored-fish% [size 10] [color 'red])) +(send charlie2 get-color) +;; ή χωρίς καθόλου ονόματα : +(send (new (add-color fish%) [size 10] [color 'red]) get-color) + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 9. Μακροεντολές +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Οι μακροεντολές μας επιτρέπουν να επεκτείνουμε +;; το συντακτικό μιάς γλώσσας. + +;; Ας προσθέσουμε έναν βρόχο while +(define-syntax-rule (while condition body ...) + (let loop () + (when condition + body ... + (loop)))) + +(let ([i 0]) + (while (< i 10) + (displayln i) + (set! i (add1 i)))) + +;; Macros are hygienic, you cannot clobber existing variables! +(define-syntax-rule (swap! x y) ; -! is idiomatic for mutation + (let ([tmp x]) + (set! x y) + (set! y tmp))) + +(define tmp 2) +(define other 3) +(swap! tmp other) +(printf "tmp = ~a; other = ~a\n" tmp other) +;; Η μεταβλητή 'tmp' μετονομάζεται σε 'tmp_1' +;; για να αποφευχθεί η σύγκρουση με τα ονόματα +;; (let ([tmp_1 tmp]) +;; (set! tmp other) +;; (set! other tmp_1)) + +;; But they are still code transformations, for example: +(define-syntax-rule (bad-while condition body ...) + (when condition + body ... + (bad-while condition body ...))) +;; αυτή η μακροεντολή είναι χαλασένη: δημιουγεί ατέρμονα βρόχο +;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστης +;; θα μπεί στον ατέρμονα βρόχο. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 10. Συμβόλαια +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται +;; από ενότητες (modules) +(module bank-account racket + (provide (contract-out + [deposit (-> positive? any)] ; οι ποσότητες είναι πάντα θετικές + [balance (-> positive?)])) + + (define amount 0) + (define (deposit a) (set! amount (+ amount a))) + (define (balance) amount) + ) + +(require 'bank-account) +(deposit 5) + +(balance) ; => 5 + +;; Πελάτες που προσπαθούν να καταθέσουν ένα μη θετικό ποσό παίρνουν +;; το μήνυμα (deposit -5) ; => deposit: contract violation +;; expected: positive? +;; given: -5 +;; more details.... + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 11. Είσοδος και έξοδος +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Η Racket έχει την έννοια του "port", που είναι παρόμοιο με τα +;; file descriptors σε άλλες γλώσσες. + +;; Ανοίγουμε το "/tmp/tmp.txt" και γράφουμε μέσα "Hello World" +;; Αυτό θα προκαλούσε σφάλμα αν το αρχείο υπήρχε ήδη +(define out-port (open-output-file "/tmp/tmp.txt")) +(displayln "Hello World" out-port) +(close-output-port out-port) + +;; Προσθέτουμε στο τέλος του "/tmp/tmp.txt" +(define out-port (open-output-file "/tmp/tmp.txt" + #:exists 'append)) +(displayln "Hola mundo" out-port) +(close-output-port out-port) + +;; Διαβάζουμε απο αρχείο ξανά +(define in-port (open-input-file "/tmp/tmp.txt")) +(displayln (read-line in-port)) +; => "Hello World" +(displayln (read-line in-port)) +; => "Hola mundo" +(close-input-port in-port) + +;; Εναλλακτικά, με το call-with-output-file δεν χρειάζεται να κλείσουμε +;; ρητά το αρχείο +(call-with-output-file "/tmp/tmp.txt" + #:exists 'update ; Rewrite the content + (λ (out-port) + (displayln "World Hello!" out-port))) + +;; Και το call-with-input-file κάνει το ίδιο πράγμα για την είσοδο +(call-with-input-file "/tmp/tmp.txt" + (λ (in-port) + (displayln (read-line in-port)))) +``` + +## Επιπλέον πηγές + +Ψάχνεις για περισσότερα ; [Getting Started with Racket](http://docs.racket-lang.org/getting-started/) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown new file mode 100644 index 00000000..dbef92d8 --- /dev/null +++ b/el-gr/scala-gr.html.markdown @@ -0,0 +1,690 @@ +--- +language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] +translators: + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +filename: learnscala-gr.scala +lang: el-gr +--- + +Scala - Η επεκτάσιμη γλώσσα + +```scala + +/* + Προετοιμαστείτε: + + 1) Κατεβάστε την Scala - http://www.scala-lang.org/downloads + 2) Κάνετε εξαγωγή στην επιθυμητή σας τοποθεσία και βάλτε τον υποφάκελο bin + στο path του συστήματος + 3) Ξεκινήστε ένα scala REPL γράφοντας scala. Θα πρέπει να βλέπετε το prompt: + + scala> + + Αυτό είναι το αποκαλούμενο REPL (Read-Eval-Print Loop) *. + Μπορείτε να πληκτρολογήσετε οποιαδήποτε έγκυρη έκφραση σε Scala μέσα του , + και το αποτέλεσμα θα τυπωθεί. Θα εξηγήσουμε πως μοιάζουν τα αρχεία της Scala + αργότερα μέσα στο tutorial , αλλά για τώρα ας αρχίσουμε με κάποια βασικά. + *[Βρόχος του Διάβασε - Αξιολόγησε - Τύπωσε] +*/ + + +///////////////////////////////////////////////// +// 1. Βασικές έννοιες +///////////////////////////////////////////////// + +// Τα σχόλια μίας γραμμής ξεκινούν με δύο "/" (:forward slashes) . + +/* + Τα σχόλια που επεκτείνονται σε πολλές γραμμές , όπως μπορείτε + να δείτε , φαίνοται κάπως έτσι. +*/ + +// Εκτύπωση με εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +println("Hello world!") +println(10) + +// Εκτύπωση χωρίς τον εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +print("Hello world") + +// Η δήλωση μεταβλητών γίνεται χρησιμοποιώντας var ή val. +// Οι δηλώσεις val είναι αμετάβλητες, ενώ οι var είναι μεταβλητές. +// Η αμεταβλητότητα είναι συμφέρουσα και προσπαθούμε να την χρησιμοποιούμε. +val x = 10 // το x είναι τώρα 10 +x = 20 // σφάλμα: αλλαγή σε val +var y = 10 +y = 20 // το y είναι τώρα 20 + +/* + Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω + δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός + χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις + περισσότερες των περιπτώσεων , ο μεταγλωττιστής της Scala μπορεί να + μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε + αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: +*/ +val z: Int = 10 +val a: Double = 1.0 + +/* + Προσέξτε ότι υπάρχει αυτόματη μετατροπή από ακέραιο (Int) σε διπλής + ακρίβειας (Double), και συνεπώς το αποτέλεσμα είναι 10.0 και όχι 10. +*/ +val b: Double = 10 + +// Λογικές τιμές +true +false + +// Λογικές Πράξεις +!true // false +!false // true +true == false // false +10 > 5 // true + +// Η αριθμιτική είναι όπως τα συνηθισμένα +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 + + +/* + Αξιολογώντας μια έκφραση στο REPL , σας δίνεται ο τύπος και + η τιμή του αποτελέσματος +*/ + +1 + 7 + +/* Η παραπάνω γραμμή έχει το εξής αποτέλεσμα: + + scala> 1 + 7 + res29: Int = 8 + + Αυτό σημαίνει ότι το αποτέλεσμα της αξιολόγησης του 1 + 7 είναι ένα αντικείμενο + τύπου Int με τιμή 8 + + Σημειώστε ότι το "res29" είναι ένα σειριακά δημιουργούμενο όνομα μεταβλητής + για να αποθηκεύονται τα αποτελέσματα των εκφράσεων που έχετε πληκτρολογήσει + και συνεπώς η έξοδός σας μπορεί να διαφέρει. +*/ + +"Τα αλφαριθμητικά στην Scala περικλείονται από διπλά εισαγωγικά" +'a' // Ένας χαρακτήρας στην Scala +// res30: Char = a +// 'Αλφαριθημτικά με μονά εισαγωγικά δεν υφίστανται <= Αυτό θα προκαλέσει σφάλμα. + +// Τα αλφαριθμητικά έχουν τις συνηθισμένες μεθόδους της Java ορισμένες πάνω τους. +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") + +// Έχουν επίσης μερικές επιπλένον μεθόδους Scala. +// Δείτε επίσης : scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) + +// Παρεμβολή αλφαριθμητικών : παρατηρήστε το πρόθεμα "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" + +// Expressions inside interpolated strings are also possible +// Εκφράσεις μέσα σε παρεμβεβλημένα αλφαριθμητικά είναι επίσης εφικτά +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" + +// Μορφοποίηση με παρεμβεβλημένα αλφαριθμητικά με το πρόθεμα "f" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" + +// Raw αλφαριθμητικά, που αγνοούν τους ειδικούς χαρακτήρες. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." + +// Μερικούς χαρακτήρες πρέπει να τους κάνουμε "escape", +// λ.χ ένα διπλό εισαγωγικό μέσα σε ένα αλφαριθμητικό : +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" + +/* + Τα τριπλά διπλά-εισαγωγικά επιτρέπουν στα αλφαριθμητικά να εκτείνονται σε + πολλαπλές γραμμές και να περιέχουν διπλά εισαγωγικά +*/ +val html = """
+

Press belo', Joe

+ +
""" + + +///////////////////////////////////////////////// +// 2. Συναρτήσεις +///////////////////////////////////////////////// + +// Οι συναρτήσεις ορίζονται ως εξής: +// +// def functionName(args...): ReturnType = { body... } +// +// Αν προέρχεστε απο πιο παραδοσιακές γλώσσες (C/C++ , Java) παρατηρήστε +// την παράλειψη του return. Στην Scala , η τελευταία έκφραση στο μπλόκ +// της συνάρτησης είναι η τιμή που επιστρέφει η συνάρτηση. +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} + +// Τα { } μπορούν να παραλειφθούν αν η συνάρτηση αποτελείται απο μια απλή έκφραση: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y + +// Η σύνταξη για την κλήση συναρτήσεων είναι γνώριμη: +sumOfSquares(3, 4) // => 25 + +// Στις περισσότερες των περιπτώσεων (με τις αναδρομικές συναρτήσεις να αποτελούν +// την πιο αξιοπρόσεκτη εξαίρεση) , ο τύπος επιστροφής της συνάρτησης μπορεί να +// παραλειφθεί, και η ίδια συμπερασματολογία τύπων που είδαμε με τις μεταβλητές +// θα δουλεύει και με τους τύπους επιστροφής της συνάρτησης: +def sq(x: Int) = x * x // Ο μεταγλωττιστής μπορεί να μαντέψει ότι + // ο τύπος επιστροφής της συνάρτησης είναι Int + +// Οι συναρτήσεις μπορούν να έχουν προκαθορισμένες τιμές: +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// Οι ανώνυμες συναρτήσεις είναι ως εξής: +(x:Int) => x * x + +// Σε αντίθεση με τα defs , ακόμα και ο τύπος εισόδου απο τις ανώνυμες +// συναρτήσεις μπορεί να παραληφθεί αν τα συμφραζόμενα το κάνουν ξεκάθαρο. +// Προσέξτε τον τύπο "Int => Int" που σημαίνει ότι μια συνάρτηση παίρνει +// ένα Int και επιστρέφει ένα Int. +val sq: Int => Int = x => x * x + +// Οι ανώνυμες συναρτήσεις μπορούν να κληθούν όπως συνήθως: +sq(10) // => 100 + +// Αν κάθε όρισμα στην ανώνυμη συνάρτηση χρησιμοποιείται μόνο μία φορά, +// η Scala επιτρέπει έναν ακόμα πιο σύντομο τρόπο να οριστεί. Αυτές +// οι ανώνυμες συναρτήσεις αποδεικνύεται ότι είναι πολύ κοινές , +// όπως θα γίνει προφανές στο μέρος των δομών δεδομένων. +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + +// Η δεσμευμένη λέξη return υπάρχει στην Scala , αλλά επιστρέφει μόνο +// από το πιο εσωτερικό def που την περικλείει. +// ΠΡΟΣΟΧΗ: Η χρήση του return στην Scala είναι επιρρεπής σε λάθη +// και θα πρέπει να αποφεύγεται. +// Δεν έχει καμία επίδραση στις ανώνυμες συναρτήσεις. Για παράδειγμα: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // Αυτή η σειρά κάνει το z την τιμή που επιστρέφει η foo! + else + z + 2 // Αυτή η γραμμή είναι η τιμή που επιστρέφει η anonFunc + } + anonFunc(x) // Αυτή η γραμμή είναι η τιμή που επιστρέφει η foo +} + + +///////////////////////////////////////////////// +// 3. Έλεγχος ροής +///////////////////////////////////////////////// + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// ΠΡΟΣΟΧΗ: Η Scala είναι σχετικά επιεικής ως αναφορά τις τελείες και +// τις παρενθέσεις. Διαβάστε τους κανόνες ξεχωριστά. +// Αυτό βοηθάει στο να γράφεις DSLs και APIs που διαβάζονται σαν τα Αγγλικά. + +(5 to 1 by -1) foreach ( println ) + +// Ένας βρόχος while : +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Ναι ξανά! Τι συνέβει; Γιατί; + +i // Εμφάνισε την τιμή του i. Σημειώστε ότι ένας βρόχος while είναι βρόχος + // με την κλασική έννοια - εκτελείται σειριακά καθώς αλλάζει η μεταβλητή + // του βρόχου. Το while είναι πολύ γρήγορο , γρηγορότερο απο τους βρόχους + // της Java , αλλά η χρήση combinators και comprehensions όπως πιο πάνω , + // είναι πιο εύκολη στην κατανόηση και στην παραλληλοποίηση. + +// Ένας βρόχος do while : +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα +// πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί +// ρητά τον τύπο που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// Η ροή του ελέγχου. + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. Δομές Δεδομένων +///////////////////////////////////////////////// + +val a = Array(1, 2, 3, 5, 8, 13) +a(0) +a(3) +a(21) // "Πετάει" exception + +val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") +m("fork") +m("spoon") +m("bottle") // "Πετάει" exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Δείτε το documentation του map εδώ - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + */ + + +// Πλειάδες + +(1, 2) + +(4, 3, 2) + +(1, 2, "three") + +(a, 2, "three") + +// Γιατί να το έχουμε αυτό; +val divideInts = (x:Int, y:Int) => (x / y, x % y) + +divideInts(10,3) // Η συνάρτηση divideInts επιστρέφει το αποτέλεσμα + // της ακαίρεας διαίρεσης και το υπόλοιπο. + +// Για να έχουμε πρόσβαση στα στοιχεία μιας πλειάδας, χρησιμοποιούμε το _._n +// όπου το n είναι ο δείκτης με βάση το 1 του στοιχείου. +val d = divideInts(10,3) + +d._1 + +d._2 + + +///////////////////////////////////////////////// +// 5. Αντικειμενοστραφής Προγραμματισμός +///////////////////////////////////////////////// + +/* + Ότι έχουμε κάνει ως τώρα σε αυτό το tutorial ήταν απλές εκφράσεις + (τιμές , συναρτήσεις , κτλ). Αυτές οι εκφράσεις βολεύουν όταν τις + γράφουμε στο REPL για γρήγορες δοκιμές, αλλά δεν μπορούν να υπάρχουν + από μόνες τους σε ένα αρχείο Scala. Για παράδειγμα , δεν μπορούμε να + έχουμε μόνο ένα "val x = 5" στο αρχείο Scala. Αντί αυτού , τα μόνα + στοιχεία του πάνω επιπέδου που επιτρέπονται στην Scala είναι: + + - αντικείμενα (objects) + - κλάσεις (classes) + - κλάσεις περίπτωσης (case classes στην Scala) + - Χαρακτηριστικά (traits , όπως ονομάζονται στην Scala) + + Και τώρα θα εξηγήσουμε τι είναι αυτά. +*/ +// Οι κλάσεις είναι παρόμοιες με τις κλάσεις σε άλλες γλώσσες. Τα ορίσματα του +// "κατασκευαστή" (constructor) δηλώνονται μετά από το όνομα της κλάσης , +// και η αρχικοποιήση γίνεται μέσα στο σώμα της κλάσης. +class Dog(br: String) { + // Κώδικας για τον "κατασκευαστή" + var breed: String = br + + // Ορίζεται μια μέθοδος bark , που επιστρέφει ένα αλφαριθμητικό + def bark = "Woof, woof!" + + // Οι τιμές και οι μέθοδοι είναι public εκτός αν χρησιμοποιήσουμε κάποια + // απο τις λέξεις κλειδιά "protected" και "private" . + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + + // Οι abstract μέθοδοι είναι απλά μέθοδοι χωρίς σώμα. Αν βγάζαμε + // το σχόλιο απο την επόμενη γραμμή η κλάση Dog θα έπρεπε να + // δηλωθεί ως abstract class Dog(...) { ... } : + // def chaseAfter(what: String): String +} + +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" + + +// Η λέξη "object" δημιουργεί ένα type ΚΑΙ ένα singleton instance αυτού. +// Είναι κοινό για τις κλάσεις στην Scala να έχουν ένα "συντροφικό object", +// όπου η συμπεριφορά για κάθε instance αιχμαλωτίζεται μέσα στις κλάσεις +// αυτές καθ' αυτές, αλλά η συμπρεριφορά που σχετίζεται με όλα τα instances +// της κλάσης πάνε μέσα στο object. Η διαφορά είναι παρόμοια με τις +// μεθόδους κλάσεων σε σχέση με στατικές μεθόδους σε άλλες γλώσσες. +// Προσέξτε οτι τα objects και οι κλάσεις μπορούν να έχουν το ίδιο όνομα. +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} + +// Οι κλάσεις περίπτωσης (case classes) είναι που έχουν την επιπλέον +// λειτουργικότητα ενσωματωμένη. Μιά συνήθης ερώτηση για αρχάριους στην +// Scala είναι πότε να χρησιμοπούνται κλάσεις και πότε case κλάσεις. +// Γενικά οι κλάσεις τείνουν να εστιάζουν στην ενθυλάκωση, τον +// πολυμορφισμό και τη συμπεριφορά. Οι τιμές μέσα σε αυτές τις κλάσεις +// τείνουν να είναι private , και μόνο οι μέθοδοι είναι εκτεθειμένες. +// Ο κύριος σκοπός των case classes είναι να κρατούν δεδομένα που είναι +// σταθερές(immutable). Συνήθως έχουν λίγες μεθόδους και οι μέθοδοι σπάνια +// έχουν παρενέργειες. +case class Person(name: String, phoneNumber: String) + +// Δημιουργία ενός instance. Πραρατηρήστε ότι τα case classes +// δεν χρειάζονται την λέξη "new" . +val george = Person("George", "1234") +val kate = Person("Kate", "4567") + +// Με τα case classes, παίρνεις μερικά προνόμια δωρεάν , όπως: +george.phoneNumber // => "1234" + +// Ελέχγεται η ισότητα για κάθε πεδίο (δεν χρειάζεται να +// κάνουμε override στο .equals) +Person("George", "1234") == Person("Kate", "1236") // => false + +// Έυκολος τρόπος να κάνουμε αντιγραφή. Δημιουργούμε έναν νέο geroge: +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") + +// Και πολλά άλλα. Τα case classes έχουν και αντιστοίχιση προτύπων +// (pattern matching) δωρεάν, δείτε παρακάτω. + +// Τα χαρακτηριστικά (traits) έρχονται σε λίγο καιρό ! + +///////////////////////////////////////////////// +// 6. Αντιστοίχιση Προτύπων +///////////////////////////////////////////////// + +// Η αντιστοίχιση προτύπων (pattern matching) είναι ένα πολύ δυνατό και +// ευρέως χρησιμοποιούμενο χαρακτηριστικό στην Scala. Παρακάτω βλέπουμε +// πως γίνεται το pattern matching σε ένα case class. Σημείωση: Σε +// αντίθεση με άλλες γλώσσες η Scala δεν χρειάζεται breaks, γιατί γίνεται +// αυτόματα όταν γίνει κάποιο match. + +def matchPerson(person: Person): String = person match { + // Μετά προσδιορίζουμε το πρότυπο (pattern): + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} + +val email = "(.*)@(.*)".r // Ορίζουμε ένα regex για το επόμενο παράδειγμα. + // (regex <- REGular EXpression) + +// Το pattern matching μπορεί να μοιάζει γνώριμο απο τα switch statements σε +// γλώσσες που ανήκουν στην οικογένεια της C αλλά είναι πολύ πιο ισχυρό. +// Στην Scala , μπορούμε να κάνουμε match πολύ περισσότερα: +def matchEverything(obj: Any): String = obj match { + // Μπορούμε να ταιριάξουμε τιμές: + case "Hello world" => "Got the string Hello world" + + // Μπορούμε να ταιριάξουμε τύπους: + case x: Double => "Got a Double: " + x + + // Μπορούμε να βάλουμε συνθήκες: + case x: Int if x > 10000 => "Got a pretty big number!" + + // Μπορούμε να ταιριάξουμε case classes όπως πρίν: + case Person(name, number) => s"Got contact info for $name!" + + // Μπορούμε να ταιριάξουμε regex: + case email(name, domain) => s"Got email address $name@$domain" + + // Μπορούμε να ταιριάξουμε πλειάδες: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" + + // Μπορούμε να ταιριάξουμε δομές δεδομένων: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" + + // Μπορούμε να ταιριάξουμε πρότυπα που το ένα είναι μέσα στο άλλο: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" +} + +// Στην πραγματικότητα , μπορούμε να κάνουμε pattern matching σε όποιο αντικείμενο +// έχει την μέθοδο "unapply". Αυτό το χαρακτηριστικό είναι τόσο ισχυρό ώστε +// η Scala επιτρέπει να ορίστούν ολόκληρες συναρτήσεις σαν patterns. +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} + + +///////////////////////////////////////////////// +// 7. Συναρτησιακός Προγραμματισμός +///////////////////////////////////////////////// + +// Η Scala επιτρέπει στις μεθόδους και τις συναρτήσεις να επιστρέφουν ή να +// δέχονται ως παραμέτρους άλλες μεθόδους ή συναρτήσεις. + +val add10: Int => Int = _ + 10 // Μια συνάρτηση που δέχεται Int και επιστρέφει Int +List(1, 2, 3) map add10 // List(11, 12, 13) - το add10 εφαρμόζεται σε κάθε στοιχείο + // μέσω του map + +// Οι ανώνυμες συναρτήσεις μπορούν να χρησιμοποιηθούν αντί +// ονοματισμένων (όπως απο πάνω) : +List(1, 2, 3) map (x => x + 10) + +// Και το σύμβολο της κάτω παύλας , μπορεί να χρησιμοποιηθεί αν υπάρχει μόνο +// ένα όρισμα στην ανώνυμη συνάρτηση. Έτσι δεσμεύεται ως η μεταβλητή. +List(1, 2, 3) map (_ + 10) + +// Αν το μπλόκ της ανώνυμης συνάρτησης ΚΑΙ η συνάρτηση που εφαρμόζεται +// (στην περίπτωσή μας το foreach και το println) παίρνουν ένα όρισμα +// μπορείτε να παραλείψετε την κάτω παύλα. +List("Dom", "Bob", "Natalia") foreach println + + +// Συνδυαστές + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// Η συνάρτηση filter παίρνει ένα κατηγορούμενο (predicate) +// που είναι μια συνάρτηση απο το A -> Boolean και διαλέγει +// όλα τα στοιχεία που ικανοποιούν αυτό το κατηγορούμενο. +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) + + +// Το foreach είναι μια μέθοδος της Scala , που ορίζεται για ορισμένες +// συλλογές (collections). Παίρνει έναν τύπο και επιστρέφει Unit +// (μια μέθοδο void) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// For comprehensions + +for { n <- s } yield sq(n) + +val nSquared2 = for { n <- s } yield sq(n) + +for { n <- nSquared2 if n < 10 } yield n + +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + +/* + Προσοχή : Αυτά δεν ήταν βρόχοι for. Η σημασιολογία ενός βρόχου for είναι + η επανάληψη, ενώ ένα for-comprehension ορίζει μια σχέση μεταξύ δύο + συνόλων δεδομένων. +*/ + +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// +/* + ΠΡΟΣΟΧΗ! Τα implicits είναι ένα σύνολο απο ισχυρά χαρακτηριστικά της Scala + και επομένως είναι εύκολο να γίνει κατάχρηση. Οι αρχάριοι στην Scala θα + πρέπει να αντισταθούν στον πειρασμό να τα χρησιμοποιήσουν έως ότου, όχι + μόνο καταλάβουν πως λειτουργούν, αλλά ακόμα εξασκηθούν πάνω τους. + Ο μόνος λόγος που συμπεριλάβαμε αυτό το κομμάτι στο tutorial είναι + γιατί είναι τόσο κοινό στις βιβλιοθήκες της Scala , που αδύνατο να κάνεις + οτιδήποτε σημαντικό χωρίς να χρησιμοποιήσεις μια που να έχει implicits. + +*/ + +// Κάθε τιμή (vals , συναρτήσεις , αντικείμενα , κτλ) μπορεί να δηλωθεί ως +// implicit χρησιμοποιώντας , ναι το μαντέψατε , την λέξη "implicit". +// Σημειώστε ότι χρησιμοποιούμε την κλάση Dog που δημιουργήσαμε στο +// 5ο μέρος των παραδειγμάτων. +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) + + +// Απο μόνη της, η λέξη implicit, δεν αλλάζει την συμπεριφορά μιάς τιμής +// οπότε οι παραπάνω μπορούν να χρησιμοποιοηθούν όπως συνήθως. +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" + +// Η διαφορά είναι ότι τώρα αυτές οι τιμές έχουν την δυνατότητα να +// χρησιμοποιηθούν όταν ένα άλλο κομμάτι κώδικα "χρειάζεται" μια +// implicit τιμή. Μια τέτοια περίπτωση είναι τα ορίσματα μιας implicit +// συνάρτησης: +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + +// Άν τροφοδοτήσουμε μια τιμή για το "homMany", η συνάρτηση συμπεριφέρεται +// ως συνήθως +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + +// Αλλά αν παραλείψουμε την παράμετρο implicit , μια implicit τιμή του ιδίου τύπου +// χρησιμοποιείται, στην περίπτωσή μας, το "myImplicitInt" +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + +// Οι παράμετροι implicit συναρτήσεων μας επιτρέπουν να προσομοιάζουμε +// κλάσεις τύπων (type classes) σε άλλες συναρτησιακές γλώσσες. +// Χρησιμοποιείται τόσο συχνά που έχει την δικιά του συντομογραφία. +// Οι επόμενες δύο γραμμές κώδικα σημαίνουν το ίδιο πράγμα. +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... + + + +// Μια άλλη περίπτωση στην οποία ο μεταγλωττιστής αναζητά μια implicit τιμή +// είναι αν έχετε obj.method (...) +// αλλά το "obj" δεν έχει την "method" ως μέθοδο. Σε αυτή την περίπτωση, +// αν υπάρχει μια implicit μετατροπή του τύπου Α => Β, όπου Α είναι ο τύπος +// του obj, ενώ το Β έχει μία μέθοδο που ονομάζεται «method», εφαρμόζεται η +// εν λόγω μετατροπή. Έτσι, έχοντας την MyImplicitFunction μέσα στο πεδίο +// εφαρμογής(scope), μπορούμε να πούμε: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" + +// Εδώ το String αρχικά μετατρέπεται σε Dog χρησιμοποιώντας την συνάρτησή μας +// παραπάνω, και μετά καλείται η κατάλληλη μέθοδος. Αυτό είναι ένα εξερετικά +// ισχυρό χαρακτηριστικό, αλλά δεν πρέπει να χρησιμοποιείται με ελαφριά την +// καρδιά. Μάλιστα, όταν ορίσατε την συνάρτηση implicit παραπάνω, ο μεταγλωττιστής +// θα πρέπει να σας έδωσε μια προειδοποιήση, ότι δεν πρέπει να το κάνετε αυτό +// εκτός αν πραγματικά γνωρίζετε τι κάνετε. + + +///////////////////////////////////////////////// +// 9. Διάφορα +///////////////////////////////////////////////// + +// Εισαγωγή βιβλιοθηκών κτλ +import scala.collection.immutable.List + +// Εισαγωγή των πάντων απο το scala.collection.immutable +import scala.collection.immutable._ + +// Εισαγωγή πολλών κλάσεων σε μία έκφραση +import scala.collection.immutable.{List, Map} + +// Δώστε ένα νέο όνομα στην εισαγωγή σας χρησιμοποιώντας το '=>' +import scala.collection.immutable.{ List => ImmutableList } + +// Εισαγωγή όλων των κλάσεων εκτός απο μερικές. +// Το επόμενο δεν εισάγει το Map και το Set: +import scala.collection.immutable.{Map => _, Set => _, _} + +// Το σημείο εισαγωγής του προγράμματος σας ορίζεται σε ένα αρχείο scala , +// χρησιμοποιώντας ένα αντικείμενο (object), με μία μέθοδο , την main. +object Application { + def main(args: Array[String]): Unit = { + // Εδω γράφουμε ... + } +} + +// Files can contain multiple classes and objects. Compile with scalac +// Τα files μπορούν να περιέχουν περισσότερες απο μία κλάσεις και +// αντικείμενα. Το compile γίνεται με την εντολή scalac + +// Εισαγωγή και εξαγωγή. + +// Για να διβάσετε ένα αρχείο γραμμή προς γραμμή +import scala.io.Source +for(line <- Source.fromFile("myfile.txt").getLines()) + println(line) + +// Για να γράψετε σε ένα αρχείο +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school](http://twitter.github.io/scala_school/) + +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) + +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) + -- cgit v1.2.3 From cb065fdf377541b09736f2e3918c4dc6caddc29f Mon Sep 17 00:00:00 2001 From: billpcs Date: Wed, 5 Aug 2015 17:06:31 +0300 Subject: update --- el-gr/racket-gr.html.markdown | 13 ++++++------- el-gr/scala-gr.html.markdown | 15 +++++++-------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 6a3f99ef..c5aa1f46 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -208,7 +208,7 @@ my-pet ; => # (set-member? (set 1 2 3) 1) ; => #t (set-member? (set 1 2 3) 4) ; => #f -;;; Πίνακες κατακερματισμού +;;; Πίνακες κατακερματισμού (Hashes) ;; Δημιουργήστε ένα αμετάβλητο πίνακα κατακερματισμού (define m (hash 'a 1 'b 2 'c 3)) @@ -355,7 +355,6 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' (eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f ;; Το `equal?' υποστηρίζει την σύγκριση των παρακάτω τύπων μεταβλητών: -;; `equal?' supports the comparison of the following datatypes: ;; αλφαριθμητικά, αλφαριθμητικά από bytes, μεταβλητά ζεύγη , διανύσματα, ;; πίνακες κατακερματισμού και δομές. ;; Για άλλα ήδη τύπων μεταβλητών το `equal?' και το `eqv?' επιστρέφουν το @@ -426,13 +425,10 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;;; ;;; Επανάληψη μέσα σε ακολουθίες: -;; Το `for' επιτρέπει την επενάληψη μέσα σε πολλά +;; Το `for' επιτρέπει την επανάληψη μέσα σε πολλά ;; άλλα ήδη από ακολουθίες: Λίστες, διανύσματα, ;; αλφαριθμητικά, σύνολα κτλ.. -;;allows iteration over many other kinds of sequences: -;; lists, vectors, strings, sets, hash tables, etc... - (for ([i (in-list '(l i s t))]) (displayln i)) @@ -488,13 +484,16 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- δεν υπάρχει `d' ;; Υπάρχουν πολλά είδη απο προϋπάρχοντες τρόπους για να συλλέγουμε ;; τιμές από τους βρόχους + (for/sum ([i 10]) (* i i)) ; => 285 (for/product ([i (in-range 1 11)]) (* i i)) ; => 13168189440000 (for/and ([i 10] [j (in-range 10 20)]) (< i j)) ; => #t (for/or ([i 10] [j (in-range 0 20 2)]) (= i j)) ; => #t -;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιύμε + +;; Και για να χρησιμοποιήσουμε ένα αφθαίρετο συνδιασμό χρησιμοποιούμε ;; το 'for/fold' (for/fold ([sum 0]) ([i '(1 2 3 4)]) (+ sum i)) ; => 10 + ;; Αυτό συχνά μπορεί να αντικαταστήσει τους κοινούς ;; προστακτικούς βρόχους (imperative loops) diff --git a/el-gr/scala-gr.html.markdown b/el-gr/scala-gr.html.markdown index dbef92d8..e29c7e70 100644 --- a/el-gr/scala-gr.html.markdown +++ b/el-gr/scala-gr.html.markdown @@ -43,11 +43,11 @@ Scala - Η επεκτάσιμη γλώσσα να δείτε , φαίνοται κάπως έτσι. */ -// Εκτύπωση με εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +// Εκτύπωση με νέα γραμμή στην επόμενη εκτύπωση println("Hello world!") println(10) -// Εκτύπωση χωρίς τον εξαναγκασμό νέας γραμμής στην επόμενη εκτύπωση +// Εκτύπωση χωρίς νέα γραμμή στην επόμενη εκτύπωση print("Hello world") // Η δήλωση μεταβλητών γίνεται χρησιμοποιώντας var ή val. @@ -62,7 +62,7 @@ y = 20 // το y είναι τώρα 20 Η Scala είναι στατικού τύπου γλώσσα, εν τούτις προσέξτε ότι στις παραπάνω δηλώσεις , δεν προσδιορίσαμε κάποιον τύπο. Αυτό συμβαίνει λόγω ενός χαρακτηριστικού της Scala που λέγεται συμπερασματολογία τύπων. Στις - περισσότερες των περιπτώσεων , ο μεταγλωττιστής της Scala μπορεί να + περισσότερες των περιπτώσεων, ο μεταγλωττιστής της Scala μπορεί να μαντέψει ποιός είναι ο τύπος μιας μεταβλητής. Μπορούμε να δηλώσουμε αναλυτικά τον τύπο μιάς μεταβλητής ως εξής: */ @@ -95,7 +95,7 @@ true == false // false /* - Αξιολογώντας μια έκφραση στο REPL , σας δίνεται ο τύπος και + Αξιολογώντας μια έκφραση στο REPL, σας δίνεται ο τύπος και η τιμή του αποτελέσματος */ @@ -133,8 +133,7 @@ true == false // false val n = 45 s"We have $n apples" // => "We have 45 apples" -// Expressions inside interpolated strings are also possible -// Εκφράσεις μέσα σε παρεμβεβλημένα αλφαριθμητικά είναι επίσης εφικτά +// Παρατηρήστε την χρήση των '{', '}' val a = Array(11, 9, 6) s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." @@ -270,7 +269,7 @@ do { // Η αναδρομή ουράς είναι ένας ιδιωματικός τρόπος να κάνεις επαναλαμβανόμενα // πράγματα στην Scala. Οι αναδρομικές συναρτήσεις απαιτούν να γράφτεί -// ρητά τον τύπο που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί +// ρητά ο τύπος που θα επιστρέψουν , αλλιώς ο μεταγλωττιστής δεν μπορεί // αλλιώς να τον συνάγει. Παρακάτω είναι μια συνάρτηση που επιστρέφει Unit. def showNumbersInRange(a:Int, b:Int):Unit = { print(a) @@ -280,7 +279,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = { showNumbersInRange(1,14) -// Η ροή του ελέγχου. +// Έλεγχος Ροής val x = 10 -- cgit v1.2.3 From b1a544d1f04fc6c9769037af5fd165e7032a2985 Mon Sep 17 00:00:00 2001 From: Ian Bertolacci Date: Wed, 5 Aug 2015 18:22:56 -0700 Subject: main(), modules, array/range/domain slicing, loop-expressions, array expressions, in depth zippered iterators Quite the addition. Modules required main() because of the begin statement issue. array/range/domain slicing was more intricate than I though. And loop/array expressions had some very very intersting behavior that necessitated a dive into zippered iterators. Some back-of-the-head anxiety about the tutorial being to in depth? Nawww. --- chapel.html.markdown | 115 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 103 insertions(+), 12 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 33bdc21d..c8489371 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -24,7 +24,7 @@ writeln( "World!" ); // each thing is printed right next to each other, so include your spacing! writeln( "There are ", 3, " commas (\",\") in this line of code" ); // Different output channels -stdout.writeln( "This goes to standard output (just like plain writeln( ) does)"); +stdout.writeln( "This goes to standard output, just like plain writeln() does"); stderr.writeln( "This goes to standard error" ); // Variables don't have to be explicitly typed as long as @@ -285,6 +285,7 @@ for i in rangeCountBy{ } // Rectangular domains are defined using the same range syntax +// However they are required to be bounded (unlike ranges) var domain1to10: domain(1) = {1..10}; // 1D domain from 1..10; var twoDimensions: domain(2) = {-2..2,0..2}; // 2D domain over product of ranges var thirdDim: range = 1..16; @@ -310,6 +311,18 @@ stringSet += "a"; // Redundant add "a" stringSet -= "c"; // Remove "c" writeln( stringSet ); +// Both ranges and domains can be sliced to produce a range or domain with the +// intersection of indices +var rangeA = 1.. ; // range from 1 to infinity +var rangeB = ..5; // range from negative infinity to 5 +var rangeC = rangeA[rangeB]; // resulting range is 1..5 +writeln( (rangeA, rangeB, rangeC ) ); + +var domainA = {1..10, 5..20}; +var domainB = {-5..5, 1..10}; +var domainC = domainA[domainB]; +writeln( (domainA, domainB, domainC) ); + // Array are similar to those of other languages. // Their sizes are defined using domains that represent their indices var intArray: [1..10] int; @@ -357,6 +370,48 @@ var dict: [dictDomain] int = [ "one" => 1, "two" => 2 ]; dict["three"] = 3; for key in dictDomain do writeln( dict[key] ); +// Arrays can be assigned to each other in different ways +var thisArray : [{0..5}] int = [0,1,2,3,4,5]; +var thatArray : [{0..5}] int; + +// Simply assign one to the other. +// This copies thisArray into thatArray, instead of just creating a reference. +// Modifying thisArray does not also modify thatArray. +thatArray = thisArray; +thatArray[1] = -1; +writeln( (thisArray, thatArray) ); + +// Assign a slice one array to a slice (of the same size) of the other. +thatArray[{4..5}] = thisArray[{1..2}]; +writeln( (thisArray, thatArray) ); + +// Operation can also be promoted to work on arrays. +var thisPlusThat = thisArray + thatArray; +writeln( thisPlusThat ); + +// Arrays and loops can also be expressions, where loop +// body's expression is the result of each iteration. +var arrayFromLoop = for i in 1..10 do i; +writeln( arrayFromLoop ); + +// An expression can result in nothing, +// such as when filtering with an if-expression +var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i; + +writeln( arrayFromLoop ); + +// Or could be written with a bracket notation +// Note: this syntax uses the 'forall' parallel concept discussed later. +var evensOrFivesAgain = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; + +// Or over the values of the array +arrayFromLoop = [ value in arrayFromLoop ] value + 1; + +// Note: this notation can get somewhat tricky. For example: +// evensOrFives = [ i in 1..10 ] if (i % 2 == 0 || i % 5 == 0) then i; +// would break. +// The reasons for this are explained in depth when discussing zipped iterators. + // Chapel procedures have similar syntax to other languages functions. proc fibonacci( n : int ) : int { if ( n <= 1 ) then return n; @@ -533,6 +588,19 @@ iter oddsThenEvens( N: int ): int { for i in oddsThenEvens( 10 ) do write( i, ", " ); writeln( ); +// Iterators can also yield conditionally, the result of which can be nothing +iter absolutelyNothing( N ): int { + for i in 1..N { + if ( N < i ) { // Always false + yield i; // Yield statement never happens + } + } +} + +for i in absolutelyNothing( 10 ){ + writeln( "Woa there! absolutelyNothing yielded ", i ); +} + // We can zipper together two or more iterators (who have the same number // of iterations) using zip() to create a single zipped iterator, where each // iteration of the zipped iterator yields a tuple of one value yielded @@ -541,6 +609,34 @@ writeln( ); for (positive, negative) in zip( 1..5, -5..-1) do writeln( (positive, negative) ); +// Zipper iteration is quite important in the assignment of arrays, +// slices of arrays, and array/loop expressions. +var fromThatArray : [1..#5] int = [1,2,3,4,5]; +var toThisArray : [100..#5] int; + +// The operation +toThisArray = fromThatArray; +// is produced through +for (i,j) in zip( toThisArray.domain, fromThatArray.domain) { + toThisArray[ i ] = fromThatArray[ j ]; +} + +toThisArray = [ j in -100..#5 ] j; +writeln( toThisArray ); +// is produced through +for (i, j) in zip( toThisArray.domain, -100..#5 ){ + toThisArray[i] = j; +} +writeln( toThisArray ); + +// This is all very important in undestanding why the statement +// var iterArray : [1..10] int = [ i in 1..10 ] if ( i % 2 == 1 ) then j; +// exhibits a runtime error. +// Even though the domain of the array and the loop-expression are +// the same size, the body of the expression can be though of as an iterator. +// Because iterators can yield nothing, that iterator yields a different number +// of things than the domain of the array or loop, which is not allowed. + // Classes are similar to those in C++ and Java. // They currently lack privatization class MyClass { @@ -813,12 +909,9 @@ proc main(){ // You may have noticed that (depending on how many cores you have) // that the parallel loop went faster than the serial loop - // A succinct way of writing a forall loop over an array: - // iterate over values - [ val in myBigArray ] val = 1 / val; - - // or iterate over indicies - [ idx in myBigArray.domain ] myBigArray[idx] = -myBigArray[idx]; + // The bracket style loop-expression described + // much earlier implicitly uses a forall loop. + [ val in myBigArray ] val = 1 / val; // Parallel operation // Atomic variables, common to many languages, are ones whose operations // occur uninterupted. Multiple threads can both modify atomic variables @@ -837,7 +930,7 @@ proc main(){ writeln( "uranium was ", was, " but is now ", replaceWith ); var isEqualTo = 235; - if uranium.compareExchange( isEqualTo, replaceWith ) { + if ( uranium.compareExchange( isEqualTo, replaceWith ) ) { writeln( "uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith ); } else { @@ -911,7 +1004,7 @@ proc main(){ // Create a barrier do{ lock$; // Read lock$ (wait) - }while count.read() < 1; // Keep waiting until a spot opens up + }while ( count.read() < 1 ); // Keep waiting until a spot opens up count.sub(1); // decrement the counter lock$.writeXF( true ); // Set lock$ to full (signal) @@ -954,7 +1047,7 @@ Who is this tutorial for? This tutorial is for people who want to learn the ropes of chapel without having to hear about what fiber mixture the ropes are, or how they were braided, or how the braid configurations differ between one another. It won't teach you how to develop amazingly performant code, and it's not exhaustive. -Refer to the [language specification](http://chapel.cray.com/language.html) and the [library documentation](http://chapel.cray.com/docs/latest/) for more details. +Refer to the [language specification](http://chapel.cray.com/language.html) and the [module documentation](http://chapel.cray.com/docs/latest/) for more details. Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to see if more topics have been added or more tutorials created. @@ -963,8 +1056,6 @@ Occasionally check back here and on the [Chapel site](http://chapel.cray.com) to * Exposition of the standard modules * Multiple Locales (distributed memory system) * Records - * Whole/sliced array assignment - * Range and domain slicing * Parallel iterators Your input, questions, and discoveries are important to the developers! -- cgit v1.2.3 From c21c4b65cb1660d6af3faecdd7643e5187f5429b Mon Sep 17 00:00:00 2001 From: Bill Panagiotopoulos Date: Thu, 6 Aug 2015 18:41:33 +0300 Subject: Small Fixes Fix small extra character and translate a small text left untranslated by mistake --- el-gr/racket-gr.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index c5aa1f46..d7c144aa 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -1,4 +1,4 @@ ----σ +--- language: racket filename: learnracket.rkt contributors: @@ -8,13 +8,11 @@ contributors: - ["Duong H. Nguyen", "https://github.com/cmpitg"] - ["Keyan Zhang", "https://github.com/keyanzhang"] translators: - - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] + - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] --- -Racket is a general purpose, multi-paradigm programming language in the Lisp/Scheme family. - -Feedback is appreciated! You can reach me at [@th3rac25](http://twitter.com/th3rac25) or th3rac25 [at] [google's email service] - +H Racket είναι μια γενικού σκοπού, πολυ-υποδειγματική γλώσσα προγραμματισμού που ανήκει +στην οικογένεια της Lisp/Scheme ```racket #lang racket ; ορίζει την γλώσσα που χρησιμοποιόυμε -- cgit v1.2.3 From 2f73cafc7042c92b1358272e6d158f5b1995c15c Mon Sep 17 00:00:00 2001 From: Levi Bostian Date: Thu, 6 Aug 2015 12:26:29 -0500 Subject: Update racket gr to include what language it is in to fix homescreen issue showing up twice. --- el-gr/racket-gr.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index d7c144aa..4c76b174 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -1,6 +1,6 @@ --- language: racket -filename: learnracket.rkt +filename: learnracket-gr.rkt contributors: - ["th3rac25", "https://github.com/voila"] - ["Eli Barzilay", "https://github.com/elibarzilay"] @@ -9,6 +9,7 @@ contributors: - ["Keyan Zhang", "https://github.com/keyanzhang"] translators: - ["Vasilis Panagiotopoulos" , "https://github.com/billpcs/"] +lang: el-gr --- H Racket είναι μια γενικού σκοπού, πολυ-υποδειγματική γλώσσα προγραμματισμού που ανήκει -- cgit v1.2.3 From 14c628e1d914a72c81daae92d204eb8892e12889 Mon Sep 17 00:00:00 2001 From: ftwbzhao Date: Fri, 7 Aug 2015 14:30:45 +0800 Subject: Update ruby-cn.html.markdown --- zh-cn/ruby-cn.html.markdown | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 99250b43..14d38137 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -7,6 +7,7 @@ contributors: - ["Joel Walden", "http://joelwalden.net"] - ["Luke Holder", "http://twitter.com/lukeholder"] - ["lidashuang", "https://github.com/lidashuang"] + - ["ftwbzhao", "https://github.com/ftwbzhao"] translators: - ["Lin Xiangyu", "https://github.com/oa414"] --- @@ -120,11 +121,11 @@ status == :approved #=> false # 数组 # 这是一个数组 -[1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] +array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # 数组可以包含不同类型的元素 -array = [1, "hello", false] #=> => [1, "hello", false] +[1, "hello", false] #=> [1, "hello", false] # 数组可以被索引 # 从前面开始 @@ -140,8 +141,8 @@ array.[] 12 #=> nil # 从尾部开始 array[-1] #=> 5 -# 同时指定开始的位置和结束的位置 -array[2, 4] #=> [3, 4, 5] +# 同时指定开始的位置和长度 +array[2, 3] #=> [3, 4, 5] # 或者指定一个范围 array[1..3] #=> [2, 3, 4] -- cgit v1.2.3 From 63a314bd07660f33664708cc3b9e6f02ca895931 Mon Sep 17 00:00:00 2001 From: ftwbzhao Date: Fri, 7 Aug 2015 15:44:47 +0800 Subject: Update go-cn.html.markdown --- zh-cn/go-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 9f6a8c15..3a461efe 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -283,4 +283,4 @@ Go的根源在[Go官方网站](http://golang.org/)。 强烈推荐阅读语言定义部分,很简单而且很简洁!(as language definitions go these days.) -学习Go还要阅读Go标准库的源代码,全部文档化了,可读性非常好,可以学到go,go style和go idioms。在文档中点击函数名,源代码就出来了! +学习Go还要阅读Go[标准库的源代码](http://golang.org/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](http://golang.org/pkg/)中点击函数名,源代码就出来了! -- cgit v1.2.3 From cfb6c3a35ff52d706d337986d62104ecdb424d88 Mon Sep 17 00:00:00 2001 From: sdcuike <303286730@qq.com> Date: Fri, 7 Aug 2015 23:06:17 +0800 Subject: =?UTF-8?q?=20~=20=20=20=20=20=20=20=E5=8F=96=E5=8F=8D=EF=BC=8C?= =?UTF-8?q?=E6=B1=82=E5=8F=8D=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zh-cn/java-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/java-cn.html.markdown b/zh-cn/java-cn.html.markdown index f08d3507..12afa59a 100644 --- a/zh-cn/java-cn.html.markdown +++ b/zh-cn/java-cn.html.markdown @@ -149,7 +149,7 @@ public class LearnJava { // 位运算操作符 /* - ~ 补 + ~ 取反,求反码 << 带符号左移 >> 带符号右移 >>> 无符号右移 -- cgit v1.2.3 From 01d5e4d6dd7a60142fb1342637c851c943f62530 Mon Sep 17 00:00:00 2001 From: TsT Date: Fri, 7 Aug 2015 17:56:09 +0200 Subject: =?UTF-8?q?Quelques=20corrections=20et=20am=C3=A9liorations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- fr-fr/lua-fr.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index b4e2a161..1f592320 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -434,9 +434,9 @@ les librairies standard: Autres références complémentaires: -* Lua for programmers -* Courte de référence de Lua -* Programming In Lua +* Lua pour programmeurs +* Référence condensée de Lua +* Programmer en Lua * Les manuels de référence Lua A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et @@ -446,4 +446,4 @@ Ce tutoriel a été originalement écrit pour tylerney disponible en tant que gist. Il a été traduit en français par Roland Yonaba (voir son github). -Amusez-vous bien avec Lua! \ No newline at end of file +Amusez-vous bien avec Lua! -- cgit v1.2.3 From 3d26429ce202f4d00f80182d460ee5b3ccdc87c4 Mon Sep 17 00:00:00 2001 From: Dave Andersen Date: Sun, 9 Aug 2015 22:43:10 -0700 Subject: update "further reading" links Change the chat room reference from Stack Overflow chat to Gitter.im, and add a link to the "Red" Stack Overflow tag. --- red.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/red.html.markdown b/red.html.markdown index 73a13606..f33060c4 100644 --- a/red.html.markdown +++ b/red.html.markdown @@ -212,7 +212,9 @@ The source can be found on [github](https://github.com/red/red). The Red/System language specification can be found [here](http://static.red-lang.org/red-system-specs-light.html). -To learn more about Rebol and Red join the [chat on StackOverflow](http://chat.stackoverflow.com/rooms/291/rebol-and-red). You will need 20 points to chat but if you ask or answer questions about Red or Rebol we will help you get those points. And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). +To learn more about Rebol and Red join the [chat on Gitter](https://gitter.im/red/red). And if that is not working for you drop a mail to us on the [Red mailing list](mailto: red-langNO_SPAM@googlegroups.com) (remove NO_SPAM). + +Browse or ask questions on [Stack Overflow](stackoverflow.com/questions/tagged/red). Maybe you want to try Red right away? That is possible on the [try Rebol and Red site](http://tryrebol.esperconsultancy.nl). -- cgit v1.2.3 From 27b9ee85fb65c9192a070890375e678a7d02f9e6 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 12 Aug 2015 06:38:17 +0900 Subject: Fixes #1196 --- objective-c.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/objective-c.html.markdown b/objective-c.html.markdown index 56640a87..91b84b47 100644 --- a/objective-c.html.markdown +++ b/objective-c.html.markdown @@ -415,7 +415,7 @@ distance = 18; // References "long distance" from MyClass implementation + (NSString *)classMethod { - return [[self alloc] init]; + return @"Some string"; } + (MyClass *)myClassFromHeight:(NSNumber *)defaultHeight -- cgit v1.2.3 From d46831e598d873940f02d2670464a3408a3c8a0a Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Sat, 15 Aug 2015 00:08:43 +0900 Subject: Update xml-pt.html.markdown --- pt-br/xml-pt.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pt-br/xml-pt.html.markdown b/pt-br/xml-pt.html.markdown index 40ddbc3a..f347f8ef 100644 --- a/pt-br/xml-pt.html.markdown +++ b/pt-br/xml-pt.html.markdown @@ -1,8 +1,8 @@ --- language: xml -filename: learnxml.xml +filename: learnxml-pt.xml contributors: - - ["João Farias", "https://github.com/JoaoGFarias"] + - ["João Farias", "https://github.com/JoaoGFarias"] translators: - ["Miguel Araújo", "https://github.com/miguelarauj1o"] lang: pt-br @@ -130,4 +130,4 @@ com a adição de definição DTD.--> 30.00 -``` \ No newline at end of file +``` -- cgit v1.2.3 From a0e8d3202b1642d9be1a8fcc6db95273415373b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ismael=20Venegas=20Castell=C3=B3?= Date: Fri, 14 Aug 2015 20:28:08 -0500 Subject: Update julia-es to v0.3.11 --- es-es/julia-es.html.markdown | 1268 ++++++++++++++++++++++++------------------ 1 file changed, 724 insertions(+), 544 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 203ee3bb..1e01c2e3 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -4,757 +4,937 @@ contributors: - ["Leah Hanson", "http://leahhanson.us"] translators: - ["Guillermo Garza", "http://github.com/ggarza"] + - ["Ismael Venegas Castelló", "https://github.com/Ismael-VC"] filename: learnjulia-es.jl lang: es-es --- -Julia es un nuevo lenguaje funcional homoiconic enfocado en computación técnica. -Aunque que tiene todo el poder de macros homoiconic, funciones de primera -clase, y control de bajo nivel, Julia es tan fácil de aprender y utilizar como -Python. +![JuliaLang](https://camo.githubusercontent.com/e1ae5c7f6fe275a50134d5889a68f0acdd09ada8/687474703a2f2f6a756c69616c616e672e6f72672f696d616765732f6c6f676f5f68697265732e706e67) -Esto se basa en la versión de desarrollo actual de Julia, del 18 de octubre de -2013. +[Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). -```ruby +En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario. -# Comentarios de una línea comienzan con una almohadilla (o signo gato) +### ¡Prueba Julia ahora mismo! -#= Commentarios multilinea pueden escribirse - usando '#=' antes de el texto y '=#' - después del texto. También se pueden anidar. +* [TryJupyter](https://try.jupyter.org) +* [JuliaBox](https://juliabox.org) +* [SageMathCloud](https://cloud.sagemath.com) + +### Resumen de Características: + +* [Despacho múltiple](http://en.wikipedia.org/wiki/Multiple_dispatch): permite definir el comportamiento de las funciones a través de múltiples combinaciones de tipos de argumentos (**métodos**). +* Sistema de **tipado dinámico**: tipos para la documentación, la optimización y el despacho. +* [Buen desempeño](http://julialang.org/benchmarks), comparado al de lenguajes **estáticamente compilados** como C. +* [Gestor de paquetes](http://docs.julialang.org/en/release-0.3/stdlib/pkg) integrado. +* [Macros tipo Lisp](http://docs.julialang.org/en/release-0.3/manual/metaprogramming/#macros) y otras comodidades para la [meta programación](http://docs.julialang.org/en/release-0.3/manual/metaprogramming). +* Llamar funciones de otros lenguajes, mediante paquetes como: **Python** ([PyCall](https://github.com/stevengj/PyCall.jl)), [Mathematica](http://github.com/one-more-minute/Mathematica.jl), **Java** ([JavaCall](http://github.com/aviks/JavaCall.jl)), **R** ([Rif](http://github.com/lgautier/Rif.jl) y [RCall](http://github.com/JuliaStats/RCall.jl)) y **Matlab** ([MATLAB](http://github.com/JuliaLang/MATLAB.jl)). +* [Llamar funciones de C y Fortran](http://docs.julialang.org/en/release-0.3/manual/calling-c-and-fortran-code) **directamente**: sin necesidad de usar envoltorios u APIs especiales. +* Poderosas características de **línea de comandos** para [gestionar otros procesos](http://docs.julialang.org/en/release-0.3/manual/running-external-programs). +* Diseñado para la [computación paralela y distribuida](http://docs.julialang.org/en/release-0.3/manual/parallel-computing) **desde el principio**. +* [Corrutinas](http://en.wikipedia.org/wiki/Coroutine): hilos ligeros "**verdes**". +* Los [tipos definidos por el usuario](http://docs.julialang.org/en/release-0.3/manual/types) son tan **rápidos y compactos** como los tipos estándar integrados. +* [Generación automática de código](http://docs.julialang.org/en/release-0.3/stdlib/base/?highlight=%40code#internals) **eficiente y especializado** para diferentes tipos de argumentos. +* [Conversiones y promociones](http://docs.julialang.org/en/release-0.3/manual/conversion-and-promotion) para tipos numéricos y de otros tipos, **elegantes y extensibles**. +* Soporte eficiente para [Unicode](http://es.wikipedia.org/wiki/Unicode), incluyendo [UTF-8](http://es.wikipedia.org/wiki/UTF-8) pero sin limitarse solo a este. +* [Licencia MIT](https://github.com/JuliaLang/julia/blob/master/LICENSE.md): libre y de código abierto. + +Esto se basa en la versión `0.3.11`. + +```julia +# Los comentarios de una línea comienzan con una almohadilla (o signo de gato). + +#= + Los commentarios multilínea pueden escribirse + usando '#=' antes de el texto y '=#' + después del texto. También se pueden anidar. =# -#################################################### -## 1. Tipos de datos primitivos y operadores. -#################################################### -# Todo en Julia es una expresión. +############################################## +# 1. Tipos de datos primitivos y operadores. # +############################################## + +# Todo en Julia es una expresión (Expr). # Hay varios tipos básicos de números. -3 # => 3 (Int64) -3.2 # => 3.2 (Float64) -2 + 1im # => 2 + 1im (Complex{Int64}) -2//3 # => 2//3 (Rational{Int64}) +3 # => 3 # Int64 +3.2 # => 3.2 # Float64 +2 + 1im # => 2 + 1im # Complex{Int64} +2 // 3 # => 2//3 # Rational{Int64} # Todos los operadores infijos normales están disponibles. -1 + 1 # => 2 -8 - 1 # => 7 -10 * 2 # => 20 -35 / 5 # => 7.0 -5/2 # => 2.5 # dividir un Int por un Int siempre resulta en un Float -div (5, 2) # => 2 # para un resultado truncado, usa div -5 \ 35 # => 7.0 -2 ^ 2 # => 4 # exponente, no es xor -12 % 10 # => 2 - -# Refuerza la precedencia con paréntesis -(1 + 3) * 2 # => 8 - -# Operadores a nivel de bit -~2 # => -3 # bitwise not -3 & 5 # => 1 # bitwise and -2 | 4 # => 6 # bitwise or -2 $ 4 # => 6 # bitwise xor -2 >>> 1 # => 1 # logical shift right -2 >> 1 # => 1 # arithmetic shift right -2 << 1 # => 4 # logical/arithmetic shift left - -# Se puede utilizar la función bits para ver la representación binaria de un -# número. +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 # dividir un Int por un Int siempre resulta + # en un Float +5 / 2 # => 2.5 +div(5, 2) # => 2 # para un resultado truncado, usa la función div +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # exponente, no es XOR +12 % 10 # => 2 + +# Refuerza la precedencia con paréntesis. +(1 + 3) * 2 # => 8 + +# Operadores a nivel de bit. +~2 # => -3 # bitwise NOT +3 & 5 # => 1 # bitwise AND +2 | 4 # => 6 # bitwise OR +2 $ 4 # => 6 # bitwise XOR +2 >>> 1 # => 1 # desplazamiento lógico hacia la derecha +2 >> 1 # => 1 # desplazamiento aritmético hacia la derecha +2 << 1 # => 4 # desplazamiento lógico/aritmético hacia la izquierda + +# Se puede utilizar la función bits para ver la representación +# binaria de un número. bits(12345) # => "0000000000000000000000000000000000000000000000000011000000111001" + bits(12345.0) # => "0100000011001000000111001000000000000000000000000000000000000000" -# Valores 'boolean' (booleanos) son primitivos -true -false - -# Operadores Boolean (booleanos) -!true # => false -!false # => true -1 == 1 # => true -2 == 1 # => false -1 != 1 # => false -2 != 1 # => true -1 < 10 # => true -1 > 10 # => false -2 <= 2 # => true -2 >= 2 # => true +# Los valores booleanos (Bool) son primitivos. +true # => true +false # => false + +# Operadores booleanos. +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true + # ¡Las comparaciones pueden ser concatenadas! -1 < 2 < 3 # => true -2 < 3 < 2 # => false +1 < 2 < 3 # => true +2 < 3 < 2 # => false -# Strings se crean con " -"Esto es un string." +# Los literales de cadenas (String) se crean con la comilla doble: " +"Esto es una cadena." -# Literales de caracteres se escriben con ' +# Los literales de caracteres (Char) se crean con la comilla simple: ' 'a' -# Una string puede ser indexado como una array de caracteres -"Esto es un string."[1] # => 'E' # Índices en Julia empiezen del 1 -# Sin embargo, esto no va a funcionar bien para strings UTF8, +# Una cadena puede ser indexada como una arreglo de caracteres. +"Esto es un string."[1] # => 'E' # Los índices en Julia comienzan en: 1 + +# Sin embargo, esto no va a funcionar bien para las cadenas UTF8 (UTF8String), # Lo que se recomienda es la iteración (map, for, etc). -# $ puede ser utilizado para la interpolación de strings: -"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" -# Se puede poner cualquier expresión de Julia dentro los paréntesis. +# $ puede ser utilizado para la interpolación de cadenas, se puede poner +# cualquier expresión de Julia dentro los paréntesis. +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" + +# Otra forma para formatear cadenas es usando el macro printf. +@printf "%d es menor de %f\n" 4.5 5.3 # 5 es menor de 5.300000 -# Otro forma de formatear strings es el macro printf -@printf "%d es menor de %f" 4.5 5.3 # 5 es menor de 5.300000 +# ¡Imprimir es muy fácil! +println("¡Hola Julia!") # ¡Hola Julia! -# Imprimir es muy fácil -println("Soy Julia. ¡Encantado de conocerte!") -#################################################### -## 2. Variables y Colecciones -#################################################### +############################## +# 2. Variables y Colecciones # +############################## # No hay necesidad de declarar las variables antes de asignarlas. -una_variable = 5 # => 5 -una_variable # => 5 +una_variable = 5 # => 5 +una_variable # => 5 -# Acceder a variables no asignadas previamente es una excepción. +# Acceder a una variable no asignada previamente es una excepción. try - otra_variable # => ERROR: some_other_var not defined + otra_variable # ERROR: otra_variable not defined catch e - println(e) + println(e) # UndefVarError(:otra_variable) end -# Los nombres de variables comienzan con una letra. -# Después de eso, puedes utilizar letras, dígitos, guiones y signos de +# Los nombres de variables comienzan con una letra o guion bajo: _. +# Después de eso, puedes utilizar letras, dígitos, guiones bajos y signos de # exclamación. -OtraVariable123! = 6 # => 6 +otraVariable_123! = 6 # => 6 + +# También puedes utilizar caracteres Unicode. +☃ = 8 # => 8 -# También puede utilizar caracteres unicode -☃ = 8 # => 8 # Estos son especialmente útiles para la notación matemática -2 * π # => 6.283185307179586 - -# Una nota sobre las convenciones de nomenclatura de Julia: -# -# * Los nombres de las variables aparecen en minúsculas, con separación de -# palabra indicado por underscore ('\ _'). -# -# * Los nombres de los tipos comienzan con una letra mayúscula y separación de -# palabras se muestra con CamelCase en vez de underscore. -# -# * Los nombres de las funciones y los macros están en minúsculas, sin -# underscore. -# -# * Funciones que modifican sus inputs tienen nombres que terminan en!. Estos -# funciones a veces se llaman mutating functions o in-place functions. - -# Los Arrays almacenan una secuencia de valores indexados entre 1 hasta n -a = Int64[] # => 0-element Int64 Array - -# Literales de arrays 1-dimensionales se pueden escribir con valores separados -# por comas. -b = [4, 5, 6] # => 3-element Int64 Array: [4, 5, 6] -b[1] # => 4 -b[end] # => 6 - -# Los arrays 2-dimensionales usan valores separados por espacios y filas -# separados por punto y coma. -matrix = [1 2; 3 4] # => 2x2 Int64 Array: [1 2; 3 4] - -# Añadir cosas a la final de una lista con push! y append! -push!(a,1) # => [1] -push!(a,2) # => [1,2] -push!(a,4) # => [1,2,4] -push!(a,3) # => [1,2,4,3] -append!(a,b) # => [1,2,4,3,4,5,6] - -# Eliminar de la final con pop -pop!(b) # => 6 y b ahora es [4,5] - -# Vamos a ponerlo de nuevo -push!(b, 6) # b es ahora [4,5,6] de nuevo. - -a[1] # => 1 # recuerdan que los índices de Julia empiezan desde 1, no desde 0! - -# end es una abreviatura para el último índice. Se puede utilizar en cualquier -# expresión de indexación -a[end] # => 6 - -# tambien hay shift y unshift -shift!(a) # => 1 y a es ahora [2,4,3,4,5,6] -unshift!(a,7) # => [7,2,4,3,4,5,6] - -# Nombres de funciónes que terminan en exclamaciones indican que modifican -# su argumento. -arr = [5,4,6] # => 3-element Int64 Array: [5,4,6] -sort(arr) # => [4,5,6]; arr es todavía [5,4,6] -sort!(arr) # => [4,5,6]; arr es ahora [4,5,6] - -# Buscando fuera de límites es un BoundsError +# (multiplicación implicita). +2π # => 6.283185307179586 + +#= + Una nota sobre las convenciones de nomenclatura de Julia: + + * Los nombres de las variables aparecen en minúsculas, con separación de + palabra indicado por un guion bajo: + + otra_variable + + * Los nombres de los tipos comienzan con una letra mayúscula y separación de + palabras se muestra con CamelCase en vez de guion bajo: + + OtroTipo + + * Los nombres de las funciones y los macros están en minúsculas, sin + underscore: + + otromacro + + * Funciones que modifican sus entradas tienen nombres que terminan en: !. + Estas funciones a veces se les llaman funciones transformadoras o + funciones in situ: + + otra_funcion! +=# + +# Los arreglos (Array) almacenan una secuencia de valores indexados de entre 1 hasta n. +a = Int64[] # => 0-element Array{Int64,1} + +# Los literales de arregos unidimensionales se pueden escribir con valores +# separados por comas. +b = [4, 5, 6] +#= + => 3-element Array{Int64,1}: + 4 + 5 + 6 +=# +b[1] # => 4 +b[end] # => 6 + +# Los arreglos bidimensionales usan valores separados por espacios y filas +# separadas por punto y coma. +matrix = [1 2; 3 4] +#= + => 2x2 Array{Int64,2}: + 1 2 + 3 4 +=# + +# Añadir cosas a la final de un arreglo con push! y append!. +push!(a, 1) # => [1] +push!(a, 2) # => [1,2] +push!(a, 4) # => [1,2,4] +push!(a, 3) # => [1,2,4,3] +append!(a, b) # => [1,2,4,3,4,5,6] + +# Eliminar del final con pop!. +pop!(b) # => 6 y b ahora es: [4,5] + +# Vamos a ponerlo de nuevo. +push!(b, 6) # b es ahora [4,5,6] de nuevo + +a[1] # => 1 # recuerda, los índices de Julia empiezan desde 1, no desde 0! + +# end es una abreviatura para el último índice. Se puede utilizar en cualquier +# expresión de indexación. +a[end] # => 6 + +# También hay shift! y unshift!. +shift!(a) # => 1 y a es ahora: [2,4,3,4,5,6] +unshift!(a, 7) # => [7,2,4,3,4,5,6] + +# Los nombres de funciónes que terminan en exclamaciones indican que modifican +# su o sus argumentos de entrada. +arr = [5, 4, 6] # => 3-element Array{Int64,1}: [5,4,6] +sort(arr) # => [4,5,6] y arr es todavía: [5,4,6] +sort!(arr) # => [4,5,6] y arr es ahora: [4,5,6] + +# Buscando fuera de límites es un BoundsError. try - a[0] # => ERROR: BoundsError() in getindex at array.jl:270 - a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 + a[0] # ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # ERROR: BoundsError() in getindex at array.jl:270 catch e - println(e) + println(e) # BoundsError() end -# Errors dan la línea y el archivo de su procedencia, aunque sea en el standard -# library. Si construyes Julia de source, puedes buscar en el source para -# encontrar estos archivos. +# Las excepciones y los errores dan la línea y el archivo de su procedencia, +# aunque provenga de la librería estándar. Si compilas Julia del código fuente, +# puedes buscar en el código para encontrar estos archivos. + +# Se puede inicializar un arreglo con un rango (Range). +a = [1:5] # => 5-element Array{Int64,1}: [1,2,3,4,5] -# Se puede inicializar arrays de un range -a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] +# Puedes mirar en los rangos con la sintaxis de rebanada. +a[1:3] # => [1,2,3] +a[2:end] # => [2,3,4,5] -# Puedes mirar en ranges con sintaxis slice. -a[1:3] # => [1, 2, 3] -a[2:end] # => [2, 3, 4, 5] +# Eliminar elementos de un arreglo por índice con splice! +arr = [3, 4, 5] +splice!(arr, 2) # => 4 y arr es ahora: [3,5] -# Eliminar elementos de una array por índice con splice! -arr = [3,4,5] -splice!(arr,2) # => 4 ; arr es ahora [3,5] +# Concatenar arreglos con append! +b = [1, 2, 3] +append!(a, b) # a ahora es: [1,2,3,4,5,1,2,3] -# Concatenar listas con append! -b = [1,2,3] -append!(a,b) # ahroa a es [1, 2, 3, 4, 5, 1, 2, 3] +# Comprueba la existencia de un elemento en un arreglo con in. +in(1, a) # => true -# Comprueba la existencia en una lista con in -in(1, a) # => true +# Examina la longitud con length. +length(a) # => 8 -# Examina la longitud con length -length(a) # => 8 +# Las tuplas (Tuple) son inmutables. +tup = (1, 2, 3) # => (1,2,3) # una tupla tipo (Int64,Int64,Int64) +tup[1] # => 1 -# Tuples son immutable. -tup = (1, 2, 3) # => (1,2,3) # un (Int64,Int64,Int64) tuple. -tup[1] # => 1 try: - tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) + tup[1] = 3 # ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) catch e - println(e) + println(e) # MethodError(setindex!,(:tup,3,1)) end -# Muchas funciones de lista también trabajan en las tuples -length(tup) # => 3 -tup[1:2] # => (1,2) -in(2, tup) # => true +# Muchas funciones de arreglos también trabajan en con las tuplas. +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true -# Se puede desempacar tuples en variables -a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 +# Se pueden desempacar las tuplas en variables individuales. +a, b, c = (1, 2, 3) # => (1,2,3) # ahora a es 1, b es 2 y c es 3 -# Los tuples se crean, incluso si se omite el paréntesis -d, e, f = 4, 5, 6 # => (4,5,6) +# Los tuplas se crean, incluso si se omiten los paréntesis. +d, e, f = 4, 5, 6 # => (4,5,6) -# Un tuple 1-elemento es distinto del valor que contiene -(1,) == 1 # => false -(1) == 1 # => true +# Una tupla de un elemento es distinta del valor que contiene. +(1,) == 1 # => false +(1) == 1 # => true -# Mira que fácil es cambiar dos valores -e, d = d, e # => (5,4) # d is now 5 and e is now 4 +# Mira que fácil es cambiar dos valores! +e, d = d, e # => (5,4) # ahora d es 5 y e es 4 +# Los diccionarios (Dict) son arreglos asociativos. +dicc_vacio = Dict() # => Dict{Any,Any} with 0 entries -# Dictionaries almanecan mapeos -dict_vacio = Dict() # => Dict{Any,Any}() +# Se puede crear un diccionario usando una literal. +dicc_lleno = ["uno" => 1, "dos" => 2, "tres" => 3] +#= + => Dict{ASCIIString,Int64} with 3 entries: + "tres" => 3 + "dos" => 2 + "uno" => 1 +=# + +# Busca valores con: []. +dicc_lleno["uno"] # => 1 + +# Obtén todas las claves con. +keys(dicc_lleno) +#= + => KeyIterator for a Dict{ASCIIString,Int64} with 3 entries. Keys: + "tres" + "dos" + "uno" +=# -# Se puede crear un dictionary usando un literal -dict_lleno = ["one"=> 1, "two"=> 2, "three"=> 3] -# => Dict{ASCIIString,Int64} +# Nota: los elementos del diccionario no están ordenados y no se guarda el orden +# en que se insertan. -# Busca valores con [] -dict_lleno["one"] # => 1 +# Obtén todos los valores. +values(dicc_lleno) +#= + => ValueIterator for a Dict{ASCIIString,Int64} with 3 entries. Values: + 3 + 2 + 1 +=# -# Obtén todas las claves -keys(dict_lleno) -# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - claves del dictionary no están ordenados ni en el orden en que se -# insertan. +# Nota: igual que el anterior en cuanto a ordenamiento de los elementos. -# Obtén todos los valores -values(dict_lleno) -# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) -# Nota - Igual que el anterior en cuanto a ordenamiento de claves. +# Comprueba si una clave existe en un diccionario con in y haskey. +in(("uno", 1), dicc_lleno) # => true +in(("tres", 3), dicc_lleno) # => false -# Compruebe si hay existencia de claves en un dictionary con in y haskey -in(("uno", 1), dict_lleno) # => true -in(("tres", 3), dict_lleno) # => false -haskey(dict_lleno, "one") # => true -haskey(dict_lleno, 1) # => false +haskey(dicc_lleno, "uno") # => true +haskey(dicc_lleno, 1) # => false -# Tratando de buscar una clave que no existe producirá un error +# Tratar de obtener un valor con una clave que no existe producirá un error. try - dict_lleno["dos"] # => ERROR: key not found: dos in getindex at dict.jl:489 + # ERROR: key not found: cuatro in getindex at dict.jl:489 + dicc_lleno["cuatro"] catch e - println(e) + println(e) # KeyError("cuatro") end -# Utilice el método get para evitar ese error proporcionando un valor -# predeterminado -# get(dictionary,key,default_value) -get(dict_lleno,"one",4) # => 1 -get(dict_lleno,"four",4) # => 4 +# Utiliza el método get para evitar este error proporcionando un valor +# predeterminado: get(diccionario, clave, valor_predeterminado). +get(dicc_lleno, "uno", 4) # => 1 +get(dicc_lleno, "cuatro", 4) # => 4 + +# Usa conjuntos (Set) para representar colecciones de valores únicos, no +# ordenados. +conjunto_vacio = Set() # => Set{Any}({}) -# Usa Sets para representar colecciones (conjuntos) de valores únicos, no -# ordenadas -conjunto_vacio = Set() # => Set{Any}() -# Iniciar una set de valores -conjunto_lleno = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) +# Iniciar una conjunto de valores. +conjunto_lleno = Set(1, 2, 2, 3, 4) # => Set{Int64}({4,2,3,1}) -# Añadir más valores a un conjunto -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) -push!(conjunto_lleno,5) # => Set{Int64}(5,4,2,3,1) +# Añadir más valores a un conjunto. +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) +push!(conjunto_lleno, 5) # => Set{Int64}({4,2,3,5,1}) -# Compruebe si los valores están en el conjunto -in(2, conjunto_lleno) # => true -in(10, conjunto_lleno) # => false +# Comprobar si los valores están en el conjunto. +in(2, conjunto_lleno) # => true +in(10, conjunto_lleno) # => false -# Hay funciones de intersección de conjuntos, la unión, y la diferencia. -conjunto_otro= Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) -intersect(conjunto_lleno, conjunto_otro) # => Set{Int64}(3,4,5) -union(conjunto_lleno, conjunto_otro) # => Set{Int64}(1,2,3,4,5,6) -setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) +# Hay funciones de intersección, unión y diferencia de conjuntos. +otro_conjunto = Set(3, 4, 5, 6) # => Set{Int64}({6,4,5,3}) +intersect(conjunto_lleno, otro_conjunto) # => Set{Int64}({3,4,5}) +union(conjunto_lleno, otro_conjunto) # => Set{Int64}({1,2,3,4,5,6}) +setdiff(Set(1, 2, 3, 4), Set(2, 3, 5)) # => Set{Int64}({1,4}) -#################################################### -## 3. Control de Flujo -#################################################### +####################### +# 3. Control de Flujo # +####################### -# Hagamos una variable +# Hagamos una variable. una_variable = 5 -# Aquí está una declaración de un 'if'. La indentación no es significativa en -# Julia +# Aquí está la declaración de un if. La indentación no es significativa en +# Julia. if una_variable > 10 - println("una_variable es completamente mas grande que 10.") -elseif una_variable < 10 # Este condición 'elseif' es opcional. - println("una_variable es mas chica que 10.") -else # Esto también es opcional. - println("una_variable es de hecho 10.") + println("una_variable es completamente mayor que 10.") +elseif una_variable < 10 # esta condición elseif es opcional + println("una_variable es menor que 10.") +else # esto también es opcional + println("De echo una_variable es 10.") end -# => imprime "una_variable es mas chica que 10." +# imprime: una_variable es menor que 10. -# For itera sobre tipos iterables -# Tipos iterables incluyen Range, Array, Set, Dict, y String. -for animal=["perro", "gato", "raton"] - println("$animal es un mamifero") - # Se puede usar $ para interpolar variables o expresiónes en strings +# El bucle for itera sobre tipos iterables, ie. Range, Array, Set, +# Dict y String. +for animal in ["perro", "gato", "ratón"] + # Se puede usar $ para interpolar variables o expresiones en ls cadenas. + println("$animal es un mamífero.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for a in ["perro"=>"mamifero","gato"=>"mamifero","raton"=>"mamifero"] - println("$(a[1]) es un $(a[2])") +for a in ["perro" => "mamífero", "gato" => "mamífero", "ratón" => "mamífero"] + println("$(a[1]) es un $(a[2]).") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -for (k,v) in ["perro"=>"mamifero", "gato"=>"mamifero", "raton"=>"mamifero"] - println("$k es un $v") +for (k,v) in ["perro"=>"mamífero", "gato"=>"mamífero", "ratón"=>"mamífero"] + println("$k es un $v.") end -# imprime: -# perro es un mamifero -# gato es un mamifero -# raton es un mamifero +#= + imprime: + perro es un mamífero. + gato es un mamífero. + ratón es un mamífero. +=# -# While itera hasta que una condición no se cumple. +# El bucle while itera hasta que una condición se deje de cumplir. x = 0 while x < 4 println(x) - x += 1 # versión corta de x = x + 1 + x += 1 # versión corta de: x = x + 1 end -# imprime: -# 0 -# 1 -# 2 -# 3 +#= +imprime: + 0 + 1 + 2 + 3 +=# -# Maneja excepciones con un bloque try/catch -try - error("ayuda") +# Maneja excepciones con un bloque try/catch. +try # intentar + error("Ooops!") catch e - println("capturando $e") + println("capturando: $e") # capturando: ErrorException("Ooops!") end -# => capturando ErrorException("ayuda") -#################################################### -## 4. Funciones -#################################################### +################ +# 4. Funciones # +################ -# Usa 'function' para crear nuevas funciones +# Usa function para crear nuevas funciones. -#function nombre(arglist) -# cuerpo... -#end +#= + function nombre(arglist) + cuerpo... + end +=# function suma(x, y) println("x es $x e y es $y") - # Las funciones devuelven el valor de su última declaración + # las funciones devuelven el valor de su última expresión x + y end +# => suma (generic function with 1 method) -suma(5, 6) # => 11 # después de imprimir "x es 5 e y es de 6" +suma(5, 6) # => 11 # después de imprimir: x es 5 e y es 6 + +# También puedes usar esta otra sintaxis para definir funciones! +resta(x, y) = x - y # => resta (generic function with 1 method) # Puedes definir funciones que toman un número variable de -# argumentos posicionales +# argumentos posicionales (el ... se llama un splat). function varargs(args...) + # Usa la palabra clave return para regresar desde cualquier + # lugar de la función. return args - # Usa la palabra clave return para devolver en cualquier lugar de la función end # => varargs (generic function with 1 method) -varargs(1,2,3) # => (1,2,3) +varargs(1, 2, 3) # => (1,2,3) +varargs([1, 2, 3]) # => ([1,2,3],) -# El ... se llama un splat. -# Acabamos de utilizar lo en una definición de función. -# También se puede utilizar en una llamada de función, -# donde va splat un Array o el contenido de un Tuple en la lista de argumentos. -Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # Produce un Set de Arrays -Set([1,2,3]...) # => Set{Int64}(1,2,3) # esto es equivalente a Set(1,2,3) +# Acabamos de utilizar el splat (...) en la definición de una función. También +# se puede utilizar al llamar a una función, donde se esparce un arreglo, tupla +# o en general una secuencia iterable en la tupla de argumentos. +varargs([1, 2, 3]...) # => (1,2,3) # igual que: varargs(1, 2, 3) -x = (1,2,3) # => (1,2,3) -Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # un Set de Tuples -Set(x...) # => Set{Int64}(2,3,1) +x = (1, 2, 3) # => (1,2,3) +varargs(x) # => ((1,2,3),) +varargs(x...) # => (1,2,3) +varargs("abc"...) # => ('a','b','c') -# Puede definir funciones con argumentos posicionales opcionales -function defaults(a,b,x=5,y=6) +# Puedes definir funciones con argumentos posicionales opcionales. +function defaults(a, b, x=5, y=6) return "$a $b y $x $y" end +# => defaults (generic function with 3 methods) + +defaults('h', 'g') # => "h g y 5 6" +defaults('h', 'g', 'j') # => "h g y j 6" +defaults('h', 'g', 'j', 'k') # => "h g y j k" -defaults('h','g') # => "h g y 5 6" -defaults('h','g','j') # => "h g y j 6" -defaults('h','g','j','k') # => "h g y j k" try - defaults('h') # => ERROR: no method defaults(Char,) - defaults() # => ERROR: no methods defaults() + defaults('h') # ERROR: `defaults` has no method matching defaults(::Char) + defaults() # ERROR: `defaults` has no method matching defaults() catch e - println(e) + println(e) # MethodError(defaults,('h',)) end -# Puedes definir funciones que toman argumentos de palabra clave -function args_clave(;k1=4,nombre2="hola") # note the ; - return ["k1"=>k1,"nombre2"=>nombre2] +# Puedes definir funciones que tomen argumentos de palabras clave. +function args_clave(;k1=4, nombre2="hola") # nota el punto y coma: ; + return ["k1" => k1, "nombre2" => nombre2] end +# => args_clave (generic function with 1 method) -args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] -args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] -args_clave() # => ["nombre2"=>"hola","k1"=>4] +args_clave(nombre2="ness") # => ["nombre2"=>"ness","k1"=>4] +args_clave(k1="mine") # => ["k1"=>"mine","nombre2"=>"hola"] +args_clave() # => ["nombre2"=>"hola","k1"=>4] -# Puedes combinar todo tipo de argumentos en la misma función -function todos_los_args(arg_normal, arg_posicional_opcional=2; arg_clave="foo") - println("argumento normal: $arg_normal") - println("argumento optional: $arg_posicional_opcional") - println("argumento de clave: $arg_clave") +# Puedes combinar todo tipo de argumentos en la misma función. +function todos_los_args(arg_posicional, arg_opcional=2; arg_clave="foo") + println("argumento posicional: $arg_posicional") + println(" argumento opcional: $arg_opcional") + println(" argumento clave: $arg_clave") end +# => todos_los_args (generic function with 2 methods) +# No se necesita punto y coma ; al llamar la función usando un argumento clave, +# esto solo es necesario en la definición de la función. todos_los_args(1, 3, arg_clave=4) -# imprime: -# argumento normal: 1 -# argumento optional: 3 -# argumento de clave: 4 +#= + imprime: + argumento posicional: 1 + argumento opcional: 3 + argumento clave: 4 +=# -# Julia tiene funciones de primera clase +# Julia tiene funciones de primera clase. function crear_suma(x) - suma = function (y) + suma = function (y) # función anónima return x + y end return suma end +# => crear_suma (generic function with 1 method) -# Esta es el sintaxis "stabby lambda" para crear funciones anónimas -(x -> x > 2)(3) # => true +# Esta es otra sintaxis (estilo cálculo lambda), para crear funciones anónimas. +(x -> x > 2)(3) # => true # Esta función es idéntica a la crear_suma implementación anterior. -function crear_suma(x) - y -> x + y -end +crear_suma(x) = y -> x + y -# También puedes nombrar la función interna, si quieres +# También puedes nombrar la función interna, si quieres. function crear_suma(x) function suma(y) x + y end suma end +# => crear_suma (generic function with 1 method) -suma_10 = crear_suma(10) -suma_10(3) # => 13 +suma_10 = crear_suma(10) # => suma (generic function with 1 method) +suma_10(3) # => 13 +# Hay funciones integradas de orden superior. +map(suma_10, [1, 2, 3]) # => [11,12,13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6,7] -# Hay funciones integradas de orden superior -map(suma_10, [1,2,3]) # => [11, 12, 13] -filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +# Se puede pasar un bloque a las funciones cuyo primer argumento posicional +# es otra función, como en map y filter. +map([1, 2, 3]) do arr + suma_10(arr) +end +#= + => 3-element Array{Int64,1}: + 11 + 12 + 13 +=# + +filter([3, 4, 5, 6, 7]) do arr + (x -> x > 5)(arr) +end +#= + => 2-element Array{Int64,1}: + 6 + 7 +=# -# Podemos usar listas por comprensión para mapeos -[suma_10(i) for i=[1, 2, 3]] # => [11, 12, 13] -[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +# Podemos usar comprensiones de listas multidimensionales. +[suma_10(i) for i = [1, 2, 3]] # => [11, 12, 13] # 1D +[suma_10(i) for i in [1, 2, 3]] # => [11, 12, 13] -#################################################### -## 5. Tipos -#################################################### +[i*j for i = [1:3], j in [1:3]] # 2D +#= + => 3x3 Array{Int64,2}: + 1 2 3 + 2 4 6 + 3 6 9 +=# + +[i*j/k for i = [1:3], j = [1:3], k in [1:3]] # 3D +#= + => 3x3x3 Array{Float64,3}: + [:, :, 1] = + 1.0 2.0 3.0 + 2.0 4.0 6.0 + 3.0 6.0 9.0 + + [:, :, 2] = + 0.5 1.0 1.5 + 1.0 2.0 3.0 + 1.5 3.0 4.5 + + [:, :, 3] = + 0.333333 0.666667 1.0 + 0.666667 1.33333 2.0 + 1.0 2.0 3.0 +=# + + +############ +# 5. Tipos # +############ -# Julia tiene sistema de tipos. # Cada valor tiene un tipo y las variables no tienen propios tipos. -# Se puede utilizar la función `typeof` para obtener el tipo de un valor. -typeof(5) # => Int64 +# Se puede utilizar la función typeof para obtener el tipo de un valor. +typeof(5) # => Int64 # en un sistema de 64 bits, de lo contrario: Int32 -# Los tipos son valores de primera clase -typeof(Int64) # => DataType -typeof(DataType) # => DataType -# DataType es el tipo que representa los tipos, incluyéndose a sí mismo. +# Los tipos son valores de primera clase, DataType es el tipo que representa a +# los tipos, incluyéndose a sí mismo. +typeof(Int64) # => DataType +typeof(DataType) # => DataType -# Los tipos se usan para la documentación, optimizaciones, y envio. -# No están comprobados estáticamente. +# Los tipos se usan para la documentación, para optimizaciones +# y el despacho múltiple. No están comprobados estáticamente. -# Los usuarios pueden definir tipos -# Son como registros o estructuras en otros idiomas. -# Nuevos tipos se definen utilizado la palabra clave `type`. +# Los usuarios pueden definir sus propios tipos. +# Son como registros o estructuras en otros idiomas. +# Un nuevo tipos se define utilizado la palabra clave type. # type Nombre -# field::OptionalType +# atributo::UnTipo # las anotaciones de tipos son opcionales # ... # end type Tigre - longituddecola::Float64 - colordelpelaje # no incluyendo una anotación de tipo es el mismo que `::Any` + longitud_cola::Float64 + color_pelaje # sin una anotación de tipo, es lo mismo que `::Any` end -# Los argumentos del constructor por default son las propiedades -# del tipo, en el orden en que están listados en la definición -tigger = Tigre(3.5,"anaranjado") # => Tiger(3.5,"anaranjado") +# Los argumentos del constructor por defecto son los atributos +# del tipo, en el orden en que están listados en la definición. +tigre = Tigre(3.5, "anaranjado") # => Tigre(3.5,"anaranjado") -# El tipo funciona como la función constructora de valores de ese tipo -sherekhan = typeof(tigger)(5.6,"fuego") # => Tiger(5.6,"fuego") +# El tipo funciona como método constructor para los valores de ese tipo. +sherekhan = typeof(tigre)(5.6, "fuego") # => Tigre(5.6,"fuego") -# Este estilo de tipos son llamados tipos concrete -# Se pueden crear instancias, pero no pueden tener subtipos. -# La otra clase de tipos es tipos abstractos (abstract types). +# Este estilo de tipos son llamados tipos concretos. +# Se pueden crear instancias de estos, pero no pueden tener subtipos. +# La otra clase de tipos son los tipos abstractos. # abstract Nombre -abstract Gato # sólo un nombre y un punto en la jerarquía de tipos - -# De los tipos Abstract no se pueden crear instancias, pero pueden tener -# subtipos. Por ejemplo, Number es un tipo abstracto. -subtypes(Number) # => 6-element Array{Any,1}: - # Complex{Float16} - # Complex{Float32} - # Complex{Float64} - # Complex{T<:Real} - # Real -subtypes(Gato) # => 0-element Array{Any,1} - -# Cada tipo tiene un supertipo, utilice la función `súper` para conseguirlo. -typeof(5) # => Int64 -super(Int64) # => Signed -super(Signed) # => Real -super(Real) # => Number -super(Number) # => Any -super(super(Signed)) # => Number -super(Any) # => Any -# Todo de estos tipos, a excepción de Int64, son abstractos. - -# <: es el operador de subtipos -type Leon <: Gato # Leon es un subtipo de Gato - color_de_crin - rugido::String -end +abstract Gato # sólo un nombre y un punto en la jerarquía de tipos + +# No se pueden crear instancias de los tipos abstractos, pero pueden tener +# subtipos. Por ejemplo, Number es un tipo abstracto. +subtypes(Number) +#= + => 2-element Array{Any,1}: + Complex{T<:Real} + Real +=# + +subtypes(Gato) # => 0-element Array{Any,1} + +# Cada tipo tiene un supertipo, utiliza la función súper para conseguirlo. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Integer +super(Integer) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Real +super(Any) # => Any -# Se puede definir más constructores para su tipo. -# Sólo defina una función del mismo nombre que el tipo -# y llame a un constructor existente para obtener un valor del tipo correcto -Leon(rugido::String) = Leon("verde",rugido) -# Este es un constructor externo porque es fuera de la definición del tipo - -type Pantera <: Gato # Pantera tambien es un a subtipo de Cat - color_de_ojos - Pantera() = new("verde") - # Panteras sólo tendrán este constructor, y ningún constructor - # predeterminado. +# Todos estos tipos, a excepción de Int64, son abstractos. + +# <: es el operador de subtipos. +type Leon <: Gato # Leon es un subtipo de Gato + color_crin + rugido::String end -# Utilizar constructores internos, como Panther hace, te da control sobre cómo -# se pueden crear valores del tipo. Cuando sea posible, debes utilizar -# constructores exteriores en lugar de los internos. -#################################################### -## 6. Envio múltiple -#################################################### +# Se pueden definir más constructores para un tipo. +# Sólo define una función del mismo nombre que el tipo y llama al constructor +# existente para obtener un valor del tipo correcto. -# En Julia, todas las funciones nombradas son funciones genéricas. -# Esto significa que se construyen a partir de muchos métodos pequeños -# Cada constructor de Leon es un método de la función genérica Leon. +# Este es un constructor externo porque es fuera de la definición del tipo. +Leon(rugido::String) = Leon("verde", rugido) -# Por ejemplo, vamos a hacer un maullar función: +type Pantera <: Gato # Pantera también es un a subtipo de Gato + color_ojos -# Definiciones para Leon, Pantera, y Tigre -function maullar(animal::Leon) - animal.rugido # acceso utilizando notación de puntos + # Pantera sólo tendrá este constructor, y ningún constructor predeterminado. + Pantera() = new("verde") end -function maullar(animal::Pantera) - "grrr" -end +# Utilizar constructores internos, como se hace en Pantera, te da control sobre +# cómo se pueden crear valores de este tipo. Cuando sea posible, debes utilizar +# constructores externos en lugar de internos. -function maullar(animal::Tigre) - "rawwwr" -end -# Prueba de la función maullar -maullar(tigger) # => "rawwr" -maullar(Leon("cafe","ROAAR")) # => "ROAAR" -maullar(Pantera()) # => "grrr" +######################## +# 6. Despacho Múltiple # +######################## -# Revisar la jerarquía de tipos locales -issubtype(Tigre,Gato) # => false -issubtype(Leon,Gato) # => true -issubtype(Pantera,Gato) # => true +# En Julia, todas las funciones nombradas son funciones genéricas. +# Esto significa que se construyen a partir de muchos métodosmás pequeños. +# Cada constructor de Leon es un método de la función genérica Leon. -# Definición de una función que toma Gatos -function mascota(gato::Gato) - println("El gato dice $(maullar(gato))") -end +# Por ejemplo, vamos a hacer métodos para para Leon, Pantera, y Tigre de una +# función genérica maullar: + +# acceso utilizando notación de puntos +maullar(animal::Leon) = animal.rugido +# => maullar (generic function with 1 method) +maullar(animal::Pantera) = "grrr" +# => maullar (generic function with 2 methods) +maullar(animal::Tigre) = "rawwwr" +# => maullar (generic function with 3 methods) + +# Se puede obtener una lista de métodos con la función methods. +methods(maullar) +#= + # 3 methods for generic function "maullar": + maullar(animal::Leon) at none:1 + maullar(animal::Pantera) at none:1 + maullar(animal::Tigre) at none:1 +=# + +# Prueba de la función maullar. +maullar(tigre) # => "rawwwr" +maullar(Leon("cafe", "ROAAR")) # => "ROAAR" +maullar(Pantera()) # => "grrr" + +# Revisar la jerarquía de tipos locales. +issubtype(Tigre, Gato) # => false # igual que: Tigre <: Gato +issubtype(Leon, Gato) # => true # igual que: Leon <: Gato +issubtype(Pantera, Gato) # => true + +# Definición de una función que acepta argumentos de tipo Gato. +mascota(gato::Gato) = println("El gato dice $(maullar(gato))") + +mascota(Leon("42")) # El gato dice 42 -mascota(Leon("42")) # => imprime "El gato dice 42" try - mascota(tigger) # => ERROR: no method mascota(Tigre)) + mascota(tigre) # ERROR: `mascota` has no method matching mascota(::Tigre) catch e - println(e) + println(e) # MethodError(mascota,(Tigre(3.5,"anaranjado"),)) end -# En los lenguajes orientados a objetos, expedición única es común. Esto -# significa que el método se recogió basándose en el tipo del primer argumento. -# En Julia, todos los tipos de argumentos contribuyen a seleccionar el mejor -# método. +# En los lenguajes orientados a objetos, el despacho simple es común. Esto +# significa que la implementación del método a llamar se selecciona en base +# al tipo del primer argumento. + +# En Julia, los tipos de todos los argumentos contribuyen a seleccionar método +# más específico. # Vamos a definir una función con más argumentos, para que podamos ver la # diferencia -function pelear(t::Tigre,c::Gato) - println("¡El tigre $(t.colordelpelaje) gana!") -end +pelear(t::Tigre, c::Gato) = println("¡El tigre $(t.color_pelaje) gana!") # => pelear (generic function with 1 method) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => ¡El tigre anaranjado gana! +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # ¡El tigre anaranjado gana! -# Vamos a cambiar el comportamiento cuando el Gato es específicamente un Leon -pelear(t::Tigre,l::Leon) = println("El león con melena $(l.color_de_crin) gana") +# Vamos a cambiar el comportamiento cuando el Gato sea específicamente un Leon. +pelear(t::Tigre, l::Leon) = println("El león con melena $(l.color_crin) gana.") # => pelear (generic function with 2 methods) -pelear(tigger,Pantera()) # => imprime ¡El tigre anaranjado gana! -pelear(tigger,Leon("ROAR")) # => imprime El león con melena verde gana +pelear(tigre, Pantera()) # ¡El tigre anaranjado gana! +pelear(tigre, Leon("ROAR")) # El león con melena verde gana. -# No necesitamos un tigre para poder luchar -pelear(l::Leon,c::Gato) = println("El gato victorioso dice $(maullar(c))") -# => fight (generic function with 3 methods) +# No necesitamos un tigre para poder luchar. +pelear(l::Leon, c::Gato) = println("El gato victorioso dice $(maullar(c)).") +# => pelear (generic function with 3 methods) + +methods(pelear) +#= + # 3 methods for generic function "pelear": + pelear(t::Tigre,l::Leon) at none:2 + pelear(t::Tigre,c::Gato) at none:1 + pelear(l::Leon,c::Gato) at none:2 +=# -pelear(Leon("balooga!"),Pantera()) # => imprime El gato victorioso dice grrr +pelear(Leon("balooga!"), Pantera()) # El gato victorioso dice grrr. try - pelear(Pantera(),Leon("RAWR")) # => ERROR: no method pelear(Pantera, Leon)) -catch + # ERROR: `pelear` has no method matching pelear(::Pantera, ::Leon) + pelear(Pantera(),Leon("RAWR")) +catch # no hacer nada con la excepción atrapada end -# Un metodo con el gato primero +# Un metodo con el tipo Gato primero. pelear(c::Gato,l::Leon) = println("El gato le gana al León") -# Warning: New definition -# pelear(Gato,Leon) at none:1 -# is ambiguous with: -# pelear(Leon,Gato) at none:1. -# To fix, define -# pelear(Leon,Leon) -# before the new definition. -# pelear (generic function with 4 methods) - -# Esta advertencia se debe a que no está claro que metodo de pelear será llamado -# en: -pelear(Leon("RAR"),Leon("cafe","rar")) # => imprime El gato victorioso dice rar -# El resultado puede ser diferente en otras versiones de Julia +#= + Warning: New definition + pelear(Gato,Leon) at none:1 + is ambiguous with: + pelear(Leon,Gato) at none:1. + To fix, define + pelear(Leon,Leon) + before the new definition. + pelear (generic function with 4 methods) +=# + +# Esta advertencia se debe a que no está claro que método de pelear +# será llamado en: +pelear(Leon("RAR"),Leon("cafe","rar")) # El gato victorioso dice rar. +# El resultado puede ser diferente en otras versiones de Julia pelear(l::Leon,l2::Leon) = println("Los leones llegan a un empate") -pelear(Leon("GR"),Leon("cafe","rar")) # => imprime Los leones llegan a un empate - - -# Un vistazo al nivel bajo -# Se puede echar un vistazo a la LLVM y el código ensamblador generado. - -area_cuadrada(l) = l * l # area_cuadrada (generic function with 1 method) - -area_cuadrada(5) # => 25 - -# ¿Qué sucede cuando damos area_cuadrada diferentes argumentos? -code_native(area_cuadrada, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Prologue - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # Fetch l from memory? - # imul RAX, RAX # Square l and store the result in RAX - # pop RBP # Restore old base pointer - # ret # Result will still be in RAX - -code_native(area_cuadrada, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) - # pop RBP - # ret - -code_native(area_cuadrada, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) - # pop RBP - # ret - # - -# Ten en cuenta que Julia usará instrucciones de "floating point" si alguno de -# los argumentos son "floats" -# Vamos a calcular el área de un círculo -area_circulo(r) = pi * r * r # circle_area (generic function with 1 method) -area_circulo(5) # 78.53981633974483 + +pelear(Leon("GR"),Leon("cafe","rar")) # Los leones llegan a un empate + + +################################ +# 7. Un vistazo de bajo nivel. # +################################ + +# Se puede echar un vistazo al código IR de LLVM y al código +# ensamblador generado. +area_cuadrado(l) = l * l # => area_cuadrado (generic function with 1 method) + +area_cuadrado(5) # => 25 + +# ¿Qué sucede cuando damos area_cuadrada diferentes tipos de argumentos? +code_native(area_cuadrado, (Int32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 # prólogo + push RBP + mov RBP, RSP + Source line: 1 + imul RDI, RDI # elevar l al cuadrado + mov RAX, RDI # almacenar el resultado en RAX + pop RBP # restaurar el puntero base anterior + ret # el resultado estará en RAX +=# + +code_native(area_cuadrado, (Float32,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulss XMM0, XMM0 # multiplicación escalar de presición simple (AVX) + pop RBP + ret +=# + +code_native(area_cuadrado, (Float64,)) +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + mulsd XMM0, XMM0 # multiplicación escalar de presición doble (AVX) + pop RBP + ret +=# + +# Ten en cuenta que Julia usará instrucciones de punto flotante si el tipo de +# alguno de los argumentos es flotante. + +# Vamos a calcular el área de un círculo. +area_circulo(r) = π * r * r # area_circulo (generic function with 1 method) +area_circulo(5) # 78.53981633974483 code_native(area_circulo, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory - # movabs RAX, 4593140240 # Load pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + Source line: 1 + cvtsi2sd XMM1, EDI # cargar entero r de la memoria + movabs RAX, 4477117456 # cargar constante matemática π + movsd XMM0, QWORD PTR [RAX] + mulsd XMM0, XMM1 # π * r + mulsd XMM0, XMM1 # (π * r) * r + pop RBP + ret +=# code_native(area_circulo, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # +#= + .section __TEXT,__text,regular,pure_instructions + Filename: none + Source line: 1 + push RBP + mov RBP, RSP + movabs RAX, 4477120336 + movsd XMM1, QWORD PTR [RAX] + Source line: 1 + mulsd XMM1, XMM0 + mulsd XMM1, XMM0 + movaps XMM0, XMM1 + pop RBP + ret +=# ``` -## ¿Listo para más? +![Julia-tan](http://www.mechajyo.org/wp/wp-content/uploads/2014/10/3a2c3b7de5dd39aa7f056a707cd4eb59.png) -Puedes obtener muchos más detalles en [The Julia Manual](http://docs.julialang.org/en/latest/manual/) +## ¿Listo para más? -El mejor lugar para obtener ayuda con Julia es el (muy amable) [lista de correos](https://groups.google.com/forum/#!forum/julia-users). +Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3). +El mejor lugar para obtener ayuda con Julia, es en su amigable [lista de correos](https://groups.google.com/forum/#!forum/julia-users). -- cgit v1.2.3 From be32914cc5fc23f733a90dd117bfe96f66fafb58 Mon Sep 17 00:00:00 2001 From: billpcs Date: Sun, 16 Aug 2015 23:26:23 +0300 Subject: fix some sentences left in english --- el-gr/racket-gr.html.markdown | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/el-gr/racket-gr.html.markdown b/el-gr/racket-gr.html.markdown index 4c76b174..4c4576bb 100644 --- a/el-gr/racket-gr.html.markdown +++ b/el-gr/racket-gr.html.markdown @@ -74,8 +74,8 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ (+ 1+2i 2-3i) ; => 3-1i ;;; Λογικές μεταβλητές -#t ; για το true -#f ; για το false +#t ; για το true (αληθής) +#f ; για το false (ψευδής) (not #t) ; => #f (and 0 #f (error "doesn't get here")) ; => #f (or #f 0 (error "doesn't get here")) ; => 0 @@ -88,9 +88,9 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;; Τα αλφαριθμητικά είναι πίνακες χαρακτήρων συγκεκριμένου μήκους "Hello, world!" "Benjamin \"Bugsy\" Siegel" ; Το backslash είναι χαρακτήρας διαφυγής -"Foo\tbar\41\x21\u0021\a\r\n" ; συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, - ; σε Unicode -"λx:(μα.α→α).xx" ; μπορούν να υπάρχουν και Unicode χαρακτήρες +"Foo\tbar\41\x21\u0021\a\r\n" ; Συμπεριλαμβάνονται οι χαρακτήες διαφυγής της C, + ; σε Unicode +"λx:(μα.α→α).xx" ; Μπορούν να υπάρχουν και Unicode χαρακτήρες ;; Μπορούμε να εννώσουμε αλφαριθμητικά! (string-append "Hello " "world!") ; => "Hello world!" @@ -109,14 +109,16 @@ H Racket είναι μια γενικού σκοπού, πολυ-υποδειγ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 2. Μεταβλητές ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; You can create a variable using define -;; a variable name can use any character except: ()[]{}",'`;#|\ +;; Μπορούμε να δημιουργήσουμε μεταβλητές +;; χρησιμοποιώντας το define. +;; Ένα όνομα μεταβλητής μπορεί να χρησιμοποιεί οποιονδήποτε +;; χαρακτήρα, εκτός από τους: ()[]{}",'`;#|\ (define some-var 5) some-var ; => 5 -;; You can also use unicode characters +;; Μπορούμε επίσης να χρησιμοποιήσουμε unicode χαρακτήρες. (define ⊆ subset?) ;; Εδώ ουστιαστικά δίνουμε στη ήδη ύπαρχουσα συνάρτηση subset? - ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. + ;; ένα νέο όνομα ⊆ , και παρακάτω την καλούμε με το νέο της όνομα. (⊆ (set 3 2) (set 1 2 3)) ; => #t ;; Αν ζητήσουμε μια μεταβλητή που δεν έχει οριστεί πρίν π.χ @@ -560,7 +562,7 @@ vec ; => #(1 2 3 4) ;; Οι ενότητες μας επιτρέπουν να οργανώνουμε τον κώδικα σε πολλαπλά ;; αρχεία και επαναχρησιμοποιούμενες βιβλιοθήκες ;; Εδώ χρησιμοποιούμε υπο-ενότητες, εμφωλευμένες μέσα σε μια -;; άλλη ενότητα που δημιουργεί αυτό το κείμενο(ξεκινώντας από +;; άλλη ενότητα που δημιουργεί αυτό το κείμενο (ξεκινώντας από ;; την γραμμή '#lang' ) (module cake racket/base ; ορίζουμε μια ενότητα 'cake' βασισμένο στο ; racket/base @@ -614,8 +616,7 @@ vec ; => #(1 2 3 4) (send charlie get-size) ; => 16 ;; Το `fish%' είναι μία τιμή "πρώτης κλάσης" -;; `fish%' is a plain "first class" value, με το οποίο μπορούμε να -;; κάνουμε προσμείξεις +;; με το οποίο μπορούμε να κάνουμε προσμείξεις (define (add-color c%) (class c% (init color) @@ -663,17 +664,17 @@ vec ; => #(1 2 3 4) ;; (set! tmp other) ;; (set! other tmp_1)) -;; But they are still code transformations, for example: +;; Αλλά ακόμα υπάρχουν ακόμη μετασχηματισμοί του κώδικα, π.χ: (define-syntax-rule (bad-while condition body ...) (when condition body ... (bad-while condition body ...))) -;; αυτή η μακροεντολή είναι χαλασένη: δημιουγεί ατέρμονα βρόχο -;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστης +;; αυτή η μακροεντολή είναι χαλασμένη: δημιουγεί ατέρμονα βρόχο +;; και αν προσπαθήσουμε να το χρησιμοποιήσουμε, ο μεταγλωττιστής ;; θα μπεί στον ατέρμονα βρόχο. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; 10. Συμβόλαια +;; 10. Συμβόλαια (Contracts) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Τα συμβόλαια βάζουν περιορισμόυς σε τιμές που προέρχονται -- cgit v1.2.3 From bd3c4e4c1a947dde9c4c42257574a9ecd298b250 Mon Sep 17 00:00:00 2001 From: Ruben Date: Sun, 23 Aug 2015 14:54:07 +0200 Subject: Update yaml-de.html.markdown --- de-de/yaml-de.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 88318014..19ea9e87 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -1,10 +1,11 @@ --- language: yaml -filename: learnyaml.yaml contributors: - ["Adam Brenecki", "https://github.com/adambrenecki"] translators: - - ["Ruben M.", https://github.com/switchhax] + - ["Ruben M.", "https://github.com/switchhax"] +filename: learnyaml-de.yaml +lang: de-de --- YAML ist eine Sprache zur Datenserialisierung, die sofort von Menschenhand geschrieben und gelesen werden kann. -- cgit v1.2.3 From b990f84123a755b8aa36db3667a59b7d774daad2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jostein=20Kj=C3=B8nigsen?= Date: Tue, 25 Aug 2015 12:29:44 +0200 Subject: Fix broken line-change in TCL docs. --- tcl.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) mode change 100755 => 100644 tcl.html.markdown diff --git a/tcl.html.markdown b/tcl.html.markdown old mode 100755 new mode 100644 index 198f675e..79b5e87d --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -121,7 +121,8 @@ puts lots\nof\n\n\n\n\n\nnewlines # A word enclosed in braces is not subject to any special interpretation or -# substitutions, except that a backslash before a brace is not counted when look#ing for the closing brace +# substitutions, except that a backslash before a brace is not counted when +# looking for the closing brace set somevar { This is a literal $ sign, and this \} escaped brace remains uninterpreted -- cgit v1.2.3 From 9650cdc12468e91cb7a64aad6017671b7a40c1ef Mon Sep 17 00:00:00 2001 From: "Q. Zero Lee" Date: Tue, 25 Aug 2015 22:41:22 +0800 Subject: Added a dollar --- tcl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index 79b5e87d..c1cd42ca 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -257,7 +257,7 @@ proc greet greeting\ name return\ \"Hello,\ \$name! proc fold {cmd args} { set res 0 foreach arg $args { - set res [cmd $res $arg] + set res [$cmd $res $arg] } } fold ::tcl::mathop::* 5 3 3 ;# -> 45 -- cgit v1.2.3 From 45c70baa69088ca4aa9189556641a773b2b9c305 Mon Sep 17 00:00:00 2001 From: Aleks-Daniel Jakimenko Date: Tue, 25 Aug 2015 22:31:25 +0300 Subject: In perl6, 0 is not falsey anymore --- perl6.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/perl6.html.markdown b/perl6.html.markdown index de7d2f25..af545793 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: (), 0, "", Nil, A type (like `Str` or `Int`), +# Only these values are Falsey: (), "", Nil, A type (like `Str` or `Int`), # and of course False itself. # Every other value is Truthy. if True { -- cgit v1.2.3 From c00ac0de6612feb54bf0b6d1040c953e2de5df81 Mon Sep 17 00:00:00 2001 From: Arthur Vieira Date: Wed, 26 Aug 2015 03:15:36 -0300 Subject: Add #push to Array besides shovel operator #push is commonly used imho and it is also used in other languages (e.g. Javascript). --- ruby.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ruby.html.markdown b/ruby.html.markdown index 66a0774d..7bd28d86 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -173,6 +173,8 @@ array[1..3] #=> [2, 3, 4] # Add to an array like this array << 6 #=> [1, 2, 3, 4, 5, 6] +# Or like this +array.push(6) #=> [1, 2, 3, 4, 5, 6] # Check if an item exists in an array array.include?(1) #=> true -- cgit v1.2.3 From 7d2339328d5bb2b0bd642809cd68a604d7d2a34d Mon Sep 17 00:00:00 2001 From: Alexander Farley Date: Wed, 26 Aug 2015 16:47:21 -0400 Subject: Updating line 167 to fix name resolution error at line 73. Also, elaborated on name resolution with set vs. variable. --- tcl.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index c1cd42ca..9ca32f1e 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -164,7 +164,7 @@ set greeting "Hello, $person(name)" # A namespace holds commands and variables namespace eval people { namespace eval person1 { - set name Neo + variable name Neo } } @@ -190,7 +190,10 @@ set greeting "Hello $people::person1::name" namespace delete :: -# Because of name resolution behaviour, it's safer to use the "variable" command to declare or to assign a value to a namespace. +# Because of name resolution behaviour, it's safer to use the "variable" command to +# declare or to assign a value to a namespace. If a variable called "name" already +# exists in the global namespace, using "set" here will assign a value to the global variable +# instead of creating a new variable in the local namespace. namespace eval people { namespace eval person1 { variable name Neo -- cgit v1.2.3 From 97b97408eab97fbe322df4266cda9ab2ed21fceb Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 28 Aug 2015 11:48:38 -0600 Subject: Fix C++ namespace explanation --- c++.html.markdown | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index ff2a98fd..883d3482 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -158,11 +158,12 @@ void foo() int main() { - // Assume everything is from the namespace "Second" - // unless otherwise specified. + // Includes all symbols from `namesapce Second` into the current scope. Note + // that simply `foo()` no longer works, since it is now ambiguous whether + // we're calling the `foo` in `namespace Second` or the top level. using namespace Second; - foo(); // prints "This is Second::foo" + Second::foo(); // prints "This is Second::foo" First::Nested::foo(); // prints "This is First::Nested::foo" ::foo(); // prints "This is global foo" } -- cgit v1.2.3