Модерни езици запрограмира за JVM  JRuby, Groovy, Scala и Clojure.
Що е Java?Програмен езикВиртуална машинаСтандартна библиотека
The beating heart of Java is not the Javaprogramming language - it is the JVM and the    entire infrastructure built aroun...
Езикът JavaСъздаден да замени С++Интегрира някои добри идеи от LispХарактеризира се с консервативен, нопрактичен дизайн
Проблемите на езикът       Java Не е чист обектно-ориентиран език Няма никаква поддръжка за функционален стил на програмир...
Че то алтернативи има         ли? 1996 - Java 1.0 1997 - 40 езика вече имат версия за JVM 2004 - 169 са JVM compatible 201...
Причината?The JVM is rock solid and heart touching atthe same time.Отлична производителност и прекрасенoptimizerОгромна ба...
Не всичко е ток и жица Java (< 7) нямаше поддръжка за динамичен метод dispatching JVM не е оптимизиран за функционален сти...
Двете страни на      СилатаЕзици портнати към JVMЕзици създадени специално за JVM
ПретендентитеJRubyJythonFantomGroovyScalaClojure
Rubyдинамичен език за програмиранекомпактен и елегантен синтаксиссъздаден да направи програмиститещастливиmade in Japan
Преди Ruby
Сега (като Ruby програмист)
Hello, Ruby# Output "I love Ruby"say = "I love Ruby"puts say # Output "I *LOVE* RUBY"say[love] = "*love*"puts say.upcase #...
JRuby - Java & Ruby  sitting in a treeRuby е елегантен език с бавен runtimeJVM е много бърз runtimeJRuby дава възможност н...
Загрявка в jirbjruby-1.6.1 :001 > puts "Hello, JRuby"Hello, JRuby => niljruby-1.6.1 :002 > arr = ["Chuck", "Sarah", "Morga...
Ако прилича на   патица...   class Duck     def walk       puts "The duck walks"     end     def quack       puts "The duc...
Java от Rubyrequire javajava_import java.lang.Systemjava_import java.util.ArrayListjava_import javax.swing.JOptionPaneSyst...
Ruby от Javaimport org.jruby.embed.InvokeFailedException;import org.jruby.embed.ScriptingContainer;public class RubyFromJa...
Стана ми интересно,къде да науча повече?http://batsov.com/articles/2011/05/18/jvm-langs-jruby/
It’s a Groovy kind of        love...
Хвала на Groovy    Groovy is like a super version of Java. It canleverage Javas enterprise capabilities but also has  cool...
def name=World; println "Hello $name!"               class Greet {                 def name                 Greet(who) { n...
Groovy e...динамиченизцяло обектно-ориентиранвдъхновен от Ruby, Python и Smalltalkсъс синтаксис много близък до този наJav...
Ключовите моментиclosuresattributesduck typingаритметика базирана на BigDecimalулеснена работа с XML, SQL, Swing, etc
Groovy & JavaGroovy програмите се компилират до JavabytecodeСъщите низове, същите регулярни изрази и т.н.Същите APIСъщия м...
// old school Java code, but also valid Groovy codeSystem.out.println("Hello, world!");// idiomatic Groovyprintln "Hello, ...
showSize([1, 2, 3])// this is the important partshowSize(null)// a listdef beers = ["Zagorka", "Bolyarka", "Shumensko", "A...
// language support for regular expressionsif ("Hello, Groovy" =~ /w+,sw+/) {    println "It matches"}// range filtering w...
JDBC подобренияimport groovy.sql.Sqlsql = Sql.newInstance("jdbc:mysql://host/db", "username", "password","com.mysql.jdbc.D...
XML                 <books>                     <book>                         <title>Dune</title>                        ...
Buildersimport groovy.xml.*                   <html>                                        <head>def page = new MarkupBui...
Swingimport java.awt.FlowLayoutbuilder = new groovy.swing.SwingBuilder()langs = ["Groovy", "Scala", "Clojure"]gui = builde...
Инструментите на      занаятаgroovy - интерпретаторgroovysh - конзолаgroovyc - компилаторgroovyconsole - графична конзола
Приложения убийци   (killer apps)Grails - модерна платформа за разработкана уеб приложения, вдъхновена от Ruby onRailsGrad...
IDE-та, нещо?IntelliJ IDEA - Bozhidar’s ChoiceEclipseNetBeans
Where do we go now?http://batsov.com/articles/2011/05/06/jvm-langs-groovy/
Ride the eSCALAtorIf I were to pick alanguage to use todayother than Java, it wouldbe Scala...                        Jame...
Отмъщението на статично  типизираните езици Scala е статично типизиран език (като Java) Scala използва type inference меха...
ООП и ФП могат дасъжителстват в мир и любов  Scala е чисто обектно-ориентиран език  Scala включва в себе си много елементи...
Expressivescala> val romanToArabic = Map("I" -> 1, "II" -> 2, "III" -> 3, "IV" -> 4, "V" -> 5)romanToArabic: scala.collect...
Компактен код, без            излишна церемония                  public boolean hasUpperCase(String word) {               ...
Оптимизиран за          Java мързелиclass Person {    private String name;    private int age;    Person(String name, int ...
Актьорско майсторство   import scala.actors.Actor._   case class Add(x: Int, y: Int)   case class Sub(x: Int, y: Int)   va...
Патоците на власт!class Duck {  def quack = println("The duck quacks")  def walk = println("The duck walks")}class Dog {  ...
Pimp my libraryscala> implicit def intarray2sum(x: Array[Int]) = x.reduceLeft(_ + _)intarray2sum: (x: Array[Int])Intscala>...
Малко повече екшънscala> println("Hello, Scala")Hello, Scalascala> val name = "Bozhidar"name: java.lang.String = Bozhidars...
...scala> import java.util.Dateimport java.util.Datescala> var currentDate = new DatecurrentDate: java.util.Date = Wed May...
Closuresscala> var x = 10x: Int = 10scala> val addToX = (y: Int) => x + yaddToX: (Int) => Int = <function1>scala> addToX(2...
Свързани списъциscala> 1 :: 2 :: 3 :: 4 :: 5 :: Nilres3: List[Int] = List(1, 2, 3, 4, 5)scala> val names = List("Neo", "Tr...
...scala> names.filter(_.startsWith("T"))res9: List[java.lang.String] = List(Trinity, Tank)scala> names.exists(_.length ==...
Pattern matchingscala> def testMatching(something: Any) = something match {     |   case 1 => "one"     |   case "two" => ...
Plain recursion    def length(list: List[Any]): Int = list match {      case head :: tail => 1 + length(tail)      case Ni...
Инвентараscala - конзола/интерпретаторscalac - компилаторfsc - fast scala compiler
IDE-татаIntelliJ IDEA - Bozhidar’s ChoiceEclipse - Official Scala IDENetBeans - на тоя етап е бран бостан
УбийцитеPlay! FrameworkLiftSBT (Simple Build Tool)Akka
The full disclosure on       Clojure
“Clojure feels like a general-purpose languagebeamed back from the near future. Its supportfor functional programming and ...
What happens when an unstoppable force meets an      immutable object?Clojure is dynamicClojure is functionalClojure is a ...
Стил public boolean hasUpperCase(String word) {     if (word == null) {         return false;     }     int len = word.len...
Компактностclass Person {    private String name;    private int age;    Person(String name, int age) {        this.name =...
Силата е на ваша         страна(defmacro and  "Evaluates exprs one at a time, from left toright. If a form  returns logica...
;;; Lists;; list creationuser> (list 1 2 3)(1 2 3)                       Сърцето на Clojure;; quoted list creationuser> (d...
;; retrieve the first five items in a listuser> (take 5 a-list)                                                     ...(1 ...
Хешове;;; Mapsuser> (hash-map :Bozhidar :Batsov :Bruce :Wayne :Selina :Kyle){:Selina :Kyle, :Bozhidar :Batsov, :Bruce :Way...
Вектори;;; Vectorsuser> (vector 1 2 3 4)[1 2 3 4]user> [1 2 3 4][1 2 3 4]user> (def a-vector [1 2 3 4 5])#user/a-vectoruse...
Програмиране с refs(def picked-numbers (ref #{})(def secret-num (.nextInt (java.util.Random.) 10))(defn guess-number [n]  ...
Атоми(def picked-numbers (atom #{})(def secret-num (.nextInt (java.util.Random.) 10))(defn guess-number [n]        (print ...
ООП по           Лиспаджийски(defmulti my-add (fn [x y] (and (string? x) (string? y))))(defmethod my-add true [x y]    (st...
Екстремист съм, какво     ми трябва? Обичайните заподозрени   Eclipse   IntelliJ   NetBeans Emacs + SLIME = Bozhidar’s Cho...
Повече инфо, моля!http://batsov.com/articles/2011/05/12/jvm-langs-clojure/
Stay hungry,stay foolish!
FIN
Модерни езици за програмиране за JVM (2011)
Upcoming SlideShare
Loading in …5
×

Модерни езици за програмиране за JVM (2011)

786 views

Published on

Слайдовете от презентацията ми за модерни езици за програмиране за JVM, която представих през декември 2011 в ТУ-София.

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
786
On SlideShare
0
From Embeds
0
Number of Embeds
8
Actions
Shares
0
Downloads
6
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Модерни езици за програмиране за JVM (2011)

  1. 1. Модерни езици запрограмира за JVM JRuby, Groovy, Scala и Clojure.
  2. 2. Що е Java?Програмен езикВиртуална машинаСтандартна библиотека
  3. 3. The beating heart of Java is not the Javaprogramming language - it is the JVM and the entire infrastructure built around it... Maximus Decimus Meridius, Roman General & Java Programmer
  4. 4. Езикът JavaСъздаден да замени С++Интегрира някои добри идеи от LispХарактеризира се с консервативен, нопрактичен дизайн
  5. 5. Проблемите на езикът Java Не е чист обектно-ориентиран език Няма никаква поддръжка за функционален стил на програмиране Не е особено експресивен Развитието му е ограничено от изискванията за обратна съвместимост
  6. 6. Че то алтернативи има ли? 1996 - Java 1.0 1997 - 40 езика вече имат версия за JVM 2004 - 169 са JVM compatible 2011 - приблизително 300 езика се целят в JVM
  7. 7. Причината?The JVM is rock solid and heart touching atthe same time.Отлична производителност и прекрасенoptimizerОгромна база съществуващ Java кодКупища страхотни иструменти
  8. 8. Не всичко е ток и жица Java (< 7) нямаше поддръжка за динамичен метод dispatching JVM не е оптимизиран за функционален стил на програмиране JVM пали относително бавно JVM имплементациите на някои езици (като Python) не са съвсем съвместими с native (C) имплементациите им
  9. 9. Двете страни на СилатаЕзици портнати към JVMЕзици създадени специално за JVM
  10. 10. ПретендентитеJRubyJythonFantomGroovyScalaClojure
  11. 11. Rubyдинамичен език за програмиранекомпактен и елегантен синтаксиссъздаден да направи програмиститещастливиmade in Japan
  12. 12. Преди Ruby
  13. 13. Сега (като Ruby програмист)
  14. 14. Hello, Ruby# Output "I love Ruby"say = "I love Ruby"puts say # Output "I *LOVE* RUBY"say[love] = "*love*"puts say.upcase # Output "I *love* Ruby"# five times5.times { puts say }
  15. 15. JRuby - Java & Ruby sitting in a treeRuby е елегантен език с бавен runtimeJVM е много бърз runtimeJRuby дава възможност на Javaпрограмистите да използват технологиикато RailsJRuby дава възможност на Rubyпрограмистите да ползват Javaбиблиотеки
  16. 16. Загрявка в jirbjruby-1.6.1 :001 > puts "Hello, JRuby"Hello, JRuby => niljruby-1.6.1 :002 > arr = ["Chuck", "Sarah", "Morgan", "Casey"] => ["Chuck", "Sarah", "Morgan", "Casey"]jruby-1.6.1 :003 > arr.length => 4jruby-1.6.1 :004 > arr.size => 4jruby-1.6.1 :005 > arr.size() => 4jruby-1.6.1 :006 > arr.each { |name| puts name }ChuckSarahMorganCasey => ["Chuck", "Sarah", "Morgan", "Casey"]jruby-1.6.1 :007 > arr.each_with_index { |name, index| puts "##{index}:#{name}"}0: Chuck1: Sarah2: Morgan3: Casey => ["Chuck", "Sarah", "Morgan", "Casey"]
  17. 17. Ако прилича на патица... class Duck def walk puts "The duck walks" end def quack puts "The duck quacks" end end class Dog def walk puts "The dog walks" end def quack puts "The dog quacks" end end def test_animal(animal) animal.walk animal.quack end test_animal(Duck.new) test_animal(Dog.new)
  18. 18. Java от Rubyrequire javajava_import java.lang.Systemjava_import java.util.ArrayListjava_import javax.swing.JOptionPaneSystem.out.println("Feel the power of JRuby")## using snake_names for Java method namesputs System.current_time_millis## regular names work as wellputs System.currentTimeMillisarray_list = ArrayList.new## the array list supports some common Ruby idiomsarray_list << 1array_list.add 2array_list << 3puts "List length is ##{array_list.length}"array_list.each { |elem| puts elem }## a glimpse of SwingJOptionPane.show_message_dialog(nil, "This is a message from the future of Ruby!")
  19. 19. Ruby от Javaimport org.jruby.embed.InvokeFailedException;import org.jruby.embed.ScriptingContainer;public class RubyFromJava { public static void main(String[] args) { ScriptingContainer container = newScriptingContainer(); container.runScriptlet("puts Ruby bridgeestablished successfully" ); }}
  20. 20. Стана ми интересно,къде да науча повече?http://batsov.com/articles/2011/05/18/jvm-langs-jruby/
  21. 21. It’s a Groovy kind of love...
  22. 22. Хвала на Groovy Groovy is like a super version of Java. It canleverage Javas enterprise capabilities but also has cool productivity features like closures, builders and dynamic typing. If you are a developer, tester or script guru, you have to love Groovy.
  23. 23. def name=World; println "Hello $name!" class Greet { def name Greet(who) { name = who[0].toUpperCase() + who[1..-1] } def salute() { println "Hello $name!" } } g = new Greet(world) // create object g.salute() // output "Hello World!"import staticorg.apache.commons.lang.WordUtils.*class Greeter extends Greet { Greeter(who) { name = capitalize(who) }}new Greeter(world).salute() groovy -e "println Hello + args[0]" World
  24. 24. Groovy e...динамиченизцяло обектно-ориентиранвдъхновен от Ruby, Python и Smalltalkсъс синтаксис много близък до този наJavaсъздаден да улесни живота на Javaпрограмистите
  25. 25. Ключовите моментиclosuresattributesduck typingаритметика базирана на BigDecimalулеснена работа с XML, SQL, Swing, etc
  26. 26. Groovy & JavaGroovy програмите се компилират до JavabytecodeСъщите низове, същите регулярни изрази и т.н.Същите APIСъщия модел за сигурност, същия нишковмоделСъщите ОО концепции
  27. 27. // old school Java code, but also valid Groovy codeSystem.out.println("Hello, world!");// idiomatic Groovyprintln "Hello, world!"// dynamic variable definitiondef name = "Bozhidar"// GString featuring string interpolationprintln "Hello, $name" // => "Hello, Bozhidar"// statically typed variableString songName = "Coding in the Name of"println "Now playing - $songName"String multiline = """this is a multilinestring. There is not need to embednewline characters in it"""println multiline// method definitiondef greet(name) { println "Hello, $name!"}// method invocationgreet "Bozhidar"greet("Bozhidar")
  28. 28. showSize([1, 2, 3])// this is the important partshowSize(null)// a listdef beers = ["Zagorka", "Bolyarka", "Shumensko", "Ariana"]// list accessprintln "My favourite beer is ${beers[1]}"beers.each { beer -> println beer }// imports can appear anywhere and support the creation ofaliasesimport static java.util.Calendar.getInstance as nowimport java.sql.Date as SDateprintln now()// java.util package is automatically imported in Groovy so thisis java.util.Dateprintln new Date()println new SDate(2011, 5, 5)
  29. 29. // language support for regular expressionsif ("Hello, Groovy" =~ /w+,sw+/) { println "It matches"}// range filtering with higher-order functions(1..10).findAll { n -> n % 2 == 0}.each { n -> println n }// mapdef capitols = [Bulgaria: "Sofia", USA: "Washington", England:"London", France:"Paris"]println capitols["Bulgaria"] // => Sofiaprintln capitols["France"] // => Paris// class definitionclass Person { def name def age Person(name, age) { this.name = name this.age = age } @Override String toString() { return "Name {$name}, age {$age}" }}def me = new Person("Bozhidar", 26)println me
  30. 30. JDBC подобренияimport groovy.sql.Sqlsql = Sql.newInstance("jdbc:mysql://host/db", "username", "password","com.mysql.jdbc.Driver")sql.eachRow("select * from tableName", { println it.id + " -- ${it.firstName} --"} ) Изход от програмата 1 -- Bozhidar -- 2 -- Jim -- 3 -- Jack -- 4 -- Valentine --
  31. 31. XML <books> <book> <title>Dune</title> <author firstname="Frank" lastname="Herbert"/> </book> <book> <title>Dune Messiah</title> <author firstname="Frank" lastname="Herbert"/> </book> <book> <title>Children of Dune</title> <author firstname="Frank" lastname="Herbert"/> </book> <book> <title>A Game of Thrones</title> <author firstname="George" lastname="Martin"/> </book> </books>def books = new XmlSlurper().parse("books.xml")books.book.each { println "Title = ${it.title}, Author: ${it.author.@firstname} ${it.author.@lastname}"}
  32. 32. Buildersimport groovy.xml.* <html> <head>def page = new MarkupBuilder() <title>Hello, Groovy!</page.html { title> head { title Hello, Groovy! } </head> body { <body> div { <div> 3.times { <p>Groovy power!</p> p "Groovy power!" <p>Groovy power!</p> } <p>Groovy power!</p> } </div> } </body>} </html>
  33. 33. Swingimport java.awt.FlowLayoutbuilder = new groovy.swing.SwingBuilder()langs = ["Groovy", "Scala", "Clojure"]gui = builder.frame(size: [290, 100], title: Groovy Swing) { panel(layout: new FlowLayout()) { panel(layout: new FlowLayout()) { for (lang in langs) { radioButton(text: lang) } } button(text: Perform Magic, actionPerformed: { builder.optionPane(message: "Feel the power of Groovy!"). createDialog(null, Message).show() }) button(text: Quit, actionPerformed: {System.exit(0)}) }}gui.show()
  34. 34. Инструментите на занаятаgroovy - интерпретаторgroovysh - конзолаgroovyc - компилаторgroovyconsole - графична конзола
  35. 35. Приложения убийци (killer apps)Grails - модерна платформа за разработкана уеб приложения, вдъхновена от Ruby onRailsGradle - могъщ build tool, създаден данаследи MavenGriffon - модерна платформа заразработка на Swing приложения
  36. 36. IDE-та, нещо?IntelliJ IDEA - Bozhidar’s ChoiceEclipseNetBeans
  37. 37. Where do we go now?http://batsov.com/articles/2011/05/06/jvm-langs-groovy/
  38. 38. Ride the eSCALAtorIf I were to pick alanguage to use todayother than Java, it wouldbe Scala... James Gosling, father of Java
  39. 39. Отмъщението на статично типизираните езици Scala е статично типизиран език (като Java) Scala използва type inference механизъм, който сериозно намалява типовите декларации Кодът написан на Scala е толкова сигурен и бърз, колкото този написан на Java
  40. 40. ООП и ФП могат дасъжителстват в мир и любов Scala е чисто обектно-ориентиран език Scala включва в себе си много елементи от функционалното програмиране higher order functions function objects pattern matching tail recursion
  41. 41. Expressivescala> val romanToArabic = Map("I" -> 1, "II" -> 2, "III" -> 3, "IV" -> 4, "V" -> 5)romanToArabic: scala.collection.immutable.Map[java.lang.String,Int] = Map((II,2),(IV,4), (I,1), (V,5), (III,3))scala> romanToArabic("I")res2: Int = 1scala> romanToArabic("II")res3: Int = 2
  42. 42. Компактен код, без излишна церемония public boolean hasUpperCase(String word) { if (word == null) { return false; Java } int len = word.length(); for (int i = 0; i < len; i++) { if (Character.isUpperCase(word.charAt(i))) { return true; } } return false; } Scaladef hasUppercase(word: String) = if (word != null) word.exists(_.isUpperCase) else false
  43. 43. Оптимизиран за Java мързелиclass Person { private String name; private int age; Person(String name, int age) { this.name = name; this.age = age; } public String getName() { Scala return name; } class Person(var name: String, var age: Int) public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
  44. 44. Актьорско майсторство import scala.actors.Actor._ case class Add(x: Int, y: Int) case class Sub(x: Int, y: Int) val mathService = actor { loop { receive { case Add(x, y) => reply(x + y) case Sub(x, y) => reply(x - y) } } } mathService !? Add(1, 3) // returns 4 mathService !? Sub(5, 2) // returns 3
  45. 45. Патоците на власт!class Duck { def quack = println("The duck quacks") def walk = println("The duck walks")}class Dog { def quack = println("The dog quacks (barks)") def walk = println("The dog walks")}def testDuckTyping(animal: { def quack; def walk }) = { animal.quack animal.walk}scala> testDuckTyping(new Duck)The duck quacksThe duck walksscala> testDuckTyping(new Dog)The dog quacks (barks)The dog walks
  46. 46. Pimp my libraryscala> implicit def intarray2sum(x: Array[Int]) = x.reduceLeft(_ + _)intarray2sum: (x: Array[Int])Intscala> val x = Array(1, 2, 3)x: Array[Int] = Array(1, 2, 3)scala> val y = Array(4, 5, 6)y: Array[Int] = Array(4, 5, 6)scala> val z = x + yz: Int = 21
  47. 47. Малко повече екшънscala> println("Hello, Scala")Hello, Scalascala> val name = "Bozhidar"name: java.lang.String = Bozhidarscala> Predef.println("My name is "+name)My name is Bozhidarscala> var someNumber: Int = 5someNumber: Int = 5scala> var names = Array("Superman", "Batman", "The Flash", "Bozhidar")names: Array[java.lang.String] = Array(Superman, Batman, The Flash,Bozhidar)scala> names.filter(name => name.startsWith("B"))res6: Array[java.lang.String] = Array(Batman, Bozhidar)scala> names.lengthres7: Int = 4scala> name.length()res8: Int = 8
  48. 48. ...scala> import java.util.Dateimport java.util.Datescala> var currentDate = new DatecurrentDate: java.util.Date = Wed May 11 15:03:20 EEST 2011scala> println("Now is " + currentDate)Now is Wed May 11 15:03:20 EEST 2011scala> currentDate.toStringres10: java.lang.String = Wed May 11 15:03:20 EEST 2011scala> currentDate.toString()res11: java.lang.String = Wed May 11 15:03:20 EEST 2011scala> currentDate toStringres12: java.lang.String = Wed May 11 15:03:20 EEST 2011
  49. 49. Closuresscala> var x = 10x: Int = 10scala> val addToX = (y: Int) => x + yaddToX: (Int) => Int = <function1>scala> addToX(2)res0: Int = 12scala> addToX(6)res1: Int = 16scala> x = 5x: Int = 5scala> addToX(10)res2: Int = 15
  50. 50. Свързани списъциscala> 1 :: 2 :: 3 :: 4 :: 5 :: Nilres3: List[Int] = List(1, 2, 3, 4, 5)scala> val names = List("Neo", "Trinity", "Morpheus", "Tank", "Dozer")names: List[java.lang.String] = List(Neo, Trinity, Morpheus, Tank,Dozer)scala> names.lengthres4: Int = 5scala> names.foreach(println)NeoTrinityMorpheusTankDozerscala> names.map(_.toUpperCase)res6: List[java.lang.String] = List(NEO, TRINITY, MORPHEUS, TANK,DOZER)scala> names.forall(_.length > 5)res7: Boolean = falsescala> names.forall(_.length > 2)res8: Boolean = true
  51. 51. ...scala> names.filter(_.startsWith("T"))res9: List[java.lang.String] = List(Trinity, Tank)scala> names.exists(_.length == 3)res10: Boolean = truescala> names.drop(2)res11: List[java.lang.String] = List(Morpheus, Tank, Dozer)scala> names.reverseres12: List[java.lang.String] = List(Dozer, Tank, Morpheus, Trinity, Neo)scala> names.sortBy(_.length)res13: List[java.lang.String] = List(Neo, Tank, Dozer, Trinity, Morpheus)scala> names.sort(_ > _)res14: List[java.lang.String] = List(Trinity, Tank, Neo, Morpheus, Dozer)scala> names.slice(2, 4)res16: List[java.lang.String] = List(Morpheus, Tank)
  52. 52. Pattern matchingscala> def testMatching(something: Any) = something match { | case 1 => "one" | case "two" => 2 | case x: Int => "an integer number" | case x: String => "some string" | case <xmltag>{content}</xmltag> => content | case head :: tail => head | case _ => "something else entirely" | }testMatching: (something: Any)Anyscala> testMatching(1)res18: Any = onescala> testMatching("two")res19: Any = 2scala> testMatching(2)res20: Any = an integer numberscala> testMatching("matrix")res21: Any = some stringscala> testMatching(<xmltag>this is in the tag</xmltag>)res22: Any = this is in the tagscala> testMatching(List(1, 2, 3))res23: Any = 1scala> testMatching(3.9)res24: Any = something else entirely
  53. 53. Plain recursion def length(list: List[Any]): Int = list match { case head :: tail => 1 + length(tail) case Nil => 0 } Tail recursiondef length(list: List[Any]): Int = { def lengthrec(list: List[Any], result: Int): Int =list match { case head :: tail => lengthrec(tail, result + 1) case Nil => result } lengthrec(list, 0)}
  54. 54. Инвентараscala - конзола/интерпретаторscalac - компилаторfsc - fast scala compiler
  55. 55. IDE-татаIntelliJ IDEA - Bozhidar’s ChoiceEclipse - Official Scala IDENetBeans - на тоя етап е бран бостан
  56. 56. УбийцитеPlay! FrameworkLiftSBT (Simple Build Tool)Akka
  57. 57. The full disclosure on Clojure
  58. 58. “Clojure feels like a general-purpose languagebeamed back from the near future. Its supportfor functional programming and software trans-actional memory is well beyond current practiceand is well suited for multicore hardware. At thesame time, Clojure is well grounded in the pastand the present. It brings together Lisp and theJava Virtual Machine. Lisp brings wisdom spanningmost of the history of programming, and Javabrings the robustness, extensive libraries, andtooling of the dominant platform available today.”
  59. 59. What happens when an unstoppable force meets an immutable object?Clojure is dynamicClojure is functionalClojure is a Lisp(1)Clojure is designed for concurrencyClojure is fighting accidental complexity
  60. 60. Стил public boolean hasUpperCase(String word) { if (word == null) { return false; } int len = word.length(); for (int i = 0; i < len; i++) { if (Character.isUpperCase(word.charAt(i))) { return true; } } return false; }(defn has-uppercase? [string] (some #(Character/isUpperCase %) string))
  61. 61. Компактностclass Person { private String name; private int age; Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; (defrecord person [name age]) } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; }}
  62. 62. Силата е на ваша страна(defmacro and "Evaluates exprs one at a time, from left toright. If a form returns logical false (nil or false), and returnsthat value and doesnt evaluate any of the other expressions,otherwise it returns the value of the last expr. (and) returns true." {:added "1.0"} ([] true) ([x] x) ([x & next] `(let [and# ~x] (if and# (and ~@next) and#))))
  63. 63. ;;; Lists;; list creationuser> (list 1 2 3)(1 2 3) Сърцето на Clojure;; quoted list creationuser> (def a-list (1 2 3 4 5 6 7 8 9 10))#user/a-list;; find the size of a listuser> (count a-list)10user> (first a-list)1user> (rest a-list)(2 3 4 5 6 7 8 9 10)user> (last a-list)10;; find the elements of the list matching a predicate(booleanfunction)user> (filter even? a-list)(2 4 6 8 10)user> (filter odd? a-list)(1 3 5 7 9);; map an anonymous(lambda) function to all elements of the listuser> (map #(* % 2) a-list)(2 4 6 8 10 12 14 16 18 20);; add an element to the beginning of the listuser> (cons 0 a-list)(0 1 2 3 4 5 6 7 8 9 10);; cons in a list specific function, conj is a general purpose one and;; works on all collection (but in a different manner)user> (conj a-list 0)(0 1 2 3 4 5 6 7 8 9 10)
  64. 64. ;; retrieve the first five items in a listuser> (take 5 a-list) ...(1 2 3 4 5);; retrieve all but the first five items in a listuser> (drop 5 a-list)(6 7 8 9 10)user> (take-while #(< % 3) a-list)(1 2)user> (drop-while #(> % 3) a-list)(1 2 3 4 5 6 7 8 9 10)user> (drop-while #(< % 3) a-list)(3 4 5 6 7 8 9 10);;; Setsuser> (set (1 2 3 4 5 1 2 3 4))#{1 2 3 4 5}user> (def a-set #{1 2 3 4 5})#user/a-setuser> (contains? a-set 3)trueuser> (contains? a-set 7)falseuser> (conj a-set 5)#{1 2 3 4 5}user> (conj a-set 6)#{1 2 3 4 5 6}user> (disj a-set 1)#{2 3 4 5}user> (get a-set 1)1user> (get a-set 7)nil
  65. 65. Хешове;;; Mapsuser> (hash-map :Bozhidar :Batsov :Bruce :Wayne :Selina :Kyle){:Selina :Kyle, :Bozhidar :Batsov, :Bruce :Wayne}user> (def a-map {:Bozhidar :Batsov, :Bruce :Wayne, :Selina :Kyle})#user/a-mapuser> a-map{:Bozhidar :Batsov, :Bruce :Wayne, :Selina :Kyle}user> (get a-map :Bozhidar):Batsovuser> (contains? a-map :Bozhidar)trueuser> (contains? a-map :Clark)falseuser> (:Bozhidar a-map):Batsovuser> (assoc a-map :Lois :Lane){:Lois :Lane, :Bozhidar :Batsov, :Bruce :Wayne, :Selina :Kyle}user> (keys a-map)(:Bozhidar :Bruce :Selina)user> (vals a-map)(:Batsov :Wayne :Kyle)user> (dissoc a-map :Bruce){:Bozhidar :Batsov, :Selina :Kyle}user> (merge a-map {:Alia :Atreides, :Arya :Stark}){:Arya :Stark, :Alia :Atreides, :Bozhidar :Batsov, :Bruce :Wayne, :Selina :Kyle}
  66. 66. Вектори;;; Vectorsuser> (vector 1 2 3 4)[1 2 3 4]user> [1 2 3 4][1 2 3 4]user> (def a-vector [1 2 3 4 5])#user/a-vectoruser> (count a-vector)5user> (conj a-vector 13)[1 2 3 4 5 13];; random access is a constant time operation invectorsuser> (nth a-vector 3)4user> (pop a-vector)[1 2 3 4]user> (peek a-vector)5
  67. 67. Програмиране с refs(def picked-numbers (ref #{})(def secret-num (.nextInt (java.util.Random.) 10))(defn guess-number [n] (print "Enter a guess between 1 and 10: ") (flush) (let [guess (java.lang.Integer/parseInt (read-line)) ] (cond (= guess n) (println "You guessed correctly") (contains? (deref picked-numbers) n) (println "Pick another number!You already tried that one.") :else (dosync (alter picked-numbers conj guess)))))user=> (guess-number secret-num)Enter a guess between 1 and 10: 1#{1}user=> (guess-number secret-num)Enter a guess between 1 and 10: 3#{1 3}user=> (guess-number secret-num)Enter a guess between 1 and 10: 5#{1 3 5}
  68. 68. Атоми(def picked-numbers (atom #{})(def secret-num (.nextInt (java.util.Random.) 10))(defn guess-number [n] (print "Enter a guess between 1 and 10: ") (flush) (let [guess (java.lang.Integer/parseInt (read-line)) ] (cond (= guess n) (println "You guessed correctly") (contains? (deref picked-numbers) n) (println "Pick another number!You already tried that one.") :else (swap! picked-numbers conj guess))))user=> (guess-number secret-num)Enter a guess between 1 and 10: 1#{1}user=> (guess-number secret-num)Enter a guess between 1 and 10: 3#{1 3}user=> (guess-number secret-num)Enter a guess between 1 and 10: 5#{1 3 5}
  69. 69. ООП по Лиспаджийски(defmulti my-add (fn [x y] (and (string? x) (string? y))))(defmethod my-add true [x y] (str x y))(defmethod my-add false [x y] (+ x y))user=> (my-add 3 4) ; => 7user=> (my-add "3" "4") ; => "34"
  70. 70. Екстремист съм, какво ми трябва? Обичайните заподозрени Eclipse IntelliJ NetBeans Emacs + SLIME = Bozhidar’s Choice
  71. 71. Повече инфо, моля!http://batsov.com/articles/2011/05/12/jvm-langs-clojure/
  72. 72. Stay hungry,stay foolish!
  73. 73. FIN

×