Лекция 11. Тестирование.Roman BrovkoЗачем тестировать? Тестирование в интерпретаторе и доктесты. Модуль unittest. Пакет py.test - на порядок лучше. Тестирование свойств и пакет hypothesis.
Лекция #5. Введение в язык программирования Python 3Яковенко КириллWeb-программирование
Лекция #5. Введение в язык программирования Python 3
Цикл лекций читается в Омском государственном университете им. Ф.М.Достоевского на факультете компьютерных наук.
Лектор: Яковенко Кирилл Сергеевич.
Лекция 2. Всё, что вы хотели знать о функциях в Python.Roman BrovkoСинтаксис объявления функций. Упаковка и распаковка аргументов. Ключевые аргументы и аргументы по умолчанию. Распаковка и оператор присваивания. Области видимости, правило LEGB, операторы global и nonlocal. Функциональное программирование, анонимные функции. Функции map, filter и zip. Генераторы списков, множеств и словарей. Немного о PEP 8.
Лекция 12. Быстрее, Python, ещё быстрее.Roman BrovkoИзмерение времени работы кода на Python с помощью модулей timeit, cProfile и line_profiler. Немного о NumPy. JIT и AOT компиляция кода на Python на примере Numba и Cython.
Лекция 6. Классы 1.Roman BrovkoСинтаксис объявления классов. Атрибуты, связанные и несвязанные методы, __dict__, __slots__. Статические методы и методы класса. Свойства, декоратор @property. Наследование, перегрузка методов и функция super. Декораторы классов. Магические методы.
Лекция 13. Многопоточность и GILRoman BrovkoМодули threading, queue и concurrent.futures. Использование потоков для параллельных вычислений на Python. GIL. Параллельность и конкурентность. Модуль asyncio. Модуль multiprocessing.
Vert.X mini-talkNorman RichardsVert.x is an asynchronous application platform that runs on the JVM and supports multiple programming languages. It uses an event-driven, non-blocking model where event handlers are used to avoid blocking threads. Verticles are deployed units that isolate classloading and contain event loops with event handlers. The event bus allows asynchronous messaging between verticles on the same or different machines. Worker verticles can be used to handle blocking operations so as not to block the event loop.
The Logical Burrito - pattern matching, term rewriting and unificationNorman RichardsThe document summarizes key concepts related to unification, including pattern matching, term rewriting, and unification. It provides examples of these concepts in languages like ML, Mathematica, Prolog, and Clojure. Unification allows terms to be matched and variables substituted so that terms become identical. Pattern matching is used for conditional dispatch. Term rewriting uses rule-based substitutions to reduce terms. Prolog demonstrates how unification works for logic programming.
Lisp 1.5 - Running historyNorman RichardsThis is a talk from the March 2015 Austin Clojure Meetup in which I explored LISP 1.5 and showed how to run the original LISP 1.5 in an IBM 7094 simulator.
Deconstructing the Functional Web with ClojureNorman RichardsProgramming for the web in Clojure isn't hard, but with layers of abstraction you can easily lose track of what is going on. In this talk, we'll dig deep into Ring, the request/response library that most Clojure web programming is based on. We'll see exactly what a Ring handler is and look at the middleware abstraction in depth. We'll then take this knowledge and deconstruct the Compojure routing framework to understand precisely how your web application responds to request. At the end of the talk you should thoroughly understand everything that happens in the request/response stack and be able to customize your web application stack with confidence.
Updated for Houston Clojure Meetup 2/28/14
core.logic introductionNorman RichardsThis document summarizes core.logic, a relational logic programming library for Clojure. It provides examples of core.logic concepts like unification, conde, fresh, membero, distincto, everyg, lvar, finite domains, and using core.logic to solve logic puzzles like map coloring, rock paper scissors, cryptarithmetic, and sudoku. Core.logic allows defining relations and facts to constrain logic variables and find all solutions that satisfy the goals.
Introduction to Zeder - a production rules toolkit for ClojureMike FogusThis document outlines an agenda for a presentation discussing decomplecting systems using Zeder pods. Some key points include decomposing systems into independent parts focused on data, behavior, and function using Zeder pods which separate reference, change, and sharing policies. Transients are discussed as a way to provide mutable but non-persistent objects for potential performance gains. The document also references the OPS5 rule language and Rete algorithm, noting how Clojure programs sometimes implement rule engines in an ad hoc way.
An Adventure in Serverless ClojureScriptNorman RichardsFor the last few hack days, I've been developing a small clojurescript application using a stack that is fairly new to me: quiescent and figwheel. At the last hack day I finished the application and deployed it as a pure-ClojureScript application with no server-side Clojure code.
I'll demo my application, and talk about some of the things I learned in the process. We'll also live code a ClojureScript web application from scratch and deploy it using Amazon S3 static hosting in a matter of minutes.
Clojure talk at Münster JUGAlex OttClojure is a Lisp-like language created by Rich Hickey that runs on the JVM and .NET. It is a functional programming language with immutable data and special features for concurrent programming. The document outlines Clojure's main features such as being dynamically typed, supporting interactive development, metaprogramming, multimethods, and protocols. It also discusses Clojure's differences from other Lisps, its base data types and data structures, syntax, interoperability with Java, concurrent programming abilities, and provides examples of functions, macros, and multimethods.
Clojure 7-LanguagesPierre de LacazeThese are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
Knowledge ExtractionPierre de LacazeThis paper describes BABAR, a knowledge extraction and representation system, completely implemented in CLOS, that is primarily geared towards organizing and reasoning about knowledge extracted from the Wikipedia Website. The system combines natural language processing techniques, knowledge representation paradigms and machine learning algorithms. BABAR is currently an ongoing independent research project that when sufficiently mature, may provide various commercial opportunities.
BABAR uses natural language processing to parse both page name and page contents. It automatically generates Wikipedia topic taxonomies thus providing a model for organizing the approximately 4,000,000 existing Wikipedia pages. It uses similarity metrics to establish concept relevancy and clustering algorithms to group topics based on semantic relevancy. Novel algorithms are presented that combine approaches from the areas of machine learning and recommender systems. The system also generates a knowledge hypergraph which will ultimately be used in conjunction with an automated reasoner to answer questions about particular topics.
Process modelsPreeti MishraThe document discusses several process models for software development projects, including code and fix, waterfall, incremental/iterative, spiral, rapid application development (RAD), and concurrent development models. Each model has advantages and disadvantages depending on factors like project size, requirements stability, and team expertise. Combinations of models may also be suitable in some cases.
Project lifecycle in IT industrysharansankarasigamaniThe document outlines the typical project lifecycle phases in IT projects: (1) Initiation which defines objectives and requirements; (2) Planning which refines scope and plans the work; (3) Execution which involves most of the work being executed and monitored; (4) Monitoring and controlling which tracks progress and implements corrective actions; (5) Closure which formally ends the project and captures lessons learned. It also discusses communicating with relevant parties during each phase and using different communication channels like upward, downward, and lateral.
ClojureScript AnatomyMike FogusA deep dive into the inner workings of ClojureScript's analysis,
88 compilation, and runtime phases. The talk focused specifically on
89 the way that traditional JavaScript abstractions thwart code-size
90 and efficiency and how ClojureScript avoids such pitfalls. Finally,
91 I told a couple "war stories" about some of the specific challenges
92 met by the Clojure/core team during the development of the compiler
93 and runtime.
Лекция 2. Всё, что вы хотели знать о функциях в Python.Roman BrovkoСинтаксис объявления функций. Упаковка и распаковка аргументов. Ключевые аргументы и аргументы по умолчанию. Распаковка и оператор присваивания. Области видимости, правило LEGB, операторы global и nonlocal. Функциональное программирование, анонимные функции. Функции map, filter и zip. Генераторы списков, множеств и словарей. Немного о PEP 8.
Лекция 12. Быстрее, Python, ещё быстрее.Roman BrovkoИзмерение времени работы кода на Python с помощью модулей timeit, cProfile и line_profiler. Немного о NumPy. JIT и AOT компиляция кода на Python на примере Numba и Cython.
Лекция 6. Классы 1.Roman BrovkoСинтаксис объявления классов. Атрибуты, связанные и несвязанные методы, __dict__, __slots__. Статические методы и методы класса. Свойства, декоратор @property. Наследование, перегрузка методов и функция super. Декораторы классов. Магические методы.
Лекция 13. Многопоточность и GILRoman BrovkoМодули threading, queue и concurrent.futures. Использование потоков для параллельных вычислений на Python. GIL. Параллельность и конкурентность. Модуль asyncio. Модуль multiprocessing.
Vert.X mini-talkNorman RichardsVert.x is an asynchronous application platform that runs on the JVM and supports multiple programming languages. It uses an event-driven, non-blocking model where event handlers are used to avoid blocking threads. Verticles are deployed units that isolate classloading and contain event loops with event handlers. The event bus allows asynchronous messaging between verticles on the same or different machines. Worker verticles can be used to handle blocking operations so as not to block the event loop.
The Logical Burrito - pattern matching, term rewriting and unificationNorman RichardsThe document summarizes key concepts related to unification, including pattern matching, term rewriting, and unification. It provides examples of these concepts in languages like ML, Mathematica, Prolog, and Clojure. Unification allows terms to be matched and variables substituted so that terms become identical. Pattern matching is used for conditional dispatch. Term rewriting uses rule-based substitutions to reduce terms. Prolog demonstrates how unification works for logic programming.
Lisp 1.5 - Running historyNorman RichardsThis is a talk from the March 2015 Austin Clojure Meetup in which I explored LISP 1.5 and showed how to run the original LISP 1.5 in an IBM 7094 simulator.
Deconstructing the Functional Web with ClojureNorman RichardsProgramming for the web in Clojure isn't hard, but with layers of abstraction you can easily lose track of what is going on. In this talk, we'll dig deep into Ring, the request/response library that most Clojure web programming is based on. We'll see exactly what a Ring handler is and look at the middleware abstraction in depth. We'll then take this knowledge and deconstruct the Compojure routing framework to understand precisely how your web application responds to request. At the end of the talk you should thoroughly understand everything that happens in the request/response stack and be able to customize your web application stack with confidence.
Updated for Houston Clojure Meetup 2/28/14
core.logic introductionNorman RichardsThis document summarizes core.logic, a relational logic programming library for Clojure. It provides examples of core.logic concepts like unification, conde, fresh, membero, distincto, everyg, lvar, finite domains, and using core.logic to solve logic puzzles like map coloring, rock paper scissors, cryptarithmetic, and sudoku. Core.logic allows defining relations and facts to constrain logic variables and find all solutions that satisfy the goals.
Introduction to Zeder - a production rules toolkit for ClojureMike FogusThis document outlines an agenda for a presentation discussing decomplecting systems using Zeder pods. Some key points include decomposing systems into independent parts focused on data, behavior, and function using Zeder pods which separate reference, change, and sharing policies. Transients are discussed as a way to provide mutable but non-persistent objects for potential performance gains. The document also references the OPS5 rule language and Rete algorithm, noting how Clojure programs sometimes implement rule engines in an ad hoc way.
An Adventure in Serverless ClojureScriptNorman RichardsFor the last few hack days, I've been developing a small clojurescript application using a stack that is fairly new to me: quiescent and figwheel. At the last hack day I finished the application and deployed it as a pure-ClojureScript application with no server-side Clojure code.
I'll demo my application, and talk about some of the things I learned in the process. We'll also live code a ClojureScript web application from scratch and deploy it using Amazon S3 static hosting in a matter of minutes.
Clojure talk at Münster JUGAlex OttClojure is a Lisp-like language created by Rich Hickey that runs on the JVM and .NET. It is a functional programming language with immutable data and special features for concurrent programming. The document outlines Clojure's main features such as being dynamically typed, supporting interactive development, metaprogramming, multimethods, and protocols. It also discusses Clojure's differences from other Lisps, its base data types and data structures, syntax, interoperability with Java, concurrent programming abilities, and provides examples of functions, macros, and multimethods.
Clojure 7-LanguagesPierre de LacazeThese are my slides from a mini Clojure tutorial presented at the "7 Languages in 7 Months" meetup group. The first part of the presentation faithfully presents material from Bruce Tate book, and the second part covers the more advanced topics of state management and macros
Knowledge ExtractionPierre de LacazeThis paper describes BABAR, a knowledge extraction and representation system, completely implemented in CLOS, that is primarily geared towards organizing and reasoning about knowledge extracted from the Wikipedia Website. The system combines natural language processing techniques, knowledge representation paradigms and machine learning algorithms. BABAR is currently an ongoing independent research project that when sufficiently mature, may provide various commercial opportunities.
BABAR uses natural language processing to parse both page name and page contents. It automatically generates Wikipedia topic taxonomies thus providing a model for organizing the approximately 4,000,000 existing Wikipedia pages. It uses similarity metrics to establish concept relevancy and clustering algorithms to group topics based on semantic relevancy. Novel algorithms are presented that combine approaches from the areas of machine learning and recommender systems. The system also generates a knowledge hypergraph which will ultimately be used in conjunction with an automated reasoner to answer questions about particular topics.
Process modelsPreeti MishraThe document discusses several process models for software development projects, including code and fix, waterfall, incremental/iterative, spiral, rapid application development (RAD), and concurrent development models. Each model has advantages and disadvantages depending on factors like project size, requirements stability, and team expertise. Combinations of models may also be suitable in some cases.
Project lifecycle in IT industrysharansankarasigamaniThe document outlines the typical project lifecycle phases in IT projects: (1) Initiation which defines objectives and requirements; (2) Planning which refines scope and plans the work; (3) Execution which involves most of the work being executed and monitored; (4) Monitoring and controlling which tracks progress and implements corrective actions; (5) Closure which formally ends the project and captures lessons learned. It also discusses communicating with relevant parties during each phase and using different communication channels like upward, downward, and lateral.
ClojureScript AnatomyMike FogusA deep dive into the inner workings of ClojureScript's analysis,
88 compilation, and runtime phases. The talk focused specifically on
89 the way that traditional JavaScript abstractions thwart code-size
90 and efficiency and how ClojureScript avoids such pitfalls. Finally,
91 I told a couple "war stories" about some of the specific challenges
92 met by the Clojure/core team during the development of the compiler
93 and runtime.
Logic programming a ruby perspectiveNorman RichardsRuby plays to many programming paradigms. It's an object-oriented language that can be used in a functional or an imperative/procedural way. But Ruby does not often get used as a logic programming language. In this talk I'll explore logic programming using Ruby. What is it, and is it a tool you want to add to your toolbox? We'll touch on several libraries, we'll primary look at an implementation of minikanren (http://minikanren.org/) for Ruby.
Prolog 7-LanguagesPierre de LacazeThe document summarizes Prolog, a logic programming language. It provides an introduction to Prolog including that it is declarative and based on logic programming. It describes the basic components of Prolog programs including facts and rules. It also covers topics like variables, lists, recursion, and solving problems like merging lists and Sudoku puzzles using Prolog. Advanced topics discussed include structure inspection, meta-logical predicates, cuts, and extra-logical predicates.
A web app in pure ClojureDane SchneiderA chronicle of my attempt to create a real time web app using pure clojure at every layer of the stack, from the client to the styles to the web server
The Lambda Calculus and The JavaScriptNorman RichardsThe document discusses the lambda calculus and its relationship to functional programming and JavaScript. It introduces Alonzo Church as the creator of lambda calculus and its use as the basis for functional programming. It then provides examples of lambda expressions, applications, and combinators to illustrate core concepts in lambda calculus and how it enables Turing completeness.
Расширение библиотеки SlickАрсений ЖижелевScala-библиотека Slick прекрасно зарекомендовала себя как развитый и удобный инструмент работы с базами данных. Поддерживаются и простейшие текстовые SQL-запросы, и строго типизированные join’ы нескольких таблиц. Для построения запросов Slick предоставляет DSL, код на котором выглядит как обработка коллекций. Причем простые подзапросы могут использоваться для конструирования более сложных.
Slick имеет весьма любопытную внутреннюю архитектуру, которая делает возможным не только продвинутое использование, но и расширение библиотеки несколькими способами, о которых и пойдет речь в докладе.
(see also video: https://youtu.be/9n1zzwOGado)
Теория языков программирования некоторые слайды к лекциямSergey StaroletovТеория языков программирования (немного об интерпретаторах, триадах, оптимизации, парсерах и прочее)
Compilers construction some lectures of whole course, it covers some methods on interpreters, optimisations, antlr, dsl (introduction)
Технологии анализа бинарного кода приложений: требования, проблемы, инструментыPositive Development User GroupВыступление Константина Панарина, посвященное анализу бинарного кода, на встрече PDUG Meetup: J'adore hardcore 20 декабря 2016 года.
Универсальный сигнатурный анализ кода на C#, Java, PHPИван КочуркинВ данном докладе затронуты такие темы, как теория и проблемы парсинга, построение и обход абстрактных синтаксических деревьев (AST) и разработка предметно-ориентированного языка (DSL).
Рассматриваются такие проблемы парсинга, как разбор контекстно-зависимых языков, обработка ошибок и др. В качестве примера применения теории приведена грамматика PHP, разработанная для генератора парсеров ANTLR.
Далее рассматриваются структура унифицированного AST, методы его обхода и сопоставления с паттернами.
Завершающей частью презентации является описание DSL, разработанного с целью записи существующих и будущих паттернов. Также приведены примеры некоторых паттернов для лучшей усвояемости материала.
Введение в Clojure (Никита Прокопов)mainstreamlesshttp://bit.ly/2mainstream
Никита Прокопов из AboutEcho.com рассказывает о Clojure, 6 марта 2013
Эта лекция — часть курса «Немейнстримовые технологии разработки», читаемого в Новосибирском Государственном Университете
Введение в автоматику - основные понятия и определения автоматикиpovnyandrey1Автоматика — это область науки и техники, занимающаяся разработкой и применением методов и средств для автоматического управления процессами без непосредственного участия человека. Основные понятия автоматики.
Презентация на тему_ _ПогрузчиПогрузчикики_.pdfsabetovagulmaralПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчикиПогрузчики
Обучение электротехнике с нуля - полное руководствоpovnyandrey1Целью данного доклада является обоснование необходимости и важности обучения электротехнике с нуля для сотрудников, не имеющих профильного образования. Ожидаемые результаты обучения включают в себя: формирование базового понимания принципов работы электротехнических устройств, освоение навыков безопасной работы с электрооборудованием, повышение эффективности выполнения рабочих задач, связанных с эксплуатацией и обслуживанием электротехнических систем, а также снижение рисков аварий и несчастных случаев, вызванных недостаточной квалификацией персонала.
Естественная философия времени 1st Edition Джеральд Джеймс УитроуsegeygeylizЕстественная философия времени 1st Edition Джеральд Джеймс Уитроу
Естественная философия времени 1st Edition Джеральд Джеймс Уитроу
Естественная философия времени 1st Edition Джеральд Джеймс Уитроу
Высоковольтные выключатели в электроэнергетике - полное руководствоpovnyandrey1Высоковольтные выключатели (ВВ) — это коммутационные аппараты, предназначенные для включения, отключения и переключения цепей высокого напряжения (от 1 кВ и выше) в нормальных и аварийных режимах. Они играют ключевую роль в защите электрооборудования от токов короткого замыкания (КЗ) и обеспечивают надежность энергосистем.
Основные функции высоковольтных выключателей
Отключение токов нагрузки (рабочих токов).
Отключение токов короткого замыкания (КЗ) с высокой скоростью.
Автоматическое срабатывание при авариях по сигналу релейной защиты.
Коммутация в нормальных и ремонтных режимах.
Принцип работы
При поступлении сигнала от защиты привод размыкает контакты.
Между контактами возникает дуга.
Дугогасительная система (масло, элегаз, вакуум) охлаждает и деионизирует дугу.
Ток прерывается, цепь отключается.
Высоковольтные выключатели — критически важные элементы энергосистем, обеспечивающие безопасность и стабильность электроснабжения. В современных сетях наиболее распространены элегазовые (SF₆) и вакуумные выключатели благодаря их высокой отключающей способности и долговечности.
Основы электроники для начинающих - базовое руководствоpovnyandrey1Цель: Дать новичкам базовое понимание принципов электроники, познакомить с основными компонентами и простыми схемами, научить безопасной работе с электронными устройствами.
Для кого:
Студенты технических специальностей.
Начинающие радиолюбители и DIY-энтузиасты.
Все, кто хочет разобраться в устройстве электронных гаджетов.
Основы электроники для начинающих - базовое руководствоpovnyandrey1
Clojure: Lisp for the modern world (русская версия)
1. CLOJURE
LISP FOR THE MODERN
WORLD
Alex Ott
alexott@gmail.com, http://alexott.net/
2. О чем пойдет речь?
Что такое Clojure?
Основы языка
Базовый синтаксис
Метапрограммирование
Полиморфизм
Конкурентное программирование
Clojure в реальной жизни
Clojure для веб-разработки
3. Что такое Clojure?
Функциональный (неизменяемые данные, ФВП, …)
Lisp-ообразный
Конкурентное программирование
Многоплатформенный (JVM, .Net, JavaScript, etc.)
Открытый исходный код и либеральная лицензия
Активное сообщество разработчиков
Коммерческое применение
Коммерческая поддержка
4. Почему ФП?
Неизменяемость данных
Отсутствие побочных эффектов
Функции в математическом смысле
Функции – объекты первого порядка
Возможность автоматической параллелизации
кода
Меньше проблем с конкурентным
выполнением кода
5. Почему Lisp?
Простой синтаксис - code as data structures
(Homoiconic)
Метапрограммирование (макросы)
Создание доменно-специфических языков
Генерация кода во время компиляции
Возможность избежать повторений
Генерация и выполнение кода в runtime
Интерактивная разработка
Динамически типизированный
6. Отличия от других Lisp’ов
Немного упрощенный синтаксис -- меньше
скобочек
Неизменяемые данные
Добавлено больше базовых структур данных:
вектора, отображения (maps) и т.п.
Расширяемый reader, но без reader macros
"Ленивые" коллекции
Мета-информация привязанная к данным и
функциям
Case-sensitive names
Исключения вместо условий/рестартов
7. Базовый синтаксис
Код – структуры данных
Выражение – список, первый элемент бывает:
Функция
Макрос
Специальная форма
Примеры:
(def a 1)
(+ 1 2)
(defn func [x] (* x x))
(defmacro when [x & body]
`(if ~x (do ~@body)))
9. Базовые типы данных
Числа (целые, рациональные, вещественные):
42, 1/3, 1N, 4.2, 42.2M
Строки: "String»
Знаки (characters): a, newline, …
Регулярные выражения: #"d+"
Логические значения: true, false
nil – как null в Java
Символ (symbol): name
Keyword: :name, (:name {:name "test"})
10. Коллекции
Разные коллекции:
Списки: (1 2 3 "abc")
Вектора: [1 2 3]
Отображения (maps): {:k1 1234 :k2 "value"}
Множества: #{:val1 "text" 1 2 10}
Persistent & transient коллекции
Вектора, отображения и множества сами являются
функциями:
([1 2 3] 2) => 3
({:a 1 :b 2 :c 3} :b) => 2
11. Persistent collections
Новая копия данных
при изменении
Затрагивается только
измененная часть
Производительность
сравнима с
коллекциями Java
12. Последовательности
Последовательности (sequences):
Коллекции Clojure & Java, массивы, iterable, …
"Ленивые" операции над
последовательностями
Могут быть бесконечными
Один набор операций над
последовательностями: map, reduce, filter, …
13. Управляющие структуры
Определение переменной: (def name value)
Определение функции: (defn name [args…]
body), (fn [args…] body), #(body)
Локальные переменные: (let [name1 value1
name2 value2] body)
Ветвление: if, cond, when, …
Последовательное выполнение: do
Цикл: loop/recur
List comprehension: for
Исключения: try/catch, throw
14. Метапрограммирование и макросы
Макросы – функции, выполняемые во время
компиляции
Макросы получают код и возвращают новый код
Генерация кода:
Стандартные функции работы со списками
Quasi-quote (`) и операторы подстановки: ~ и ~@
Суффикс # для генерации уникальных имен
macroexpand-1 & macroexpand для отладки
Большая часть библиотеки Clojure – макросы
15. Макросы: примеры
Макрос (любой из двух):
(defmacro when [test & body]
(list 'if test (cons 'do body)))
(defmacro when [x & body]
`(if ~x (do ~@body)))
Использование:
(when (pos? a)
(println "positive") (/ b a))
Раскрывается в:
(if (pos? a)
(do (println "positive") (/ b a)))
16. Полиморфизм: мультиметоды
CLOS-подобный полиморфизм
Диспатчеризация в зависимости от любого
условия и количества аргументов
Диспатчеризация выполняется функцией
Диспатчеризация во время выполнения
Возможность построения иерархических
зависимостей между типами
17. Мультиметоды: примеры
Определение:
(defmulti m-example class)
(defmethod m-example String [this]
(println "This is string '" this "'"))
(defmethod m-example java.util.Collection [this]
(print "This is collection!"))
Использование:
(m-example "Hello") => "This is string 'Hello'"
(m-example [1 2 3]) => "This is collection!"
(m-example '(1 2 3)) => "This is collection!”
19. Полиморфизм: протоколы
Способ решения expression problem
Диспатчеризация только по типу данных
Быстрее чем мультиметоды
defprotocol: определяет протокол
deftype: новые типы данных (низкоуровневый)
defrecord: новые типы данных (только данные)
Можно реализовать протокол для произвольных
классов или интерфейсов (extend-protocol &
extend-type)
21. Concurrency: пространство и время
Clojure разделяет
концепции состояния Code Code Code
(state) и имени (past) (present) (future)
(identity)
Состояние (значение) Identity
(ref/agent/atom
name)
не изменяется!
Identity просто
указывает на новое State S1
[1 2 3 4]
State S2
[1 2 3 4 5 6 7]
State S3
[?????]
состояние
22. Конкурентное программирование
Средства для изменяемых данных:
Ссылки (refs): синхронное, координированное
изменение (STM)
Агенты: асинхронное, некоординированное
изменение
Атомы: синхронное, некоординированное
изменение
Vars: thread-local изменение
@ или deref для доступа к данным
Валидаторы и функции-наблюдатели
23. Конкурентное программирование
Параллельное выполнение кода:
future
pmap, pvalues, pcalls
потоки JVM
Синхронизация: promise
Отложенное выполнение кода: delay
Конкурентные примитивы из JVM
25. Взаимодействие с платформой
Взаимодействие с платформой:
Создание объектов: (Class.) или (new Class)
Вызов методов или доступ к членам классов:
`.’, `..’ или doto
Генерация классов и интерфейсов
Вызов Clojure кода из Java, и т.п.
Примитивы для работы с массивами
Генерация и перехват исключений
27. IDE & средства сборки кода
Поддержка в IDE/редакторах:
Eclipse (Counterclocwise)
Netbeans (Enclojure)
IntelliJ IDEA (La Clojure)
Emacs + SLIME или nRepl
VimClojure
Textmate, Sublime Text 2, Jedit
Средства сборки кода:
Поддержка Clojure в Maven, Ant, Cake, Gradle
Leiningen: самый популярный
28. Библиотеки и репозитории
Простой доступ к библиотекам JVM
Библиотеки написанные на Clojure:
Web-разработка: Compojure, Ring, Scriptjure, Noir
RDBMS: ClojureQL, clojure.java.jdbc, Korma
NoSQL: Monger, Clouch, …
Contrib библиотеки: core.*
GUI: Seesaw
Логическое программирование: core.logic
Репозитории: Maven Central, Clojars.org
29. Как все это дело изучать?
Много книг
Интерактивные сайты:
4clojure.com, tryclj.com, himera.herokuapp.com,
…
Множество видео-лекций
Списки рассылки: clojure, clojure-russian, …
Группы пользователей
Конференции в США и Европе
IRC
Clojure/core: поддержка, тренинги, …
30. Webdev: server side
Ring – низкоуровневая основа:
Функции-обработчики
Объекты request/response
Middleware – функции-обертки для обработчика
Более высокоуровневые фреймворки:
Compojure – упрощение разработки с Ring
Noir – микрофреймворк на базе Ring
Hiccup – генерация HTML
Плугины для Leiningen: lein-ring, lein-noir, …
Standalone или war
32. Webdev: ClojureScript
Подмножество Clojure:
Пространства имен
Неизменяемые данные
….
Библиотеки из Clojure & JavaScript
Производительный
Оптимизуется с помощью Google Closure
Может выполняться на Node.js
Отличия от Clojure:
нет ссылок/транзакций, агентов и vars – только атомы
отличия в объявлении пространств имен
нет компиляции и вычисления кода в run-time
нет Java-специфичных вещей, как gen-class, gen-interface, …
33. Webdev: deployment
Поддержка развертывания для:
Google App Engine
Heroku
RedHat's OpenShift
Elastic Beanstalk
Платформо-специфичные библиотеки
Плагины для Leiningen