From bcb1b623b1db1057085982507399c62eaa053e7b Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Fri, 23 Jun 2017 13:35:19 -0700 Subject: [scala/en] Make return value example actually demonstrate issue Previously the `return z` didn't actually have any effect on the output, since the outer function just return the anon function's result directly. Updated to make the outer function do something to demonstrate the difference. Also renamed functions to make what they're doing easier to follow, and added a couple examples of behavior w/ explanations --- scala.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index 5eb94986..e541f4b3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -253,16 +253,20 @@ weirdSum(2, 4) // => 16 // def that surrounds it. // WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: -def foo(x: Int): Int = { - val anonFunc: Int => Int = { z => +def addTenButMaybeTwelve(x: Int): Int = { + val anonMaybeAddTwo: 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 addTenButMaybeTwelve! else z + 2 // This line is the return value of anonFunc } - anonFunc(x) // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of foo } +addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 +addTenButMaybeTwelve(7) // Returns 7: 7 > 5, return value set to z, so + // last line doesn't get called and 10 is not added + ///////////////////////////////////////////////// // 3. Flow Control -- cgit v1.2.3 From 23cee36b4c056dcd3c01676132cb9a6588fb75ad Mon Sep 17 00:00:00 2001 From: Joel Bradshaw Date: Thu, 29 Jun 2017 10:49:44 -0700 Subject: Update more function mentions in comments --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scala.html.markdown b/scala.html.markdown index e541f4b3..192af953 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -258,9 +258,9 @@ def addTenButMaybeTwelve(x: Int): Int = { if (z > 5) return z // This line makes z the return value of addTenButMaybeTwelve! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonMaybeAddTwo } - anonMaybeAddTwo(x) + 10 // This line is the return value of foo + anonMaybeAddTwo(x) + 10 // This line is the return value of addTenButMaybeTwelve } addTenButMaybeTwelve(2) // Returns 14 as expected: 2 <= 5, adds 12 -- cgit v1.2.3 From 2e218f5dfbc2015cc429e9ae8e3a0e38c0e9098b Mon Sep 17 00:00:00 2001 From: Oleg Gromyak Date: Sat, 28 Oct 2017 20:13:12 +0300 Subject: [python/ua] Add Ukrainian translation --- uk-ua/python-ua.html.markdown | 818 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 818 insertions(+) create mode 100644 uk-ua/python-ua.html.markdown diff --git a/uk-ua/python-ua.html.markdown b/uk-ua/python-ua.html.markdown new file mode 100644 index 00000000..2406678d --- /dev/null +++ b/uk-ua/python-ua.html.markdown @@ -0,0 +1,818 @@ +--- +language: python +lang: uk-ua +contributors: + - ["Louie Dinh", "http://ldinh.ca"] + - ["Amin Bandali", "https://aminb.org"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["evuez", "http://github.com/evuez"] + - ["asyne", "https://github.com/justblah"] + - ["habi", "http://github.com/habi"] +translators: + - ["Oleg Gromyak", "https://github.com/ogroleg"] +filename: learnpython-ua.py +--- + +Мову Python створив Гвідо ван Россум на початку 90-х. Наразі це одна з +найбільш популярних мов. Я закохався у Python завдяки простому і зрозумілому +синтаксису. Це майже як виконуваний псевдокод. + +З вдячністю чекаю ваших відгуків: [@louiedinh](http://twitter.com/louiedinh) +або louiedinh [at] [поштовий сервіс від Google] + +Примітка: Ця стаття стосується Python 2.7, проте має працювати і +у інших версіях Python 2.x. Python 2.7 підходить до кінця свого терміну, +його підтримку припинять у 2020, тож наразі краще починати вивчення Python +з версії 3.x. +Аби вивчити Python 3.x, звертайтесь до статті по Python 3. + +```python +# Однорядкові коментарі починаються з символу решітки. + +""" Текст, що займає декілька рядків, + може бути записаний з використанням 3 знаків " і + зазвичай використовується у якості + вбудованої документації +""" + +#################################################### +## 1. Примітивні типи даних та оператори +#################################################### + +# У вас є числа +3 # => 3 + +# Математика працює досить передбачувано +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7 + +# А ось з діленням все трохи складніше. Воно цілочисельне і результат +# автоматично округлюється у меншу сторону. +5 / 2 # => 2 + +# Аби правильно ділити, спершу варто дізнатися про числа +# з плаваючою комою. +2.0 # Це число з плаваючою комою +11.0 / 4.0 # => 2.75 ох... Так набагато краще + +# Результат цілочисельного ділення округлюється у меншу сторону +# як для додатніх, так і для від'ємних чисел. +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # Працює і для чисел з плаваючою комою +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 + +# Зверніть увагу, що ми також можемо імпортувати модуль для ділення, +# див. розділ Модулі +# аби звичне ділення працювало при використанні лише '/'. +from __future__ import division + +11 / 4 # => 2.75 ...звичне ділення +11 // 4 # => 2 ...цілочисельне ділення + +# Залишок від ділення +7 % 3 # => 1 + +# Піднесення до степеня +2 ** 4 # => 16 + +# Приорітет операцій вказується дужками +(1 + 3) * 2 # => 8 + +# Логічні оператори +# Зверніть увагу: ключові слова «and» і «or» чутливі до регістру букв +True and False # => False +False or True # => True + +# Завважте, що логічні оператори також використовуються і з цілими числами +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True + +# Для заперечення використовується not +not True # => False +not 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 + +# Порівняння можуть бути записані ланцюжком! +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# Рядки позначаються символом " або ' +"Це рядок." +'Це теж рядок.' + +# І рядки також можна додавати! +"Привіт " + "світ!" # => "Привіт світ!" +# Рядки можна додавати і без '+' +"Привіт " "світ!" # => "Привіт світ!" + +# ... або множити +"Привіт" * 3 # => "ПривітПривітПривіт" + +# З рядком можна працювати як зі списком символів +"Це рядок"[0] # => 'Ц' + +# Ви можете дізнатися довжину рядка +len("Це рядок") # => 8 + +# Символ % використовується для форматування рядків, наприклад: +"%s можуть бути %s" % ("рядки", "інтерпольовані") + +# Новий спосіб форматування рядків — використання методу format. +# Це бажаний спосіб. +"{} є {}".format("Це", "заповнювач") +"{0} можуть бути {1}".format("рядки", "форматовані") +# Якщо ви не хочете рахувати, то можете скористатися ключовими словами. +"{name} хоче з'істи {food}".format(name="Боб", food="лазанью") + +# None - це об'єкт +None # => None + +# Не використовуйте оператор рівності '=='' для порівняння +# об'єктів з None. Використовуйте для цього «is» +"etc" is None # => False +None is None # => True + +# Оператор 'is' перевіряє ідентичність об'єктів. Він не +# дуже корисний при роботі з примітивними типами, проте +# незамінний при роботі з об'єктами. + +# None, 0 і порожні рядки/списки рівні False. +# Всі інші значення рівні True +bool(0) # => False +bool("") # => False + + +#################################################### +## 2. Змінні та колекції +#################################################### + +# В Python є оператор print +print "Я Python. Приємно познайомитись!" # => Я Python. Приємно познайомитись! + +# Отримати дані з консолі просто +input_string_var = raw_input( + "Введіть щось: ") # Повертає дані у вигляді рядка +input_var = input("Введіть щось: ") # Працює з даними як з кодом на python +# Застереження: будьте обережні при використанні методу input() + +# Оголошувати змінні перед ініціалізацією не потрібно. +some_var = 5 # За угодою використовується нижній_регістр_з_підкресленнями +some_var # => 5 + +# При спробі доступу до неініціалізованої змінної +# виникне виняткова ситуація. +# Див. розділ Потік управління, аби дізнатись про винятки більше. +some_other_var # Помилка в імені + +# if може використовуватися як вираз +# Такий запис еквівалентний тернарному оператору '?:' у мові С +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + +# Списки зберігають послідовності +li = [] +# Можна одразу створити заповнений список +other_li = [4, 5, 6] + +# Об'єкти додаються у кінець списку за допомогою методу append +li.append(1) # li тепер дорівнює [1] +li.append(2) # li тепер дорівнює [1, 2] +li.append(4) # li тепер дорівнює [1, 2, 4] +li.append(3) # li тепер дорівнює [1, 2, 4, 3] +# І видаляються з кінця методом pop +li.pop() # => повертає 3 і li стає рівним [1, 2, 4] +# Повернемо елемент назад +li.append(3) # li тепер знову дорівнює [1, 2, 4, 3] + +# Поводьтесь зі списком як зі звичайним масивом +li[0] # => 1 +# Присвоюйте нові значення вже ініціалізованим індексам за допомогою = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Зверніть увагу: повертаємось до попереднього значення +# Звертаємось до останнього елементу +li[-1] # => 3 + +# Спроба вийти за границі масиву призводить до помилки в індексі +li[4] # помилка в індексі + +# Можна звертатися до діапазону, використовуючи так звані зрізи +# (Для тих, хто любить математику: це називається замкнуто-відкритий інтервал). +li[1:3] # => [2, 4] +# Опускаємо початок +li[2:] # => [4, 3] +# Опускаємо кінець +li[:3] # => [1, 2, 4] +# Вибираємо кожен другий елемент +li[::2] # => [1, 4] +# Перевертаємо список +li[::-1] # => [3, 4, 2, 1] +# Використовуйте суміш вищеназваного для більш складних зрізів +# li[початок:кінець:крок] + +# Видаляємо довільні елементи зі списку оператором del +del li[2] # li тепер [1, 2, 3] + +# Ви можете додавати списки +li + other_li # => [1, 2, 3, 4, 5, 6] +# Зверніть увагу: значення li та other_li при цьому не змінились. + +# Поєднувати списки можна за допомогою методу extend +li.extend(other_li) # Тепер li дорівнює [1, 2, 3, 4, 5, 6] + +# Видалити перше входження значення +li.remove(2) # Тепер li дорівнює [1, 3, 4, 5, 6] +li.remove(2) # Помилка значення, оскільки у списку li немає 2 + +# Вставити елемент за вказаним індексом +li.insert(1, 2) # li знову дорівнює [1, 2, 3, 4, 5, 6] + +# Отримати індекс першого знайденого елементу +li.index(2) # => 1 +li.index(7) # Помилка значення, оскільки у списку li немає 7 + +# Перевірити елемент на входження у список можна оператором in +1 in li # => True + +# Довжина списку обчислюється за допомогою функції len +len(li) # => 6 + +# Кортежі схожі на списки, лише незмінні +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Виникає помилка типу + +# Все те ж саме можна робити і з кортежами +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Ви можете розпаковувати кортежі (або списки) у змінні +a, b, c = (1, 2, 3) # a == 1, b == 2 и c == 3 +d, e, f = 4, 5, 6 # дужки можна опустити +# Кортежі створюються за замовчуванням, якщо дужки опущено +g = 4, 5, 6 # => (4, 5, 6) +# Дивіться, як легко обміняти значення двох змінних +e, d = d, e # тепер d дорівнює 5, а e дорівнює 4 + +# Словники містять асоціативні масиви +empty_dict = {} +# Ось так описується попередньо заповнений словник +filled_dict = {"one": 1, "two": 2, "three": 3} + +# Значення можна отримати так само, як і зі списку +filled_dict["one"] # => 1 + +# Можна отримати всі ключі у виді списку за допомогою методу keys +filled_dict.keys() # => ["three", "two", "one"] +# Примітка: збереження порядку ключів у словників не гарантується +# Ваші результати можуть не співпадати з цими. + +# Можна отримати і всі значення у вигляді списку, використовуйте метод values +filled_dict.values() # => [3, 2, 1] +# Те ж зауваження щодо порядку ключів діє і тут + +# Отримуйте всі пари ключ-значення у вигляді списку кортежів +# за допомогою "items()" +filled_dict.items() # => [("one", 1), ("two", 2), ("three", 3)] + +# За допомогою оператору in можна перевіряти ключі на входження у словник +"one" in filled_dict # => True +1 in filled_dict # => False + +# Спроба отримати значення за неіснуючим ключем викине помилку ключа +filled_dict["four"] # помилка ключа + +# Аби уникнути цього, використовуйте метод get() +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None +# Метод get також приймає аргумент за замовчуванням, значення якого буде +# повернуто при відсутності вказаного ключа +filled_dict.get("one", 4) # => 1 +filled_dict.get("four", 4) # => 4 +# Зверніть увагу, що filled_dict.get("four") все ще => None +# (get не встановлює значення елементу словника) + +# Присвоюйте значення ключам так само, як і в списках +filled_dict["four"] = 4 # тепер filled_dict["four"] => 4 + +# Метод setdefault() вставляє пару ключ-значення лише +# за відсутності такого ключа +filled_dict.setdefault("five", 5) # filled_dict["five"] повертає 5 +filled_dict.setdefault("five", 6) # filled_dict["five"] все ще повертає 5 + + +# Множини містять... ну, загалом, множини +# (які схожі на списки, проте в них не може бути елементів, які повторюються) +empty_set = set() +# Ініціалізація множини набором значень +some_set = set([1,2,2,3,4]) # some_set тепер дорівнює set([1, 2, 3, 4]) + +# Порядок не гарантовано, хоча інколи множини виглядають відсортованими +another_set = set([4, 3, 2, 2, 1]) # another_set тепер set([1, 2, 3, 4]) + +# Починаючи з Python 2.7, ви можете використовувати {}, аби створити множину +filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} + +# Додавання нових елементів у множину +filled_set.add(5) # filled_set тепер дорівнює {1, 2, 3, 4, 5} + +# Перетин множин: & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Об'єднання множин: | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Різниця множин: - +{1,2,3,4} - {2,3,5} # => {1, 4} + +# Симетрична різниця множин: ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Перевіряємо чи множина зліва є надмножиною множини справа +{1, 2} >= {1, 2, 3} # => False + +# Перевіряємо чи множина зліва є підмножиною множини справа +{1, 2} <= {1, 2, 3} # => True + +# Перевірка на входження у множину: in +2 in filled_set # => True +10 in filled_set # => False + + +#################################################### +## 3. Потік управління +#################################################### + +# Для початку створимо змінну +some_var = 5 + +# Так виглядає вираз if. Відступи у python дуже важливі! +# результат: «some_var менше, ніж 10» +if some_var > 10: + print("some_var набагато більше, ніж 10.") +elif some_var < 10: # Вираз elif є необов'язковим. + print("some_var менше, ніж 10.") +else: # Це теж необов'язково. + print("some_var дорівнює 10.") + + +""" +Цикли For проходять по спискам + +Результат: + собака — це ссавець + кішка — це ссавець + миша — це ссавець +""" +for animal in ["собака", "кішка", "миша"]: + # Можете використовувати оператор {0} для інтерполяції форматованих рядків + print "{0} — це ссавець".format(animal) + +""" +"range(число)" повертає список чисел +від нуля до заданого числа +Друкує: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) +""" +"range(нижня_границя, верхня_границя)" повертає список чисел +від нижньої границі до верхньої +Друкує: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print i + +""" +Цикли while продовжуються до тих пір, поки вказана умова не стане хибною. +Друкує: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Короткий запис для x = x + 1 + +# Обробляйте винятки блоками try/except + +# Працює у Python 2.6 і вище: +try: + # Аби створити виняток, використовується raise + raise IndexError("Помилка у індексі!") +except IndexError as e: + pass # pass — оператор, який нічого не робить. Зазвичай тут відбувається + # відновлення після помилки. +except (TypeError, NameError): + pass # Винятки можна обробляти групами, якщо потрібно. +else: # Необов'язковий вираз. Має слідувати за останнім блоком except + print("Все добре!") # Виконається лише якщо не було ніяких винятків +finally: # Виконується у будь-якому випадку + print "Тут ми можемо звільнити ресурси" + +# Замість try/finally для звільнення ресурсів +# ви можете використовувати вираз with +with open("myfile.txt") as f: + for line in f: + print line + + +#################################################### +## 4. Функції +#################################################### + +# Використовуйте def для створення нових функцій +def add(x, y): + print "x дорівнює {0}, а y дорівнює {1}".format(x, y) + return x + y # Повертайте результат за допомогою ключового слова return + + +# Виклик функції з аргументами +add(5, 6) # => друкує «x дорівнює 5, а y дорівнює 6» і повертає 11 + +# Інший спосіб виклику функції — виклик з іменованими аргументами +add(y=6, x=5) # Іменовані аргументи можна вказувати у будь-якому порядку + + +# Ви можете визначити функцію, яка приймає змінну кількість аргументів, +# які будуть інтерпретовані як кортеж, за допомогою * +def varargs(*args): + return args + + +varargs(1, 2, 3) # => (1,2,3) + + +# А також можете визначити функцію, яка приймає змінне число +# іменованих аргументів, котрі будуть інтерпретовані як словник, за допомогою ** +def keyword_args(**kwargs): + return kwargs + + +# Давайте подивимось що з цього вийде +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + +# Якщо хочете, можете використовувати обидва способи одночасно +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) + + +""" +all_the_args(1, 2, a=3, b=4) друкує: + (1, 2) + {"a": 3, "b": 4} +""" + +# Коли викликаєте функції, то можете зробити навпаки! +# Використовуйте символ * аби розпакувати позиційні аргументи і +# ** для іменованих аргументів +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # еквівалентно foo(1, 2, 3, 4) +all_the_args(**kwargs) # еквівалентно foo(a=3, b=4) +all_the_args(*args, **kwargs) # еквівалентно foo(1, 2, 3, 4, a=3, b=4) + +# ви можете передавати довільне число позиційних або іменованих аргументів +# іншим функціям, які їх приймають, розпаковуючи за допомогою +# * або ** відповідно +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + + +# Область визначення функцій +x = 5 + + +def set_x(num): + # Локальна змінна x - не те ж саме, що глобальна змінна x + x = num # => 43 + print x # => 43 + + +def set_global_x(num): + global x + print x # => 5 + x = num # глобальна змінна x тепер дорівнює 6 + print x # => 6 + + +set_x(43) +set_global_x(6) + +# В Python функції є об'єктами першого класу +def create_adder(x): + def adder(y): + return x + y + + return adder + + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Також є і анонімні функції +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Присутні вбудовані функції вищого порядку +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + +filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# Для зручного відображення і фільтрації можна використовувати +# включення у вигляді списків +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Ви також можете скористатися включеннями множин та словників +{x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} +{x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Класи +#################################################### + +# Аби отримати клас, ми наслідуємо object. +class Human(object): + # Атрибут класу. Він розділяється всіма екземплярами цього класу. + species = "H. sapiens" + + # Звичайний конструктор, буде викликаний при ініціалізації екземпляру класу + # Зверніть увагу, що подвійне підкреслення на початку та наприкінці імені + # використовується для позначення об'єктів та атрибутів, + # які використовуються Python, але знаходяться у просторах імен, + # якими керує користувач. Не варто вигадувати для них імена самостійно. + def __init__(self, name): + # Присвоєння значення аргумента атрибуту класу name + self.name = name + + # Ініціалізуємо властивість + self.age = 0 + + # Метод екземпляру. Всі методи приймають self у якості першого аргументу + def say(self, msg): + return "%s: %s" % (self.name, msg) + + # Методи класу розділяються між усіма екземплярами + # Вони викликаються з вказанням викликаючого класу + # у якості першого аргументу + @classmethod + def get_species(cls): + return cls.species + + # Статичний метод викликається без посилання на клас або екземпляр + @staticmethod + def grunt(): + return "*grunt*" + + # Властивість. + # Перетворює метод age() в атрибут тільки для читання + # з таким же ім'ям. + @property + def age(self): + return self._age + + # Це дозволяє змінювати значення властивості + @age.setter + def age(self, age): + self._age = age + + # Це дозволяє видаляти властивість + @age.deleter + def age(self): + del self._age + + +# Створюємо екземпляр класу +i = Human(name="Данило") +print(i.say("привіт")) # Друкує: «Данило: привіт» + +j = Human("Меланка") +print(j.say("Привіт")) # Друкує: «Меланка: привіт» + +# Виклик методу класу +i.get_species() # => "H. sapiens" + +# Зміна розділюваного атрибуту +Human.species = "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" + +# Виклик статичного методу +Human.grunt() # => "*grunt*" + +# Оновлюємо властивість +i.age = 42 + +# Отримуємо значення +i.age # => 42 + +# Видаляємо властивість +del i.age +i.age # => виникає помилка атрибуту + +#################################################### +## 6. Модулі +#################################################### + +# Ви можете імпортувати модулі +import math + +print(math.sqrt(16)) # => 4 + +# Ви можете імпортувати окремі функції з модуля +from math import ceil, floor + +print(ceil(3.7)) # => 4.0 +print(floor(3.7)) # => 3.0 + +# Можете імпортувати всі функції модуля. +# Попередження: краще так не робіть +from math import * + +# Можете скорочувати імена модулів +import math as m + +math.sqrt(16) == m.sqrt(16) # => True +# Ви також можете переконатися, що функції еквівалентні +from math import sqrt + +math.sqrt == m.sqrt == sqrt # => True + +# Модулі в Python — це звичайні Python-файли. Ви +# можете писати свої модулі та імпортувати їх. Назва +# модуля співпадає з назвою файлу. + +# Ви можете дізнатися, які функції та атрибути визначені +# в модулі +import math + +dir(math) + + +# Якщо у вас є Python скрипт з назвою math.py у тій же папці, що +# і ваш поточний скрипт, то файл math.py +# може бути завантажено замість вбудованого у Python модуля. +# Так трапляється, оскільки локальна папка має перевагу +# над вбудованими у Python бібліотеками. + +#################################################### +## 7. Додатково +#################################################### + +# Генератори +# Генератор "генерує" значення тоді, коли вони запитуються, замість того, +# щоб зберігати все одразу + +# Метод нижче (*НЕ* генератор) подвоює всі значення і зберігає їх +# в `double_arr`. При великих розмірах може знадобитися багато ресурсів! +def double_numbers(iterable): + double_arr = [] + for i in iterable: + double_arr.append(i + i) + return double_arr + + +# Тут ми спочатку подвоюємо всі значення, потім повертаємо їх, +# аби перевірити умову +for value in double_numbers(range(1000000)): # `test_non_generator` + print value + if value > 5: + break + + +# Натомість ми можемо скористатися генератором, аби "згенерувати" +# подвійне значення, як тільки воно буде запитане +def double_numbers_generator(iterable): + for i in iterable: + yield i + i + + +# Той самий код, але вже з генератором, тепер дозволяє нам пройтися по +# значенням і подвоювати їх одне за одним якраз тоді, коли вони обробляються +# за нашою логікою, одне за одним. А як тільки ми бачимо, що value > 5, ми +# виходимо з циклу і більше не подвоюємо більшість значень, +# які отримали на вхід (НАБАГАТО ШВИДШЕ!) +for value in double_numbers_generator(xrange(1000000)): # `test_generator` + print value + if value > 5: + break + +# Між іншим: ви помітили використання `range` у `test_non_generator` і +# `xrange` у `test_generator`? +# Як `double_numbers_generator` є версією-генератором `double_numbers`, так +# і `xrange` є аналогом `range`, але у вигляді генератора. +# `range` поверне нам масив з 1000000 значень +# `xrange`, у свою чергу, згенерує 1000000 значень для нас тоді, +# коли ми їх запитуємо / будемо проходитись по ним. + +# Аналогічно включенням у вигляді списків, ви можете створювати включення +# у вигляді генераторів. +values = (-x for x in [1, 2, 3, 4, 5]) +for x in values: + print(x) # друкує -1 -2 -3 -4 -5 + +# Включення у вигляді генератора можна явно перетворити у список +values = (-x for x in [1, 2, 3, 4, 5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + +# Декоратори +# Декоратор – це функція вищого порядку, яка приймає та повертає функцію. +# Простий приклад використання – декоратор add_apples додає елемент 'Apple' в +# список fruits, який повертає цільова функція get_fruits. +def add_apples(func): + def get_fruits(): + fruits = func() + fruits.append('Apple') + return fruits + return get_fruits + +@add_apples +def get_fruits(): + return ['Banana', 'Mango', 'Orange'] + +# Друкуємо список разом з елементом 'Apple', який знаходиться в ньому: +# Banana, Mango, Orange, Apple +print ', '.join(get_fruits()) + +# У цьому прикладі beg обертає say +# Beg викличе say. Якщо say_please дорівнюватиме True, то повідомлення, +# що повертається, буде змінено. +from functools import wraps + + +def beg(target_function): + @wraps(target_function) + def wrapper(*args, **kwargs): + msg, say_please = target_function(*args, **kwargs) + if say_please: + return "{} {}".format(msg, "Будь ласка! Я бідний :(") + return msg + + return wrapper + + +@beg +def say(say_please=False): + msg = "Ви можете купити мені пива?" + return msg, say_please + + +print say() # Ви можете купити мені пива? +print say(say_please=True) # Ви можете купити мені пива? Будь ласка! Я бідний :( +``` + +## Готові до більшого? + +### Безкоштовні онлайн-матеріали + +* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) +* [Dive Into Python](http://www.diveintopython.net/) +* [Официальная документация](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) + +### Платні + +* [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) + -- cgit v1.2.3 From 3743c596d8a6519d21e11dfa161aed4a92a742bc Mon Sep 17 00:00:00 2001 From: Thales Mello Date: Thu, 8 Mar 2018 18:03:32 -0300 Subject: Improvements to syntax and comments Improve code by using context managers to handle closing of files. Also, replace the flame-war indexing comment for one with some explanations to why things are as they are. --- pythonstatcomp.html.markdown | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 6dde1cf0..0e6f1f87 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -38,18 +38,16 @@ r.text # raw page source print(r.text) # prettily formatted # save the page source in a file: os.getcwd() # check what's the working directory -f = open("learnxinyminutes.html", "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open("learnxinyminutes.html", "wb") as f: + f.write(r.text.encode("UTF-8")) # downloading a csv fp = "https://raw.githubusercontent.com/adambard/learnxinyminutes-docs/master/" fn = "pets.csv" r = requests.get(fp + fn) print(r.text) -f = open(fn, "wb") -f.write(r.text.encode("UTF-8")) -f.close() +with open(fn, "wb") as f: + f.write(r.text.encode("UTF-8")) """ for more on the requests module, including APIs, see http://docs.python-requests.org/en/latest/user/quickstart/ @@ -71,8 +69,8 @@ pets # 1 vesuvius 6 23 fish # 2 rex 5 34 dog -""" R users: note that Python, like most normal programming languages, starts - indexing from 0. R is the unusual one for starting from 1. +""" R users: note that Python, like most C-influenced programming languages, starts + indexing from 0. R starts indexing at 1 due to Fortran influnce. """ # two different ways to print out a column -- cgit v1.2.3 From bb18dc81548a68b25227306bead977d55da23c66 Mon Sep 17 00:00:00 2001 From: Thales Mello Date: Fri, 9 Mar 2018 14:29:43 -0300 Subject: Update pythonstatcomp.html.markdown --- pythonstatcomp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 0e6f1f87..082c7025 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -70,7 +70,7 @@ pets # 2 rex 5 34 dog """ R users: note that Python, like most C-influenced programming languages, starts - indexing from 0. R starts indexing at 1 due to Fortran influnce. + indexing from 0. R starts indexing at 1 due to Fortran influence. """ # two different ways to print out a column -- cgit v1.2.3 From 6be6c9ba7eaa4fb97d4eb72ccff56fc81f53c998 Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Fri, 6 Apr 2018 13:14:31 +0800 Subject: Added Malay translation for clojure macros --- ms-my/clojure-macros-my.html.markdown | 154 ++++++++++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 ms-my/clojure-macros-my.html.markdown diff --git a/ms-my/clojure-macros-my.html.markdown b/ms-my/clojure-macros-my.html.markdown new file mode 100644 index 00000000..099f376e --- /dev/null +++ b/ms-my/clojure-macros-my.html.markdown @@ -0,0 +1,154 @@ +--- +language: "clojure macros" +filename: learnclojuremacros-ms.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +--- + +Sama seperti Lisp yang lain, sifat Clojure yang mempunyai [homoiconicity](https://en.wikipedia.org/wiki/Homoiconic) +membolehkan anda untuk menggunakan sepenuhnya language ini untuk menulis code yang boleh generate code sendiri yang +dipanggil "macro". Macro memberi cara yang sangat menarik untuk mengubahsuai language mengikut kehendak anda. + +Jaga-jaga. Penggunaan macro boleh dikatakan tidak elok jika digunakan secara berlebihan jika function sahaja sudah mencukupi. +Gunakan macro hanya apabila anda mahu lebih kawalan terhadap sesuatu form. + +Biasakan diri dengan Clojure terlebih dahulu. Pastikan anda memahami semuanya di +[Clojure in Y Minutes](/docs/ms-my/clojure-my/). + +```clojure +;; Define macro menggunakan defmacro. Macro anda akan output list yang boleh +;; dijalankan sebagai code clojure. +;; +;; Macro ini adalah sama seperti (reverse "Hello World") +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; Lihat hasil macro tersebut menggunakan macroexpand atau macroexpand-1. +;; +;; Pastikan panggilan kepada macro tersebut mempunyai tanda petikan +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; Anda boleh menggunakan eval terus kepada macroexpand untuk mendapatkan hasil: +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Tetapi anda sepatutnya menggunakan cara yang lebih ringkas, sama seperti panggilan kepada function: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; Anda boleh memudahkan cara untuk membuat macro dengan mengguna tanda petikan +;; untuk membuat list untuk macro: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; Perhatikan yang reverse bukan lagi function tetapi adalah simbol. + +;; Macro boleh mengambil argument. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; Tetapi jika anda membuat cara yang sama menggunakan tanda petikan, anda akan mendapat error sebab +;; argument tersebut juga akan mempunyai tanda petikan. Untuk mengatasi masalah ini, Clojure memberi +;; cara untuk meletak tanda petikan untuk macro: `. Di dalam `, anda boleh menggunakan ~ untuk mendapatkan scope luaran +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; Anda boleh menggunakan destructuring untuk argument seperti biasa. Gunakan ~@ untuk mengembangkan variable +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; Jangan lupa do! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless) mengembalikan body jika argument yang pertama adalah false. +;; Jika tidak, (unless) akan memulangkan nil + +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; Jika tidak berhati-hati, macro boleh memeningkan anda dengan mencampuradukkan nama variable +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; Untuk mengelakkan masalah ini, gunakan gensym untuk mendapatkan identifier yang berbeza +(gensym 'x) ; -> x1281 (atau yang sama waktu dengannya) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; Anda boleh menggunakan # di dalam ` untuk menghasilkan gensym untuk setiap simbol secara automatik +(defmacro define-x-hygienically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygienically) ; -> (2) +(list x) ; -> (4) + +;; Kebiasaannya helper function digunakan untuk membuat macro. Jom buat beberapa function untuk +;; membuatkan program boleh memahami inline arithmetic. Saja suka-suka. +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Diberi argument [x (+ y)], pulangkan (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; Kita boleh test terlebih dahulu tanpa membuat macro +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; Tetapi, kita perlu membuat macro jika kita mahu jalankan code tersebut +(defmacro inline-2 [form] + (inline-2-helper form)) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (sepatutnya, 3N, sebab nombor tersebut ditukarkan kepada pecahan rasional menggunakan /) +``` + +### Bacaaan Lanjut + +Writing Macros daripada [Clojure for the Brave and True](http://www.braveclojure.com/) +[http://www.braveclojure.com/writing-macros/](http://www.braveclojure.com/writing-macros/) + +Dokumen rasmi +[http://clojure.org/macros](http://clojure.org/macros) + +Bila perlu guna macro? +[http://dunsmor.com/lisp/onlisp/onlisp_12.html](http://dunsmor.com/lisp/onlisp/onlisp_12.html) -- cgit v1.2.3 From baf637514363d208cb2eddf159135a51ca3ae33c Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Fri, 6 Apr 2018 19:17:07 +0800 Subject: Added Malay translation for Common Lisp --- ms-my/common-lisp-my.html.markdown | 692 +++++++++++++++++++++++++++++++++++++ 1 file changed, 692 insertions(+) create mode 100644 ms-my/common-lisp-my.html.markdown diff --git a/ms-my/common-lisp-my.html.markdown b/ms-my/common-lisp-my.html.markdown new file mode 100644 index 00000000..f5914aae --- /dev/null +++ b/ms-my/common-lisp-my.html.markdown @@ -0,0 +1,692 @@ +--- + +language: "Common Lisp" +filename: commonlisp-ms.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +--- + +Common Lisp ialah programming language yang general-purpose (boleh digunakan untuk semua benda) dan multi-paradigm (konsep yang pelbagai) sesuai untuk pelbagai kegunaan di dalam +industri aplikasi. Common Lisp biasa digelar sebagai programmable programming language (programming language yang boleh di-program-kan). + +Sumber bacaan yang klasik ialah [Practical Common Lisp](http://www.gigamonkeys.com/book/). Sumber bacaan yang lain dan +yang terbaru ialah [Land of Lisp](http://landoflisp.com/). Buku baru mengenai best practices (amalan terbaik), +[Common Lisp Recipes](http://weitz.de/cl-recipes/), baru sahaja diterbitkan. + + + +```common-lisp + +;;;----------------------------------------------------------------------------- +;;; 0. Syntax +;;;----------------------------------------------------------------------------- + +;;; General form (Bentuk umum) + +;;; Ada dua asas dalam syntax CL: ATOM dan S-EXPRESSION. +;;; Kebiasaannya, gabungan S-expression dipanggil sebagai `forms`. + +10 ; atom; bermaksud seperti yang ditulis iaitu nombor 10 +:thing ; juga atom; bermaksud simbol :thing +t ; juga atom, bermaksud true (ya/betul/benar) +(+ 1 2 3 4) ; s-expression +'(4 :foo t) ; juga s-expression + + +;;; Comment (Komen) + +;;; Comment satu baris bermula dengan semicolon; gunakan empat untuk comment +;;; mengenai file, tiga untuk seksyen penghuraian, dua untuk yang dalam definition, +;;; dan satu untuk satu baris. Sebagai contoh, + +;;;; life.lisp + +;;; Foo bar baz, disebabkan quu quux. Sangat optimum untuk krakaboom dan umph. +;;; Diperlukan oleh function LINULUKO. Ini merepek sahaja kebaboom. + +(defun meaning (life) + "Memulangkan hasil pengiraan makna KEHIDUPAN" + (let ((meh "abc")) + ;; Jalankan krakaboom + (loop :for x :across meh + :collect x))) ; Simpan hasil ke x, kemudian pulangkan + +;;; Komen berbentuk blok, sebaliknya, membenarkan komen untuk bentuk bebas. Komen +;;; tersebut berada di antara #| dan |# + +#| Ini adalah komen berbentuk blok di mana + tulisan boleh ditulis dalam beberapa baris dan + #| + juga boleh dalam bentuk nested (berlapis-lapis)! + |# +|# + + +;;; Environment (benda-benda yang diperlukan untuk program menggunakan Common Lisp) + +;;; Common Lisp ada banyak jenis; kebanyakannya mengikut standard. SBCL +;;; ialah titik permulaan yang baik. Quicklisp boleh digunakan untuk install +;;; library third party. + +;;; CL kebiasaannya digunakan dengan text editor dan Real Eval Print +;;; Loop (REPL) yang dilancarkan dengan serentak. REPL membolehkan kita menjelajah +;;; program secara interaktif semasa program tersebut sedang berjalan secara "live". + + +;;;----------------------------------------------------------------------------- +;;; 1. Datatype primitif dan operator +;;;----------------------------------------------------------------------------- + +;;; Simbol + +'foo ; => FOO Perhatikan simbol menjadi huruf besar secara automatik. + +;;; INTERN menjadikan string sebagai simbol secara manual. + +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + +;;; Nombor + +9999999999999999999999 ; integer +#b111 ; binary => 7 +#o111 ; octal => 73 +#x111 ; hexadecimal => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; ratio +#C(1 2) ; complex number + +;;; Function ditulis sebagai (f x y z ...) di mana f ialah function dan +;;; x, y, z, ... adalah argument. + +(+ 1 2) ; => 3 + +;;; Jika anda ingin membuat data sebagai data bukannya function, gunakan QUOTE +;;; untuk mengelakkan data tersebut daripada dikira oleh program + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; Singkatan untuk QUOTE ialah ' (tanda petikan) + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; Operasi arithmetic asas + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Boolean + +t ; true; semua nilai yang bukan NIL ialah true +nil ; false; termasuklah list yang kosong: () +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; Character + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; String ialah array character yang tidak berubah panjang + +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; backslash ialah escape character + +;;; String boleh digabungkan + +(concatenate 'string "Hello, " "world!") ; => "Hello, world!" + +;;; String boleh diperlakukan seperti urutan character + +(elt "Apple" 0) ; => #\A + +;;; FORMAT digunakan untuk output mengikut format, daripada penggubahan string +;;; yang simple sehinggalah loop dan conditional. Argument pertama untuk FORMAT +;;; menentukan ke mana string akan pergi. Jika NIL, FORMAT +;;; akan pulangkan string sebagai data string; jika T, FORMAT akan output +;;; ke standard output, biasanya di screen, kemudian pulangkan NIL. + +(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!" +(format t "~A, ~A!" "Hello" "world") ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 2. Variable +;;;----------------------------------------------------------------------------- + +;;; Anda boleh membuat variable global (dynamically scoped) menggunakan DEFVAR dan +;;; DEFPARAMETER. Nama variable boleh guna mana-mana character kecuali: ()",'`;#|\ + +;;; Beza antara DEFVAR dengan DEFPARAMETER ialah DEFVAR tidak akan ubah nilai +;;; variable jika dijalankan semula. Manakala DEFPARAMETER, akan mengubah nilai +;;; jika dijalankan semula. + +;;; Kebiasaannya, variable global diletakkan earmuff (asterisk) pada nama. + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;;; Anda juga boleh menggunakan character unicode. +(defparameter *AΛB* nil) + +;;; Variable yang tidak wujud boleh diakses tetapi akan menyebabkan undefined +;;; behavior. Jangan buat. + +;;; Anda boleh membuat local binding menggunakan LET. Dalam snippet berikut, `me` +;;; terikat dengan "dance with you" hanya dalam (let ...). LET mesti akan pulangkan +;;; nilai `form` yang paling terakhir. + +(let ((me "dance with you")) me) ; => "dance with you" + + +;;;-----------------------------------------------------------------------------; +;;; 3. Struct dan collection +;;;-----------------------------------------------------------------------------; + + +;;; Struct + +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T +(dog-name *rover*) ; => "rover" + +;;; DOG-P, MAKE-DOG, dan DOG-NAME semuanya dibuat oleh DEFSTRUCT secara automatik + + +;;; Pair + +;;; CONS membuat pair. CAR dan CDR pulangkan head (kepala) dan tail (ekor) CONS-pair. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + + +;;; List + +;;; List ialah data structure linked-list, dihasilkan daripada pair CONS dan +;;; berakhir dengan NIL (atau '()) menandakan akhirnya list tersebut + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; LIST ialah constructor untuk memudahkan penghasilan list + +(list 1 2 3) ; => '(1 2 3) + +;;; Apabila argument pertama untuk CONS ialah atom dan argument kedua ialah +;;; list, CONS akan pulangkan CONS-pair baru dengan argument pertama sebagai +;;; item pertama dan argument kedua sebagai CONS-pair yang lain + +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;;; Gunakan APPEND untuk menggabungkan list + +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Atau CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; List ialah type utama, jadi ada pelbagai function untuk mengendalikan +;;; list, contohnya: + +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => NIL +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Vector + +;;; Vector ialah array yang tidak berubah panjang + +#(1 2 3) ; => #(1 2 3) + +;;; Gunakan CONCATENATE untuk menggabungkan vector + +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + + +;;; Array + +;;; Vector dan string adalah sejenis array. + +;;; 2D array + +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;;; Perhatian: nilai awal MAKE-ARRAY adalah bergantung kepada jenis Common Lisp. +;;; Untuk meletakkan nilai awal secara manual: + +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) + +;;; Untuk mengakses element di kedudukan 1, 1, 1: + +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 + + +;;; Adjustable vector (vector yang boleh berubah) + +;;; Adjustable vector mempunyai rupa yang sama dengan +;;; vector yang tidak berubah panjang. + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) + +;;; Tambah element baru + +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) + + +;;; Set hanyalah list: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; Tetapi, anda perlukan data structure yang lebih baik untuk digunakan dengan +;;; data set yang sangat banyak + +;;; Kamus dibuat menggunakan hash table. + +;;; Bina hash table + +(defparameter *m* (make-hash-table)) + +;;; Tetapkan nilai + +(setf (gethash 'a *m*) 1) + +;;; Baca nilai + +(gethash 'a *m*) ; => 1, T + +;;; CL boleh memulangkan beberapa nilai (multiple value). + +(values 1 2) ; => 1, 2 + +;;; dan boleh digunakan dengan MULTIPLE-VALUE-BIND untuk bind setiap nilai + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) + +;;; GETHASH antara contoh function yang memulangkan multiple value. Value +;;; pertama ialah nilai untuk key dalam hash table; jika key tidak +;;; jumpa GETHASH akan pulangkan NIL. + +;;; Value kedua menentukan sama ada key tersebut betul-betul wujud dalam hash +;;; table. Jika key tidak jumpa dalam table value tersebut ialah NIL. Cara ini +;;; membolehkan kita untuk periksa sama ada value untuk key ialah NIL. + +;;; Dapatkan value yang tidak wujud akan pulangkan nil + +(gethash 'd *m*) ;=> NIL, NIL + +;;; Anda boleh menentukan value default untuk key yang tidak wujud + +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;;; Jom lihat penggunaan multiple return value di dalam code. + +(multiple-value-bind (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + + +;;;----------------------------------------------------------------------------- +;;; 3. Function +;;;----------------------------------------------------------------------------- + +;;; Gunakan LAMBDA untuk membuat anonymous function. Function sentiasa memulangkan +;;; value untuk expression terakhir. + +(lambda () "Hello World") ; => # + +;;; Gunakan FUNCALL untuk memanggil anonymous function + +(funcall (lambda () "Hello World")) ; => "Hello World" +(funcall #'+ 1 2 3) ; => 6 + +;;; Panggilan kepada FUNCALL juga boleh terjadi apabila lambda tersebut ialah CAR +;;; (yang pertama) untuk list (yang tidak mempunyai tanda petikan) + +((lambda () "Hello World")) ; => "Hello World" +((lambda (val) val) "Hello World") ; => "Hello World" + +;;; FUNCALL digunakan apabila argument sudah diketahui. Jika tidak, gunakan APPLY + +(apply #'+ '(1 2 3)) ; => 6 +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;;; Untuk menamakan sebuah function, guna DEFUN + +(defun hello-world () "Hello World") +(hello-world) ; => "Hello World" + +;;; Simbol () di atas bermaksud list kepada argument + +(defun hello (name) (format nil "Hello, ~A" name)) +(hello "Steve") ; => "Hello, Steve" + +;;; Function boleh ada argument optional (tidak wajib); argument tersebut bernilai +;;; NIL secara default + +(defun hello (name &optional from) + (if from + (format t "Hello, ~A, from ~A" name from) + (format t "Hello, ~A" name))) + +(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas + +;;; Nilai default boleh ditetapkan untuk argument tersebut + +(defun hello (name &optional (from "The world")) + (format nil "Hello, ~A, from ~A" name from)) + +(hello "Steve") ; => Hello, Steve, from The world +(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas + +;;; Function juga mempunyai keyword argument untuk membolehkan argument diletakkan +;;; tidak mengikut kedudukan + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~A ~A, from ~A" honorific name from)) + +(generalized-greeter "Jim") +; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + + +;;;----------------------------------------------------------------------------- +;;; 4. Kesamaan +;;;----------------------------------------------------------------------------- + +;;; CL mempunyai sistem kesaksamaan yang canggih. Antaranya adalah seperti berikut. + +;;; Untuk nombor, guna `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL + +;;; Untuk identiti object (lebih kurang) guna EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL + +;;; untuk list, string, dan bit-vector, guna EQUAL +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 5. Control Flow +;;;----------------------------------------------------------------------------- + +;;; Conditional (syarat) + +(if t ; test expression + "this is true" ; then expression + "this is false") ; else expression +; => "this is true" + +;;; Dalam conditional, semua value yang bukan NIL ialah true + +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;;; Guna COND untuk meletakkan beberapa test +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;;; TYPECASE adalah seperti switch tetapi untuk data type value tersebut +(typecase 1 + (string :string) + (integer :int)) +; => :int + + +;;; Loop + +;;; Recursion + +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) + +(fact 5) ; => 120 + +;;; Iteration + +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) + +(fact 5) ; => 120 + +(loop :for x :across "abc" :collect x) +; => (#\a #\b #\c #\d) + +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 + + +;;;----------------------------------------------------------------------------- +;;; 6. Mutation +;;;----------------------------------------------------------------------------- + +;;; Guna SETF untuk meletakkan nilai baru untuk variable yang sedia ada. Ini sama +;;; seperti contoh hash table di atas. + +(let ((variable 10)) + (setf variable 2)) +; => 2 + +;;; Sebaik-baiknya kurangkan penggunaan destructive function dan elakkan +;;; mutation jika boleh. + + +;;;----------------------------------------------------------------------------- +;;; 7. Class dan object +;;;----------------------------------------------------------------------------- + +;;; Takde dah class untuk haiwan. Jom buat Human-Powered Mechanical +;;; Conveyances (Kenderaan Mekanikal Berkuasa Manusia). + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;;; Argument untuk DEFCLASS, mengikut susunan ialah: +;;; 1. nama class +;;; 2. list untuk superclass +;;; 3. list untuk slot +;;; 4. specifier optional (tidak wajib) + +;;; Apabile list untuk superclass tidak ditetapkan, list yang kosong bermaksud +;;; class standard-object. Ini *boleh* ditukar, kalau anda tahu apa yang anda buat. +;;; Baca Art of the Metaobject Protocol untuk maklumat lebih lanjut. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;;; Panggilan DESCRIBE kepada class HUMAN-POWERED-CONVEYANCE di REPL akan memberi: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;;; Perhatikan apa yang berlaku. CL memang direka sebagai sistem interaktif. + +;;; Untuk membuat method, jom kira berapa panjang lilitan untuk +;;; roda basikal menggunakan formula: C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;;; Nilai PI memang sudah ada dalam CL + +;;; Katakanlah kita ingin ambil tahu efficiency value (nilai keberkesanan) +;;; rower (pendayung) di dalam canoe (perahu) adalah berbentuk logarithmic. Ini +;;; boleh ditetapkan di dalam constructor/initializer. + +;;; Untuk initialize instance selepas CL sudah siap construct: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;;; Kemudian untuk construct sesebuah instance dan periksa purata efficiency... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;----------------------------------------------------------------------------- +;;; 8. Macro +;;;----------------------------------------------------------------------------- + +;;; Macro membolehkan anda untuk menambah syntax language. CL tidak ada +;;; WHILE loop, tetapi, kita boleh mencipta syntax ter. Jika kita buat menggunakan +;;; naluri, kita akan dapat: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym)) (done (gensym))) + `(tagbody + ,block-name + (unless ,condition + (go ,done)) + (progn + ,@body) + (go ,block-name) + ,done))) + +;;; Jom lihat versi yang lebih high-level: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;;; Namun, dengan compiler yang modern, cara ini tidak diperlukan; form LOOP +;;; compile sama sahaja dan juga mudah dibaca. + +;;; Perhatikan ``` digunakan, sama juga `,` dan `@`. ``` ialah operator jenis quote +;;; yang dipanggil quasiquote; operator tersebut membolehkan penggunaan `,` . +;;; `,` membolehkan variable "di-unquote-kan". @ mengembangkan list. + +;;; GENSYM membuat simbol unik yang pasti tidak wujud di tempat-tempat yang +;;; lain. Ini kerana macro dikembangkan semasa compile dan +;;; nama variable di dalam macro boleh bertembung dengan nama variable yang +;;; digunakan dalam code yang biasa. + +;;; Baca Practical Common Lisp dan On Lisp untuk maklumat lebih lanjut mengenai macro. +``` + + +## Bacaan lanjut + +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) + + +## Maklumat tambahan + +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) + + +## Kredit + +Terima kasih banyak diucapkan kepada ahli Scheme yang membuat permulaan yang sangat +bagus dan mudah untuk diguna pakai untuk Common Lisp. + +- [Paul Khuong](https://github.com/pkhuong) untuk review yang bagus. -- cgit v1.2.3 From 42cda056229f30031f22210e859d95aae8e59219 Mon Sep 17 00:00:00 2001 From: Burhanuddin Baharuddin Date: Sat, 7 Apr 2018 15:03:47 +0800 Subject: Add Malay translation for Elisp --- ms-my/elisp-my.html.markdown | 347 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 347 insertions(+) create mode 100644 ms-my/elisp-my.html.markdown diff --git a/ms-my/elisp-my.html.markdown b/ms-my/elisp-my.html.markdown new file mode 100644 index 00000000..73dff0f4 --- /dev/null +++ b/ms-my/elisp-my.html.markdown @@ -0,0 +1,347 @@ +--- +language: elisp +contributors: + - ["Bastien Guerry", "https://bzg.fr"] + - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] +translators: + - ["Burhanuddin Baharuddin", "https://github.com/burhanloey"] +lang: ms-my +filename: learn-emacs-lisp-ms.el +--- + +```scheme +;; Ini adalah pengenalan kepada Emacs Lisp dalam masa 15 minit (v0.2d) +;; +;; Mula-mula pastikan anda sudah membaca artikel daripada Peter Norvig ini: +;; http://norvig.com/21-days.html +;; +;; Kemudian install GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs (atau lihat arahan untuk distro anda) +;; OSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; Maklumat lanjut boleh didapati di: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; Amaran penting: +;; +;; Tutorial ini tidak akan merosakkan komputer anda melainkan jika anda berasa +;; terlalu marah sehingga anda menghempap komputer anda ke lantai. Kalau begitu, +;; saya dengan ini tidak akan bertanggungjawab terhadap apa-apa. Berseronoklah ya! + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Buka Emacs. +;; +;; Tekan `q' untuk tutup mesej selamat datang. +;; +;; Sekarang lihat garis kelabu di bahagian bawah window: +;; +;; "*scratch*" ialah nama ruangan untuk anda edit. +;; Ruangan ini disebut sebagai "buffer". +;; +;; Buffer scratch ialah buffer yang default setiap kali Emacs dibuka. +;; Anda bukannya edit file: anda edit buffer yang kemudiannya +;; boleh save ke file. +;; +;; "Lisp interaction (interaksi)" merujuk kepada command yang wujud di sini. +;; +;; Emacs mempunyai beberapa command yang sedia ada dalam setiap buffer, +;; dan sesetengah command yang lain boleh didapati jika sesetengah mode +;; diaktifkan. Di sini kita menggunakan `lisp-interaction-mode', yang +;; mempunyai command untuk menjalankan dan mengendalikan code Elisp. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Semicolon akan menjadikan comment sepanjang baris tersebut. +;; +;; Program Elisp mengandungi symbolic expressions ("sexps"): +(+ 2 2) + +;; Symbolic expression di atas dibaca begini "Tambah 2 pada 2". + +;; Sexps dilitupi oleh parentheses, dan boleh dalam bentuk nested (parentheses +;; dalam parentheses): +(+ 2 (+ 1 1)) + +;; Symbolic expression mengandungi atom atau symbolic expression +;; yang lain. Untuk contoh di atas, 1 dan 2 ialah atom, +;; (+ 2 (+ 1 1)) dan (+ 1 1) ialah symbolic expression. + +;; Dengan menggunakan `lisp-interaction-mode', anda boleh evaluate +;; (mendapatkan hasil pengiraan) sexps. Letak cursor selepas parenthesis penutup +;; kemudian tekan control dan j ("C-j"). + +(+ 3 (+ 1 2)) +;; ^ cursor di sini +;; `C-j' => 6 + +;; `C-j' memasukkan jawapan pengiraan ke dalam buffer. + +;; `C-xC-e' memaparkan jawapan yang sama di bahagian bawah Emacs, +;; yang dipanggil "minibuffer". Secara umumnya kita akan menggunakan `C-xC-e', +;; sebab kita tidak mahu memenuhi buffer dengan teks yang tidak penting. + +;; `setq' menyimpan value ke dalam variable: +(setq my-name "Bastien") +;; `C-xC-e' => "Bastien" (terpapar di mini-buffer) + +;; `insert' akan memasukkan "Hello!" di tempat di mana cursor berada: +(insert "Hello!") +;; `C-xC-e' => "Hello!" + +;; Di atas, kita menggunakan `insert' dengan satu argument "Hello!", tetapi +;; kita boleh meletakkan beberapa argument -- di sini kita letak dua: + +(insert "Hello" " world!") +;; `C-xC-e' => "Hello world!" + +;; Anda boleh menggunakan variable selain string: +(insert "Hello, I am " my-name) +;; `C-xC-e' => "Hello, I am Bastien" + +;; Anda boleh menggabungkan sexps untuk membuat function: +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' => hello + +;; Anda boleh evaluate function: +(hello) +;; `C-xC-e' => Hello, I am Bastien + +;; Parentheses kosong di dalam function bermaksud function tersebut tidak +;; terima argument. Sekarang kita tukar function untuk menerima satu argument. +;; Di sini, argument tersebut dinamakan "name": + +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' => hello + +;; Sekarang panggil function tersebut dengan string "you" sebagai value +;; untuk argument: +(hello "you") +;; `C-xC-e' => "Hello you" + +;; Yay! + +;; Tarik nafas. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Sekarang tukar ke buffer baru dengan nama "*test*" di window yang lain: + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' +;; => [The screen has two windows and cursor is in the *test* buffer] + +;; Gerakkan mouse ke window atas dan klik kiri untuk pergi balik ke buffer scratch. +;; Cara lain adalah dengan menggunakan `C-xo' (i.e. tekan control-x kemudian +;; tekan o) untuk pergi ke window yang lain. + +;; Anda boleh menggabungkan beberapa sexps menggunakan `progn': +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' +;; => [The screen has two windows and cursor is in the *test* buffer] + +;; Mulai dari sekarang saya tidak akan beritahu anda untuk tekan `C-xC-e' lagi: +;; buat untuk setiap sexp yang akan datang. + +;; Pergi balik ke buffer *scratch* menggunakan mouse atau `C-xo'. + +;; Seelok-eloknya padam buffer tersebut: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; Atau pergi balik ke window lain: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; Anda boleh menetapkan value dengan local variable menggunakan `let': +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; Tidak perlu menggunakan `progn', sebab `let' juga menggabungkan +;; beberapa sexps. + +;; Jom format string: +(format "Hello %s!\n" "visitor") + +;; %s ialah tempat untuk meletakkan string, digantikan dengan "visitor". +;; \n ialah character untuk membuat baris baru. + +;; Jom tukar function kita menggunakan format: +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; Jom buat function lain menggunakan `let': +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; argument untuk function + your-name ; variable "Bastien" daripada let + )))) + +;; Kemudian evaluate: +(greeting "you") + +;; Sesetengah function adalah interaktif: +(read-from-minibuffer "Enter your name: ") + +;; Function tersebut akan memulangkan kembali apa yang anda masukkan ke prompt. + +;; Jom jadikan function `greeting' untuk prompt nama anda: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; argument untuk function + your-name ; variable daripada let, yang dimasukkan dari prompt + )))) + +(greeting "Bastien") + +;; Jom siapkan function dengan memaparkan result di window yang lain: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; Test function tersebut: +(greeting "Bastien") + +;; Tarik nafas. + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; Jom simpan senarai nama: +;; Jika anda ingin membuat list(senarai) data, guna ' untuk elak +;; daripada list tersebut evaluate. +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; Dapatkan elemen pertama daripada list menggunakan `car': +(car list-of-names) + +;; Dapatkan semua elemen kecuali yang pertama menggunakan `cdr': +(cdr list-of-names) + +;; Tambah elemen di awal list menggunakan `push': +(push "Stephanie" list-of-names) + +;; NOTA: `car' dan `cdr' tidak ubah suai list, tetapi `push' ya. +;; Perbezaan ini penting: sesetengah function tiada side-effects (kesan sampingan) +;; (seperti `car') dan yang lain ada side-effect (seperti `push'). + +;; Jom panggil `hello' untuk setiap elemen dalam `list-of-names': +(mapcar 'hello list-of-names) + +;; Tukar `greeting' supaya ucapkan hello kepada semua orang dalam `list-of-names': +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; Ingat lagi function `hello' di atas? Function tersebut mengambil satu +;; argument, iaitu nama. `mapcar' memanggil `hello', kemudian menggunakan setiap +;; nama dalam `list-of-names' sebagai argument untuk function `hello'. + +;; Sekarang kita susun sedikit untuk apa yang terpapar di buffer: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) akan pergi ke permulaan buffer. +;; (search-forward "Hello") akan mencari string "Hello". +;; (while x y) evaluate sexp(s) y selagi x masih pulangkan sesuatu. +;; Jika x pulangkan `nil', kita akan keluar daripada while loop. + +(replace-hello-by-bonjour) + +;; Anda akan dapat melihat semua "Hello" dalam buffer *test* +;; ditukarkan dengan "Bonjour". + +;; Anda juga akan dapat error: "Search failed: Hello". +;; +;; Bagi mengelakkan error tersebut, anda perlu beritahu `search-forward' sama ada +;; perlu berhenti mencari pada suatu ketika, dan sama ada perlu diam jika +;; tidak jumpa apa yang dicari: + +;; (search-forward "Hello" nil 't) selesai masalah: + +;; Argument `nil' cakap: carian tidak mengikut kedudukan. +;; Argument `'t' cakap: diam saja jika tidak jumpa apa yang dicari. + +;; Kita guna sexp ini di function berikut, barulah tidak keluar error: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; Ucap hello pada nama-nama dalam `list-of-names' + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; Ganti "Hello" dengan "Bonjour" + (while (search-forward "Hello" nil 't) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; Jom jadikan nama-nama tersebut bold: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil 't) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; Function ini memperkenalkan `re-search-forward': anda mencari menggunakan +;; pattern iaitu "regular expression", bukannya mencari string "Bonjour". + +;; Regular expression tersebut ialah "Bonjour \\(.+\\)!" dan dibaca begini: +;; string "Bonjour ", dan +;; kumpulan | ini ialah \\( ... \\) +;; mana-mana character | ini ialah . +;; yang boleh berulang | ini ialah + +;; dan string "!". + +;; Dah sedia? Test function tersebut! + +(boldify-names) + +;; `add-text-properties' tambah... ciri-ciri teks, seperti face. + +;; OK, kita sudah selesai. Selamat ber-hacking! + +;; Jika anda ingin tahu lebih mengenai variable atau function: +;; +;; C-h v a-variable RET +;; C-h f a-function RET +;; +;; Jika anda ingin membaca manual Emacs Lisp menggunakan Emacs: +;; +;; C-h i m elisp RET +;; +;; Jika ingin membaca pengenalan kepada Emacs Lisp secara online: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html +``` -- cgit v1.2.3 From 3f02799903c104631ccf778dabb30ba8b116b7bc Mon Sep 17 00:00:00 2001 From: Ben Quigley Date: Sun, 8 Apr 2018 13:44:35 -0400 Subject: Removed semicolons No semicolons needed in Python --- pythonstatcomp.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 6dde1cf0..66eeb7ad 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -205,7 +205,7 @@ hre["DeathY"] = extractYear(hre.Death) hre["EstAge"] = hre.DeathY.astype(int) - hre.BirthY.astype(int) # simple scatterplot, no trend line, color represents dynasty -sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False); +sns.lmplot("BirthY", "EstAge", data=hre, hue="Dynasty", fit_reg=False) # use scipy to run a linear regression from scipy import stats @@ -222,7 +222,7 @@ rval**2 # 0.020363950027333586 pval # 0.34971812581498452 # use seaborn to make a scatterplot and plot the linear regression trend line -sns.lmplot("BirthY", "EstAge", data=hre); +sns.lmplot("BirthY", "EstAge", data=hre) """ For more information on seaborn, see - http://web.stanford.edu/~mwaskom/software/seaborn/ -- cgit v1.2.3 From 47f49bc28b4546ecbb114e43cdd7ab3378bc1913 Mon Sep 17 00:00:00 2001 From: Anton Alekseev Date: Tue, 10 Apr 2018 21:12:03 +0300 Subject: Fix dead link to style guide, mention Emacs mode --- solidity.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index a0f8cd40..6174286c 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -829,7 +829,6 @@ someContractAddress.callcode('function_name'); ## Additional resources - [Solidity Docs](https://solidity.readthedocs.org/en/latest/) - [Smart Contract Best Practices](https://github.com/ConsenSys/smart-contract-best-practices) -- [Solidity Style Guide](https://ethereum.github.io/solidity//docs/style-guide/): Ethereum's style guide is heavily derived from Python's [pep8](https://www.python.org/dev/peps/pep-0008/) style guide. - [EthFiddle - The JsFiddle for Solidity](https://ethfiddle.com/) - [Browser-based Solidity Editor](https://remix.ethereum.org/) - [Gitter Solidity Chat room](https://gitter.im/ethereum/solidity) @@ -850,9 +849,10 @@ someContractAddress.callcode('function_name'); - [Hacking Distributed Blog](http://hackingdistributed.com/) ## Style -- Python's [PEP8](https://www.python.org/dev/peps/pep-0008/) is used as the baseline style guide, including its general philosophy +- [Solidity Style Guide](http://solidity.readthedocs.io/en/latest/style-guide.html): Ethereum's style guide is heavily derived from Python's [PEP 8](https://www.python.org/dev/peps/pep-0008/) style guide. ## Editors +- [Emacs Solidity Mode](https://github.com/ethereum/emacs-solidity) - [Vim Solidity](https://github.com/tomlion/vim-solidity) - Editor Snippets ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) -- cgit v1.2.3 From a80844cac53e372b0f8b423dca90151d5adb0417 Mon Sep 17 00:00:00 2001 From: "Shawn M. Hanes" Date: Wed, 11 Apr 2018 17:55:04 -0400 Subject: [Java/en] Added Lambdas section. --- java.html.markdown | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index ab2be4a2..18a3b21a 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -11,6 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] + - ["Shawn M. Hanes", "https://github.com/smhanes15"] filename: LearnJava.java --- @@ -858,6 +859,108 @@ public class EnumTest { // The enum body can include methods and other fields. // You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html +// Getting Started with Lambda Expressions +// +// New to Java version 8 are lambda expressions. Lambdas are more commonly found +// in functional programming languages, which means they are methods which can +// be created without belonging to a class, passed around as if it were itself +// an object, and executed on demand. +// +// Final note, lambdas must implement a functional interface. A functional +// interface is one which has only a single abstract method declared. It can +// have any number of default methods. Lambda expressions can be used as an +// instance of that functional interface. Any interface meeting the requirements +// is treated as a functional interface. You can read more about interfaces +// above. +// +import java.util.Map; +import java.util.HashMap; +import java.util.function.*; +import java.security.SecureRandom; + +public class Lambdas { + public static void main(String[] args) { + // Lambda declaration syntax: + // -> + + // We will use this hashmap in our examples below. + Map planets = new HashMap<>(); + planets.put("Mercury", "87.969"); + planets.put("Venus", "224.7"); + planets.put("Earth", "365.2564"); + planets.put("Mars", "687"); + planets.put("Jupiter", "4,332.59"); + planets.put("Saturn", "10,759"); + planets.put("Uranus", "30,688.5"); + planets.put("Neptune", "60,182"); + + // Lambda with zero parameters using the Supplier functional interface + // from java.util.function.Supplier. The actual lambda expression is + // what comes after numPlanets =. + Supplier numPlanets = () -> Integer.toString(planets.size()); + System.out.format("Number of Planets: %s\n\n", numPlanets.get()); + + // Lambda with one parameter and using the Consumer functional interface + // from java.util.function.Consumer. This is because planets is a Map, + // which implements both Collection and Iterable. The forEach used here, + // found in Iterable, applies the lambda expression to each member of + // the Collection. The default implementation of forEach behaves as if: + /* + for (T t : this) + action.accept(t); + */ + + // The actual lambda expression is the parameter passed to forEach. + planets.keySet().forEach((p) -> System.out.format("%s\n", p)); + + // If you are only passing a single argument, then the above can also be + // written as (note absent parentheses around p): + planets.keySet().forEach(p -> System.out.format("%s\n", p)); + + // Tracing the above, we see that planets is a HashMap, keySet() returns + // a Set of its keys, forEach applies each element as the lambda + // expression of: (parameter p) -> System.out.format("%s\n", p). Each + // time, the element is said to be "consumed" and the statement(s) + // referred to in the lambda body is applied. Remember the lambda body + // is what comes after the ->. + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format("%s\n", planet); + } + + // This example differs from the above in that a different forEach + // implementation is used: the forEach found in the HashMap class + // implementing the Map interface. This forEach accepts a BiConsumer, + // which generically speaking is a fancy way of saying it handles + // the Set of each Key -> Value pairs. This default implementation + // behaves as if: + /* + for (Map.Entry entry : map.entrySet()) + action.accept(entry.getKey(), entry.getValue()); + */ + + // The actual lambda expression is the parameter passed to forEach. + String orbits = "%s orbits the Sun in %s Earth days.\n"; + planets.forEach((K, V) -> System.out.format(orbits, K, V)); + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format(orbits, planet, planets.get(planet)); + } + + // Or, if following more closely the specification provided by the + // default implementation: + for (Map.Entry planet : planets.entrySet()) { + System.out.format(orbits, planet.getKey(), planet.getValue()); + } + + // These examples cover only the very basic use of lambdas. It might not + // seem like much or even very useful, but remember that a lambda can be + // created as an object that can later be passed as parameters to other + // methods. + } +} ``` ## Further Reading -- cgit v1.2.3 From cc0329efbb5fb9330e6c79a40f8dd2967bda5931 Mon Sep 17 00:00:00 2001 From: "Shawn M. Hanes" Date: Wed, 11 Apr 2018 18:12:59 -0400 Subject: [Java/en] Added Lambdas section. --- java.html.markdown | 164 ++++++++++++++++++++++++++--------------------------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 18a3b21a..ca0b04c2 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -11,7 +11,7 @@ contributors: - ["Michael Dähnert", "https://github.com/JaXt0r"] - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] - - ["Shawn M. Hanes", "https://github.com/smhanes15"] + - ["Shawn M. Hanes", "https://github.com/smhanes15"] filename: LearnJava.java --- @@ -879,87 +879,87 @@ import java.util.function.*; import java.security.SecureRandom; public class Lambdas { - public static void main(String[] args) { - // Lambda declaration syntax: - // -> - - // We will use this hashmap in our examples below. - Map planets = new HashMap<>(); - planets.put("Mercury", "87.969"); - planets.put("Venus", "224.7"); - planets.put("Earth", "365.2564"); - planets.put("Mars", "687"); - planets.put("Jupiter", "4,332.59"); - planets.put("Saturn", "10,759"); - planets.put("Uranus", "30,688.5"); - planets.put("Neptune", "60,182"); - - // Lambda with zero parameters using the Supplier functional interface - // from java.util.function.Supplier. The actual lambda expression is - // what comes after numPlanets =. - Supplier numPlanets = () -> Integer.toString(planets.size()); - System.out.format("Number of Planets: %s\n\n", numPlanets.get()); - - // Lambda with one parameter and using the Consumer functional interface - // from java.util.function.Consumer. This is because planets is a Map, - // which implements both Collection and Iterable. The forEach used here, - // found in Iterable, applies the lambda expression to each member of - // the Collection. The default implementation of forEach behaves as if: - /* - for (T t : this) - action.accept(t); - */ - - // The actual lambda expression is the parameter passed to forEach. - planets.keySet().forEach((p) -> System.out.format("%s\n", p)); - - // If you are only passing a single argument, then the above can also be - // written as (note absent parentheses around p): - planets.keySet().forEach(p -> System.out.format("%s\n", p)); - - // Tracing the above, we see that planets is a HashMap, keySet() returns - // a Set of its keys, forEach applies each element as the lambda - // expression of: (parameter p) -> System.out.format("%s\n", p). Each - // time, the element is said to be "consumed" and the statement(s) - // referred to in the lambda body is applied. Remember the lambda body - // is what comes after the ->. - - // The above without use of lambdas would look more traditionally like: - for (String planet : planets.keySet()) { - System.out.format("%s\n", planet); - } - - // This example differs from the above in that a different forEach - // implementation is used: the forEach found in the HashMap class - // implementing the Map interface. This forEach accepts a BiConsumer, - // which generically speaking is a fancy way of saying it handles - // the Set of each Key -> Value pairs. This default implementation - // behaves as if: - /* - for (Map.Entry entry : map.entrySet()) - action.accept(entry.getKey(), entry.getValue()); - */ - - // The actual lambda expression is the parameter passed to forEach. - String orbits = "%s orbits the Sun in %s Earth days.\n"; - planets.forEach((K, V) -> System.out.format(orbits, K, V)); - - // The above without use of lambdas would look more traditionally like: - for (String planet : planets.keySet()) { - System.out.format(orbits, planet, planets.get(planet)); - } - - // Or, if following more closely the specification provided by the - // default implementation: - for (Map.Entry planet : planets.entrySet()) { - System.out.format(orbits, planet.getKey(), planet.getValue()); - } - - // These examples cover only the very basic use of lambdas. It might not - // seem like much or even very useful, but remember that a lambda can be - // created as an object that can later be passed as parameters to other - // methods. - } + public static void main(String[] args) { + // Lambda declaration syntax: + // -> + + // We will use this hashmap in our examples below. + Map planets = new HashMap<>(); + planets.put("Mercury", "87.969"); + planets.put("Venus", "224.7"); + planets.put("Earth", "365.2564"); + planets.put("Mars", "687"); + planets.put("Jupiter", "4,332.59"); + planets.put("Saturn", "10,759"); + planets.put("Uranus", "30,688.5"); + planets.put("Neptune", "60,182"); + + // Lambda with zero parameters using the Supplier functional interface + // from java.util.function.Supplier. The actual lambda expression is + // what comes after numPlanets =. + Supplier numPlanets = () -> Integer.toString(planets.size()); + System.out.format("Number of Planets: %s\n\n", numPlanets.get()); + + // Lambda with one parameter and using the Consumer functional interface + // from java.util.function.Consumer. This is because planets is a Map, + // which implements both Collection and Iterable. The forEach used here, + // found in Iterable, applies the lambda expression to each member of + // the Collection. The default implementation of forEach behaves as if: + /* + for (T t : this) + action.accept(t); + */ + + // The actual lambda expression is the parameter passed to forEach. + planets.keySet().forEach((p) -> System.out.format("%s\n", p)); + + // If you are only passing a single argument, then the above can also be + // written as (note absent parentheses around p): + planets.keySet().forEach(p -> System.out.format("%s\n", p)); + + // Tracing the above, we see that planets is a HashMap, keySet() returns + // a Set of its keys, forEach applies each element as the lambda + // expression of: (parameter p) -> System.out.format("%s\n", p). Each + // time, the element is said to be "consumed" and the statement(s) + // referred to in the lambda body is applied. Remember the lambda body + // is what comes after the ->. + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format("%s\n", planet); + } + + // This example differs from the above in that a different forEach + // implementation is used: the forEach found in the HashMap class + // implementing the Map interface. This forEach accepts a BiConsumer, + // which generically speaking is a fancy way of saying it handles + // the Set of each Key -> Value pairs. This default implementation + // behaves as if: + /* + for (Map.Entry entry : map.entrySet()) + action.accept(entry.getKey(), entry.getValue()); + */ + + // The actual lambda expression is the parameter passed to forEach. + String orbits = "%s orbits the Sun in %s Earth days.\n"; + planets.forEach((K, V) -> System.out.format(orbits, K, V)); + + // The above without use of lambdas would look more traditionally like: + for (String planet : planets.keySet()) { + System.out.format(orbits, planet, planets.get(planet)); + } + + // Or, if following more closely the specification provided by the + // default implementation: + for (Map.Entry planet : planets.entrySet()) { + System.out.format(orbits, planet.getKey(), planet.getValue()); + } + + // These examples cover only the very basic use of lambdas. It might not + // seem like much or even very useful, but remember that a lambda can be + // created as an object that can later be passed as parameters to other + // methods. + } } ``` -- cgit v1.2.3 From 3fd6697c5eba4cb4fd6aff8ac58109d2cd79dbbb Mon Sep 17 00:00:00 2001 From: Michael Filonenko Date: Sun, 15 Apr 2018 20:46:42 +0300 Subject: Common Lisp: ru-ru --- ru-ru/common-lisp-ru.html.markdown | 704 +++++++++++++++++++++++++++++++++++++ 1 file changed, 704 insertions(+) create mode 100644 ru-ru/common-lisp-ru.html.markdown diff --git a/ru-ru/common-lisp-ru.html.markdown b/ru-ru/common-lisp-ru.html.markdown new file mode 100644 index 00000000..d5f9bf0e --- /dev/null +++ b/ru-ru/common-lisp-ru.html.markdown @@ -0,0 +1,704 @@ +--- + +language: "Common Lisp" +filename: commonlisp.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Michael Filonenko", "https://github.com/filonenko-mikhail"] +lang: ru-ru +--- + +Common Lisp - мультипарадигменный язык программирования общего назначения, подходящий для широкого +спектра задач. +Его частенько называют программируемым языком программирования. + +Идеальная отправная точка - книга [Common Lisp на практике (перевод)](http://lisper.ru/pcl/). +Ещё одна популярная книга [Land of Lisp](http://landoflisp.com/). +И одна из последних книг [Common Lisp Recipes](http://weitz.de/cl-recipes/) вобрала в себя лучшие +архитектурные решения на основе опыта коммерческой работки автора. + + + +```common-lisp + +;;;----------------------------------------------------------------------------- +;;; 0. Синтаксис +;;;----------------------------------------------------------------------------- + +;;; Основные формы + +;;; Существует два фундамента CL: АТОМ и S-выражение. +;;; Как правило, сгруппированные S-выражения называют `формами`. + +10 ; атом; вычисляется в самого себя +:thing ; другой атом; вычисляется в символ :thing +t ; ещё один атом, обозначает `истину` (true) +(+ 1 2 3 4) ; s-выражение +'(4 :foo t) ; ещё одно s-выражение + +;;; Комментарии + +;;; Однострочные комментарии начинаются точкой с запятой. Четыре знака подряд +;;; используют для комментария всего файла, три для раздела, два для текущего +;;; определения; один для текущей строки. Например: + +;;;; life.lisp + +;;; То-сё - пятое-десятое. Оптимизировано для максимального бадабума и ччччч. +;;; Требуется для функции PoschitatBenzinIsRossiiVBelarus + +(defun meaning (life) + "Возвращает смысл Жизни" + (let ((meh "abc")) + ;; Вызывает бадабум + (loop :for x :across meh + :collect x))) ; сохранить значения в x, и потом вернуть + +;;; А вот целый блок комментария можно использовать как угодно. +;;; Для него используются #| и |# + +#| Целый блок комментария, который размазан + на несколько строк + #| + которые могут быть вложенными! + |# +|# + +;;; Чем пользоваться + +;;; Существует несколько реализаций: и коммерческих, и открытых. +;;; Все они максимально соответствуют стандарту языка. +;;; SBCL, например, добротен. А за дополнительными библиотеками +;;; нужно ходить в Quicklisp + +;;; Обычно разработка ведется в текстовом редакторе с запущенным в цикле +;;; интерпретатором (в CL это Read Eval Print Loop). Этот цикл (REPL) +;;; позволяет интерактивно выполнять части программы вживую сразу наблюдая +;;; результат. + +;;;----------------------------------------------------------------------------- +;;; 1. Базовые типы и операторы +;;;----------------------------------------------------------------------------- + +;;; Символы + +'foo ; => FOO Символы автоматически приводятся к верхнему регистру. + +;;; INTERN создаёт символ из строки. + +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + +;;; Числа + +9999999999999999999999 ; целые +#b111 ; двоичные => 7 +#o111 ; восьмеричные => 73 +#x111 ; шестнадцатиричные => 273 +3.14159s0 ; с плавающей точкой +3.14159d0 ; с плавающей точкой с двойной точностью +1/2 ; рациональные) +#C(1 2) ; комплексные + +;;; Вызов функции пишется как s-выражение (f x y z ....), где f это функция, +;;; x, y, z, ... аругменты. + +(+ 1 2) ; => 3 + +;;; Если вы хотите просто представить код как данные, воспользуйтесь формой QUOTE +;;; Она не вычисляет аргументы, а возвращает их как есть. +;;; Она даёт начало метапрограммированию + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; QUOTE можно сокращенно записать знаком ' + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; Арифметические операции + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 +(mod 5 2) ; => 1 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; Булевые + +t ; истина; любое не-NIL значение `истинно` +nil ; ложь; а ещё пустой список () тоже `ложь` +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; Строковые символы + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; Строки это фиксированные массивы символов + +"Hello, world!" +"Тимур \"Каштан\" Бадтрудинов" ; экранировать двойную кавычку обратным слешом + +;;; Строки можно соединять + +(concatenate 'string "ПРивет, " "мир!") ; => "ПРивет, мир!" + +;;; Можно пройтись по строке как по массиву символов + +(elt "Apple" 0) ; => #\A + +;;; Для форматированного вывода используется FORMAT. Он умеет выводить, как просто значения, +;;; так и производить циклы и учитывать условия. Первый агрумент указывает куда отправить +;;; результат. Если NIL, FORMAT вернет результат как строку, если T результат отправиться +;;; консоль вывода а форма вернет NIL. + +(format nil "~A, ~A!" "Привет" "мир") ; => "Привет, мир!" +(format t "~A, ~A!" "Привет" "мир") ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 2. Переменные +;;;----------------------------------------------------------------------------- + +;;; С помощью DEFVAR и DEFPARAMETER вы можете создать глобальную (динамческой видимости) +;;; переменную. +;;; Имя переменной может состоять из любых символов кроме: ()",'`;#|\ + +;;; Разница между DEFVAR и DEFPARAMETER в том, что повторное выполнение DEFVAR +;;; переменную не поменяет. А вот DEFPARAMETER меняет переменную при каждом вызове. + +;;; Обычно глобальные (динамически видимые) переменные содержат звездочки в имени. + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;;; Можете использовать unicode. +(defparameter *КУКУ* nil) + +;;; Доступ к необъявленной переменной - это непредсказуемое поведение. Не делайте так. + +;;; С помощью LET можете сделать локальное связывание. +;;; В следующем куске кода, `я` связывается с "танцую с тобой" только +;;; внутри формы (let ...). LET всегда возвращает значение последней формы. + +(let ((я "танцую с тобой")) я) ; => "танцую с тобой" + + +;;;-----------------------------------------------------------------------------; +;;; 3. Структуры и коллекции +;;;-----------------------------------------------------------------------------; + + +;;; Структуры + +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T +(dog-name *rover*) ; => "rover" + +;;; DEFSTRUCT автоматически создала DOG-P, MAKE-DOG, и DOG-NAME + + +;;; Пары (cons-ячейки) + +;;; CONS создаёт пары. CAR и CDR возвращают начало и конец CONS-пары. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + + +;;; Списки + +;;; Списки это связанные CONS-пары, в конце самой последней из которых стоит NIL +;;; (или '() ). + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; Списки с произвольным количеством элементов удобно создавать с помощью LIST + +(list 1 2 3) ; => '(1 2 3) + +;;; Если первый аргумент для CONS это атом и второй аргумент список, CONS +;;; возвращает новую CONS-пару, которая представляет собой список + +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;;; Чтобы объединить списки, используйте APPEND + +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Или CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; Списки это самый используемый элемент языка. Поэтому с ними можно делать +;;; многие вещи. Вот несколько примеров: + +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => NIL +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; Вектора + +;;; Вектора заданные прямо в коде - это массивы с фиксированной длинной. + +#(1 2 3) ; => #(1 2 3) + +;;; Для соединения векторов используйте CONCATENATE + +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + + +;;; Массивы + +;;; И вектора и строки это подмножества массивов. + +;;; Двухмерные массивы + +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;;; Внимание: значение по-умолчанию элемента массива зависит от реализации. +;;; Лучше явно указывайте: + +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) + +;;; Для доступа к элементу в позиции 1, 1, 1: + +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 + + +;;; Вектора с изменяемой длиной + +;;; Вектора с изменяемой длиной при выводе на консоль выглядят также, +;;; как и вектора, с константной длиной + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) + +;;; Добавление новых элементов + +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) + + +;;; Множества, это просто списки: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; Несмотря на все, для действительно больших объемов данных, вам нужно что-то +;;; лучше, чем просто связанные списки + +;;; Словари представлены хеш таблицами. + +;;; Создание хеш таблицы: + +(defparameter *m* (make-hash-table)) + +;;; Установка пары ключ-значение + +(setf (gethash 'a *m*) 1) + +;;; Возврат значения по ключу + +(gethash 'a *m*) ; => 1, T + +;;; CL выражения умеют возвращать сразу несколько значений. + +(values 1 2) ; => 1, 2 + +;;; которые могут быть распределены по переменным с помощью MULTIPLE-VALUE-BIND + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) + +;;; GETHASH как раз та функция, которая возвращает несколько значений. Первое +;;; значение - это значение по ключу в хеш таблицу. Если ключ не был найден, +;;; возвращает NIL. + +;;; Второе возвращаемое значение, указывает был ли ключ в хеш таблице. Если ключа +;;; не было, то возвращает NIL. Таким образом можно проверить, это значение +;;; NIL, или ключа просто не было. + +;;; Вот возврат значений, в случае когда ключа в хеш таблице не было: + +(gethash 'd *m*) ;=> NIL, NIL + +;;; Можете задать значение по умолчанию. + +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;;; Давайте обработаем возврат несколько значений. + +(multiple-value-bind (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + + +;;;----------------------------------------------------------------------------- +;;; 3. Функции +;;;----------------------------------------------------------------------------- + +;;; Для создания анонимных функций используйте LAMBDA. Функций всегда возвращают +;;; значение последнего своего выражения. Как выглядит функция при выводе в консоль +;;; зависит от реализации. + +(lambda () "Привет Мир") ; => # + +;;; Для вызова анонимной функции пользуйтесь FUNCALL + +(funcall (lambda () "Привет Мир")) ; => "Привет мир" +(funcall #'+ 1 2 3) ; => 6 + +;;; FUNCALL сработает и тогда, когда анонимная функция стоит в начале +;;; неэкранированного списка + +((lambda () "Привет Мир")) ; => "Привет Мир" +((lambda (val) val) "Привет Мир") ; => "Привет Мир" + +;;; FUNCALL используется, когда аргументы заранее известны. +;;; В противном случае используйте APPLY + +(apply #'+ '(1 2 3)) ; => 6 +(apply (lambda () "Привет Мир") nil) ; => "Привет Мир" + +;;; Для обычной функции с именем используйте DEFUN + +(defun hello-world () "Привет Мир") +(hello-world) ; => "Привет Мир" + +;;; Выше видно пустой список (), это место для определения аргументов + +(defun hello (name) (format nil "Hello, ~A" name)) +(hello "Григорий") ; => "Привет, Григорий" + +;;; Можно указать необязательные аргументы. По умолчанию они будут NIL + +(defun hello (name &optional from) + (if from + (format t "Приветствие для ~A от ~A" name from) + (format t "Привет, ~A" name))) + +(hello "Георгия" "Василия") ; => Приветствие для Георгия от Василия + +;;; Можно явно задать значения по умолчанию + +(defun hello (name &optional (from "Мира")) + (format nil "Приветствие для ~A от ~A" name from)) + +(hello "Жоры") ; => Приветствие для Жоры от Мира +(hello "Жоры" "альпаки") ; => Приветствие для Жоры от альпаки + +;;; Можно также задать именованные параметры + +(defun generalized-greeter (name &key (from "Мира") (honorific "Господин")) + (format t "Здравствуйте, ~A ~A, от ~A" honorific name from)) + +(generalized-greeter "Григорий") +; => Здравствуйте, Господин Григорий, от Мира + +(generalized-greeter "Григорий" :from "альпаки" :honorific "гражданин") +; => Здравствуйте, Гражданин Григорий, от альпаки + + +;;;----------------------------------------------------------------------------- +;;; 4. Равенство или эквивалентность +;;;----------------------------------------------------------------------------- + +;;; У CL сложная система эквивалентности. Взглянем одним глазом. + +;;; Для чисел используйте `=' +(= 3 3.0) ; => T +(= 2 1) ; => NIL + +;;; Для идентичености объектов используйте EQL +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL + +;;; Для списков, строк, и битовых векторов - EQUAL +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 5. Циклы и ветвления +;;;----------------------------------------------------------------------------- + +;;; Ветвления + +(if t ; проверямое значение + "случилась истина" ; если, оно было истинно + "случилась ложь") ; иначе, когда оно было ложно +; => "случилась истина" + +;;; В форме ветвления if, все не-NIL значения это `истина` + +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;;; COND это цепочка проверок для нахождения искомого +(cond ((> 2 2) (error "мимо!")) + ((< 2 2) (error "опять мимо!")) + (t 'ok)) ; => 'OK + +;;; TYPECASE выбирает ветку исходя из типа выражения +(typecase 1 + (string :string) + (integer :int)) +; => :int + + +;;; Циклы + +;;; С рекурсией + +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) + +(fact 5) ; => 120 + +;;; И без + +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) + +(fact 5) ; => 120 + +(loop :for x :across "abc" :collect x) +; => (#\a #\b #\c #\d) + +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 + + +;;;----------------------------------------------------------------------------- +;;; 6. Установка значений в переменные (и не только) +;;;----------------------------------------------------------------------------- + +;;; Для присвоения переменной нового значения используйте SETF. Это уже было +;;; при работе с хеш таблицами. + +(let ((variable 10)) + (setf variable 2)) +; => 2 + +;;; Для функционального подхода в программировании, старайтесь избегать измений +;;; в переменных. + +;;;----------------------------------------------------------------------------- +;;; 7. Классы и объекты +;;;----------------------------------------------------------------------------- + +;;; Никаких больше животных в примерах. Берем устройства приводимые в движение +;;; мускульной силой человека. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "Устройство движимое человеческой силой")) + +;;; Аргументы DEFCLASS: +;;; 1. Имя класса +;;; 2. Список родительских классов +;;; 3. Список полей +;;; 4. Необязательная метаинформация + +;;; Если родительские классы не заданы, используется "стандартный" класс +;;; Это можно *изменить*, но хорошенько подумайте прежде. Если все-таки +;;; решились вам поможет "Art of the Metaobject Protocol" + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;;; Если вызвать DESCRIBE для HUMAN-POWERED-CONVEYANCE то получите следующее: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;;; CL задизайнен как интерактивная система. В рантайме доступна информация о +;;; типе объектов. + +;;; Давайте посчитаем расстояние, которое пройдет велосипед за один оборот колеса +;;; по формуле C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;;; PI - это константа в CL + +;;; Предположим мы нашли, что критерий эффективности логарифмически связан +;;; с гребцами каноэ. Тогда вычисление можем сделать сразу при инициализации. + +;;; Инициализируем объект после его создания: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + + +;;; Давайте проверим что получилось с этой самой эффективностью... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;----------------------------------------------------------------------------- +;;; 8. Макросы +;;;----------------------------------------------------------------------------- + +;;; Макросы позволяют расширить синаксис языка. В CL нет например цикла WHILE, +;;; но его проще простого реализовать на макросах. Если мы отбросим наши +;;; ассемблерные (или алгольные) инстинкты, мы взлетим на крыльях: + +(defmacro while (condition &body body) + "Пока `условие` истинно, выполняется `тело`. +`Условие` проверяется перед каждым выполнением `тела`" + (let ((block-name (gensym)) (done (gensym))) + `(tagbody + ,block-name + (unless ,condition + (go ,done)) + (progn + ,@body) + (go ,block-name) + ,done))) + +;;; Взглянем на более высокоуровневую версию этого макроса: + +(defmacro while (condition &body body) + "Пока `условие` истинно, выполняется `тело`. +`Условие` проверяется перед каждым выполнением `тела`" + `(loop while ,condition + do + (progn + ,@body))) + +;;; В современных комиляторах LOOP так же эффективен как и приведенный +;;; выше код. Поэтому используйте его, его проще читать. + +;;; В макросах используются символы ```, `,` и `@`. ``` - это оператор +;;; квазиквотирования - это значит что форма исполнятся не будет, а вернется +;;; как данные. Оператаор `,` позволяет исполнить форму внутри +;;; квазиквотирования. Оператор `@` исполняет форму внутри квазиквотирования +;;; но полученный список вклеивает по месту. + +;;; GENSYM создаёт уникальный символ, который гарантировано больше нигде в +;;; системе не используется. Так надо потому, что макросы разворачиваются +;;; во время компиляции и переменные объявленные в макросе могут совпасть +;;; по имени с переменными в обычном коде. + +;;; Дальнйешую информацию о макросах ищите в книгах Practical Common Lisp +;;; и On Lisp +``` + +## Для чтения + +На русском +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) + +На английском +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) + + +## Дополнительная информация + +На русском + +- [Lisper.ru](http://lisper.ru/) + +На английском + +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) + + +## Благодарности в английской версии + +Спасибо людям из Scheme за отличную статью, взятую за основу для +Common Lisp. + + +- [Paul Khuong](https://github.com/pkhuong) за хорошую вычитку. -- cgit v1.2.3 From 50021745fa4cd0d5ad5a475f2b2f126fcc662767 Mon Sep 17 00:00:00 2001 From: erikarvstedt <36110478+erikarvstedt@users.noreply.github.com> Date: Mon, 7 May 2018 12:47:20 +0200 Subject: css: add selector groups --- css.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 3b378d44..64dc097c 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -135,6 +135,10 @@ selector::after {} .parent * { } /* all descendants */ .parent > * { } /* all children */ +/* Group any number of selectors to define styles that affect all selectors + in the group */ +selector1, selector2 { } + /* #################### ## PROPERTIES #################### */ -- cgit v1.2.3 From e1d76fb6f34a3391c45175667ed6d0d5f8e84910 Mon Sep 17 00:00:00 2001 From: x89k Date: Tue, 15 May 2018 10:19:34 +1000 Subject: Create montilang.html.markdown --- montilang.html.markdown | 234 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 234 insertions(+) create mode 100644 montilang.html.markdown diff --git a/montilang.html.markdown b/montilang.html.markdown new file mode 100644 index 00000000..c7bee5a2 --- /dev/null +++ b/montilang.html.markdown @@ -0,0 +1,234 @@ +--- + +language: "MontiLang" +filename: montilang.ml +contributors: + - ["Leo Whitehead", "https://github.com/lduck11007"] +--- + +MontiLang is a Stack-Oriented concatenative imperative programming language. Its syntax +is roughly based off of forth with similar style for doing arithmetic in [reverse polish notation.](https://en.wikipedia.org/wiki/Reverse_Polish_notation) + +A good way to start with MontiLang is to read the documentation and examples at [montilang.ml](http://montilang.ml), +then download MontiLang or build from source code with the instructions provided. + +``` +/# Monti Reference sheet #/ +/# +Comments are multiline +Nested comments are not supported +#/ +/# Whitespace is all arbitrary, indentation is optional #/ +/# All programming in Monti is done by manipulating the parameter stack +arithmetic and stack operations in MontiLang are similar to FORTH +https://en.wikipedia.org/wiki/Forth_(programming_language) +#/ + +/# in Monti, everything is either a string or a number. Operations treat all numbers +similarly to floats, but anything without a remainder is treated as type int #/ + +/# numbers and strings are added to the stack from left to right #/ + +/# Arithmetic works by manipulating data on the stack #/ + +5 3 + PRINT . /# 8 #/ + +/# 5 and 3 are pushed onto the stack + '+' replaces top 2 items on stack with sum of top 2 items + 'PRINT' prints out the top item on the stack + '.' pops the top item from the stack. + #/ + +6 7 * PRINT . /# 42 #/ +1360 23 - PRINT . /# 1337 #/ +12 12 / PRINT . /# 1 #/ +13 2 % PRINT . /# 1 #/ + +37 NEG PRINT . /# -37 #/ +-12 ABS PRINT . /# 12 #/ +52 23 MAX PRINT . /# 52 #/ +52 23 MIN PRINT . /# 23 #/ + +/# 'PSTACK' command prints the entire stack, 'CLEAR' clears the entire stack #/ + +3 6 8 PSTACK CLEAR /# [3, 6, 8] #/ + +/# Monti comes with some tools for stack manipulation #/ + +2 DUP PSTACK CLEAR /# [2, 2] - Duplicate the top item on the stack#/ +2 6 SWAP PSTACK CLEAR /# [6, 2] - Swap top 2 items on stack #/ +1 2 3 ROT PSTACK CLEAR /# [2, 3, 1] - Rotate top 3 items on stack #/ +2 3 NIP PSTACK CLEAR /# [3] - delete second item from the top of the stack #/ +4 5 6 TRIM PSTACK CLEAR /# [5, 6] - Deletes first item on stack #/ +/# variables are assigned with the syntax 'VAR [name]'#/ +/# When assigned, the variable will take the value of the top item of the stack #/ + +6 VAR six . /# assigns var 'six' to be equal to 6 #/ +3 6 + VAR a . /# assigns var 'a' to be equal to 9 #/ + +/# the length of the stack can be calculated with the statement 'STKLEN' #/ +1 2 3 4 STKLEN PRINT CLEAR /# 4 #/ + +/# strings are defined with | | #/ + +|Hello World!| VAR world . /# sets variable 'world' equal to string 'Hello world! #/ + +/# variables can be called by typing its name. when called, the value of the variable is pushed +to the top of the stack #/ +world PRINT . + +/# with the OUT statement, the top item on the stack can be printed without a newline #/ + +|world!| |Hello, | OUT SWAP PRINT CLEAR + +/# Data types can be converted between strings and integers with the commands 'TOINT' and 'TOSTR'#/ +|5| TOINT PSTACK . /# [5] #/ +45 TOSTR PSTACK . /# ['45'] #/ + +/# User input is taken with INPUT and pushed to the stack. If the top item of the stack is a string, +the string is used as an input prompt #/ + +|What is your name? | INPUT NIP +|Hello, | OUT SWAP PRINT CLEAR + + +/# FOR loops have the syntax 'FOR [condition] [commands] ENDFOR' At the moment, [condition] can +only have the value of an integer. Either by using an integer, or a variable call to an integer. +[commands] will be interpereted the amount of time specified in [condition] #/ +/# E.G: this prints out 1 to 10 #/ + +1 VAR a . +FOR 10 + a PRINT 1 + VAR a +ENDFOR + +/# the syntax for while loops are similar. A number is evaluated as true if it is larger than +0. a string is true if its length > 0. Infinite loops can be used by using literals. +#/ +10 var loop . +WHILE loop + loop print + 1 - var loop +ENDWHILE +/# +this loop would count down from 10. + +IF statements are pretty much the same, but only are executed once. +#/ +IF loop + loop PRINT . +ENDIF + +/# This would only print 'loop' if it is larger than 0 #/ + +/# If you would want to use the top item on the stack as loop parameters, this can be done with the ':' character #/ + +/# eg, if you wanted to print 'hello' 7 times, instead of using #/ + +FOR 7 + |hello| PRINT . +ENDFOR + +/# this could be used #/ +7 +FOR : + |hello| PRINT . +ENDFOR + +/# Equality and inequality statements use the top 2 items on the stack as parameters, and replace the top two items with the output #/ +/# If it is true, the top 2 items are replaced with '1'. If false, with '0'. #/ + +7 3 > PRINT . /# 1 #/ +2 10 > PRINT . /# 0 #/ +5 9 <= PRINT . /# 1 #/ +5 5 == PRINT . /# 1 #/ +5 7 == PRINT . /# 0 #/ +3 8 != PRINT . /# 1 #/ + +/# User defined commands have the syntax of 'DEF [name] [commands] ENDDEF'. #/ +/# eg, if you wanted to define a function with the name of 'printseven' to print '7' 10 times, this could be used #/ + +DEF printseven + FOR 10 + 7 PRINT . + ENDFOR +ENDDEF + +/# to run the defined statement, simply type it and it will be run by the interpereter #/ + +printseven + +/# Montilang supports AND, OR and NOT statements #/ + +1 0 AND PRINT . /# 0 #/ +1 1 AND PRINT . /# 1 #/ +1 0 OR PRINT . /# 1 #/ +0 0 OR PRINT . /# 0 #/ +1 NOT PRINT . /# 0 #/ +0 NOT PRINT . /# 1 #/ + +/# Preprocessor statements are made inbetween '&' characters #/ +/# currently, preprocessor statements can be used to make c++-style constants #/ + +&DEFINE LOOPSTR 20& +/# must have & on either side with no spaces, 'DEFINE' is case sensative. #/ +/# All statements are scanned and replaced before the program is run, regardless of where the statements are placed #/ + +FOR LOOPSTR 7 PRINT . ENDFOR /# Prints '7' 20 times. At run, 'LOOPSTR' in source code is replaced with '20' #/ + +/# Multiple files can be used with the &INCLUDE & Command that operates similar to c++, where the file specified is tokenized, + and the &INCLUDE statement is replaced with the file #/ + +/# E.G, you can have a program be run through several files. If you had the file 'name.mt' with the following data: + +[name.mt] +|Hello, | OUT . name PRINT . + +a program that asks for your name and then prints it out can be defined as such: #/ + +|What is your name? | INPUT VAR name . &INCLUDE name.mt& + +/# ARRAYS: #/ + +/# arrays are defined with the statement 'ARR' +When called, everything currently in the stack is put into one +array and all items on the stack are replaced with the new array. #/ + +2 3 4 ARR PSTACK . /# [[2, 3, 4]] #/ + +/# the statement 'LEN' adds the length of the last item on the stack to the stack. +This can be used on arrays, as well as strings. #/ + +3 4 5 ARR LEN PRINT . /# 3 #/ + +/# values can be appended to an array with the statement 'APPEND' #/ + +1 2 3 ARR 5 APPEND . PRINT . /# [1, 2, 3, 5] #/ + +/# an array at the top of the stack can be wiped with the statement 'WIPE' #/ +3 4 5 ARR WIPE PRINT . /# [] #/ + +/# The last item of an array can be removed with the statement 'DROP' #/ + +3 4 5 ARR DROP PRINT . /# [3, 4] +/# arrays, like other datatypes can be stored in variables #/ +5 6 7 ARR VAR list . +list PRINT . /# [5, 6, 7] #/ + +/# Values at specific indexes can be changed with the statement 'INSERT ' #/ +4 5 6 ARR +97 INSERT 1 . PRINT /# 4, 97, 6 #/ + +/# Values at specific indexes can be deleted with the statement 'DEL ' #/ +1 2 3 ARR +DEL 1 PRINT . /# [1, 3] #/ + +/# items at certain indexes of an array can be gotten with the statement 'GET ' #/ + +1 2 3 ARR GET 2 PSTACK /# [[1, 2, 3], 3] #/ +``` + +## Extra information + +- [MontiLang.ml](http://montilang.ml/) +- [Github Page](https://github.com/lduck11007/MontiLang) -- cgit v1.2.3 From 198df4779beaa51e94aca69deff7ad7a572a3f06 Mon Sep 17 00:00:00 2001 From: ShuLiang Date: Fri, 25 May 2018 15:28:37 +0800 Subject: update to swift 4.1 --- zh-cn/swift-cn.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index c25b2918..18bc52ed 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -110,7 +110,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible." // -// Mark: 数组与字典(关联数组) +// MARK: 数组与字典(关联数组) // /* @@ -214,9 +214,9 @@ func greet(name: String, day: String) -> String { } greet("Bob", day: "Tuesday") -// 第一个参数表示外部参数名和内部参数名使用同一个名称。 +// 第一个参数`_`表示不使用外部参数名,忽略`_`表示外部参数名和内部参数名使用同一个名称。 // 第二个参数表示外部参数名使用 `externalParamName` ,内部参数名使用 `localParamName` -func greet2(requiredName requiredName: String, externalParamName localParamName: String) -> String { +func greet2(_ requiredName: String, externalParamName localParamName: String) -> String { return "Hello \(requiredName), the day is \(localParamName)" } greet2(requiredName:"John", externalParamName: "Sunday") // 调用时,使用命名参数来指定参数的值 @@ -250,7 +250,7 @@ var increment = makeIncrementer() increment(7) // 强制进行指针传递 (引用传递),使用 `inout` 关键字修饰函数参数 -func swapTwoInts(inout a: Int, inout b: Int) { +func swapTwoInts(a: inout Int, b: inout Int) { let tempA = a a = b b = tempA @@ -521,7 +521,7 @@ class MyShape: Rect { // 在 optional 属性,方法或下标运算符后面加一个问号,可以优雅地忽略 nil 值,返回 nil。 // 这样就不会引起运行时错误 (runtime error) - if let reshape = self.delegate?.canReshape?() where reshape { + if let reshape = self.delegate?.canReshape?() { // 注意语句中的问号 self.delegate?.reshape?() } @@ -575,10 +575,10 @@ print(foundAtIndex == 2) // true // 自定义运算符可以以下面的字符打头: // / = - + * % < > ! & | ^ . ~ // 甚至是 Unicode 的数学运算符等 -prefix operator !!! {} +prefix operator !!! // 定义一个前缀运算符,使矩形的边长放大三倍 -prefix func !!! (inout shape: Square) -> Square { +prefix func !!! (shape: inout Square) -> Square { shape.sideLength *= 3 return shape } @@ -591,8 +591,8 @@ print(mySquare.sideLength) // 4 print(mySquare.sideLength) // 12 // 运算符也可以是泛型 -infix operator <-> {} -func <-> (inout a: T, inout b: T) { +infix operator <-> +func <-> (a: inout T, b: inout T) { let c = a a = b b = c -- cgit v1.2.3 From a462b444e06f75c9f98983e925b8f79a1092d277 Mon Sep 17 00:00:00 2001 From: Brian Stearns Date: Thu, 31 May 2018 15:53:10 -0400 Subject: Correct English a/an usage --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scala.html.markdown b/scala.html.markdown index 016e2b4f..28424684 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -716,7 +716,7 @@ import scala.collection.immutable.{Map => _, Set => _, _} // Java classes can also be imported. Scala syntax can be used import java.swing.{JFrame, JWindow} -// Your programs entry point is defined in an scala file using an object, with a +// Your programs entry point is defined in a scala file using an object, with a // single method, main: object Application { def main(args: Array[String]): Unit = { -- cgit v1.2.3 From 8aa693c8cb1b5e7136603ce8e000d2142a6a20e6 Mon Sep 17 00:00:00 2001 From: Yvan Sraka Date: Sat, 9 Jun 2018 18:35:45 +0200 Subject: Fix typos in French version of Dynamic Programming tutorial --- fr-fr/dynamic-programming-fr.html.markdown | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/fr-fr/dynamic-programming-fr.html.markdown b/fr-fr/dynamic-programming-fr.html.markdown index 24e8c95f..b3660ac9 100644 --- a/fr-fr/dynamic-programming-fr.html.markdown +++ b/fr-fr/dynamic-programming-fr.html.markdown @@ -8,7 +8,6 @@ translators: lang: fr-fr --- - # Programmation dynamique ## Introduction @@ -17,9 +16,9 @@ La programmation dynamique est une technique très efficace pour résoudre une c ## Moyens de résoudre ces problèmes -1.) *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation. +1. *De haut en bas* : Commençons à résoudre le problème en le séparant en morceaux. Si nous voyons que le problème a déjà été résolu, alors nous retournons la réponse précédemment sauvegardée. Si le problème n'a pas été résolu, alors nous le résolvons et sauvegardons la réponse. C'est généralement facile et intuitif de réfléchir de cette façon. Cela s'appelle la Mémorisation. -2.) *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique. +2. *De bas en haut* : Il faut analyser le problème et trouver les sous-problèmes, et l'ordre dans lequel il faut les résoudre. Ensuite, nous devons résoudre les sous-problèmes et monter jusqu'au problème que nous voulons résoudre. De cette façon, nous sommes assurés que les sous-problèmes sont résolus avant de résoudre le vrai problème. Cela s'appelle la Programmation Dynamique. ## Exemple de Programmation Dynamique @@ -27,7 +26,7 @@ Le problème de la plus grande sous-chaîne croissante est de trouver la plus gr Premièrement, nous avons à trouver la valeur de la plus grande sous-chaîne (LSi) à chaque index `i`, avec le dernier élément de la sous-chaîne étant ai. Alors, la plus grande sous-chaîne sera le plus gros LSi. Pour commencer, LSi est égal à 1, car ai est le seul élément de la chaîne (le dernier). Ensuite, pour chaque `j` tel que `j Date: Sat, 9 Jun 2018 19:06:33 +0200 Subject: Translate Lambda Calculus in French --- fr-fr/lambda-calculus-fr.html.markdown | 105 +++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 fr-fr/lambda-calculus-fr.html.markdown diff --git a/fr-fr/lambda-calculus-fr.html.markdown b/fr-fr/lambda-calculus-fr.html.markdown new file mode 100644 index 00000000..68868830 --- /dev/null +++ b/fr-fr/lambda-calculus-fr.html.markdown @@ -0,0 +1,105 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] +translators: + - ["Yvan Sraka", "https://github.com/yvan-sraka"] +--- + +# Lambda-calcul + +Le Lambda-calcul (λ-calcul), créé à l'origine par [Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), est le plus petit langage de programmation au monde. En dépit de ne pas avoir de nombres, de chaînes, de booléens, ou de tout type de données sans fonction, le lambda calcul peut être utilisé pour représenter n'importe quelle machine de Turing! + +Le Lambda-calcul est composé de 3 éléments : **variables**, **fonctions** et **applications**. + + +| Nom | Syntaxe | Exemple | Explication | +|-------------|------------------------------------|-----------|---------------------------------------------------| +| Variable | `` | `x` | une variable nommée "x" | +| Fonction | `λ.` | `λx.x` | une fonction avec le paramètre "x" et le corps "x"| +| Application | `` | `(λx.x)a` | appel de la fonction "λx.x" avec l'argument "a" | + +La fonction la plus fondamentale est la fonction identité: `λx.x` qui est équivalente à `f(x) = x`. Le premier "x" est l'argument de la fonction, et le second est le corps de la fonction. + +## Variables libres et liées : + +- Dans la fonction `λx.x`, "x" s'appelle une variable liée car elle est à la fois dans le corps de la fonction et l'un des paramètres. +- Dans `λx.y`, "y" est appelé une variable libre car elle n'a pas été déclarée plus tôt. + +## Évaluation : + +L'évaluation est réalisée par [β-Réduction](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), qui est essentiellement une substitution lexicale. + +Lors de l'évaluation de l'expression `(λx.x)a`, nous remplaçons toutes les occurrences de "x" dans le corps de la fonction par "a". + +- `(λx.x)a` vaut après évaluation: `a` +- `(λx.y)a` vaut après évaluation: `y` + +Vous pouvez même créer des fonctions d'ordre supérieur: + +- `(λx.(λy.x))a` vaut après évaluation: `λy.a` + +Bien que le lambda-calcul ne prenne traditionnellement en charge que les fonctions à un seul paramètre, nous pouvons créer des fonctions multi-paramètres en utilisant une technique appelée currying. + +- `(λx.λy.λz.xyz)` est équivalent à `f(x, y, z) = x(y(z))` + +Parfois, `λxy.` est utilisé de manière interchangeable avec: `λx.λy.` + +---- + +Il est important de reconnaître que le lambda-calcul traditionnel n'a pas de nombres, de caractères ou tout autre type de données sans fonction! + +## Logique booléenne : + +Il n'y a pas de "Vrai" ou de "Faux" dans le calcul lambda. Il n'y a même pas 1 ou 0. + +Au lieu: + +`T` est représenté par: `λx.λy.x` + +`F` est représenté par: `λx.λy.y` + +Premièrement, nous pouvons définir une fonction "if" `λbtf` qui renvoie `t` si `b` est vrai et `f` si `b` est faux + +`IF` est équivalent à: `λb.λt.λf.b t f` + +En utilisant `IF`, nous pouvons définir les opérateurs logiques de base booléens: + +`a AND b` est équivalent à: `λab.IF a b F` + +`a OR b` est équivalent à: `λab.IF a T b` + +`a NOT b` est équivalent à: `λa.IF a F T` + +*Note: `IF a b c` est equivalent à : `IF(a(b(c)))`* + +## Nombres : + +Bien qu'il n'y ait pas de nombres dans le lambda-calcul, nous pouvons encoder des nombres en utilisant les [nombres de Church](https://en.wikipedia.org/wiki/Church_encoding). + +Pour tout nombre n: n = λf.fn donc: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +Pour incrémenter un nombre de Church, nous utilisons la fonction successeur `S(n) = n + 1` qui est: + +`S = λn.λf.λx.f((n f) x)` + +En utilisant `S`, nous pouvons définir la fonction `ADD`: + +`ADD = λab.(a S)n` + +**Défi:** essayez de définir votre propre fonction de multiplication! + +## Pour aller plus loin : + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file -- cgit v1.2.3 From d2fb2730e6abcfc3db04ad4f72c3592243eda100 Mon Sep 17 00:00:00 2001 From: root Date: Fri, 15 Jun 2018 06:17:34 +0000 Subject: Add lang to tr-tr --- tr-tr/c++-tr.html.markdown | 1 + tr-tr/git-tr.html.markdown | 1 + 2 files changed, 2 insertions(+) diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index a1318876..267743f1 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -1,5 +1,6 @@ --- language: c++ +lang: tr-tr filename: learncpp.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown index 533bb21a..72197050 100644 --- a/tr-tr/git-tr.html.markdown +++ b/tr-tr/git-tr.html.markdown @@ -1,5 +1,6 @@ --- category: tool +lang: tr-tr tool: git contributors: - ["Jake Prather", "http://github.com/JakeHP"] -- cgit v1.2.3 From 1f4fea47fdf512f500d2ac01748ab691cf8c1cab Mon Sep 17 00:00:00 2001 From: Alexey Rogachev Date: Sat, 16 Jun 2018 21:10:19 +0600 Subject: Fixed a typo --- ruby.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ruby.html.markdown b/ruby.html.markdown index bbc8c558..4bc872da 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -413,7 +413,7 @@ end # Destructuring -# Ruby will automatically destrucure arrays on assignment to multiple variables: +# Ruby will automatically destructure arrays on assignment to multiple variables: a, b, c = [1, 2, 3] a #=> 1 b #=> 2 -- cgit v1.2.3 From 13812cc1741729cca7f714be89500da647e09e5c Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 17 Jun 2018 13:02:17 -0400 Subject: feat(mips.html.markdown): Added description and comments for MIPS --- mips.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 mips.html.markdown diff --git a/mips.html.markdown b/mips.html.markdown new file mode 100644 index 00000000..b3be1bb8 --- /dev/null +++ b/mips.html.markdown @@ -0,0 +1,16 @@ +--- +language: "MIPS" +filename: MIPS.mips +contributors: + - ["Stanley Lim", "https://github.com/Spiderpig86"] +--- + +The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language is designed to work with the MIPS microprocessor paradigm designed by J. L. Hennessy in 1981. These RISC processors are used in embedded systems such as gateways and routers. + +[Read More](https://en.wikipedia.org/wiki/MIPS_architecture) + +```assembly +# Comments are denoted with a '#' + +# Everything that occurs after a '#' will be ignored by the assembler's lexer. +``` \ No newline at end of file -- cgit v1.2.3 From 1697484447c8313c822668a6fe5f87ed1c51e321 Mon Sep 17 00:00:00 2001 From: Adem Budak Date: Wed, 20 Jun 2018 02:54:22 +0300 Subject: Fixed: Several typos --- tr-tr/c++-tr.html.markdown | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/tr-tr/c++-tr.html.markdown b/tr-tr/c++-tr.html.markdown index a1318876..f9f22a1d 100644 --- a/tr-tr/c++-tr.html.markdown +++ b/tr-tr/c++-tr.html.markdown @@ -27,12 +27,12 @@ tipten bağımsızlık, exception'lar ve sınıflar gibi yüksek-seviyeli özell Bu hız ve kullanışlılık C++'ı en çok kullanılan dillerden biri yapar. ```c++ -////////////////// +////////////////////// // C ile karşılaştırma -////////////////// +////////////////////// // C++ _neredeyse_ C'nin bir üstkümesidir, değişken tanımı, basit tipleri -ve fonksiyonları için temelde aynı sözdizimini paylaşır. +// ve fonksiyonları için temelde aynı sözdizimini paylaşır. // Aynı C gibi, programın başlangıç noktası bir integer döndüren // main fonksiyonudur. @@ -105,7 +105,7 @@ int main() //////////////////////////////// // Default fonksiyon argümanları -/////////////////////////////i// +//////////////////////////////// // Eğer çağırıcı tarafından fonksiyona argüman sağlanmamışsa, // fonksiyona default argüman verebilirsin @@ -263,7 +263,7 @@ string retVal = tempObjectFun(); // Bu iki satırda aslında ne oluyor: // - tempObjectFun fonksiyonundan bir string nesnesi dönüyor // - dönmüş olan nesneyle yeni bir string oluşturuyor -/ - dönmüş olan nesne yok ediliyor +// - dönmüş olan nesne yok ediliyor // İşte bu dönen nesneye geçici nesne denir. Geçici nesneler fonksiyon nesne // döndürdüğünde oluşturulur ve ifade işini bitirdiğinde yok edilir (Aslında, // standard'ın söylediği şey bu ama derleyiciler bu davranışı değiştirmemize @@ -366,7 +366,6 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType) // Sınıfı tanımla. // Sınıflar genelde header (.h veya .hpp) dosyalarında tanımlanır. class Dog { - // Member variables and functions are private by default. // Üye değişkenler ve fonksiyonlar default olarak private'dir. std::string name; int weight; @@ -548,7 +547,7 @@ int main () { // Şablonlar C++ dilinde tipten bağımsız programlama için kullanılır. // Zaten aşina olduğun tipten bağımsız programlamayla başladık. Bir tip parametresi -alan fonksiyon veya sınıf tanımlamaık için: +// alan fonksiyon veya sınıf tanımlamaık için: template class Box { public: @@ -801,9 +800,9 @@ sort(tester.begin(), tester.end(), [](const pair& lhs, const pair dog_ids; // number_of_dogs = 3; @@ -842,9 +841,9 @@ for(auto elem: arr) { // arr dizisinin elemanlarıyla ilgili bir şeyler yap } -///////////////////// +//////////////// // Güzel Şeyler -///////////////////// +//////////////// // C++ dilinin bakış açısı yeni başlayanlar için (hatta dili iyi bilenler için bile) // şaşırtıcı olabilir. -- cgit v1.2.3 From 4fbd630dc859868e05dfd33f8af78cc28ec27de7 Mon Sep 17 00:00:00 2001 From: luthub <40150792+luthub@users.noreply.github.com> Date: Sun, 24 Jun 2018 18:10:33 +0200 Subject: [python3/de] Fix a few typos --- de-de/python3-de.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/de-de/python3-de.html.markdown b/de-de/python3-de.html.markdown index 33897225..b313727c 100644 --- a/de-de/python3-de.html.markdown +++ b/de-de/python3-de.html.markdown @@ -152,7 +152,7 @@ print("Ich bin Python. Schön, dich kennenzulernen!") some_var = 5 # kleinschreibung_mit_unterstrichen entspricht der Norm some_var #=> 5 -# Das Ansprechen einer noch nicht deklarierte Variable löst eine Exception aus. +# Das Ansprechen einer noch nicht deklarierten Variable löst eine Exception aus. # Unter "Kontrollstruktur" kann noch mehr über # Ausnahmebehandlung erfahren werden. some_unknown_var # Löst einen NameError aus @@ -225,7 +225,7 @@ a, b, c = (1, 2, 3) # a ist jetzt 1, b ist jetzt 2 und c ist jetzt 3 # Tupel werden standardmäßig erstellt, wenn wir uns die Klammern sparen d, e, f = 4, 5, 6 # Es ist kinderleicht zwei Werte zu tauschen -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # d ist nun 5 und e ist nun 4 # Dictionarys (Wörterbucher) speichern Schlüssel-Werte-Paare @@ -379,8 +379,8 @@ with open("meineDatei.txt") as f: print(line) # Python bietet ein fundamentales Konzept der Iteration. -# Das Objekt, auf das die Interation, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". -# Die range Method gibt ein solches Objekt aus. +# Das Objekt, auf das die Iteration, also die Wiederholung einer Methode angewandt wird heißt auf Englisch "iterable". +# Die range Methode gibt ein solches Objekt aus. filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() @@ -396,8 +396,8 @@ our_iterable[1] # TypeError # Ein iterable ist ein Objekt, das weiß wie es einen Iteratoren erschafft. our_iterator = iter(our_iterable) -# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es geraden hat während wir durch es gehen. -# Das jeweeils nächste Objekt bekommen wir mit "next()" +# Unser Iterator ist ein Objekt, das sich merkt, welchen Status es gerade hat während wir durch es gehen. +# Das jeweils nächste Objekt bekommen wir mit "next()" next(our_iterator) #=> "one" # Es hält den vorherigen Status @@ -442,7 +442,7 @@ def keyword_args(**kwargs): # Rufen wir es mal auf, um zu sehen, was passiert keyword_args(big="foot", loch="ness") #=> {"big": "foot", "loch": "ness"} -# Wir können beides gleichzeitig machem, wenn wir wollen +# Wir können beides gleichzeitig machen, wenn wir wollen def all_the_args(*args, **kwargs): print(args) print(kwargs) -- cgit v1.2.3 From 86b8304bc28abab2c1565710deaced66e7a72606 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 24 Jun 2018 14:00:07 -0400 Subject: feat(mips.html.markdown): Added info for data section --- mips.html.markdown | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/mips.html.markdown b/mips.html.markdown index b3be1bb8..952cc551 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -13,4 +13,24 @@ The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language # Comments are denoted with a '#' # Everything that occurs after a '#' will be ignored by the assembler's lexer. + +# Programs typically contain a .data and .text sections + +.data # Section where data is stored in memory (allocated in RAM), similar to variables in higher level languages + + # Declarations follow a ( label: .type value(s) ) form of declaration + hello_world .asciiz "Hello World\n" # Declare a null terminated string + num1: .word 42 # Integers are referred to as words (32 bit value) + arr1: .word 1, 2, 3, 4, 5 # Array of words + arr2: .byte 'a', 'b' # Array of chars (1 byte each) + buffer: .space 60 # Allocates space in the RAM (not cleared to 0) + + # Datatype sizes + _byte: .byte 'a' # 1 byte + _halfword: .half 53 # 2 bytes + _word: .word 3 # 4 bytes + _float: .float 3.14 # 4 bytes + _double: .double 7.0 # 8 bytes + + ``` \ No newline at end of file -- cgit v1.2.3 From 254879a3be6829fa13d984a73dcda994aa3cd83d Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 24 Jun 2018 14:55:47 -0400 Subject: feat(mips.html.markdown): Added basics of loading and storing instructions --- mips.html.markdown | 49 +++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index 952cc551..1c857ba4 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -19,18 +19,47 @@ The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language .data # Section where data is stored in memory (allocated in RAM), similar to variables in higher level languages # Declarations follow a ( label: .type value(s) ) form of declaration - hello_world .asciiz "Hello World\n" # Declare a null terminated string - num1: .word 42 # Integers are referred to as words (32 bit value) - arr1: .word 1, 2, 3, 4, 5 # Array of words - arr2: .byte 'a', 'b' # Array of chars (1 byte each) - buffer: .space 60 # Allocates space in the RAM (not cleared to 0) +hello_world .asciiz "Hello World\n" # Declare a null terminated string + num1: .word 42 # Integers are referred to as words (32 bit value) + arr1: .word 1, 2, 3, 4, 5 # Array of words + arr2: .byte 'a', 'b' # Array of chars (1 byte each) + buffer: .space 60 # Allocates space in the RAM (not cleared to 0) # Datatype sizes - _byte: .byte 'a' # 1 byte - _halfword: .half 53 # 2 bytes - _word: .word 3 # 4 bytes - _float: .float 3.14 # 4 bytes - _double: .double 7.0 # 8 bytes + _byte: .byte 'a' # 1 byte + _halfword: .half 53 # 2 bytes + _word: .word 3 # 4 bytes + _float: .float 3.14 # 4 bytes + _double: .double 7.0 # 8 bytes + .align 2 # Memory alignment of data, where number indicates byte alignment in powers of 2. (.align 2 represents word alignment since 2^2 = 4 bytes) + +.text # Section that contains instructions and program logic +.globl _main # Declares an instruction label as global, making it accessible to other files + + _main: # MIPS programs execute instructions sequentially, where this will be executed first + + # Let's print "hello world" + la $a0, hello_world # Load address of string stored in memory + li $v0, 4 # Load the syscall value (indicating type of functionality) + syscall # Perform the specified syscall with the given argument ($a0) + + # Registers (used to hold data during program execution) + # $t0 - $t9 # Temporary registers used for intermediate calculations inside subroutines (not saved across function calls) + # $s0 - $s7 # Saved registers where values are saved across subroutine calls. Typically saved in stack + # $a0 - $a3 # Argument registers for passing in arguments for subroutines + # $v0 - $v1 # Return registers for returning values to caller function + + # Types of load/store instructions + la $t0, label # Copy the address of a value in memory specified by the label into register $t0 + lw $t0, label # Copy a word value from memory + lw $t1, 4($s0) # Copy a word value from an address stored in a register with an offset of 4 bytes (addr + 4) + lb $t2, label # Copy a byte value to the lower order portion of the register $t2 + lb $t2, 0($s0) # Copy a byte value from the source address in $s0 with offset 0 + # Same idea with 'lh' for halfwords + + sw $t0, label # Store word value into memory address mapped by label + sw $t0, 8($s0) # Store word value into address specified in $s0 and offset of 8 bytes + # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist ``` \ No newline at end of file -- cgit v1.2.3 From 2dbfcc8faf8c5f1b144a0b0387ac545bf17a3a75 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Tue, 26 Jun 2018 17:43:39 -0400 Subject: Fix sentence mistake in fsharp.html.markdown --- fsharp.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index bbf477ba..dd85552d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -306,7 +306,7 @@ module DataTypeExamples = // ------------------------------------ // Union types (aka variants) have a set of choices - // Only case can be valid at a time. + // Only one case can be valid at a time. // ------------------------------------ // Use "type" with bar/pipe to define a union type -- cgit v1.2.3 From 8f5f8d576bf248a2af9689cb88161f06e2a47e02 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 16:52:13 +0630 Subject: Initial Commit --- processing.html.markdown | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 processing.html.markdown diff --git a/processing.html.markdown b/processing.html.markdown new file mode 100644 index 00000000..707e09c9 --- /dev/null +++ b/processing.html.markdown @@ -0,0 +1,27 @@ +--- +language: "Processing" +filename: learnprocessing.pde +contributors: + - ["Phone Thant Ko", "http://github.com/phonethantko"] +--- +Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to +learn fundamentals of computer programming in a visual context. While the language is based off on Java language, +its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) +The language also comes with its official IDE to compile and run the scripts. + +```Processing +// Single-line comment starts with // + +/* + Since Processing is based on Java the syntax for its comments are the same as Java (as you may have noticed above)! + Multi-line comments are wrapped around /* */ +*/ + +// In Processing, your program's entry point is a function named setup() with a void return type. +// Note! The syntax looks strikingly similar to that of C++ +void setup() { + // This prints out the classic output "Hello World!" to the console when run. + println("Hello World!"); // Another language with a semi-column trap, aint it? +} + +``` -- cgit v1.2.3 From 45432cdc0d9ccf083d4f32be4fa175ee0fa6bbe2 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 16:59:16 +0630 Subject: Update processing.html.markdown --- processing.html.markdown | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 707e09c9..f4b90882 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -5,15 +5,17 @@ contributors: - ["Phone Thant Ko", "http://github.com/phonethantko"] --- Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to -learn fundamentals of computer programming in a visual context. While the language is based off on Java language, -its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) +learn fundamentals of computer programming in a visual context. +While the language is based off on Java language, +its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) The language also comes with its official IDE to compile and run the scripts. ```Processing // Single-line comment starts with // /* - Since Processing is based on Java the syntax for its comments are the same as Java (as you may have noticed above)! + Since Processing is based on Java, + the syntax for its comments are the same as Java (as you may have noticed above)! Multi-line comments are wrapped around /* */ */ -- cgit v1.2.3 From 96335abf1079668a5cbe10037de9a58ea6e98af8 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Fri, 29 Jun 2018 18:02:18 +0630 Subject: 29/06/2018 - 6:02PM --- processing.html.markdown | 69 +++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 63 insertions(+), 6 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index f4b90882..2d70e082 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -4,26 +4,83 @@ filename: learnprocessing.pde contributors: - ["Phone Thant Ko", "http://github.com/phonethantko"] --- +## Introduction + Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to learn fundamentals of computer programming in a visual context. While the language is based off on Java language, its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) The language also comes with its official IDE to compile and run the scripts. -```Processing +```processing +/* --------- + Comments + --------- +*/ + // Single-line comment starts with // /* - Since Processing is based on Java, - the syntax for its comments are the same as Java (as you may have noticed above)! - Multi-line comments are wrapped around /* */ + Since Processing is based on Java, + the syntax for its comments are the same as Java (as you may have noticed above)! + Multi-line comments are wrapped as seen here. */ +/* --------------------------------------- + Writing and Running Processing Programs + --------------------------------------- + */ + // In Processing, your program's entry point is a function named setup() with a void return type. -// Note! The syntax looks strikingly similar to that of C++ +// Note! The syntax looks strikingly similar to that of C++. void setup() { // This prints out the classic output "Hello World!" to the console when run. - println("Hello World!"); // Another language with a semi-column trap, aint it? + println("Hello World!"); // Another language with a semi-column trap, ain't it? } +// Normally, we put all the static codes inside the setup() method as the name suggests. +// It can range from setting the background colours, setting the canvas size. +// You will see more of them throughout this document. + +// Now that we know how to write the working script and how to run it, +// we will proceed to explore what data types and collections are supported in Processing. + +/* ----------------------- + Datatypes & collections + ------------------------ +*/ + +// According to Processing References, Processing supports 8 primitive datatypes as follows. + +boolean booleanValue = true; // Boolean +byte byteValueOfA = 23; // Byte +char charValueOfA = 'A'; // Char +color colourValueOfWhiteM = color(255, 255, 255); // Colour (Specified using color() method) +color colourValueOfWhiteH = #FFFFFF; // Colour (Specified using hash value) +int intValue = 5; // Integer (Number without decimals) +long longValue = 2147483648L; // "L" is added to the number to mark it as a long +float floatValue = 1.12345; // Float (32-bit floating-point numbers) +double doubleValue = 1.12345D; // Double (64-bit floating-point numbers) + +// NOTE! +// Although datatypes "long" and "double" work in the language, +// processing functions do not use these datatypes, therefore +// they need to be converted into "int" and "float" datatypes respectively, +// using (int) and (float) syntax before passing into a function. + + + + ``` +Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without +having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of +the program flow. +However, that does not apply when you introduce external libraries, packages and even your own classes. +(Trust me! Processing projects can get really large) + +## What's Next? + +Here, I have compiled some useful resources: + + - [Processing Website](http://processing.org) + - [Processing Sketches](http://openprocessing.org) -- cgit v1.2.3 From faca0e79445f90e51acc4c4345795de6ae69c9ab Mon Sep 17 00:00:00 2001 From: hra Date: Sun, 1 Jul 2018 15:05:02 -0700 Subject: add for/of to js --- javascript.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/javascript.html.markdown b/javascript.html.markdown index 85c8a52d..f2dd08c8 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -248,6 +248,13 @@ for (var x in person){ description += person[x] + " "; } // description = 'Paul Ken 18 ' +// The for/of statement allows iteration over an iterator. +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets = 'cat dog hamster hedgehog ' + // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ house.contains = "bear"; -- cgit v1.2.3 From 2a3d19ef73cf273e5ab0b0a6d640172b47b6bb92 Mon Sep 17 00:00:00 2001 From: hra Date: Sun, 1 Jul 2018 15:10:13 -0700 Subject: add for/of to js (change description) --- javascript.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index f2dd08c8..35bcf988 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -248,7 +248,9 @@ for (var x in person){ description += person[x] + " "; } // description = 'Paul Ken 18 ' -// The for/of statement allows iteration over an iterator. +// The for/of statement allows iteration over iterable objects (including the built-in String, +// Array, e.g. the Array-like arguments or NodeList objects, TypedArray, Map and Set, +// and user-defined iterables). var myPets = ""; var pets = ["cat", "dog", "hamster", "hedgehog"]; for (var pet of pets){ -- cgit v1.2.3 From c258855144e5c59b8fa84730878e179fbb19807f Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:14:50 +0630 Subject: 2/7/18 11:14PM --- processing.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 2d70e082..83f774ee 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -8,9 +8,9 @@ contributors: Processing is a programming language for creation of digital arts and multimedia content, allowing non-programmers to learn fundamentals of computer programming in a visual context. -While the language is based off on Java language, +While the language is based on Java language, its syntax has been largely influenced by both Java and Javascript syntaxes. [See more here](https://processing.org/reference/) -The language also comes with its official IDE to compile and run the scripts. +The language is statically typed, and also comes with its official IDE to compile and run the scripts. ```processing /* --------- @@ -38,10 +38,19 @@ void setup() { println("Hello World!"); // Another language with a semi-column trap, ain't it? } -// Normally, we put all the static codes inside the setup() method as the name suggests. +// Normally, we put all the static codes inside the setup() method as the name suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. // You will see more of them throughout this document. +// If you want to run the codes indefinitely, it has to be placed in draw() method. +// draw() must exist if you want the code to run continuously and obviously, there can only be one draw() method. +int i = 0; +void draw() { + // This block of code loops forever until stopped + print(i); + i++; // Increment Operator! +} + // Now that we know how to write the working script and how to run it, // we will proceed to explore what data types and collections are supported in Processing. @@ -68,8 +77,73 @@ double doubleValue = 1.12345D; // Double (64-bit floating-point numbers) // they need to be converted into "int" and "float" datatypes respectively, // using (int) and (float) syntax before passing into a function. - - +// There is a whole bunch of default composite datatypes available for use in Processing. +// Primarily, I will brief through the most commonly used ones to save time. + +// String +// While char datatype uses '', String datatype uses "" - double quotes. +String sampleString = "Hello, Processing!"; +// String can be constructed from an array of char datatypes as well. We will discuss array very soon. +char source = {'H', 'E', 'L', 'L', 'O'}; +String stringFromSource = new String(source); // HELLO +// As in Java, strings can be concatenated using the "+" operator. +print("Hello " + "World!"); // Hello World! + +// Array +// Arrays in Processing can hold any datatypes including Objects themselves. +// Since arrays are similar to objects, they must be created with the keyword "new". +int[] intArray = new int[5]; +int[] intArrayWithValues = {1, 2, 3}; // You can also populate with data. + +// ArrayList +// Functions are similar to those of array; arraylists can hold any datatypes. +// The only difference is arraylists resize dynamically, +// as it is a form of resizable-array implementation of the Java "List" interface. +ArrayList intArrayList = new ArrayList(); + +// Object +// Since it is based on Java, Processing supports object-oriented programming. +// That means you can basically define any datatypes of your own and manipulate them to your needs. +// Of course, a class has to be defined before for the object you want. +// Format --> ClassName InstanceName +SomeRandomClass myObject // then instantiate later +//or +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor + +// Processing comes up with more collections (eg. - Dictionaries and Lists) by default, +// for the simplicity sake, I will leave them out of discussion here. + +/* ----------- + Maths + ------------ +*/ +// Arithmetic +1 + 1 // 2 +2 - 1 // 0 +2 * 3 // 6 +3 / 2 // 1 +3.0 / 2 // 1.5 +3.0 % 2 // 1.0 + +// Processing also comes with a set of functions that simplify mathematical operations. +float f = sq(3); // f = 9.0 +float p = pow(3, 3); // p = 27.0 +int a = abs(-13) // a = 13 +int r1 = round(3.1); // r1 = 3 +int r2 = round(3.7); // r2 = 4 +float sr = sqrt(25); // sr = 5.0 + +// Vectors +// Processing provides an easy way to implement vectors in its environment using PVector class. +// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) + +// Trigonometry +// Processing also supports trigonometric operations by supplying a set of functions. +// sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. +// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +float one = sin(PI/2); // one = 1.0 +// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From dd92983e8b2e85606c01c252e888c96fb43bb865 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:17:25 +0630 Subject: 2/7/18 11:17AM --- processing.html.markdown | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 83f774ee..f352b9c4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -108,7 +108,7 @@ ArrayList intArrayList = new ArrayList(); // Format --> ClassName InstanceName SomeRandomClass myObject // then instantiate later //or -SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Assuming we have nothing to pass into the constructor +SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. @@ -135,15 +135,18 @@ float sr = sqrt(25); // sr = 5.0 // Vectors // Processing provides an easy way to implement vectors in its environment using PVector class. -// It can describe a two or three dimensional vector and comes with a set of methods which are useful for matrices operations. -// You can find more information on PVector class and its functions here. (https://processing.org/reference/PVector.html) +// It can describe a two or three dimensional vector and +// comes with a set of methods which are useful for matrices operations. +// You can find more information on PVector class and its functions here. +// (https://processing.org/reference/PVector.html) // Trigonometry // Processing also supports trigonometric operations by supplying a set of functions. // sin(), cos(), tan(), asin(), acos(), atan() and also degrees() and radians() for convenient conversion. -// However, a thing to note is those functions take angle in radians as the parameter so it has to be converted beforehand. +// However, those functions take angle in radians as the parameter so it has to be converted beforehand. float one = sin(PI/2); // one = 1.0 -// As you may have noticed, there exists a set of constants for trigonometric uses; PI, HALF_PI, QUARTER_PI and so on... +// As you may have noticed, there exists a set of constants for trigonometric uses; +// PI, HALF_PI, QUARTER_PI and so on... ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From e7603786a8fcb88508b1298053c2a78ad65c9ed7 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 11:50:32 +0630 Subject: 2/7/18 11:50AM --- processing.html.markdown | 73 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 6 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index f352b9c4..91d75cb4 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -54,9 +54,9 @@ void draw() { // Now that we know how to write the working script and how to run it, // we will proceed to explore what data types and collections are supported in Processing. -/* ----------------------- - Datatypes & collections - ------------------------ +/* ------------------------ + Datatypes & collections + ------------------------ */ // According to Processing References, Processing supports 8 primitive datatypes as follows. @@ -113,10 +113,11 @@ SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing comes up with more collections (eg. - Dictionaries and Lists) by default, // for the simplicity sake, I will leave them out of discussion here. -/* ----------- - Maths - ------------ +/* ------------ + Maths + ------------ */ + // Arithmetic 1 + 1 // 2 2 - 1 // 0 @@ -148,6 +149,66 @@ float one = sin(PI/2); // one = 1.0 // As you may have noticed, there exists a set of constants for trigonometric uses; // PI, HALF_PI, QUARTER_PI and so on... +/* ------------- + Control Flow + ------------- +*/ + +// Conditional Statements +// If Statements - The same syntax as if statements in Java. +if (author.getAppearance().equals("hot")) { + print("Narcissism at its best!"); +} else { + // You can check for other conditions here. + print("Something is really wrong here!"); +} +// A shortcut for if-else statements can also be used. +int i = 3; +String value = (i > 5) ? "Big" : "Small"; // "Small" + +// Switch-case structure can be used to check multiple conditions more concisely. +int value = 2; +switch(value) { + case 0: + print("Nought!"); // This doesn't get executed. + break; // Jumps to the next statement + case 1: + print("Getting there..."); // This again doesn't get executed. + break; + case 2: + print("Bravo!"); // This line gets executed. + break; + default: + print("Not found!"); // This line gets executed if our value was some other value. + break; +} + +// Iterative statements +// For Statements - Again, the same syntax as in Java +for(int i = 0; i < 5; i ++){ + print(i); // prints from 0 to 4 +} + +// While Statements - Again, nothing new if you are familiar with Java syntax. +int j = 3; +while(j > 0) { + print(j); + j--; // This is important to prevent from the code running indefinitely. +} + +// loop()| noLoop() | redraw() | exit() +// These are more of Processing-specific functions to configure program flow. +loop(); // allows the draw() method to run forever while +noLoop(); // only allows it to run once. +redraw(); // runs the draw() method once more. +exit(); // This stops the program. It is useful for programs with draw() running continuously. +``` +Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. + +```processing + + + ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of -- cgit v1.2.3 From 90ee44541ef66d4f8d0507c1b2080cf409078064 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 12:15:25 +0630 Subject: 2/7/18 12:15PM --- processing.html.markdown | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 91d75cb4..6423baa7 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -203,9 +203,44 @@ noLoop(); // only allows it to run once. redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` +## Drawing with Processing Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. ```processing +/* ------ + Shapes + ------ +*/ + +// 2D Shapes + +// Point +point(x, y); // In 2D space +point(x, y, z); // In 3D space +// Draws a point in the coordinate space. + +// Line +line(x1, y1, x2, y2); // In 2D space +line(x1, y1, z1, x2, y2, z2); // In 3D space +// Draws a line connecting two points defined by (x1, y1) and (x2, y2) + +// Rectangle +rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners +rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +// Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. + +// Quad +quad(x,y,x2,y2,x3,y3,x4,y4) +// Draws a quadrilateral with parameters defining coordinates of each corner point. + +// Arc; +arc(x, y, width, height, start, stop, [mode]); +// While the first four parameters are self-explanatory, +// start and end defined the angles the arc starts and ends (in radians). +// Optional parameter [mode] defines the filling; +// PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes + + -- cgit v1.2.3 From fa305fc98763d4c2cd204cfe9b5f0bc59daefc14 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 14:55:22 +0630 Subject: 2/7/18 2:55PM --- processing.html.markdown | 84 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 79 insertions(+), 5 deletions(-) diff --git a/processing.html.markdown b/processing.html.markdown index 6423baa7..88c7c289 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -40,6 +40,8 @@ void setup() { // Normally, we put all the static codes inside the setup() method as the name suggest since it only runs once. // It can range from setting the background colours, setting the canvas size. +background(color); // setting the background colour +size(width,height,[renderer]); // setting the canvas size with optional parameter defining renderer // You will see more of them throughout this document. // If you want to run the codes indefinitely, it has to be placed in draw() method. @@ -204,7 +206,7 @@ redraw(); // runs the draw() method once more. exit(); // This stops the program. It is useful for programs with draw() running continuously. ``` ## Drawing with Processing -Since you will have understood the basics of the language, we will now look into the best part of Processing; DRAWING. +Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing /* ------ @@ -222,27 +224,99 @@ point(x, y, z); // In 3D space // Line line(x1, y1, x2, y2); // In 2D space line(x1, y1, z1, x2, y2, z2); // In 3D space -// Draws a line connecting two points defined by (x1, y1) and (x2, y2) +// Draws a line connecting two points defined by (x1, y1) and (x2, y2). + +// Triangle +triangle(x1, y1, x2, y2, x3, y3); +// Draws a triangle connecting three points defined by coordinate paramters. // Rectangle rect(a, b, c, d, [r]); // With optional parameter defining the radius of all corners -rect(a, b, c, d, tl, tr, br, bl); // With optional set of parameters defining radius of each corner +rect(a, b, c, d, [tl, tr, br, bl]); // With optional set of parameters defining radius of each corner // Draws a rectangle with {a, b} as a top left coordinate and c and d as width and height respectively. // Quad -quad(x,y,x2,y2,x3,y3,x4,y4) +quad(x, y, x2, y2, x3, y3, x4, y4); // Draws a quadrilateral with parameters defining coordinates of each corner point. -// Arc; +// Ellipse +ellipse(x, y, width, height); +// Draws an eclipse at point {x, y} with width and height specified. + +// Arc arc(x, y, width, height, start, stop, [mode]); // While the first four parameters are self-explanatory, // start and end defined the angles the arc starts and ends (in radians). // Optional parameter [mode] defines the filling; // PIE gives pie-like outline, CHORD gives the chord-like outline and OPEN is CHORD without strokes +// Curves +// Processing provides two implementation of curves; using curve() and bezier(). +// Since I plan to keep this simple I won't be discussing any further details. +// However, if you want to implement it in your sketch, here are the references: +// (https://processing.org/reference/curve_.html)(https://processing.org/reference/bezier_.html) + +// 3D Shapes + +// 3D space can be configured by setting "P3D" to the renderer parameter in size() method. +size(width, height, P3D); +// In 3D space, you will have to translate to the particular coordinate to render the 3D shapes. +// Box +box(size); // Cube with same length defined by size +box(w, h, d); // Box with width, height and depth separately defined +// Sphere +sphere(radius); // Its size is defined using the radius parameter +// Mechanism behind rendering spheres is implemented by tessellating triangles. +// That said, how much detail being rendered is controlled by function sphereDetail(res) +// More information here: (https://processing.org/reference/sphereDetail_.html) + +// Irregular Shapes +// What if you wanted to draw something that's not made available by Processing's functions? +// You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. +// More information here: (https://processing.org/reference/beginShape_.html) + +/* --------------- + Transformations + --------------- +*/ + +// Transformations are particularly useful to keep track of the coordinate space +// and the vertices of the shapes you have drawn. +// Particularly, matrix stack methods; pushMatrix(), popMatrix() and translate(x,y) +pushMatrix(); // Saves the current coordinate system to the stack +// ... apply all the transformations here ... +popMatrix(); // Restores the saved coordinate system +// Using them, the coordinate system can be preserved and visualized without causing any conflicts. + +// Translate +translate(x, y); // Translates to point{x, y} i.e. - setting origin to that point +translate(x, y, z); // 3D counterpart of the function + +// Rotate +rotate(angle); // Rotate the amount specified by the angle parameter +// It has 3 3D counterparts to perform rotation, each for every dimension, +// namely: rotateX(angle), rotateY(angle), rotateZ(angle) + +// Scale +scale(s); // Scale the coordinate system by either expanding or contracting it. + +/* -------------------- + Styling and Textures + -------------------- +*/ + + + +/* ------- + Imports + ------- +*/ +// The power of Processing can be further visualized when we import libraries and packages into our sketches. +// Import statement can be written as below at the top of the source code. +import processing.something.*; ``` Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without -- cgit v1.2.3 From 66c6297749cbff4272a12b852741c365bec9149a Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 15:18:30 +0630 Subject: 2/7/18 3:18PM --- processing.html.markdown | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/processing.html.markdown b/processing.html.markdown index 88c7c289..e3d83f80 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -209,6 +209,7 @@ exit(); // This stops the program. It is useful for programs with draw() running Since you will have understood the basics of the language by now, we will now look into the best part of Processing; DRAWING. ```processing + /* ------ Shapes ------ @@ -276,6 +277,7 @@ sphere(radius); // Its size is defined using the radius parameter // What if you wanted to draw something that's not made available by Processing's functions? // You can use beginShape(), endShape(), vertex(x,y) to define shapes by specifying each point. // More information here: (https://processing.org/reference/beginShape_.html) +// You can also use custom made shapes using PShape class.(https://processing.org/reference/PShape.html) /* --------------- Transformations @@ -307,7 +309,30 @@ scale(s); // Scale the coordinate system by either expanding or contracting it. -------------------- */ +// Colours +// As I have discussed earlier, the background colour can be configured using background() function. +// You can define a color object beforehand and then pass it to the function as an argument. +color c = color(255, 255, 255); // WHITE! +// By default, Processing uses RGB colour scheme but it can be configured to HSB using colorMode(). +// Read here: (https://processing.org/reference/colorMode_.html) +background(color); // By now, the background colour should be white. +// You can use fill() function to select the colour for filling the shapes. +// It has to be configured before you start drawing shapes so the colours gets applied. +fill(color(0, 0, 0)); +// If you just want to colour the outlines of the shapes then you can use stroke() function. +stroke(255, 255, 255, 200); // stroke colour set to yellow with transparency set to a lower value. + +// Images +// Processing can render images and use them in several ways. Mostly stored as PImage datatype. +filter(shader); // Processing supports several filter functions for image manipulation. +texture(image); // PImage can be passed into arguments for texture-mapping the shapes. +``` +If you want to take things further, there are more things Processing is powered for. Rendering models, shaders and whatnot. +There's too much to cover in a short documentation, so I will leave them out here. Shoud you be interested, please check out the references. +```processing +// Before we move on, I will touch a little bit more on how to import libraries +// so you can extend Processing's functionality to another horizon. /* ------- Imports -- cgit v1.2.3 From fb78575d55b64860d781e651b3b958d8ba04bdf4 Mon Sep 17 00:00:00 2001 From: Phone Thant Ko Date: Mon, 2 Jul 2018 16:15:09 +0630 Subject: 2/7/18 4:14PM --- processing.html.markdown | 67 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 66 insertions(+), 1 deletion(-) diff --git a/processing.html.markdown b/processing.html.markdown index e3d83f80..84c2dee1 100644 --- a/processing.html.markdown +++ b/processing.html.markdown @@ -344,11 +344,76 @@ There's too much to cover in a short documentation, so I will leave them out her import processing.something.*; ``` +## DTC? + +Down To Code? Let's get our hands dirty! + +Let us see an example from openprocessing to visualize how much Processing is capable of within few lines of code. +Copy the code below into your Processing IDE and see the magic. + +```processing + +// Disclaimer: I did not write this program since I currently am occupied with internship and +// this sketch is adapted from openprocessing since it shows something cool with simple codes. +// Retrieved from: (https://www.openprocessing.org/sketch/559769) + +float theta; +float a; +float col; +float num; + +void setup() { + size(600,600); +} + +void draw() { + background(#F2F2F2); + translate(width/2, height/2); + theta = map(sin(millis()/1000.0), -1, 1, 0, PI/6); + + float num=6; + for (int i=0; i30) { + pushMatrix(); + translate(0, -30); + rotate(theta); + branch(len); + popMatrix(); + + pushMatrix(); + translate(0, -30); + rotate(-theta); + branch(len); + popMatrix(); + + } +} + +``` + Processing is easy to learn and is particularly useful to create multimedia contents (even in 3D) without having to type a lot of codes. It is so simple that you can read through the code and get a rough idea of the program flow. However, that does not apply when you introduce external libraries, packages and even your own classes. -(Trust me! Processing projects can get really large) +(Trust me! Processing projects can get real humongous...) ## What's Next? -- cgit v1.2.3 From c2e2fca15ce0d0398b341f3e4e8e0fcbc9987a65 Mon Sep 17 00:00:00 2001 From: luc4leone Date: Mon, 2 Jul 2018 14:15:02 +0200 Subject: Delete broken link to Eloquent Javascript - The Annotated Version by Gordon Zhu --- javascript.html.markdown | 5 ----- 1 file changed, 5 deletions(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index e7066291..52084e93 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -600,10 +600,6 @@ of the language. [Eloquent Javascript][8] by Marijn Haverbeke is an excellent JS book/ebook with attached terminal -[Eloquent Javascript - The Annotated Version][9] by Gordon Zhu is also a great -derivative of Eloquent Javascript with extra explanations and clarifications for -some of the more complicated examples. - [Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. @@ -624,6 +620,5 @@ Mozilla Developer Network. [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: http://eloquentjavascript.net/ -[9]: http://watchandcode.com/courses/eloquent-javascript-the-annotated-version [10]: http://jstherightway.org/ [11]: https://javascript.info/ -- cgit v1.2.3 From e42e4b9b22d6d1e267d5c5931dd40f050401ba44 Mon Sep 17 00:00:00 2001 From: Fake4d Date: Tue, 3 Jul 2018 16:16:17 +0200 Subject: Update bash-de.html.markdown Variable was not initialised in this stage for this loop - Removed the $ --- de-de/bash-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/bash-de.html.markdown b/de-de/bash-de.html.markdown index 7928b136..7a0db157 100644 --- a/de-de/bash-de.html.markdown +++ b/de-de/bash-de.html.markdown @@ -180,7 +180,7 @@ esac # 'for' Schleifen iterieren über die angegebene Zahl von Argumenten: # Der Inhalt von $Variable wird dreimal ausgedruckt. -for $Variable in {1..3} +for Variable in {1..3} do echo "$Variable" done -- cgit v1.2.3 From 626af76c4d38a705f35e0c07b877404c03fa6b1d Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 17:08:23 +0800 Subject: create learnawk-cn.awk --- zh-cn/awk-cn.html.markdown | 361 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 361 insertions(+) create mode 100644 zh-cn/awk-cn.html.markdown diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown new file mode 100644 index 00000000..fcd17b4f --- /dev/null +++ b/zh-cn/awk-cn.html.markdown @@ -0,0 +1,361 @@ +--- +language: awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Tian Zhipeng", "https://github.com/tianzhipeng-git"] +filename: learnawk-cn.awk +lang: zh-cn +--- + +AWK is a standard tool on every POSIX-compliant UNIX system. It's like a +stripped-down Perl, perfect for text-processing tasks and other scripting +needs. It has a C-like syntax, but without semicolons, manual memory +management, or static typing. It excels at text processing. You can call to it +from a shell script, or you can use it as a stand-alone scripting language. + +Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always +count on it, whereas Perl's future is in question. AWK is also easier to read +than Perl. For simple text-processing scripts, particularly ones that read +files line by line and split on delimiters, AWK is probably the right tool for +the job. + +```awk +#!/usr/bin/awk -f + +# Comments are like this + +# AWK programs consist of a collection of patterns and actions. The most +# important pattern is called BEGIN. Actions go into brace blocks. +BEGIN { + + # BEGIN will run at the beginning of the program. It's where you put all + # the preliminary set-up code, before you process any text files. If you + # have no text files, then think of BEGIN as the main entry point. + + # Variables are global. Just set them or use them, no need to declare.. + count = 0 + + # Operators just like in C and friends + a = count + 1 + b = count - 1 + c = count * 1 + d = count / 1 # integer division + e = count % 1 # modulus + f = count ^ 1 # exponentiation + + a += 1 + b -= 1 + c *= 1 + d /= 1 + e %= 1 + f ^= 1 + + # Incrementing and decrementing by one + a++ + b-- + + # As a prefix operator, it returns the incremented value + ++a + --b + + # Notice, also, no punctuation such as semicolons to terminate statements + + # Control statements + if (count == 0) + print "Starting with count of 0" + else + print "Huh?" + + # Or you could use the ternary operator + print (count == 0) ? "Starting with count of 0" : "Huh?" + + # Blocks consisting of multiple lines use braces + while (a < 10) { + print "String concatenation is done" " with a series" " of" + " space-separated strings" + print a + + a++ + } + + for (i = 0; i < 10; i++) + print "Good ol' for loop" + + # As for comparisons, they're the standards: + a < b # Less than + a <= b # Less than or equal + a != b # Not equal + a == b # Equal + a > b # Greater than + a >= b # Greater than or equal + + # Logical operators as well + a && b # AND + a || b # OR + + # In addition, there's the super useful regular expression match + if ("foo" ~ "^fo+$") + print "Fooey!" + if ("boo" !~ "^fo+$") + print "Boo!" + + # Arrays + arr[0] = "foo" + arr[1] = "bar" + # Unfortunately, there is no other way to initialize an array. Ya just + # gotta chug through every value line by line like that. + + # You also have associative arrays + assoc["foo"] = "bar" + assoc["bar"] = "baz" + + # And multi-dimensional arrays, with some limitations I won't mention here + multidim[0,0] = "foo" + multidim[0,1] = "bar" + multidim[1,0] = "baz" + multidim[1,1] = "boo" + + # You can test for array membership + if ("foo" in assoc) + print "Fooey!" + + # You can also use the 'in' operator to traverse the keys of an array + for (key in assoc) + print assoc[key] + + # The command line is in a special array called ARGV + for (argnum in ARGV) + print ARGV[argnum] + + # You can remove elements of an array + # This is particularly useful to prevent AWK from assuming the arguments + # are files for it to process + delete ARGV[1] + + # The number of command line arguments is in a variable called ARGC + print ARGC + + # AWK has several built-in functions. They fall into three categories. I'll + # demonstrate each of them in their own functions, defined later. + + return_value = arithmetic_functions(a, b, c) + string_functions() + io_functions() +} + +# Here's how you define a function +function arithmetic_functions(a, b, c, d) { + + # Probably the most annoying part of AWK is that there are no local + # variables. Everything is global. For short scripts, this is fine, even + # useful, but for longer scripts, this can be a problem. + + # There is a work-around (ahem, hack). Function arguments are local to the + # function, and AWK allows you to define more function arguments than it + # needs. So just stick local variable in the function declaration, like I + # did above. As a convention, stick in some extra whitespace to distinguish + # between actual function parameters and local variables. In this example, + # a, b, and c are actual parameters, while d is merely a local variable. + + # Now, to demonstrate the arithmetic functions + + # Most AWK implementations have some standard trig functions + localvar = sin(a) + localvar = cos(a) + localvar = atan2(a, b) # arc tangent of b / a + + # And logarithmic stuff + localvar = exp(a) + localvar = log(a) + + # Square root + localvar = sqrt(a) + + # Truncate floating point to integer + localvar = int(5.34) # localvar => 5 + + # Random numbers + srand() # Supply a seed as an argument. By default, it uses the time of day + localvar = rand() # Random number between 0 and 1. + + # Here's how to return a value + return localvar +} + +function string_functions( localvar, arr) { + + # AWK, being a string-processing language, has several string-related + # functions, many of which rely heavily on regular expressions. + + # Search and replace, first instance (sub) or all instances (gsub) + # Both return number of matches replaced + localvar = "fooooobar" + sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" + gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" + + # Search for a string that matches a regular expression + # index() does the same thing, but doesn't allow a regular expression + match(localvar, "t") # => 4, since the 't' is the fourth character + + # Split on a delimiter + split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] + + # Other useful stuff + sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" + substr("foobar", 2, 3) # => "oob" + substr("foobar", 4) # => "bar" + length("foo") # => 3 + tolower("FOO") # => "foo" + toupper("foo") # => "FOO" +} + +function io_functions( localvar) { + + # You've already seen print + print "Hello world" + + # There's also printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3) + + # AWK doesn't have file handles, per se. It will automatically open a file + # handle for you when you use something that needs one. The string you used + # for this can be treated as a file handle, for purposes of I/O. This makes + # it feel sort of like shell scripting: + + print "foobar" >"/tmp/foobar.txt" + + # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + close("/tmp/foobar.txt") + + # Here's how you run something in the shell + system("echo foobar") # => prints foobar + + # Reads a line from standard input and stores in localvar + getline localvar + + # Reads a line from a pipe + "echo foobar" | getline localvar # localvar => "foobar" + close("echo foobar") + + # Reads a line from a file and stores in localvar + getline localvar <"/tmp/foobar.txt" + close("/tmp/foobar.txt") +} + +# As I said at the beginning, AWK programs consist of a collection of patterns +# and actions. You've already seen the all-important BEGIN pattern. Other +# patterns are used only if you're processing lines from files or standard +# input. +# +# When you pass arguments to AWK, they are treated as file names to process. +# It will process them all, in order. Think of it like an implicit for loop, +# iterating over the lines in these files. these patterns and actions are like +# switch statements inside the loop. + +/^fo+bar$/ { + + # This action will execute for every line that matches the regular + # expression, /^fo+bar$/, and will be skipped for any line that fails to + # match it. Let's just print the line: + + print + + # Whoa, no argument! That's because print has a default argument: $0. + # $0 is the name of the current line being processed. It is created + # automatically for you. + + # You can probably guess there are other $ variables. Every line is + # implicitly split before every action is called, much like the shell + # does. And, like the shell, each field can be access with a dollar sign + + # This will print the second and fourth fields in the line + print $2, $4 + + # AWK automatically defines many other variables to help you inspect and + # process each line. The most important one is NF + + # Prints the number of fields on this line + print NF + + # Print the last field on this line + print $NF +} + +# Every pattern is actually a true/false test. The regular expression in the +# last pattern is also a true/false test, but part of it was hidden. If you +# don't give it a string to test, it will assume $0, the line that it's +# currently processing. Thus, the complete version of it is this: + +$0 ~ /^fo+bar$/ { + print "Equivalent to the last pattern" +} + +a > 0 { + # This will execute once for each line, as long as a is positive +} + +# You get the idea. Processing text files, reading in a line at a time, and +# doing something with it, particularly splitting on a delimiter, is so common +# in UNIX that AWK is a scripting language that does all of it for you, without +# you needing to ask. All you have to do is write the patterns and actions +# based on what you expect of the input, and what you want to do with it. + +# Here's a quick example of a simple script, the sort of thing AWK is perfect +# for. It will read a name from standard input and then will print the average +# age of everyone with that first name. Let's say you supply as an argument the +# name of a this data file: +# +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# +# Here's the script: + +BEGIN { + + # First, ask the user for the name + print "What name would you like the average age for?" + + # Get a line from standard input, not from files on the command line + getline name <"/dev/stdin" +} + +# Now, match every line whose first field is the given name +$1 == name { + + # Inside here, we have access to a number of useful variables, already + # pre-loaded for us: + # $0 is the entire line + # $3 is the third field, the age, which is what we're interested in here + # NF is the number of fields, which should be 3 + # NR is the number of records (lines) seen so far + # FILENAME is the name of the file being processed + # FS is the field separator being used, which is " " here + # ...etc. There are plenty more, documented in the man page. + + # Keep track of a running total and how many lines matched + sum += $3 + nlines++ +} + +# Another special pattern is called END. It will run after processing all the +# text files. Unlike BEGIN, it will only run if you've given it input to +# process. It will run after all the files have been read and processed +# according to the rules and actions you've provided. The purpose of it is +# usually to output some kind of final report, or do something with the +# aggregate of the data you've accumulated over the course of the script. + +END { + if (nlines) + print "The average age for " name " is " sum / nlines +} + +``` +Further Reading: + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. -- cgit v1.2.3 From 72ab89ea9a2fb41ca685248e6cac89c5e153d16b Mon Sep 17 00:00:00 2001 From: tianzhipeng Date: Wed, 4 Jul 2018 21:56:04 +0800 Subject: translate awk to zh-cn --- zh-cn/awk-cn.html.markdown | 277 ++++++++++++++++++++------------------------- 1 file changed, 120 insertions(+), 157 deletions(-) diff --git a/zh-cn/awk-cn.html.markdown b/zh-cn/awk-cn.html.markdown index fcd17b4f..1fafa559 100644 --- a/zh-cn/awk-cn.html.markdown +++ b/zh-cn/awk-cn.html.markdown @@ -8,41 +8,35 @@ filename: learnawk-cn.awk lang: zh-cn --- -AWK is a standard tool on every POSIX-compliant UNIX system. It's like a -stripped-down Perl, perfect for text-processing tasks and other scripting -needs. It has a C-like syntax, but without semicolons, manual memory -management, or static typing. It excels at text processing. You can call to it -from a shell script, or you can use it as a stand-alone scripting language. - -Why use AWK instead of Perl? Mostly because AWK is part of UNIX. You can always -count on it, whereas Perl's future is in question. AWK is also easier to read -than Perl. For simple text-processing scripts, particularly ones that read -files line by line and split on delimiters, AWK is probably the right tool for -the job. +AWK是POSIX兼容的UNIX系统中的标准工具. 它像简化版的Perl, 非常适用于文本处理任务和其他脚本类需求. +它有着C风格的语法, 但是没有分号, 没有手动内存管理, 没有静态类型. +他擅长于文本处理, 你可以通过shell脚本调用AWK, 也可以用作独立的脚本语言. + +为什么使用AWK而不是Perl, 大概是因为AWK是UNIX的一部分, 你总能依靠它, 而Perl已经前途未卜了. +AWK比Perl更易读. 对于简单的文本处理脚本, 特别是按行读取文件, 按分隔符分隔处理, AWK极可能是正确的工具. ```awk #!/usr/bin/awk -f -# Comments are like this +# 注释使用井号 -# AWK programs consist of a collection of patterns and actions. The most -# important pattern is called BEGIN. Actions go into brace blocks. +# AWK程序由一系列 模式(patterns) 和 动作(actions) 组成. +# 最重要的模式叫做 BEGIN. 动作由大括号包围. BEGIN { - # BEGIN will run at the beginning of the program. It's where you put all - # the preliminary set-up code, before you process any text files. If you - # have no text files, then think of BEGIN as the main entry point. + # BEGIN在程序最开始运行. 在这里放一些在真正处理文件之前的准备和setup的代码. + # 如果没有文本文件要处理, 那就把BEGIN作为程序的主入口吧. - # Variables are global. Just set them or use them, no need to declare.. + # 变量是全局的. 直接赋值使用即可, 无需声明. count = 0 - # Operators just like in C and friends + # 运算符和C语言系一样 a = count + 1 b = count - 1 c = count * 1 - d = count / 1 # integer division - e = count % 1 # modulus - f = count ^ 1 # exponentiation + d = count / 1 # 整数除法 + e = count % 1 # 取余 + f = count ^ 1 # 取幂 a += 1 b -= 1 @@ -51,26 +45,26 @@ BEGIN { e %= 1 f ^= 1 - # Incrementing and decrementing by one + # 自增1, 自减1 a++ b-- - # As a prefix operator, it returns the incremented value + # 前置运算, 返回增加之后的值 ++a --b - # Notice, also, no punctuation such as semicolons to terminate statements + # 注意, 不需要分号之类的标点来分隔语句 - # Control statements + # 控制语句 if (count == 0) print "Starting with count of 0" else print "Huh?" - # Or you could use the ternary operator + # 或者三目运算符 print (count == 0) ? "Starting with count of 0" : "Huh?" - # Blocks consisting of multiple lines use braces + # 多行的代码块用大括号包围 while (a < 10) { print "String concatenation is done" " with a series" " of" " space-separated strings" @@ -82,126 +76,118 @@ BEGIN { for (i = 0; i < 10; i++) print "Good ol' for loop" - # As for comparisons, they're the standards: - a < b # Less than - a <= b # Less than or equal - a != b # Not equal - a == b # Equal - a > b # Greater than - a >= b # Greater than or equal + # 标准的比较运算符 + a < b # 小于 + a <= b # 小于或等于 + a != b # 不等于 + a == b # 等于 + a > b # 大于 + a >= b # 大于或等于 - # Logical operators as well - a && b # AND - a || b # OR + # 也有逻辑运算符 + a && b # 且 + a || b # 或 - # In addition, there's the super useful regular expression match + # 并且有超实用的正则表达式匹配 if ("foo" ~ "^fo+$") print "Fooey!" if ("boo" !~ "^fo+$") print "Boo!" - # Arrays + # 数组 arr[0] = "foo" arr[1] = "bar" - # Unfortunately, there is no other way to initialize an array. Ya just - # gotta chug through every value line by line like that. + # 不幸的是, 没有其他方式初始化数组. 必须像这样一行一行的赋值. - # You also have associative arrays + # 关联数组, 类似map或dict的用法. assoc["foo"] = "bar" assoc["bar"] = "baz" - # And multi-dimensional arrays, with some limitations I won't mention here + # 多维数组. 但是有一些局限性这里不提了. multidim[0,0] = "foo" multidim[0,1] = "bar" multidim[1,0] = "baz" multidim[1,1] = "boo" - # You can test for array membership + # 可以检测数组包含关系 if ("foo" in assoc) print "Fooey!" - # You can also use the 'in' operator to traverse the keys of an array + # 可以使用in遍历数组 for (key in assoc) print assoc[key] - # The command line is in a special array called ARGV + # 命令行参数是一个叫ARGV的数组 for (argnum in ARGV) print ARGV[argnum] - # You can remove elements of an array - # This is particularly useful to prevent AWK from assuming the arguments - # are files for it to process + # 可以从数组中移除元素 + # 在 防止awk把文件参数当做数据来处理 时delete功能很有用. delete ARGV[1] - # The number of command line arguments is in a variable called ARGC + # 命令行参数的个数是一个叫ARGC的变量 print ARGC - # AWK has several built-in functions. They fall into three categories. I'll - # demonstrate each of them in their own functions, defined later. + # AWK有很多内置函数, 分为三类, 会在接下来定义的各个函数中介绍. return_value = arithmetic_functions(a, b, c) string_functions() io_functions() } -# Here's how you define a function +# 定义函数 function arithmetic_functions(a, b, c, d) { - # Probably the most annoying part of AWK is that there are no local - # variables. Everything is global. For short scripts, this is fine, even - # useful, but for longer scripts, this can be a problem. + # 或许AWK最让人恼火的地方是没有局部变量, 所有东西都是全局的, + # 对于短的脚本还好, 对于长一些的就会成问题. - # There is a work-around (ahem, hack). Function arguments are local to the - # function, and AWK allows you to define more function arguments than it - # needs. So just stick local variable in the function declaration, like I - # did above. As a convention, stick in some extra whitespace to distinguish - # between actual function parameters and local variables. In this example, - # a, b, and c are actual parameters, while d is merely a local variable. + # 这里有一个技巧, 函数参数是对函数局部可见的, 并且AWK允许定义多余的参数, + # 因此可以像上面那样把局部变量插入到函数声明中. + # 为了方便区分普通参数(a,b,c)和局部变量(d), 可以多键入一些空格. - # Now, to demonstrate the arithmetic functions + # 现在介绍数学类函数 - # Most AWK implementations have some standard trig functions + # 多数AWK实现中包含标准的三角函数 localvar = sin(a) localvar = cos(a) localvar = atan2(a, b) # arc tangent of b / a - # And logarithmic stuff + # 对数 localvar = exp(a) localvar = log(a) - # Square root + # 平方根 localvar = sqrt(a) - # Truncate floating point to integer + # 浮点型转为整型 localvar = int(5.34) # localvar => 5 - # Random numbers - srand() # Supply a seed as an argument. By default, it uses the time of day - localvar = rand() # Random number between 0 and 1. + # 随机数 + srand() # 接受随机种子作为参数, 默认使用当天的时间 + localvar = rand() # 0到1之间随机 - # Here's how to return a value + # 函数返回 return localvar } function string_functions( localvar, arr) { - # AWK, being a string-processing language, has several string-related - # functions, many of which rely heavily on regular expressions. + # AWK, 作为字符处理语言, 有很多字符串相关函数, 其中大多数都严重依赖正则表达式. - # Search and replace, first instance (sub) or all instances (gsub) - # Both return number of matches replaced + # 搜索并替换, 第一个出现的 (sub) or 所有的 (gsub) + # 都是返回替换的个数 localvar = "fooooobar" sub("fo+", "Meet me at the ", localvar) # localvar => "Meet me at the bar" gsub("e+", ".", localvar) # localvar => "m..t m. at th. bar" - # Search for a string that matches a regular expression - # index() does the same thing, but doesn't allow a regular expression - match(localvar, "t") # => 4, since the 't' is the fourth character + # 搜索匹配正则的字符串 + # index() 也是搜索, 不支持正则 + match(localvar, "t") # => 4, 't'在4号位置. (译者注: awk是1开始计数的,不是常见的0-base) - # Split on a delimiter + # 按分隔符分隔 split("foo-bar-baz", arr, "-") # a => ["foo", "bar", "baz"] - # Other useful stuff + # 其他有用的函数 sprintf("%s %d %d %d", "Testing", 1, 2, 3) # => "Testing 1 2 3" substr("foobar", 2, 3) # => "oob" substr("foobar", 4) # => "bar" @@ -212,99 +198,81 @@ function string_functions( localvar, arr) { function io_functions( localvar) { - # You've already seen print + # 你已经见过的print函数 print "Hello world" - # There's also printf + # 也有printf printf("%s %d %d %d\n", "Testing", 1, 2, 3) - # AWK doesn't have file handles, per se. It will automatically open a file - # handle for you when you use something that needs one. The string you used - # for this can be treated as a file handle, for purposes of I/O. This makes - # it feel sort of like shell scripting: - + # AWK本身没有文件句柄, 当你使用需要文件的东西时会自动打开文件, 做文件I/O时, 字符串就是打开的文件句柄. + # 这看起来像Shell print "foobar" >"/tmp/foobar.txt" - # Now the string "/tmp/foobar.txt" is a file handle. You can close it: + # 现在"/tmp/foobar.txt"字符串是一个文件句柄, 你可以关闭它 close("/tmp/foobar.txt") - # Here's how you run something in the shell + # 在shell里运行一些东西 system("echo foobar") # => prints foobar - # Reads a line from standard input and stores in localvar + # 从标准输入中读一行, 并存储在localvar中 getline localvar - # Reads a line from a pipe + # 从管道中读一行, 并存储在localvar中 "echo foobar" | getline localvar # localvar => "foobar" close("echo foobar") - # Reads a line from a file and stores in localvar + # 从文件中读一行, 并存储在localvar中 getline localvar <"/tmp/foobar.txt" close("/tmp/foobar.txt") } -# As I said at the beginning, AWK programs consist of a collection of patterns -# and actions. You've already seen the all-important BEGIN pattern. Other -# patterns are used only if you're processing lines from files or standard -# input. -# -# When you pass arguments to AWK, they are treated as file names to process. -# It will process them all, in order. Think of it like an implicit for loop, -# iterating over the lines in these files. these patterns and actions are like -# switch statements inside the loop. +# 正如开头所说, AWK程序由一系列模式和动作组成. 你已经看见了重要的BEGIN pattern, +# 其他的pattern在你需要处理来自文件或标准输入的的数据行时才用到. +# +# 当你给AWK程序传参数时, 他们会被视为要处理文件的文件名, 按顺序全部会处理. +# 可以把这个过程看做一个隐式的循环, 遍历这些文件中的所有行. +# 然后这些模式和动作就是这个循环里的switch语句一样 /^fo+bar$/ { - # This action will execute for every line that matches the regular - # expression, /^fo+bar$/, and will be skipped for any line that fails to - # match it. Let's just print the line: - + # 这个动作会在匹配这个正则(/^fo+bar$/)的每一行上执行. 不匹配的则会跳过. + # 先让我们打印它: print - # Whoa, no argument! That's because print has a default argument: $0. - # $0 is the name of the current line being processed. It is created - # automatically for you. + # 哦, 没有参数, 那是因为print有一个默认参数 $0. + # $0 是当前正在处理的行, 自动被创建好了. - # You can probably guess there are other $ variables. Every line is - # implicitly split before every action is called, much like the shell - # does. And, like the shell, each field can be access with a dollar sign + # 你可能猜到有其他的$变量了. + # 每一行在动作执行前会被分隔符分隔. 像shell中一样, 每个字段都可以用$符访问 - # This will print the second and fourth fields in the line + # 这个会打印这行的第2和第4个字段 print $2, $4 - # AWK automatically defines many other variables to help you inspect and - # process each line. The most important one is NF - - # Prints the number of fields on this line + # AWK自动定义了许多其他的变量帮助你处理行. 最常用的是NF变量 + # 打印这一行的字段数 print NF - # Print the last field on this line + # 打印这一行的最后一个字段 print $NF } -# Every pattern is actually a true/false test. The regular expression in the -# last pattern is also a true/false test, but part of it was hidden. If you -# don't give it a string to test, it will assume $0, the line that it's -# currently processing. Thus, the complete version of it is this: +# 每一个模式其实是一个true/false判断, 上面那个正则其实也是一个true/false判断, 只不过被部分省略了. +# 没有指定时默认使用当前处理的整行($0)进行匹配. 因此, 完全版本是这样: $0 ~ /^fo+bar$/ { print "Equivalent to the last pattern" } a > 0 { - # This will execute once for each line, as long as a is positive + # 只要a是整数, 这块会在每一行上执行. } -# You get the idea. Processing text files, reading in a line at a time, and -# doing something with it, particularly splitting on a delimiter, is so common -# in UNIX that AWK is a scripting language that does all of it for you, without -# you needing to ask. All you have to do is write the patterns and actions -# based on what you expect of the input, and what you want to do with it. +# 就是这样, 处理文本文件, 一次读一行, 对行做一些操作. 按分隔符分隔, 这在UNIX中很常见, awk都帮你做好了. +# 你所需要做的是基于自己的需求写一些模式和动作. -# Here's a quick example of a simple script, the sort of thing AWK is perfect -# for. It will read a name from standard input and then will print the average -# age of everyone with that first name. Let's say you supply as an argument the -# name of a this data file: +# 这里有一个快速的例子, 展示了AWK所擅长做的事. +# 它从标准输入读一个名字, 打印这个first name下所有人的平均年龄. +# 示例数据: # # Bob Jones 32 # Jane Doe 22 @@ -312,41 +280,36 @@ a > 0 { # Bob Smith 29 # Bob Barker 72 # -# Here's the script: +# 示例脚本: BEGIN { - # First, ask the user for the name + # 首先, 问用户要一个名字 print "What name would you like the average age for?" - # Get a line from standard input, not from files on the command line + # 从标准输入获取名字 getline name <"/dev/stdin" } -# Now, match every line whose first field is the given name +# 然后, 用给定的名字匹配每一行的第一个字段. $1 == name { - # Inside here, we have access to a number of useful variables, already - # pre-loaded for us: - # $0 is the entire line - # $3 is the third field, the age, which is what we're interested in here - # NF is the number of fields, which should be 3 - # NR is the number of records (lines) seen so far - # FILENAME is the name of the file being processed - # FS is the field separator being used, which is " " here - # ...etc. There are plenty more, documented in the man page. - - # Keep track of a running total and how many lines matched + # 这里我们要使用几个有用的变量, 已经提前为我们加载好的: + # $0 是整行 + # $3 是第三个字段, 就是我们所感兴趣的年龄 + # NF 字段数, 这里是3 + # NR 至此为止的行数 + # FILENAME 在处理的文件名 + # FS 在使用的字段分隔符, 这里是空格" " + # ...等等, 还有很多, 在帮助文档中列出. + + # 跟踪 总和以及行数 sum += $3 nlines++ } -# Another special pattern is called END. It will run after processing all the -# text files. Unlike BEGIN, it will only run if you've given it input to -# process. It will run after all the files have been read and processed -# according to the rules and actions you've provided. The purpose of it is -# usually to output some kind of final report, or do something with the -# aggregate of the data you've accumulated over the course of the script. +# 另一个特殊的模式叫END. 它会在处理完所有行之后运行. 不像BEGIN, 它只会在有输入的时候运行. +# 它在所有文件依据给定的模式和动作处理完后运行, 目的通常是输出一些最终报告, 做一些数据聚合操作. END { if (nlines) @@ -354,8 +317,8 @@ END { } ``` -Further Reading: +更多: -* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) -* [Awk man page](https://linux.die.net/man/1/awk) -* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [Awk 教程](http://www.grymoire.com/Unix/Awk.html) +* [Awk 手册](https://linux.die.net/man/1/awk) +* [The GNU Awk 用户指南](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk在大多数Linux中预装 -- cgit v1.2.3 From b13b8af2345893ac0f6c94690c753e8a496c2df6 Mon Sep 17 00:00:00 2001 From: dhu23 <36485423+dhu23@users.noreply.github.com> Date: Fri, 6 Jul 2018 09:19:22 -0400 Subject: Update kdb+.html.markdown change the each-left and each right example to make them more distinguishable. --- kdb+.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 097f177b..5c6e66fd 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -689,14 +689,14 @@ first each (1 2 3;4 5 6;7 8 9) / each-left (\:) and each-right (/:) modify a two-argument function / to treat one of the arguments and individual variables instead of a list -1 2 3 +\: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 +1 2 3 +\: 11 22 33 +/ => 12 23 34 +/ => 13 24 35 +/ => 14 25 36 1 2 3 +/: 1 2 3 -/ => 2 3 4 -/ => 3 4 5 -/ => 4 5 6 +/ => 12 13 14 +/ => 23 24 25 +/ => 34 35 36 / The true alternatives to loops in q are the adverbs scan (\) and over (/) / their behaviour differs based on the number of arguments the function they -- cgit v1.2.3 From 779840f985125d2a39b14ffed15aab8ccc882f66 Mon Sep 17 00:00:00 2001 From: dhu23 <36485423+dhu23@users.noreply.github.com> Date: Fri, 6 Jul 2018 09:23:09 -0400 Subject: Update kdb+.html.markdown fixed typos --- kdb+.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 5c6e66fd..027b6571 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -693,7 +693,7 @@ first each (1 2 3;4 5 6;7 8 9) / => 12 23 34 / => 13 24 35 / => 14 25 36 -1 2 3 +/: 1 2 3 +1 2 3 +/: 11 22 33 / => 12 13 14 / => 23 24 25 / => 34 35 36 -- cgit v1.2.3 From a78942e8f3e2c8b728bdf0ba5e4f8117027b85a2 Mon Sep 17 00:00:00 2001 From: i Date: Fri, 6 Jul 2018 11:41:46 -0400 Subject: clear up wording --- go.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 47d9c234..df677894 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -15,15 +15,15 @@ contributors: --- Go was created out of the need to get work done. It's not the latest trend -in computer science, but it is the newest fastest way to solve real-world +in programming language theory, but it is a way to solve real-world problems. -It has familiar concepts of imperative languages with static typing. +It draws concepts from imperative languages with static typing. It's fast to compile and fast to execute, it adds easy-to-understand -concurrency to leverage today's multi-core CPUs, and has features to -help with large-scale programming. +concurrency because multi-core CPUs are now common, and it's used successfully +in large codebases (~100 million loc at Google, Inc.). -Go comes with a great standard library and an enthusiastic community. +Go comes with a good standard library and a sizeable community. ```go // Single line comment @@ -48,7 +48,7 @@ import ( // executable program. Love it or hate it, Go uses brace brackets. func main() { // Println outputs a line to stdout. - // Qualify it with the package name, fmt. + // It comes from the package fmt. fmt.Println("Hello world!") // Call another function within this package. -- cgit v1.2.3 From b3d8f0cdc7eef9659ad2fab04c4047c2851ab381 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sat, 7 Jul 2018 12:08:10 -0400 Subject: feat(mips.html.markdown): Started working on math --- mips.html.markdown | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/mips.html.markdown b/mips.html.markdown index 1c857ba4..b1ef40c4 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -37,7 +37,7 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string .text # Section that contains instructions and program logic .globl _main # Declares an instruction label as global, making it accessible to other files - _main: # MIPS programs execute instructions sequentially, where this will be executed first + _main: # MIPS programs execute instructions sequentially, where the code under this label will be executed firsts # Let's print "hello world" la $a0, hello_world # Load address of string stored in memory @@ -62,4 +62,12 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string sw $t0, 8($s0) # Store word value into address specified in $s0 and offset of 8 bytes # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist +### Math ### + _math: + # Remember to load your values into a register + lw $t0, num # From the data section + li $t0, 5 # Or from an immediate (constant) + li $t1, 6 + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + ``` \ No newline at end of file -- cgit v1.2.3 From 4c025bc12b9a204ff205281b0bd6048ae969140b Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 15:05:27 -0400 Subject: feat(mips.html.markdown): Added mathematical operations and logical operator examples --- mips.html.markdown | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index b1ef40c4..5e6a9c99 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -65,9 +65,30 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string ### Math ### _math: # Remember to load your values into a register - lw $t0, num # From the data section - li $t0, 5 # Or from an immediate (constant) + lw $t0, num # From the data section + li $t0, 5 # Or from an immediate (constant) li $t1, 6 - add $t2, $t0, $t1 # $t2 = $t0 + $t1 + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + sub $t2, $t0, $t1 # $t2 = $t0 - $t1 + mul $t2, $t0, $t1 # $t2 = $t0 * $t1 + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + + # Bitwise Shifting + sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in register + srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount in a register + + # Bitwise operators + and $t0, $t1, $t2 # Bitwise AND + andi $t0, $t1, 0xFFF # Bitwise AND with immediate + or $t0, $t1, $t2 # Bitwise OR + ori $t0, $t1, 0xFFF # Bitwise OR with immediate + xor $t0, $t1, $t2 # Bitwise XOR + xori $t0, $t1, 0xFFF # Bitwise XOR with immediate + nor $t0, $t1, $t2 # Bitwise NOR ``` \ No newline at end of file -- cgit v1.2.3 From 6f32ec9859005b370994402848547c8a90400de2 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 15:16:26 -0400 Subject: chore(mips.html.markdown): Fixed formatting of comments --- mips.html.markdown | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index 5e6a9c99..e40c4b64 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -68,27 +68,27 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string lw $t0, num # From the data section li $t0, 5 # Or from an immediate (constant) li $t1, 6 - add $t2, $t0, $t1 # $t2 = $t0 + $t1 - sub $t2, $t0, $t1 # $t2 = $t0 - $t1 - mul $t2, $t0, $t1 # $t2 = $t0 * $t1 - div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) - div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + add $t2, $t0, $t1 # $t2 = $t0 + $t1 + sub $t2, $t0, $t1 # $t2 = $t0 - $t1 + mul $t2, $t0, $t1 # $t2 = $t0 * $t1 + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' # Bitwise Shifting - sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 - sllv $t0, $t1, $t2 # Shift left by a variable amount in register - srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) - srlv $t0, $t1, $t2 # Shift right by a variable amount in a register - sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) - srav $t0, $t1, $t2 # Shift right by a variable amount in a register + sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in register + srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount in a register # Bitwise operators - and $t0, $t1, $t2 # Bitwise AND - andi $t0, $t1, 0xFFF # Bitwise AND with immediate - or $t0, $t1, $t2 # Bitwise OR - ori $t0, $t1, 0xFFF # Bitwise OR with immediate - xor $t0, $t1, $t2 # Bitwise XOR - xori $t0, $t1, 0xFFF # Bitwise XOR with immediate - nor $t0, $t1, $t2 # Bitwise NOR + and $t0, $t1, $t2 # Bitwise AND + andi $t0, $t1, 0xFFF # Bitwise AND with immediate + or $t0, $t1, $t2 # Bitwise OR + ori $t0, $t1, 0xFFF # Bitwise OR with immediate + xor $t0, $t1, $t2 # Bitwise XOR + xori $t0, $t1, 0xFFF # Bitwise XOR with immediate + nor $t0, $t1, $t2 # Bitwise NOR ``` \ No newline at end of file -- cgit v1.2.3 From 119c4172bb4eec083b23a86f784809705276e51a Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:16:51 -0400 Subject: chore(mips.html.markdown): Content now wraps at 80 chars --- .vscode/settings.json | 3 ++ mips.html.markdown | 101 +++++++++++++++++++++++++++++++++++--------------- 2 files changed, 75 insertions(+), 29 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..ae758328 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "editor.rulers": [80, 120], +} \ No newline at end of file diff --git a/mips.html.markdown b/mips.html.markdown index e40c4b64..6a9a7c2a 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -5,7 +5,10 @@ contributors: - ["Stanley Lim", "https://github.com/Spiderpig86"] --- -The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language is designed to work with the MIPS microprocessor paradigm designed by J. L. Hennessy in 1981. These RISC processors are used in embedded systems such as gateways and routers. +The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language +is designed to work with the MIPS microprocessor paradigm designed by J. L. +Hennessy in 1981. These RISC processors are used in embedded systems such as +gateways and routers. [Read More](https://en.wikipedia.org/wiki/MIPS_architecture) @@ -16,14 +19,18 @@ The MIPS (Microprocessor without Interlocked Pipeline Stages) Assembly language # Programs typically contain a .data and .text sections -.data # Section where data is stored in memory (allocated in RAM), similar to variables in higher level languages +.data # Section where data is stored in memory (allocated in RAM), similar to +variables in higher level languages # Declarations follow a ( label: .type value(s) ) form of declaration hello_world .asciiz "Hello World\n" # Declare a null terminated string - num1: .word 42 # Integers are referred to as words (32 bit value) + num1: .word 42 # Integers are referred to as words + # (32 bit value) + arr1: .word 1, 2, 3, 4, 5 # Array of words arr2: .byte 'a', 'b' # Array of chars (1 byte each) - buffer: .space 60 # Allocates space in the RAM (not cleared to 0) + buffer: .space 60 # Allocates space in the RAM + # (not cleared to 0) # Datatype sizes _byte: .byte 'a' # 1 byte @@ -32,34 +39,62 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string _float: .float 3.14 # 4 bytes _double: .double 7.0 # 8 bytes - .align 2 # Memory alignment of data, where number indicates byte alignment in powers of 2. (.align 2 represents word alignment since 2^2 = 4 bytes) + .align 2 # Memory alignment of data, where + # number indicates byte alignment in + # powers of 2. (.align 2 represents + #word alignment since 2^2 = 4 bytes) -.text # Section that contains instructions and program logic -.globl _main # Declares an instruction label as global, making it accessible to other files +.text # Section that contains instructions + # and program logic +.globl _main # Declares an instruction label as + # global, making it accessible to + # other files - _main: # MIPS programs execute instructions sequentially, where the code under this label will be executed firsts + _main: # MIPS programs execute instructions + # sequentially, where the code under + # this label will be executed firsts # Let's print "hello world" - la $a0, hello_world # Load address of string stored in memory - li $v0, 4 # Load the syscall value (indicating type of functionality) - syscall # Perform the specified syscall with the given argument ($a0) + la $a0, hello_world # Load address of string stored in + # memory + li $v0, 4 # Load the syscall value (indicating + # type of functionality) + syscall # Perform the specified syscall with + # the given argument ($a0) # Registers (used to hold data during program execution) - # $t0 - $t9 # Temporary registers used for intermediate calculations inside subroutines (not saved across function calls) - # $s0 - $s7 # Saved registers where values are saved across subroutine calls. Typically saved in stack - # $a0 - $a3 # Argument registers for passing in arguments for subroutines - # $v0 - $v1 # Return registers for returning values to caller function + # $t0 - $t9 # Temporary registers used for + # intermediate calculations inside + # subroutines (not saved across + # function calls) + + # $s0 - $s7 # Saved registers where values are + # saved across subroutine calls. + # Typically saved in stack + + # $a0 - $a3 # Argument registers for passing in + # arguments for subroutines + # $v0 - $v1 # Return registers for returning + # values to caller function # Types of load/store instructions - la $t0, label # Copy the address of a value in memory specified by the label into register $t0 + la $t0, label # Copy the address of a value in + # memory specified by the label into + # register $t0 lw $t0, label # Copy a word value from memory - lw $t1, 4($s0) # Copy a word value from an address stored in a register with an offset of 4 bytes (addr + 4) - lb $t2, label # Copy a byte value to the lower order portion of the register $t2 - lb $t2, 0($s0) # Copy a byte value from the source address in $s0 with offset 0 + lw $t1, 4($s0) # Copy a word value from an address + # stored in a register with an offset + # of 4 bytes (addr + 4) + lb $t2, label # Copy a byte value to the lower order + # portion of the register $t2 + lb $t2, 0($s0) # Copy a byte value from the source + # address in $s0 with offset 0 # Same idea with 'lh' for halfwords - sw $t0, label # Store word value into memory address mapped by label - sw $t0, 8($s0) # Store word value into address specified in $s0 and offset of 8 bytes + sw $t0, label # Store word value into memory address + # mapped by label + sw $t0, 8($s0) # Store word value into address + # specified in $s0 and offset of 8 bytes # Same idea using 'sb' and 'sh' for bytes and halfwords. 'sa' does not exist ### Math ### @@ -71,16 +106,24 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string add $t2, $t0, $t1 # $t2 = $t0 + $t1 sub $t2, $t0, $t1 # $t2 = $t0 - $t1 mul $t2, $t0, $t1 # $t2 = $t0 * $t1 - div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be supported in some versons of MARS) - div $t0, $t1 # Performs $t0 / $t1. Get the quotient using 'mflo' and remainder using 'mfhi' + div $t2, $t0, $t1 # $t2 = $t0 / $t1 (Might not be + # supported in some versons of MARS) + div $t0, $t1 # Performs $t0 / $t1. Get the quotient + # using 'mflo' and remainder using 'mfhi' # Bitwise Shifting - sll $t0, $t0, 2 # Bitwise shift to the left with immediate (constant value) of 2 - sllv $t0, $t1, $t2 # Shift left by a variable amount in register - srl $t0, $t0, 5 # Bitwise shift to the right (does not sign preserve, sign-extends with 0) - srlv $t0, $t1, $t2 # Shift right by a variable amount in a register - sra $t0, $t0, 7 # Bitwise arithmetic shift to the right (preserves sign) - srav $t0, $t1, $t2 # Shift right by a variable amount in a register + sll $t0, $t0, 2 # Bitwise shift to the left with + # immediate (constant value) of 2 + sllv $t0, $t1, $t2 # Shift left by a variable amount in + # register + srl $t0, $t0, 5 # Bitwise shift to the right (does + # not sign preserve, sign-extends with 0) + srlv $t0, $t1, $t2 # Shift right by a variable amount in + # a register + sra $t0, $t0, 7 # Bitwise arithmetic shift to the right + # (preserves sign) + srav $t0, $t1, $t2 # Shift right by a variable amount + # in a register # Bitwise operators and $t0, $t1, $t2 # Bitwise AND -- cgit v1.2.3 From e566cee6c046fe680c7be0a745d447c3818420d9 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:32:51 -0400 Subject: chore(mips.html.markdown): Fixed minor space issue --- mips.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mips.html.markdown b/mips.html.markdown index 6a9a7c2a..dd7bc7b5 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -1,6 +1,6 @@ --- -language: "MIPS" -filename: MIPS.mips +language: "MIPS Assembly" +filename: MIPS.asm contributors: - ["Stanley Lim", "https://github.com/Spiderpig86"] --- @@ -42,7 +42,7 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string .align 2 # Memory alignment of data, where # number indicates byte alignment in # powers of 2. (.align 2 represents - #word alignment since 2^2 = 4 bytes) + # word alignment since 2^2 = 4 bytes) .text # Section that contains instructions # and program logic -- cgit v1.2.3 From 3315df63f9d28f52d23fd16d907554f1655366e2 Mon Sep 17 00:00:00 2001 From: spiderpig86 Date: Sun, 8 Jul 2018 21:34:28 -0400 Subject: chore(.vscode): Removed config folder --- .vscode/settings.json | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index ae758328..00000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "editor.rulers": [80, 120], -} \ No newline at end of file -- cgit v1.2.3 From 8c30522d58e6c006274952a75c5acd4d104c8828 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:12:23 -0700 Subject: added info about tuples, integrated wild card use into a function definition --- haskell.html.markdown | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 266cf11b..cad036f1 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -124,6 +124,9 @@ last [1..5] -- 5 fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 +-- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) +snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this + ---------------------------------------------------- -- 3. Functions ---------------------------------------------------- @@ -159,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples: -foo (x, y) = (x + 1, y + 2) +-- Pattern matching on tuples, using wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -203,9 +206,9 @@ foo = (4*) . (10+) foo 5 -- 60 -- fixing precedence --- Haskell has an operator called `$`. This operator applies a function --- to a given parameter. In contrast to standard function application, which --- has highest possible priority of 10 and is left-associative, the `$` operator +-- Haskell has an operator called `$`. This operator applies a function +-- to a given parameter. In contrast to standard function application, which +-- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that -- the expression on its right is applied as the parameter to the function on its left. @@ -223,7 +226,7 @@ even . fib $ 7 -- false -- 5. Type signatures ---------------------------------------------------- --- Haskell has a very strong type system, and every valid expression has a type. +-- Haskell has a very strong type system, and every valid expression has a type. -- Some basic types: 5 :: Integer -- cgit v1.2.3 From 093e6b62a1aae230f965ad8d1ee2ff8a6b128055 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:15:26 -0700 Subject: moved comment on sndOfTriple --- haskell.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index cad036f1..6a48b60c 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -162,8 +162,8 @@ fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- Pattern matching on tuples, using wild card (_) to bypass naming an unused value -sndOfTriple (_, y, _) = y +-- Pattern matching on tuples +sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write -- cgit v1.2.3 From c421b1bd0d18ab57c88665bd14b289e75724cf37 Mon Sep 17 00:00:00 2001 From: Alex Grejuc Date: Tue, 10 Jul 2018 15:34:42 -0700 Subject: trimmed loc over 80 chars --- haskell.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 6a48b60c..e9ddf54d 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -125,7 +125,7 @@ fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 -- pair element accessing does not work on n-tuples (i.e. triple, quadruple, etc) -snd ("snd", "can't touch this", "da na na na") -- error! see function below to get around this +snd ("snd", "can't touch this", "da na na na") -- error! see function below ---------------------------------------------------- -- 3. Functions @@ -163,7 +163,7 @@ fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) -- Pattern matching on tuples -sndOfTriple (_, y, _) = y -- you can use a wild card (_) to bypass naming an unused value +sndOfTriple (_, y, _) = y -- use a wild card (_) to bypass naming unused value -- Pattern matching on lists. Here `x` is the first element -- in the list, and `xs` is the rest of the list. We can write @@ -210,7 +210,7 @@ foo 5 -- 60 -- to a given parameter. In contrast to standard function application, which -- has highest possible priority of 10 and is left-associative, the `$` operator -- has priority of 0 and is right-associative. Such a low priority means that --- the expression on its right is applied as the parameter to the function on its left. +-- the expression on its right is applied as parameter to function on its left. -- before even (fib 7) -- false -- cgit v1.2.3 From 1298dfef8f89092faca9789a6044e835f6b82bd8 Mon Sep 17 00:00:00 2001 From: Ali Mohammad Pur Date: Sat, 14 Jul 2018 19:17:46 +0430 Subject: [Citron/en] Add basic explanations --- citron.html.markdown | 212 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 212 insertions(+) create mode 100644 citron.html.markdown diff --git a/citron.html.markdown b/citron.html.markdown new file mode 100644 index 00000000..bd3c398c --- /dev/null +++ b/citron.html.markdown @@ -0,0 +1,212 @@ +--- +language: citron +filename: learncitron.ctr +contributors: + - ["AnotherTest", ""] +lang: en-us +--- +```ruby +# Comments start with a '#' +# All comments encompass a single line + +########################################### +## 1. Primitive Data types and Operators +########################################### + +# You have numbers +3. # 3 + +# Numbers are all doubles in interpreted mode + +# Mathematical operator precedence is not respected. +# binary 'operators' are evaluated in ltr order +1 + 1. # 2 +8 - 4. # 4 +10 + 2 * 3. # 36 + +# Division is always floating division +35 / 2 # 17.5. + +# Integer division is non-trivial, you may use floor +(35 / 2) floor # 17. + +# Booleans are primitives +True. +False. + +# Boolean messages +True not. # False +False not. # True +1 = 1. # True +1 !=: 1. # False +1 < 10. # True + +# Here, `not` is a unary message to the object `Boolean` +# Messages are comparable to instance method calls +# And they have three different forms: +# 1. Unary messages: Length > 1, and they take no arguments: + False not. +# 2. Binary Messages: Length = 1, and they take a single argument: + False & True. +# 3. Keyword messages: must have at least one ':', they take as many arguments +# as they have `:` s + False either: 1 or: 2. # 2 + +# Strings +'This is a string'. +'There are no character types exposed to the user'. +# "You cannot use double quotes for strings" <- Error + +# Strins can be summed +'Hello, ' + 'World!'. # 'Hello, World!' + +# Strings allow access to their characters +'This is a beautiful string' at: 0. # 'T' + +########################################### +## intermission: Basic Assignment +########################################### + +# You may assign values to the current scope: +var name is value. # assignes `value` into `name` + +# You may also assign values into the current object's namespace +my name is value. # assigns `value` into the current object's `name` property + +# Please note that these names are checked at compile (read parse if in interpreted mode) time +# but you may treat them as dynamic assignments anyway + +########################################### +## 2. Lists(Arrays?) and Tuples +########################################### + +# Arrays are allowed to have multiple types +Array new < 1 ; 2 ; 'string' ; Nil. # Array new < 1 ; 2 ; 'string' ; Nil + +# Tuples act like arrays, but are immutable. +# Any shenanigans degrade them to arrays, however +[1, 2, 'string']. # [1, 2, 'string'] + +# They can interoperate with arrays +[1, 'string'] + (Array new < 'wat'). # Array new < 1 ; 'string' ; 'wat' + +# Indexing into them +[1, 2, 3] at: 1. # 2 + +# Some array operations +var arr is Array new < 1 ; 2 ; 3. + +arr head. # 1 +arr tail. # Array new < 2 ; 3. +arr init. # Array new < 1 ; 2. +arr last. # 3 +arr push: 4. # Array new < 1 ; 2 ; 3 ; 4. +arr pop. # 4 +arr pop: 1. # 2, `arr` is rebound to Array new < 1 ; 3. + +# List comprehensions +[x * 2 + y,, arr, arr + [4, 5],, x > 1]. # Array ← 7 ; 9 ; 10 ; 11 +# fresh variable names are bound as they are encountered, +# so `x` is bound to the values in `arr` +# and `y` is bound to the values in `arr + [4, 5]` +# +# The general format is: [expr,, bindings*,, predicates*] + + +#################################### +## 3. Functions +#################################### + +# A simple function that takes two variables +var add is {:a:b ^a + b.}. + +# this function will resolve all its names except the formal arguments +# in the context it is called in. + +# Using the function +add applyTo: 3 and: 5. # 8 +add applyAll: [3, 5]. # 8 + +# Also a (customizable -- more on this later) pseudo-operator allows for a shorthand +# of function calls +# By default it is REF[args] + +add[3, 5]. # 8 + +# To customize this behaviour, you may simply use a compiler pragma: +#:callShorthand () + +# And then you may use the specified operator. +# Note that the allowed 'operator' can only be made of any of these: []{}() +# And you may mix-and-match (why would anyone do that?) + +add(3, 5). # 8 + +# You may also use functions as operators in the following way: + +3 `add` 5. # 8 +# This call binds as such: add[(3), 5] +# because the default fixity is left, and the default precedance is 1 + +# You may change the precedence/fixity of this operator with a pragma +#:declare infixr 1 add + +3 `add` 5. # 8 +# now this binds as such: add[3, (5)]. + +# There is another form of functions too +# So far, the functions were resolved in a dynamic fashion +# But a lexically scoped block is also possible +var sillyAdd is {\:x:y add[x,y].}. + +# In these blocks, you are not allowed to declare new variables +# Except with the use of Object::'letEqual:in:` +# And the last expression is implicitly returned. + +# You may also use a shorthand for lambda expressions +var mul is \:x:y x * y. + +# These capture the named bindings that are not present in their +# formal parameters, and retain them. (by ref) + +########################################### +## 5. Control Flow +########################################### + +# inline conditional-expressions +var citron is 1 = 1 either: 'awesome' or: 'awful'. # citron is 'awesome' + +# multiple lines is fine too +var citron is 1 = 1 + either: 'awesome' + or: 'awful'. + +# looping +10 times: {:x + Pen writeln: x. +}. # 10. -- side effect: 10 lines in stdout, with numbers 0 through 9 in them + +# Citron properly supports tail-call recursion in lexically scoped blocks +# So use those to your heart's desire + +# mapping most data structures is as simple as `fmap:` +[1, 2, 3, 4] fmap: \:x x + 1. # [2, 3, 4, 5] + +# You can use `foldl:accumulator:` to fold a list/tuple +[1, 2, 3, 4] foldl: (\:acc:x acc * 2 + x) accumulator: 4. # 90 + +# That expression is the same as +(2 * (2 * (2 * (2 * 4 + 1) + 2) + 3) + 4) + +################################### +## 6. IO +################################### + +# IO is quite simple +# With `Pen` being used for console output +# and Program::'input' and Program::'waitForInput' being used for console input + +Pen writeln: 'Hello, ocean!' # prints 'Hello, ocean!\n' to the terminal + +Pen writeln: Program waitForInput. # reads a line and prints it back +``` -- cgit v1.2.3 From 3ab2e88b4af9d072fbd2e0e2b9c0fe849d46892b Mon Sep 17 00:00:00 2001 From: YAN HUI HANG Date: Sun, 15 Jul 2018 15:33:01 +0800 Subject: SKI, SK and Iota --- lambda-calculus.html.markdown | 95 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 94 insertions(+), 1 deletion(-) diff --git a/lambda-calculus.html.markdown b/lambda-calculus.html.markdown index 6103c015..72ed78ba 100644 --- a/lambda-calculus.html.markdown +++ b/lambda-calculus.html.markdown @@ -3,6 +3,7 @@ category: Algorithms & Data Structures name: Lambda Calculus contributors: - ["Max Sun", "http://github.com/maxsun"] + - ["Yan Hui Hang", "http://github.com/yanhh0"] --- # Lambda Calculus @@ -114,8 +115,100 @@ Using successor, we can define add: **Challenge:** try defining your own multiplication function! +## Get even smaller: SKI, SK and Iota + +### SKI Combinator Calculus + +Let S, K, I be the following functions: + +`I x = x` + +`K x y = x` + +`S x y z = x z (y z)` + +We can convert an expression in the lambda calculus to an expression +in the SKI combinator calculus: + +1. `λx.x = I` +2. `λx.c = Kc` +3. `λx.(y z) = S (λx.y) (λx.z)` + +Take the church number 2 for example: + +`2 = λf.λx.f(f x)` + +For the inner part `λx.f(f x)`: +``` + λx.f(f x) += S (λx.f) (λx.(f x)) (case 3) += S (K f) (S (λx.f) (λx.x)) (case 2, 3) += S (K f) (S (K f) I) (case 2, 1) +``` + +So: +``` + 2 += λf.λx.f(f x) += λf.(S (K f) (S (K f) I)) += λf.((S (K f)) (S (K f) I)) += S (λf.(S (K f))) (λf.(S (K f) I)) (case 3) +``` + +For the first argument `λf.(S (K f))`: +``` + λf.(S (K f)) += S (λf.S) (λf.(K f)) (case 3) += S (K S) (S (λf.K) (λf.f)) (case 2, 3) += S (K S) (S (K K) I) (case 2, 3) +``` + +For the second argument `λf.(S (K f) I)`: +``` + λf.(S (K f) I) += λf.((S (K f)) I) += S (λf.(S (K f))) (λf.I) (case 3) += S (S (λf.S) (λf.(K f))) (K I) (case 2, 3) += S (S (K S) (S (λf.K) (λf.f))) (K I) (case 1, 3) += S (S (K S) (S (K K) I)) (K I) (case 1, 2) +``` + +Merging them up: +``` + 2 += S (λf.(S (K f))) (λf.(S (K f) I)) += S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I)) +``` + +Expanding this, we would end up with the same expression for the +church number 2 again. + +### SK Combinator Calculus + +The SKI combinator calculus can still be reduced further. We can +remove the I combinator by noting that `I = SKK`. We can substitute +all `I`'s with `SKK`. + +### Iota Combinator + +The SK combinator calculus is still not minimal. Defining: + +``` +ι = λf.((f S) K) +``` + +We have: + +``` +I = ιι +K = ι(ιI) = ι(ι(ιι)) +S = ι(K) = ι(ι(ι(ιι))) +``` + ## For more advanced reading: 1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) 2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) -3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) \ No newline at end of file +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) +5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) -- cgit v1.2.3 From f6300aad29005e9b5f95bf63fdfbfbb8cc3dca7d Mon Sep 17 00:00:00 2001 From: Vitalie Lazu Date: Fri, 20 Jul 2018 16:22:47 +0300 Subject: Added Romanian translation for Elixir --- ro-ro/elixir-ro.html.markdown | 459 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 459 insertions(+) create mode 100644 ro-ro/elixir-ro.html.markdown diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown new file mode 100644 index 00000000..d8b261af --- /dev/null +++ b/ro-ro/elixir-ro.html.markdown @@ -0,0 +1,459 @@ +--- +language: elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] + - ["Dzianis Dashkevich", "https://github.com/dskecse"] + - ["Ryan Plant", "https://github.com/ryanplant-au"] + - ["Ev Bogdanov", "https://github.com/evbogdanov"] +translators: + - ["Vitalie Lazu", "https://github.com/vitaliel"] + +filename: learnelixir-ro.ex +--- + +Elixir este un limbaj funcțional modern construit pe baza mașinii virtuale Erlang. +E total compatibil cu Erlang, dar are o sintaxă mai prietenoasă și propune mai multe +posibilități. + +```elixir + +# Comentariile de o linie încep cu simbolul diez. + +# Pentru comentarii pe mai multe linii nu există sintaxă separată, +# de aceea folosiți mai multe linii cu comentarii. + +# Pentru a folosi shell-ul elixir utilizați comanda `iex`. +# Compilați modulele cu comanda `elixirc`. + +# Ambele comenzi vor lucra în terminal, dacă ați instalat Elixir corect. + +## --------------------------- +## -- Tipuri de bază +## --------------------------- + +# Numere +3 # număr întreg +0x1F # număr întreg +3.0 # număr cu virgulă mobilă + +# Atomii, sunt constante nenumerice. Ei încep cu `:`. +:salut # atom + +# Tuplele sunt păstrate în memorie consecutiv. +{1,2,3} # tuple + +# Putem accesa elementul tuplelui folosind funcția `elem`: +elem({1, 2, 3}, 0) #=> 1 + +# Listele sunt implementate ca liste înlănțuite. +[1,2,3] # listă + +# Fiecare listă ne vidă are cap (primul element al listei) +# și coadă (restul elementelor). +# Putem accesa capul și coada listei cum urmează: +[cap | coadă] = [1,2,3] +cap #=> 1 +coadă #=> [2, 3] + +# În Elixir, ca și în Erlang, simbolul `=` denotă potrivirea șabloanelor și +# nu atribuire. +# +# Aceasta înseamnă că expresia din stînga (șablonul) se potrivește cu +# expresia din dreaptă. +# +# În modul acesta exemplul de mai sus lucrează accesînd capul și coada unei liste. + +# Potrivirea șablonului va da eroare cînd expresiile din stînga și dreapta nu se +# potrivesc, în exemplu acesta tuplele au lungime diferită. +{a, b, c} = {1, 2} #=> ** (MatchError) + +# Există și date binare +<<1,2,3>> + +# Sunt două tipuri de șiruri de caractere +"salut" # șir de caractere Elixir +'salut' # listă de caractere Erlang + +# Șir de caractere pe mai multe linii +""" +Sunt un șir de caractere +pe mai multe linii. +""" +#=> "Sunt un șir de caractere\npe mai multe linii..\n" + +# Șirurile de caractere sunt codificate în UTF-8: +"Bună dimineața" #=> "Bună dimineața" + +# Șirurile de caractere sunt date binare, listele de caractere doar liste. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# `?a` în Elixir întoarce codul ASCII pentru litera `a` +?a #=> 97 + +# Pentru a concatena listele folosiți `++`, pentru date binare - `<>` +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'Salut ' ++ 'lume' #=> 'Salut lume' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"Salut " <> "lume" #=> "Salut lume" + +# Diapazoanele sunt reprezentate ca `început..sfîrșit` (inclusiv) +1..10 #=> 1..10 +început..sfîrșit = 1..10 # Putem folosi potrivirea șabloanelor cu diapazoane de asemenea +[început, sfîrșit] #=> [1, 10] + +# Dicţionarele stochează chei şi o valoare pentru fiecare cheie +genuri = %{"Ion" => "bărbat", "Maria" => "femeie"} +genuri["Ion"] #=> "bărbat" + +# Dicționare cu chei de tip atom au sintaxă specială +genuri = %{ion: "bărbat", maria: "femeie"} +genuri.ion #=> "bărbat" + +## --------------------------- +## -- Operatori +## --------------------------- + +# Operații matematice +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# În Elixir operatorul `/` întotdeauna întoarce un număr cu virgulă mobilă. + +# Folosiți `div` pentru împărțirea numerelor întregi +div(10, 2) #=> 5 + +# Pentru a obține restul de la împărțire utilizați `rem` +rem(10, 3) #=> 1 + +# Există și operatori booleni: `or`, `and` and `not`. +# Acești operatori așteaptă ca primul argument o expresie booleană. +true and true #=> true +false or true #=> true +1 and true #=> ** (BadBooleanError) + +# Elixir de asemenea oferă `||`, `&&` și `!` care acceptă argumente de orice tip. +# Toate valorile în afară de `false` și `nil` se vor evalua ca `true`. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil +!true #=> false + +# Operatori de comparație: `==`, `!=`, `===`, `!==`, `<=`, `>=`, `<` și `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# `===` și `!==` au strictețe mai mare cînd comparăm numere întregi și reale: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Putem compara de asemenea și date de diferite tipuri: +1 < :salut #=> true + +# La compararea diferitor tipuri folosiți următoare prioritate: +# număr < atom < referință < funcție < port < proces < tuple < listă < șir de caractere + +# Cităm pe Joe Armstrong în acest caz: "Ordinea actuală nu e importantă, +dar că ordinea totală este bine definită este important." + +## --------------------------- +## -- Ordinea execuției +## --------------------------- + +# expresia `if` +if false do + "Aceasta nu veți vedea niciodată" +else + "Aceasta veți vedea" +end + +# expresia opusă `unless` +unless true do + "Aceasta nu veți vedea niciodată" +else + "Aceasta veți vedea" +end + +# Țineți minte potrivirea șabloanelor? Multe structuri în Elixir se bazează pe ea. + +# `case` ne permite să comparăm o valoare cu multe șabloane: +case {:unu, :doi} do + {:patru, :cinci} -> + "Aceasta nu se potrivește" + {:unu, x} -> + "Aceasta se potrivește și atribuie lui `x` `:doi` în acest bloc" + _ -> + "Aceasta se va potrivi cu orice valoare" +end + +# Simbolul `_` se numește variabila anonimă. +# Folosiți-l pentru valori ce nu vă interesează. +# De exemplu, dacă doar capul listei ne intereseaza: +[cap | _] = [1,2,3] +cap #=> 1 + +# Pentru o citire mai bună putem scri: +[cap | _coadă] = [:a, :b, :c] +cap #=> :a + +# `cond` ne permite să verificăm multe condiții de odată. +# Folosiți `cond` în schimbul la multe expresii `if`. +cond do + 1 + 1 == 3 -> + "Aceasta nu veți vedea niciodată" + 2 * 5 == 12 -> + "Pe mine la fel" + 1 + 2 == 3 -> + "Aceasta veți vedea" +end + +# Este obușnuit de setat ultima condiție cu `true`, care se va potrivi întotdeauna. +cond do + 1 + 1 == 3 -> + "Aceasta nu veți vedea niciodată" + 2 * 5 == 12 -> + "Pe mine la fel" + true -> + "Aceasta veți vedea (este else în esență)" +end + +# Blocul `try/catch` se foloște pentru prelucrarea excepțiilor. +# Elixir suportă blocul `after` care se execută în orice caz. +try do + throw(:salut) +catch + mesaj -> "Am primit #{mesaj}." +after + IO.puts("Sunt în blocul after.") +end +#=> Sunt în blocul after. +# "Am primit salut" + +## --------------------------- +## -- Module și Funcții +## --------------------------- + +# Funcții anonime (atenție la punct la apelarea funcției) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Ele de asemenea aceptă multe clauze și expresii de gardă. +# Expresiile de gardă vă permit să acordați potrivirea șabloanelor, +# ele sunt indicate după cuvîntul cheie `when`: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir de asemenea oferă multe funcții incorporate. +# Ele sunt accesibile în scopul curent. +is_number(10) #=> true +is_list("salut") #=> false +elem({1,2,3}, 0) #=> 1 + +# Puteți grupa cîteva funcții într-un modul. În interiorul modulului folosiți `def` +# pentru a defini funcțiile necesare. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Pentru a compila modulul nostru simplu Math îl salvăm ca `math.ex` și utilizăm `elixirc`. +# în terminal: elixirc math.ex + +# În interiorul modulului putem defini funcții cu `def` și funcții private cu `defp`. +defmodule PrivateMath do + # O funcție definită cu `def` este accesibilă pentru apelare din alte module, + def sum(a, b) do + do_sum(a, b) + end + + # O funcție privată poate fi apelată doar local. + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Declarația funcției de asemenea suportă expresii de gardă și multe clauze: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +Geometry.area({:circle, "not_a_number"}) #=> ** (FunctionClauseError) + +# Din cauza variabilelor imutabile, un rol important îl ocupă funcțiile recursive +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Modulele în Elixir suportă atribute, există atribute incorporate și +# puteți adăuga altele. +defmodule MyMod do + @moduledoc """ + Este un atribut incorporat + """ + + @my_data 100 # Acesta e atributul nostru + IO.inspect(@my_data) #=> 100 +end + +# Operatorul |> permite transferarea rezultatului unei expresii din stînga +# ca primul argument al unei funcții din dreapta. +Range.new(1,10) +|> Enum.map(fn x -> x * x end) +|> Enum.filter(fn x -> rem(x, 2) == 0 end) +#=> [4, 16, 36, 64, 100] + +## --------------------------- +## -- Structuri și Excepții +## --------------------------- + +# Structurile sunt extensii a dicționarelor ce au valori implicite, +# verificări în timpul compilării și polimorfism +defmodule Person do + defstruct name: nil, age: 0, height: 0 +end + +joe_info = %Person{ name: "Joe", age: 30, height: 180 } +#=> %Person{age: 30, height: 180, name: "Joe"} + +# Acesarea cîmpului din structură +joe_info.name #=> "Joe" + +# Actualizarea valorii cîmpului +older_joe_info = %{ joe_info | age: 31 } +#=> %Person{age: 31, height: 180, name: "Joe"} + +# Blocul `try` cu cuvîntul cheie `rescue` e folosit pentru a prinde excepții +try do + raise "o eroare" +rescue + RuntimeError -> "a fost prinsă o eroare runtime" + _error -> "aici vor fi prinse toate erorile" +end +#=> "a fost prinsă o eroare runtime" + +# Toate excepțiile au un mesaj +try do + raise "o eroare" +rescue + x in [RuntimeError] -> + x.message +end +#=> "o eroare" + +## --------------------------- +## -- Concurența +## --------------------------- + +# Concurența în Elixir se bazează pe modelul actor. Pentru a scrie programe +# concurente avem nevoie de trei lucruri: +# 1. Crearea proceselor +# 2. Trimiterea mesajelor +# 3. Primirea mesajelor + +# Un nou proces se crează folosind funcția `spawn`, care primește o funcție +# ca argument. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# `spawn` întoarce identificatorul procesului pid, îl puteți folosi pentru +# a trimite mesaje procesului. Mesajele se transmit folosind operatorul `send`. +# Pentru primirea mesajelor se folosește mecanismul `receive`: + +# Blocul `receive do` este folosit pentru așteptarea mesajelor și prelucrarea lor +# cînd au fost primite. Blocul `receive do` va procesa doar un singur mesaj primit. +# Pentru a procesa mai multe mesaje, funcția cu blocul `receive do` trebuie +# recursiv să se auto apeleze. + +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Aria = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Aria = #{3.14 * r * r}") + area_loop() + end + end +end + +# Compilați modulul și creați un proces +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> +# Un alt mod +pid = spawn(Geometry, :area_loop, []) + +# Trimiteți un mesaj către `pid` care se va potrivi cu un șablon din blocul `receive` +send pid, {:rectangle, 2, 3} +#=> Aria = 6 +# {:rectangle,2,3} + +send pid, {:circle, 2} +#=> Aria = 12.56000000000000049738 +# {:circle,2} + +# Interpretatorul este de asemenea un proces, puteți folosi `self` +# pentru a primi identificatorul de proces: +self() #=> #PID<0.27.0> + +## --------------------------- +## -- Agenții +## --------------------------- + +# Un agent este un proces care urmărește careva valori ce se schimbă. + +# Creați un agent cu `Agent.start_link`, transmițînd o funcție. +# Stare inițială a agentului va fi rezultatul funcției. +{ok, my_agent} = Agent.start_link(fn -> ["roșu", "verde"] end) + +# `Agent.get` primește numele agentului și o `fn` care primește starea curentă +# Orice va întoarce `fn` este ceea ce veți primi înapoi: +Agent.get(my_agent, fn colors -> colors end) #=> ["roșu", "verde"] + +# Actualizați starea agentului în acelaș mod: +Agent.update(my_agent, fn colors -> ["albastru" | colors] end) +``` + +## Link-uri utile + +* [Primii pași](http://elixir-lang.org/getting-started/introduction.html) de pe [situl Elixir](http://elixir-lang.org) +* [Documentația oficială Elixir](http://elixir-lang.org/docs/master/) +* [Un mic conspect pe Elixir](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf) +* [Cartea "Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) de Dave Thomas +* [Cartea "Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) de Fred Hebert +* [Cartea "Programming Erlang: Software for a Concurrent World"](https://pragprog.com/book/jaerlang2/programming-erlang) de Joe Armstrong -- cgit v1.2.3 From 81f9f0fec80b3c459937dd59be8384433251e3f8 Mon Sep 17 00:00:00 2001 From: Stanley Lim Date: Fri, 20 Jul 2018 10:39:43 -0400 Subject: feat(mips.html.markdown): Added examples for branching and conditionals --- mips.html.markdown | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-) diff --git a/mips.html.markdown b/mips.html.markdown index dd7bc7b5..418761bf 100644 --- a/mips.html.markdown +++ b/mips.html.markdown @@ -134,4 +134,68 @@ hello_world .asciiz "Hello World\n" # Declare a null terminated string xori $t0, $t1, 0xFFF # Bitwise XOR with immediate nor $t0, $t1, $t2 # Bitwise NOR -``` \ No newline at end of file +## BRANCHING ## + _branching: + # The basic format of these branching instructions typically follow + #