- PVSM.RU - https://www.pvsm.ru -
Добрый день.
Меня зовут Головач Иван, я практикующий Java Tech Lead с опытом в программировании 10+ лет (Java EE, J2ME, C, C++, M-language, Delphi), который перешел на Scala.
Я подготовил и прочитал как обычные курсы по программированию (Java Core + Junior Java Developer [1]), так и спецкурсы (Multicore Programming for JVM (раз [2] и два [3])).
В данный момент я стартую спецкурс по Scala и в этом топике хочу поделиться материалами, которые я нашел наиболее интересными/информативными (курс готовился более года).
Программа курса [4]
Материалы: «Разное» [5]
Материалы: Object Oriented Programming in Scala [6]
Материалы: Functional Programming in Scala [7]
Материалы: Higher kinded types [8]
Материалы: Parser combinators [9]
Материалы: Metaprogramming / Reflection [10]
Материалы: Metaprogramming / Macroses [11]
Материалы: Scalaz [12]
Материалы: Netty [13]
Материалы: Akka [14]
Материалы: Finagle [15]
Материалы: Zookeeper [16]
Материалы: Использование FP в финансовой отрасли [17]
Спецкурс по Scala ставит своими целями
1. Глубоко изучить язык, включая такие «темные уголки» как macroses, path dependent types, generics of higher kind. Научиться создавать внутренние и внешние DSL. разобраться, почему в финансовой отрасли так популярны функциональные языки программирования.
2. Разобраться, почему при написании кода на функциональных языках программирования (и на Scala в частности) часто используют математические библиотеки обращающиеся к алгебре и теории категорий.
3. Посмотреть, почему современные стартапы (типа Twitter и LinkedIn) зачастую пишут свою инфраструктуру на Scala.
Спецкурс стартует 27 февраля 2015 года и состоит из 16 вебинаров по 2-2.5 часа. Длительность 3 месяца (1-2 занятия в неделю). Все лекции записываются на видео и предоставляются слушателям. Вся необходимая литература предоставляется в электронном виде. Я отвечаю на вопросы как в ходе вебинаров, так и в остальное время. Вы имеете возможность общаться с 15-20 другими слушателями, которые параллельно изучают Scala.
Данные статьи представляют собой краткие обзоры языка (15-20 страниц). Носят скорее идеологический/исторический характер — как сам автор (Одерский) видит свое детище, что он считает самым важным/отличительным/характерным.
Данные статьи освещают и проясняют основные характеристики языка.
Охват материала на небольшую книгу, но не книги. От «классиков».
Да, сама Coursera написана на Scala [32].
На рынке присутствует большое количество книг (порядка 20) по Scala, но мне в наибольшей степени понравились следующие 4
«Functional Programming in Scala» [40] — сильная книга от одного из контрибюторов в Scalaz.
В Scala включен пакет (scala.util.parsing [42]), который предоставляет инструменты для описания грамматики External DSL на Scala в формате близком к EBNF. Т.е. это «внутренний DSL» для создания «внешних DSL».
In Scala, parsers are implemented as monads — hence defining combinators for parsers are just monadic transformations implementing sequencing, alternation or any other composition operations.
В ряде предметных областей можно строить API в виде неких примитивных элементов (в данном случае парсеров) и способов комбинирования этих элементов определенным образом (комбинаторы). В данном случае в самом ядре языка есть все необходимое для построение внешних DSL.
A particularly interesting aspect of macros is that they are based on the same API used also for Scala’s runtime reflection, provided in package scala.reflect.api. This enables the sharing of generic code between macros and implementations that utilize runtime reflection.
Until 2.10, Scala has not had any reflection capabilities of its own. Instead, one could use part of the Java reflection API, namely that dealing with providing the ability to dynamically inspect classes and objects and access their members. However, many Scala-specific elements are unrecoverable under standalone Java reflection, which only exposes Java elements (no functions, no traits) and types (no existential, higher-kinded, path-dependent and abstract types). In addition, Java reflection is also unable to recover runtime type info of Java types that are generic at compile-time; a restriction that carried through to runtime reflection on generic types in Scala.
In Scala 2.10, a new reflection library was introduced not only to address the shortcomings of Java’s runtime reflection on Scala-specific and generic types, but to also add a more powerful toolkit of general reflective capabilities to Scala.… with full-featured runtime reflection for Scala types and generics…
A particularly interesting aspect of macros is that they are based on the same API used also for Scala’s runtime reflection, provided in package scala.reflect.api. This enables the sharing of generic code between macros and implementations that utilize runtime reflection.
Our flavor of macros is reminiscent of Lisp macros, adapted to incorporate type safety and rich syntax. Unlike infamous C/C++ preprocessor macros, Scala macros: 1) are written in full-fledged Scala, 2) work with expression trees, not with raw strings, 3) cannot change syntax of Scala. [here [61]]
Macros are functions that are called by the compiler during compilation. Within these functions the programmer has access to compiler APIs. For example, it is possible to generate, analyze and typecheck code. You can learn more about macros from documentation. [here [61]]
Def macros are shipped as an experimental feature of Scala since version 2.10.0. A subset of def macros, pending a thorough specification, is tentatively scheduled to become stable in one of the future versions of Scala.
Experimental feature — Also note that macros are considered an experimental and advanced feature, so in order to write macros you need to enable them. Do that either with import scala.language.experimental.macros on per-file basis or with -language:experimental.macros (providing a compiler switch) on per-compilation basis. Your users, however, don’t need to enable anything — macros look like normal methods and can be used as normal methods, without any compiler switches or additional configurations.
Netty [78] — an asynchronious and event-driven network application framework for rapid development of maintanable high performance protocol servers and clients. Netty — это de fakto стандарт для использования java.net.*, NIO и NIO.2 (Akka и Finagle используют «под капотом» Netty, Zookeeper напрямую NIO/NIO.2). Хотя можно и напрямую реализовывать шаблоны асинхронной обработки сообщений Reactor [79] / Proactor [80] / Asynchronous Completion Token [81] / Acceptor-Connector [82] однако это сопряжено с большим количеством шаблонного кода и затенению функционала предметной области. Преимуществом Netty является как декларативность кода, так и то, что библиотека представляет собой конструктор протоколов (http, ftp, smtp, websockets, ...).
Akka [91] — de facto стандарт framework-а для многопоточных и распределенных архитектур на основе акторов для JVM. Начиная c версии Scala 2.10.0 Akka вытеснила «родную» реализация акторов [92].
Finagle [107] — A Protocol-Agnostic extensible RPC System for the JVM, used to construct high-concurrency servers. Написанная и используемая в twitter.com. Основной принцип — «We must program locally, communicate globally» [108]. Часть Twitter-стека [109] (вместе с Ostrich, Zipkin, Mesos, Iago, ZooKeeper, Scalding). Finagle включает в себя функции балансировки нагрузки, connection pooling, вызов с timeout-ом, мониторинг, сбор статистики.
Zookeeper [120] — fail-safe централизованный сервис для управления конфигурационной информацией, именованием, распределенной синхронизации и других групповых сервисов, составная часть Twitter-стека [109]. Может быть использован для созданий базовых структур данных (кластерных) — очередей, блокировок, барьеров. Подходит для таких распределенных алгоритмов как two-phase-commit, выборы лидера и других.
По ряду причин (возможность описания предметной области на языке комбинаторов) функциональные языки программирования любят использовать в финансовой отрасли, что создает спрос на «функциональщиков» в Нью-Йорке и Лондоне.
P.S. На любые вопросы с удовольствием ответим по
skype: GolovachCourses
email: GolovachCourses@gmail.com
Автор: IvanGolovach
Источник [137]
Сайт-источник PVSM.RU: https://www.pvsm.ru
Путь до страницы источника: https://www.pvsm.ru/java/83750
Ссылки в тексте:
[1] Java Core + Junior Java Developer: http://habrahabr.ru/company/golovachcourses/blog/215275/
[2] раз: http://habrahabr.ru/company/golovachcourses/blog/217051/
[3] два: http://habrahabr.ru/company/golovachcourses/blog/231755/
[4] Программа курса: http://habrahabr.ru/company/golovachcourses/blog/251239/#0
[5] Материалы: «Разное»: http://habrahabr.ru/company/golovachcourses/blog/251239/#1_1
[6] Материалы: Object Oriented Programming in Scala: http://habrahabr.ru/company/golovachcourses/blog/251239/#1_2
[7] Материалы: Functional Programming in Scala: http://habrahabr.ru/company/golovachcourses/blog/251239/#1_3
[8] Материалы: Higher kinded types: http://habrahabr.ru/company/golovachcourses/blog/251239/#2_2
[9] Материалы: Parser combinators: http://habrahabr.ru/company/golovachcourses/blog/251239/#2_3
[10] Материалы: Metaprogramming / Reflection: http://habrahabr.ru/company/golovachcourses/blog/251239/#2_4
[11] Материалы: Metaprogramming / Macroses: http://habrahabr.ru/company/golovachcourses/blog/251239/#2_5
[12] Материалы: Scalaz: http://habrahabr.ru/company/golovachcourses/blog/251239/#3_1
[13] Материалы: Netty: http://habrahabr.ru/company/golovachcourses/blog/251239/#4_1
[14] Материалы: Akka: http://habrahabr.ru/company/golovachcourses/blog/251239/#4_2
[15] Материалы: Finagle: http://habrahabr.ru/company/golovachcourses/blog/251239/#4_3
[16] Материалы: Zookeeper: http://habrahabr.ru/company/golovachcourses/blog/251239/#4_4
[17] Материалы: Использование FP в финансовой отрасли: http://habrahabr.ru/company/golovachcourses/blog/251239/#4_5
[18] A Tour of the Scala Programming Language": http://www.scala-lang.org/docu/files/ScalaTour-1.6.pdf
[19] «An Overview of the Scala Programming Language»: http://www.cse.unt.edu/~tarau/teaching/ScalaCourse/ScalaPapers/ScalaOverview.pdf
[20] «A Scala Tutorial for Java programmers»: http://scala-lang.org/docu/files/ScalaTutorial.pdf
[21] PayPal Style Guide: https://github.com/paypal/scala-style-guide
[22] Twitter.com: «Effective Scala»: http://twitter.github.io/effectivescala/
[23] scala-lang.org: Style Guide: http://docs.scala-lang.org/style/
[24] «Scalable Component Abstractions»: http://infoscience.epfl.ch/record/64423/files/ScalableComponent.pdf
[25] «Type classes as objects and implicits»: http://infoscience.epfl.ch/record/150280/files/TypeClasses.pdf
[26] «Matching Objects With Patterns»: http://infoscience.epfl.ch/record/98468/files/MatchingObjectsWithPatterns-TR.pdf
[27] «Learning Scala»: http://www.scala-lang.org/node/1305
[28] «Learning Scala in Small Bites»: http://matt.might.net/articles/learning-scala-in-small-bites/
[29] Twitter.com: Scala School!: https://twitter.github.io/scala_school/
[30] Odersky + Coursera = «Functional Programming Principles in Scala»: https://www.coursera.org/course/progfun
[31] Odersky + Coursera = «Principles of Reactive Programming»: https://www.coursera.org/course/reactive
[32] сама Coursera написана на Scala: https://tech.coursera.org/blog/2014/02/18/why-we-love-scala-at-coursera/
[33] «Programming in Scala. 2ed»: http://www.amazon.com/Programming-Scala-Comprehensive-Step---Step/dp/0981531644/
[34] «Scala for the Impatient»: http://www.amazon.com/Scala-Impatient-Cay-S-Horstmann/dp/0321774094
[35] «Scala in Depth»: http://www.amazon.com/Scala-Depth-Joshua-D-Suereth/dp/1935182706
[36] «DSLs in Action»: http://www.amazon.com/DSLs-Action-Debasish-Ghosh/dp/1935182455/
[37] «Independently Extensible Solutions to the Expression Problem»: http://infoscience.epfl.ch/record/52625/files/IC_TECH_REPORT_200433.pdf
[38] «Scala's Selfless Trait Pattern»: http://www.artima.com/scalazine/articles/selfless_trait_pattern.html
[39] «Scala's Stackable Trait Pattern»: http://www.artima.com/scalazine/articles/stackable_trait_pattern.html
[40] «Functional Programming in Scala»: http://www.amazon.com/Functional-Programming-Scala-Paul-Chiusano/dp/1617290653/
[41] «Fighting Bit Rot with Types»: http://drops.dagstuhl.de/opus/volltexte/2009/2338/pdf/09005.OderskyM.2338.pdf
[42] scala.util.parsing: http://www.scala-lang.org/api/2.10.2/index.html#scala.util.parsing.package
[43] «Parser Combinators in Scala»: http://www.cs.kuleuven.be/publicaties/rapporten/cw/CW491.pdf
[44] «Combinator Parsing, Chapter 31 of Programming in Scala, First Edition»: http://www.artima.com/pins1ed/combinator-parsing.html
[45] «Monadic Parser Combinators»: http://eprints.nottingham.ac.uk/237/1/monparsing.pdf
[46] «How to replace failure by a list of successes: A method for exception handling, backtracking, and pattern matching in lazy functional languages: https://rkrishnan.org/files/wadler-1985.pdf
[47] »Higher-order functions for parsing": http://eprints.nottingham.ac.uk/221/1/parsing.pdf
[48] «Functional parsers»: http://roman-dushkin.narod.ru/files/fp__jeroen_fokker_001.pdf
[49] «Deterministic, Error-Correcting Combinator Parsers»: https://karczmarczuk.users.greyc.fr/TEACH/Doc/det_parsers.pdf
[50] «Parsec: Direct Style Monadic Parser Combinators: For The Real World»: http://dspace.library.uu.nl/bitstream/handle/1874/2535/2001-35.pdf
[51] «Packrat Parsing: Simple, Powerful, Lazy, Linear Time»: http://www.brynosaurus.com/pub/lang/packrat-icfp02.pdf
[52] «Monadic Parsing in Haskell»: http://www.cs.nott.ac.uk/~gmh/pearl.pdf
[53] «Pickler Combinators (functional Pearl)»: http://research.microsoft.com/pubs/64036/picklercombinators.pdf
[54] «Instant Pickles: Generating Object-Oriented Pickler Combinators for Fast and Extensible Serialization»: http://infoscience.epfl.ch/record/187787/files/oopsla-pickling_1.pdf
[55] «Even Higher-Order Functions for Parsing or Why Would Anyone Ever Want To Use a Sixth-Order Function? (functional pearl)»: http://www.westpoint.edu/eecs/SiteAssets/SitePages/Faculty%20Publication%20Documents/Okasaki/jfp98sixth.pdf
[56] «scala-lang.org: Reflection: Overview»: http://docs.scala-lang.org/overviews/reflection/overview.html
[57] «scala-lang.org: Reflection: Environment, Universes, and Mirrors»: http://docs.scala-lang.org/overviews/reflection/environment-universes-mirrors.html
[58] «scala-lang.org: Reflection: Symbols, Trees, and Types»: http://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html
[59] «scala-lang.org: Reflection: Annotations, Names, Scopes, and More»: http://docs.scala-lang.org/overviews/reflection/annotations-names-scopes.html
[60] «scala-lang.org: Reflection: TypeTags and Manifests»: http://docs.scala-lang.org/overviews/reflection/typetags-manifests.html
[61] here: http://scalamacros.org/index.html
[62] «scala-lang.org: Def Macros»: http://docs.scala-lang.org/overviews/macros/overview.html
[63] «scala-lang.org: Quasiquotes»: http://docs.scala-lang.org/overviews/quasiquotes/intro.html
[64] «scala-lang.org: Macro Bundles»: http://docs.scala-lang.org/overviews/macros/bundles.html
[65] «Scala Macros, a Technical Report»: http://infoscience.epfl.ch/record/183862/files/2012-07-09-MetaPaper.pdf
[66] «What Are Macros Good For?»: http://scalamacros.org/paperstalks/2014-02-04-WhatAreMacrosGoodFor.pdf
[67] «Scala Macros: Let Our Powers Combine! On How Rich Syntax and Static Types Work with Metaprogramming»: http://infoscience.epfl.ch/record/186844/files/2013-04-22-LetOurPowersCombine.pdf
[68] «Scala Macros, a Technical Report»: https://github.com/scalamacros/scalamacros.github.com/blob/master/paperstalks/2012-07-09-MetaPaper.pdf
[69] «Quasiquotes for Scala, a Technical Report»: http://infoscience.epfl.ch/record/185242
[70] «Yin-Yang: Concealing the Deep Embedding of DSLs»: http://infoscience.epfl.ch/record/203432/files/p73-jovanovic.pdf
[71] «learning Scalaz»: http://eed3si9n.com/learning-scalaz/
[72] «Scalaz — Resources For Beginners»: http://hacking-scala.org/post/49050104489/scalaz-resources-for-beginners
[73] «Introduction to Category Theory in Scala»: https://hseeberger.wordpress.com/2010/11/25/introduction-to-category-theory-in-scala/
[74] «Applicatives are generalized functors»: https://hseeberger.wordpress.com/2011/01/31/applicatives-are-generalized-functors/
[75] Apocalisp blog: https://apocalisp.wordpress.com/
[76] Higher Order. Philosophy and functional programming.: http://blog.higher-order.com/
[77] «Scalaz: For the Rest of Us»: http://arosien.github.io/scalaz-base-talk-201208/#slide1
[78] Netty: http://netty.io
[79] Reactor: http://www.dre.vanderbilt.edu/~schmidt/PDF/reactor-siemens.pdf
[80] Proactor: http://www.cs.wustl.edu/~schmidt/PDF/proactor.pdf
[81] Asynchronous Completion Token: https://www.dre.vanderbilt.edu/~schmidt/PDF/ACT.pdf
[82] Acceptor-Connector: http://www.cs.wustl.edu/~schmidt/PDF/Acc-Con.pdf
[83] Full code of example: io.netty.example.echo.*: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/echo
[84] Full code of example: io.netty.example.telnet.*: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/telnet
[85] Full code of example: io.netty.example.factorial.*: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/factorial
[86] Full code of example: io.netty.example.http.*: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/http
[87] Full code of example: io.netty.example.socksproxy.*: https://github.com/netty/netty/tree/master/example/src/main/java/io/netty/example/socksproxy
[88] «Netty Best Practices»: http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#1.0
[89] Netty 4 at Twitter: Reduced GC Overhead: https://blog.twitter.com/2013/netty-4-at-twitter-reduced-gc-overhead
[90] Related articles: http://netty.io/wiki/related-articles.html
[91] Akka: http://akka.io
[92] Начиная c версии Scala 2.10.0 Akka вытеснила «родную» реализация акторов: http://docs.scala-lang.org/overviews/core/actors-migration-guide.html
[93] Terminology, Concepts: http://doc.akka.io/docs/akka/2.1.4/general/terminology.html
[94] Actor Systems: http://doc.akka.io/docs/akka/2.1.4/general/actor-systems.html
[95] What is an Actor?: http://doc.akka.io/docs/akka/2.1.4/general/actors.html
[96] Supervision and Monitoring: http://doc.akka.io/docs/akka/2.1.4/general/supervision.html
[97] Actor References, Paths and Addresses: http://doc.akka.io/docs/akka/2.1.4/general/addressing.html
[98] Akka and the Java Memory Model: http://doc.akka.io/docs/akka/2.1.4/general/jmm.html
[99] Message Delivery Guarantees: http://doc.akka.io/docs/akka/2.1.4/general/message-delivery-guarantees.html
[100] Scala API: Actors: http://doc.akka.io/docs/akka/2.1.4/scala/actors.html
[101] Scala API: Typed Actors: http://doc.akka.io/docs/akka/2.1.4/scala/typed-actors.html
[102] Scala API: Event Bus: http://doc.akka.io/docs/akka/2.1.4/scala/event-bus.html
[103] Scala API: Scheduler: http://doc.akka.io/docs/akka/2.1.4/scala/scheduler.html
[104] Scala API: Futures: http://doc.akka.io/docs/akka/2.1.4/scala/futures.html
[105] Scala API: Dataflow Concurrency: http://doc.akka.io/docs/akka/2.1.4/scala/dataflow.html
[106] Scala API: Fault Tolerance: http://doc.akka.io/docs/akka/2.1.4/scala/fault-tolerance.html
[107] Finagle: https://twitter.github.io/finagle/
[108] «We must program locally, communicate globally»: http://monkey.org/~marius/talks/twittersystems/#9
[109] Twitter-стека: http://blog.oskarsson.nu/post/40196324612/the-twitter-stack
[110] Protocols: http://twitter.github.io/finagle/guide/Protocols.html
[111] Futures: http://twitter.github.io/finagle/guide/Futures.html
[112] Services & Filters: http://twitter.github.io/finagle/guide/ServicesAndFilters.html
[113] Servers: http://twitter.github.io/finagle/guide/Servers.html
[114] Clients: http://twitter.github.io/finagle/guide/Clients.html
[115] Names: http://twitter.github.io/finagle/guide/Names.html
[116] Metrics: http://twitter.github.io/finagle/guide/Metrics.html
[117] «Finagle: A Protocol-Agnostic RPC System»: https://blog.twitter.com/2011/finagle-a-protocol-agnostic-rpc-system
[118] «How to build a simple distributed search engine using Scala and Finagle framework»: http://twitter.github.io/scala_school/searchbird.html
[119] «Thrift: Scalable Cross-Language Services Implementation»: http://thrift.apache.org/static/files/thrift-20070401.pdf
[120] Zookeeper: http://zookeeper.apache.org/
[121] «ZooKeeper Programmer's Guide»: http://zookeeper.apache.org/doc/trunk/zookeeperProgrammers.html
[122] «Programming with ZooKeeper — A basic tutorial»: http://zookeeper.apache.org/doc/trunk/zookeeperTutorial.html
[123] «ZooKeeper Internals»: http://zookeeper.apache.org/doc/trunk/zookeeperInternals.html
[124] «ZooKeeper Recipes and Solutions»: http://zookeeper.apache.org/doc/current/recipes.html
[125] «The Chubby lock service for loosely coupled distributed systems»: http://static.usenix.org/events/osdi06/tech/full_papers/burrows/burrows_html/
[126] «Zab: High-performance broadcast for primary-backup systems»: http://www-leland.stanford.edu/class/cs347/reading/zab.pdf
[127] «ZooKeeper: Wait-free Coordination for Internet-scale Systems.»: https://www.usenix.org/legacy/event/usenix10/tech/full_papers/Hunt.pdf
[128] «ZooKeeper — A Reliable, Scalable Distributed Coordination System»: http://highscalability.com/blog/2008/7/15/zookeeper-a-reliable-scalable-distributed-coordination-syste.html
[129] «Composing Contracts: An Adventure in Financial Engineering»: http://www.cs.uu.nl/docs/vakken/ia/stof/compcontracts.pdf
[130] «Commercial Uses: Going functional on exotic trades»: http://www.spinellis.gr/pubs/jrnl/2008-JFP-ExoticTrades/html/FSNB08.pdf
[131] «Scala at EDF Trading. Implementing a Domain-Specific Language for Derivative Pricing with Scala.»: http://vimeo.com/6702641
[132] «Compositional specification of commercial contracts»: http://www.itu.dk/~elsborg/sttt06.pdf
[133] «An Algebraic Specification of a Language for Describing Financial Products»: http://www.st.ewi.tudelft.nl/~arie/papers/risla95/risla95.pdf
[134] «Domain-Specific Languages versus Object-Oriented Frameworks: A Financial Engineering Case Study»: http://www.st.ewi.tudelft.nl/~arie/papers/stja97.pdf
[135] «Adventures in financial and software engineering»: https://falconair.github.io/2015/01/30/composingcontracts.html
[136] «Financial Domain-Specific Language Listing : http://dslfin.org/resources.html
[137] Источник: http://habrahabr.ru/post/251239/
Нажмите здесь для печати.