This document provides an introduction to the Scala programming language. It discusses that Scala is a hybrid language that is both object-oriented and functional, runs on the JVM, and provides seamless interoperability with Java. It highlights features of Scala such as pattern matching, traits, case classes, immutable data structures, lazy evaluation, and actors for concurrency.
Functional Patterns for the non-mathematicianBrian Lonsdorf
Fluentconf 2014 talk:
Functional design patterns such as lenses, arrows, functors, and monads all come from category theory. To fully grok them, you’ll probably have to wade through the whitest white papers, fighting the mathematical syntax and abstract examples.
I’m hoping to demonstrate the ideas into javascript. I’ll be showing direct and practical applications for every day programming.
Второе выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless
Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.
Functional Patterns for the non-mathematicianBrian Lonsdorf
Fluentconf 2014 talk:
Functional design patterns such as lenses, arrows, functors, and monads all come from category theory. To fully grok them, you’ll probably have to wade through the whitest white papers, fighting the mathematical syntax and abstract examples.
I’m hoping to demonstrate the ideas into javascript. I’ll be showing direct and practical applications for every day programming.
Второе выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless
Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.
Выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless
Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
Contact
FUNCTIONAL PROGRAMING AND EVENT SOURCING - A PAIR MADE IN HEAVEN - EXTENDED, 2 HOURS LONG BRAINWASH
TL;DR: This is talk is a solid introduction to two (supposedly) different topics: FP & ES. I will cover both the theory and the practice. We will emerage ES+FP application starting from ES+OO one.
While reading blogs or attending conferences, you might have heard about Event Sourcing. But didn't you get this feeling, that while there is a lot of theory out there, it is really hard to see a hands-on example? And even if you find some, those are always orbiting around Object Oriented concepts?
Greg Young once said "When we talk about Event Sourcing, current state is a left-fold of previous behaviours. Nothing new to Functional Programmers". If Functional Programming is such a natural concept for event sourced systems, shouldn't they fit together on a single codebase?
In this talk we will quickly introduce Event Sourcing (but without going into details), we will introduce some functional concepts as well (like State monad). Armoured with that knowledge we will try to transform sample ES application (OO-style, tightly coupled with framework) to frameworkless, FP-style solution).
Talk is targeted for beginner and intermediate audience. Examples will be in Scala but nothing fancy - normal syntax.
This talk is an extended version of a presentation "Event Sourcing & Functional Programming - a pair made in heaven". It is enriched with content of presentations: "Monads - asking the right question" and "It's all been done before - The Hitchhiker's Guide to Time Travel".
Slides of a talk I gave at work on Scala. It is geared toward Java developers. Some of the examples are in my company's domain, which is analyzing energy usage (i.e. a "read" is an electric meter read).
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Type classes 101 - classification beyond inheritanceAlexey Raga
Inheritance and interfaces implementation are often used in languages like Java in order to express "Is-a" and "Can-do" capabilities. In Scala we can do better by separating these concerns using the concept of type classes.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Java som sprog har ikke bevæget sig meget de seneste år. Vi har stadig ikke closures eller funktionelle aspekter som f.eks. C# har haft siden version 3. Er Scala svaret på enhver Javaudviklers bønner eller er sproget kun interessant for tågehoveder som mig, som begynder at synes bedre og bedre om funktionsorientering? Er den store portion syntaktisk sukker, Scala bringer på bordet, bare tomme kalorier?
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Выступление в рамках спецкурса "Немейнстримовые технологии разработки", читаемого в НГУ. http://bit.ly/mainstreamless
Аудио дорожка работает, но нужно иметь некоторое терпение, так как грузится она не моментально.
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...PROIDEA
Contact
FUNCTIONAL PROGRAMING AND EVENT SOURCING - A PAIR MADE IN HEAVEN - EXTENDED, 2 HOURS LONG BRAINWASH
TL;DR: This is talk is a solid introduction to two (supposedly) different topics: FP & ES. I will cover both the theory and the practice. We will emerage ES+FP application starting from ES+OO one.
While reading blogs or attending conferences, you might have heard about Event Sourcing. But didn't you get this feeling, that while there is a lot of theory out there, it is really hard to see a hands-on example? And even if you find some, those are always orbiting around Object Oriented concepts?
Greg Young once said "When we talk about Event Sourcing, current state is a left-fold of previous behaviours. Nothing new to Functional Programmers". If Functional Programming is such a natural concept for event sourced systems, shouldn't they fit together on a single codebase?
In this talk we will quickly introduce Event Sourcing (but without going into details), we will introduce some functional concepts as well (like State monad). Armoured with that knowledge we will try to transform sample ES application (OO-style, tightly coupled with framework) to frameworkless, FP-style solution).
Talk is targeted for beginner and intermediate audience. Examples will be in Scala but nothing fancy - normal syntax.
This talk is an extended version of a presentation "Event Sourcing & Functional Programming - a pair made in heaven". It is enriched with content of presentations: "Monads - asking the right question" and "It's all been done before - The Hitchhiker's Guide to Time Travel".
Slides of a talk I gave at work on Scala. It is geared toward Java developers. Some of the examples are in my company's domain, which is analyzing energy usage (i.e. a "read" is an electric meter read).
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
Type classes 101 - classification beyond inheritanceAlexey Raga
Inheritance and interfaces implementation are often used in languages like Java in order to express "Is-a" and "Can-do" capabilities. In Scala we can do better by separating these concerns using the concept of type classes.
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Java som sprog har ikke bevæget sig meget de seneste år. Vi har stadig ikke closures eller funktionelle aspekter som f.eks. C# har haft siden version 3. Er Scala svaret på enhver Javaudviklers bønner eller er sproget kun interessant for tågehoveder som mig, som begynder at synes bedre og bedre om funktionsorientering? Er den store portion syntaktisk sukker, Scala bringer på bordet, bare tomme kalorier?
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Scala er et Java-relateret, statisk typet programmeringssprog i hastig fremmarch. Sproget kombinerer aspekter fra objekt- og funktionsorienterede sprog og fokuserer på skalerbarhed og effektivitet, både på det kodemæssige og afviklingsmæssige niveau. Syntaksen er elegant og koncis. Samtidig indeholder sproget stærke konstruktioner til understøttelse af parallelle applikationer, der udnytter fremtidens hardwarearkitekturer.
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteGoogle
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
👉👉 Click Here To Get More Info 👇👇
https://sumonreview.com/ai-pilot-review/
AI Pilot Review: Key Features
✅Deploy AI expert bots in Any Niche With Just A Click
✅With one keyword, generate complete funnels, websites, landing pages, and more.
✅More than 85 AI features are included in the AI pilot.
✅No setup or configuration; use your voice (like Siri) to do whatever you want.
✅You Can Use AI Pilot To Create your version of AI Pilot And Charge People For It…
✅ZERO Manual Work With AI Pilot. Never write, Design, Or Code Again.
✅ZERO Limits On Features Or Usages
✅Use Our AI-powered Traffic To Get Hundreds Of Customers
✅No Complicated Setup: Get Up And Running In 2 Minutes
✅99.99% Up-Time Guaranteed
✅30 Days Money-Back Guarantee
✅ZERO Upfront Cost
See My Other Reviews Article:
(1) TubeTrivia AI Review: https://sumonreview.com/tubetrivia-ai-review
(2) SocioWave Review: https://sumonreview.com/sociowave-review
(3) AI Partner & Profit Review: https://sumonreview.com/ai-partner-profit-review
(4) AI Ebook Suite Review: https://sumonreview.com/ai-ebook-suite-review
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
Check out the webinar slides to learn more about how XfilesPro transforms Salesforce document management by leveraging its world-class applications. For more details, please connect with sales@xfilespro.com
If you want to watch the on-demand webinar, please click here: https://www.xfilespro.com/webinars/salesforce-document-management-2-0-smarter-faster-better/
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Understanding Globus Data Transfers with NetSageGlobus
NetSage is an open privacy-aware network measurement, analysis, and visualization service designed to help end-users visualize and reason about large data transfers. NetSage traditionally has used a combination of passive measurements, including SNMP and flow data, as well as active measurements, mainly perfSONAR, to provide longitudinal network performance data visualization. It has been deployed by dozens of networks world wide, and is supported domestically by the Engagement and Performance Operations Center (EPOC), NSF #2328479. We have recently expanded the NetSage data sources to include logs for Globus data transfers, following the same privacy-preserving approach as for Flow data. Using the logs for the Texas Advanced Computing Center (TACC) as an example, this talk will walk through several different example use cases that NetSage can answer, including: Who is using Globus to share data with my institution, and what kind of performance are they able to achieve? How many transfers has Globus supported for us? Which sites are we sharing the most data with, and how is that changing over time? How is my site using Globus to move data internally, and what kind of performance do we see for those transfers? What percentage of data transfers at my institution used Globus, and how did the overall data transfer performance compare to the Globus users?
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfJay Das
With the advent of artificial intelligence or AI tools, project management processes are undergoing a transformative shift. By using tools like ChatGPT, and Bard organizations can empower their leaders and managers to plan, execute, and monitor projects more effectively.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
8. “I can honestly say if someone had shown me the Programming Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.“
James Strachan, creator of Groovy
9. “If I were to pick a language to use today other than Java, it would be Scala.”
James Gosling
19. object MyApp {
def main(args: Array[String]) {
val user = args(0)
println(“Hello, ”+user+“!”)
}
}
Local type inference
less… “typing”
20. class StringArrayFactory {
def create: Array[String] = {
val array: Array[String] =
Array[String](“1”, “2”, “3”)
array
}
}
Local type inference
less… “typing”
21. class StringArrayFactory {
def create = {
val array = Array(“1”, “2”, “3”)
array
}
}
Local type inference
less… “typing”
22. // Scala
class Person(
var name: String,
var age: Int
)
Declaring classes
…concisely
// Java
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
41. val doub: Int => Int = (x: Int) => x * 2
doub(1)
2
First class functions
functions are objects too
42. val doub = (x: Int) => x * 2
List(1, 2, 3).map(doub)
List(2, 4, 6)
First class functions
as higher order parameters
43. List[Int](1, 2, 3).map((x: Int) => x * 2)
// more type inference
List(1, 2, 3).map(x => x * 2)
// or even shorter
List(1, 2, 3).map(_ * 2)
Functions with sugar
make code sweeter
44. var step = 1
val inc = x => x + step
inc(5)
6
step = 2
inc(5)
7
Closures
functions that “capture” their environment
45. // Java
button.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
System.out.println(e);
}
}
// Scala
listenTo(button)
reactions += { case e => println(e) }
First class functions
because you write them in Java all the time
47. Pattern matching
…is concise
// Scala
reactions += {
case m: MouseEntered =>
println(“I see it!”)
case m: MouseExited =>
println(“Lost it.”)
case m: MouseClicked =>
println(“Poked!”)
}
// Java
button.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
System.out.println(“I see it!”);
}
public void mouseExited(MouseEvent e) {
System.out.println(“Lost it.”);
}
public void mouseClicked(MouseEvent e) {
System.out.println(“Poked!”);
}
}
// ...alternative - isinstanceof
48. trait Tree
case class Node(l: Tree, r: Tree)
extends Tree
case object Leaf
extends Tree
Pattern matching
…is precise
49. def b(t: Tree): Int = t match {
case Node(Leaf, Node(_, _)) |
Node(Node(_, _), Leaf) => -1
case Node(l, r) =>
val (ld, rd) = (b(l), b(r))
if (ld == rd) ld + 1 else -1
case Leaf => 0
case _ => error(“Unknown tree!”)
}
Pattern matching
…is precise
50. sealed trait Tree
...
def b(t: Tree): Int = t match {
case Node(Leaf, Node(_, _)) |
Node(Node(_, _), Leaf) => -1
case Node(l, r) =>
val (ld, rd) = (b(l), b(r))
if (ld == rd) ld + 1 else -1
case Leaf => 0
}
Pattern matching
…is exhaustive
51. def matchingMeSoftly(a: Any): Any =
a match {
case 11 => “eleven”
case s: String => “’%s’”.format(s)
case <tag>{t}</tag> => t
case Array(1, 2, 3) => “1, 2, 3”
case head :: tail => tail
case _ => null
}
Pattern matching
…is extensible
53. lazy values
don’t compute if there’s no demand
class User(id: Int) {
lazy val followernum =
from(followers)(f =>
where(id === f.fid)
compute(countDistinct(f.fid))
)
}
54. Call by name
evaluate only when you have to
def withErrorOut(body: =>Unit) = {
val old = Console.out
Console.setOut(Console.err)
try body
finally Console.setOut(old)
}
...
withErrorOut {
if (n < 0) println(“n too small”)
}
61. for comprehensions
traverse anything
for (x <- List(1, 2, 3)) println(x)
List(1, 2, 3).foreach(x => println(x))
for (x <- 0 until 10) println(x)
(0 until 10).foreach(x => println(x))
Range(0, 10, 1).foreach(x => println(x))
62. for comprehensions
map anything
for (x <- List(1, 2, 3)) yield x * 2
List(1, 2, 3).map(x => x * 2)
for (x <- List(1, 2); y <- List(1, 2))
yield x * y
List(1, 2).flatMap(x =>
List(1, 2).map(y => x * y)
)
List(1, 2, 2, 4)
63. for comprehensions
like SQL queries
for {
p <- people
if p.age > 25
s <- schools
if p.degree == s.degree
} yield (p, s)
// pairs of people older than 25 and
// schools they possibly attended
64. Collections
easy to create
val phonebook = Map(
“Jean” -> “123456”,
“Damien” -> “666666”)
val meetings = ArrayBuffer(
“Dante”, “Damien”, “Sophie”)
println(phonebook(meetings(1)))
65. Collections
high-level combinators
// Java
boolean isOk = true
for (int i = 0; i < name.length(); i++) {
if (isLetterOrDigit(name.charAt(i)) {
isOk = false;
break;
}
}
68. Collections
high-level combinators
// count the total number of different
// surnames shared by at least 2 adults
people.filter(_.age >= 18)
69. Collections
high-level combinators
// count the total number of different
// surnames shared by at least 2 adults
people.filter(_.age >= 18)
.groupBy(_.surname): Map[String, List[Person]]
70. Collections
high-level combinators
// count the total number of different
// surnames shared by at least 2 adults
people.filter(_.age >= 18)
.groupBy(_.surname): Map[String, List[Person]]
.count { case (s, l) => l.size >= 2 }
71. Lists
an immutable sequence
val countdown = List(3, 2, 1)
3
2
1
countdown
72. Lists
an immutable sequence
val countdown = List(3, 2, 1)
val longer = 4 :: countdown
3
2
1
4
countdown
longer
73. Lists
an immutable sequence
val countdown = List(3, 2, 1)
val longer = 4 :: countdown
val fast = 10 :: countdown
3
2
1
4
10
countdown
longer
fast
74. Lists
an immutable sequence
val countdown = List(3, 2, 1)
val longer = 4 :: countdown
val fast = 10 :: countdown
val withzero = countdown ::: List(0)
3
2
1
4
10
3
2
1
0
countdown
longer
fast
withzero
75. Buffers
mutable sequences
val b = ArrayBuffer(1, 2, 3)
b += 4
b += 5
b += 6
ArrayBuffer(1, 2, 3, 4, 5, 6)
76. Maps
mutable or immutable, sorted or unsorted
import collection._
val m = mutable.Map(“Heidfeld” -> 1,
“Schumacher” -> 2)
m += “Hakkinen” -> 3
val im = immutable.Map(“Schumacher” -> 1)
77. Hash tries
persistence through efficient structural sharing
val im0: Map[Int, Int] = ...
im0
78. Hash tries
persistence through efficient structural sharing
val im0: Map[Int, Int] = ...
val im1 = im0 + (1 -> 1)
im0
im1
79. Hash tries
persistence through efficient structural sharing
val im0: Map[Int, Int] = ...
val im1 = im0 + (1 -> 1)
val im2 = im1 + (2 -> 2)
im0
im1
im2
80. Hash tries
persistence through efficient structural sharing
val im0: Map[Int, Int] = ...
val im1 = im0 + (1 -> 1)
val im2 = im1 + (2 -> 2)
val im3 = im2 + (3 -> 6)
im0
im1
im2
im3
85. actors
road to safer concurrency
val a = actor {
react {
case i: Int => println(i)
}
}
...
a ! 5
86. Custom control flow
it’s all about control
def myWhile(c: =>Boolean)(b: =>Unit) {
if (c) {
b
myWhile(c)(b)
}
}
87. Custom control flow
it’s all about control
@tailrec
def myWhile(c: =>Boolean)(b: =>Unit) {
if (c) {
b
myWhile(c)(b)
}
}
88. Custom control flow
it’s all about control
@tailrec
def myWhile(c: =>Boolean)(b: =>Unit) {
if (c) {
b
myWhile(c)(b)
}
}
var i = 0
myWhile (i < 5) {
i += 1
}
89. ARM
automatic resource management
withFile (“~/.bashrc”) { f =>
for (l <- f.lines) {
if (“#”.r.findFirstIn(l) != None)
println(l)
}
}
90. ScalaTest
behavioral testing framework
“A list” should {
“be a double reverse of itself” in {
val ls = List(1, 2, 3, 4, 5, 6)
ls.reverse.reverse should equal (ls)
}
}
91. BaySick
Basic DSL in Scala
10 PRINT “Baysick Lunar Lander v0.9”
20 LET ('dist := 100)
30 LET ('v := 1)
40 LET ('fuel := 1000)
50 LET ('mass := 1000)
...
95. implicit conversions
pimping your libraries since 2006
import scalaj.collection._
val list = new java.util.ArrayList[Int]
list.add(1)
list.add(2)
list.add(3)
...
for (x <- list) yield x * 2
96. implicit conversions
pimping your libraries since 2006
import scalaj.collection._
val list = new java.util.ArrayList[Int]
list.add(1)
list.add(2)
list.add(3)
...
for (x <- list) yield x * 2
// list.map(x => x * 2)
97. implicit conversions
pimping your libraries since 2006
import scalaj.collection._
val list = new java.util.ArrayList[Int]
list.add(1)
list.add(2)
list.add(3)
...
for (x <- list) yield x * 2
// jlist2slist(list).map(x => x * 2)
98. implicit arguments
restricting operations on types
val is = SortedSet(1, 2, 3)
case class Man(id: Int)
...
implicit object MenOrd extends Ordering[Man] {
def compare(x: Man, y: Man) = x.id – y.id
}
val ms = SortedSet(Person(1), Person(2))