https://superruzafa.github.io/visual-scala-reference/index-en.html
https://www.youtube.com/watch?v=MfEkOcMILDo Ammonite REPL
http://www.slatekit.com/scala101.html
https://habrahabr.ru/post/330816/
http://underscore.io/blog/posts/2017/05/29/why-we-open-sourced-our-books.html
https://www.coursera.org/learn/progfun2/home/welcome
https://www.reactivesystems.eu/2015/11/22/10-scala-features-most-java-developers-love.html
http://ktoso.github.io/scala-types-of-types/
http://pedrorijo.com/blog/scala-interview-questions/
https://leanpub.com/theneophytesguidetoscala
https://habrahabr.ru/post/326002/
https://conferences.oreilly.com/strata/strata-ny-2016/public/schedule/detail/51593
https://github.com/deanwampler/JustEnoughScalaForSpark
http://javarevisited.blogspot.com/2017/03/top-30-scala-and-functional-programming.html
https://www.udemy.com/scala-for-java-developers-ru/learn/v4/overview Golovach
http://www.lihaoyi.com/post/WhatsFunctionalProgrammingAllAbout.html
https://kapeli.com/dash API for many lang documentation app
https://scala.fluentcode.com/ source code for many scala projects
https://github.com/propensive/rapture
https://www.slideshare.net/pnicolas/advanced-scala-concepts
http://allaboutscala.com/ https://github.com/nadimbahadoor/allaboutscala
chess engine: http://marianogappa.github.io/software/2017/03/24/ostinato-a-chess-engine-written-in-scala-that-runs-on-the-browser-docker-and-the-repl/
http://ru-scala.livejournal.com/
https://www.youtube.com/watch?v=A7_Fk2X3C60&t=38s Keep it simple in Scala
https://www.youtube.com/watch?v=J1GP1X8bgRE Russian Kalinin Denis
https://www.youtube.com/watch?v=__PLkxx6Yko Russian Scala Performance
http://docs.scala-lang.org/overviews/collections/introduction
https://www.coursera.org/specializations/scala
https://habrahabr.ru/company/golovachcourses/blog/256651/ List of videolectures
https://madusudanan.com/tags/#Scala
https://alexn.org/blog/2017/01/30/asynchronous-programming-scala.html
http://scalafp.com/book/introduction-why-i-wrote-book.html
https://leanpub.com/mastering-advanced-scala
https://habrahabr.ru/hub/scala/
https://bigdatauniversity.com/courses/introduction-to-scala/
https://advancedweb.hu/2017/01/10/vim-scala-ag-ctags/
https://github.com/deanwampler/JustEnoughScalaForSpark
https://www.coursera.org/learn/progfun1/programming/Ey6Jf/recursion
https://github.com/lampepfl/progfun-wiki/blob/gh-pages/CheatSheet.md
https://www.scala-exercises.org/
http://fruzenshtein.com/scala-oop-9-things-you-didnt-know/
http://fruzenshtein-school.usefedora.com/courses/scala-oop-basics/lectures/1754782
runWith
collect vs map
apply()
PartialFunction
lift
Option
isEmpty
getOrElse
applyThen
Some
orElse
None
eta-expansion
https://gist.github.com/manjuraj/8c767ac4d6814be2813e examples
https://bradcollins.com/tag/scala/ scala examples
object Demo extends App {
val f: String => String =
Map ("France" -> "Paris", "Japan" -> "Tokyo)
val g: String => Int = {
case "Paris" => 5,
case "Tokyo" => 15
}
val h: String => Int = g compose f // country -> capital ID // compose in trait Function1
println (h("france")) //
}
val names = Stream(
"Rehoboam",
"Abijah",
"Asa",
"Jehoshaphat",
"Jehoram",
"Ahaziah")
val groupedByInitial = names.groupBy(_.head)
// groupedByInitial: Map[Char,Stream[String]] =
// Map(
// J -> Stream(Jehoshaphat, Jehoram),
// A -> Stream(Abijah, Asa, Ahaziah),
// R -> Stream(Rehoboam) )
val groupedByInitialAndSorted =
groupedByInitial.toStream.sortBy(_._1)
// val groupedByInitialAndSorted: Stream[(Char, Stream[String])] =
// Stream(
// A -> Stream(Abijah, Asa, Ahaziah),
// J -> Stream(Jehoshaphat, Jehoram),
// R -> Stream(Rehoboam) )
val pairs = Array(1, 2, 3).zip(Array("four", "five", "six"))
pairs: Array[(Int, String)] = Array((1,four), (2,five), (3,six))
for ((k, v) <- pairs) yield k.toString + v
res243: Array[String] = Array(1four, 2five, 3six)
val numbers = List(5, 4, 8, 6, 2) numbers.fold(0) { (z, i) => a + i}// result = 25
Do not do this:
var sum = 0
for (elem <- elements) {
sum += elem.value
}
Avoid doing this, prefer the available operators instead, like foldLeft :
val sum = elements.foldLeft(0)((acc, e) => acc + e.value)
Or even better, know thy standard library and always prefer to use the built-in functions
val sum = elements.map(_.value).sum
Make power of 2 for every element in Array:
def f1 (x: Array[Int]): Array[Int] = for (k <- x) yield k*k
def f2 (x: Array[Int]): Array[Int] = x map {k=> k*k}
object Demo extend App{
def prod[A,B] (set0: Set[A], set1: Set[B]) : Set[(A,B)] =
for ( e0 <- set0; e1 <- set1) yield (e0,e1)
val set0: Set[Char]=Set('A','B','C')
val set1: Set[Int]=Set(0,1)
val set2: Set[(Char,Int)]=prod(set0, set1)
print(set2)
}
scalacOptions := Seq( "-deprecation", "-Xlint", "-feature", "-unchecked", "-Xfatal-warnings", "-Ywarn-unused-import", "-Yno-adapted-args", "-language:higherKinds", "-language:existentials", "-encoding", "UTF-8", "-Ypartial-unification" )
Type classes
https://habrahabr.ru/post/318960/
trait Ordering[T] { def compare(a: T, b: T): Int }
наш универсальный алгоритм занимается сортировкой. Он должен принимать тип данных, с которыми он работает:
def sort[T](list: List[T]): List[T]
так как внутри алгоритма производится сравнение элементов, то этому алгоритму необходимо передать экземпляр класса Ordering для нашего типа T:
def sort[T: Ordering](list: List[T]): List[T]
либо, что тоже самое:
def sort[T](list: List[T])(implicit o: Ordering[T]): List[T]
week 2
http://stackoverflow.com/questions/6963792/scala-set-function
http://shirleyisnotageek.blogspot.com/2015/09/scala-note-2-functional-sets.html
https://github.com/shirleyyoung0812/Scala-notes
https://gist.github.com/huydx/5329449
https://github.com/ardlema/scala-higher-order-functions
def sum(f: Int=>Int, a:Int, b: Int) : Int =
if (a>b) 0
else f(a) + sum(f,a+1,b)
Usage :
sum (x =>x*x, 5, 10)
Issue: sum() above is not tail-recursive; below is tail-recursive version
def sum(f: Int=>Int, a:Int, b: Int) : Int = {
def loop(a:Int, acc: Int): Int={
if (a>b) acc
else loop (a+1, f(a)+acc)
}
loop(a,0)
}
Currying - function returns function
def sum2(f: Int=>Int): (Int,Int) => Int = {
def sumF(a:Int, acc: Int): Int=
if (a>b) 0
else f(a)+ sumF (a+1, b)
sumF
}
object exercise{
def mapReduce (
f: Int => Int,
combine: (Int, Int) => Int,
zero: Int
) (a: Int, b:Int) : Int =
if (a>b) zero
else combine (f(a) , mapReduce(f, combine, zero)(a+1,b))
def product (f: Int=> Int)(a: Int, b: Int): Int = mapReduce(f, (x,y)=>x*y,1) (a,b)
product(x=>x*x)
def fact(n: Int) = product(x=>x)(1,n)
}
Clousera Scala
https://class.coursera.org/progfun-2012-001/assignment/index
sbt compile | run | test | submit | console
Week 3
https://github.com/rohshall/coursera-scala/blob/master/objsets/src/main/scala/objsets/TweetSet.scala
Week #2 FunSets
https://gist.github.com/3844369
https://github.com/rohshall/coursera-scala/tree/master/funsets/src
https://github.com/dipeshshah-co-cc/Coursera-Scala/tree/master/funsets/src/main/scala/funsets
https://github.com/evgeny-goldin/scala-progfun/tree/master/funsets/src
https://github.com/groodt/coursera_scala/tree/master/funsets/src/main/scala/funsets
Week 1: Pascal triangle
https://gist.github.com/3764694 Scala
http://stackoverflow.com/questions/1763954/c-pascals-triangle
http://stackoverflow.com/questions/5096232/pascal-triangle-recursive-program-optimization-in-c
https://www.reddit.com/r/programming/comments/5glb3f/disadvantages_of_purely_functional_programming/
http://www.lexicallyscoped.com/2015/06/06/intro-to-ocaml.html
http://www.vasinov.com/blog/16-months-of-functional-programming/
Scala
http://blog.codacy.com/2015/07/03/how-to-learn-scala/
http://www.lihaoyi.com/Ammonite/ REPL
https://www.youtube.com/user/FunctionalTV/videos
https://www.youtube.com/watch?v=srrKNsVj_Tc
https://docs.google.com/presentation/d/1QBcVx9T9QxU1D5HdGE6g1f9K5IwQT03Ug3QNOrAwtls/edit#slide=id.p
http://scala.bythebay.io/schedule.html
http://www.scala-lang.org/docu/files/collections-api/collections.html
https://media.pragprog.com/titles/pb7con/Bonus_Chapter.pdf Actors in Scala
http://www.lihaoyi.com/post/BenchmarkingScalaCollections.html
http://www.atomicscala.com/ Book by Bruce Eckel
https://www.youtube.com/user/DrMarkCLewis
https://github.com/stanch/reftree
https://www.reddit.com/r/scala/comments/4sk4j2/can_someone_help_me_get_started_with_scala/
https://twitter.github.io/scala_school/
http://twitter.github.io/effectivescala/
https://www.youtube.com/watch?v=DzFt0YkZo8M
https://www.manning.com/books/functional-programming-in-scala
https://advancedweb.hu/2015/06/11/vim-scala/
https://www.scala-exercises.org/
https://github.com/Sergey80/scala-samples
http://underscore.io/training/courses/advanced-scala/
http://ktoso.github.io/scala-types-of-types/
https://gist.github.com/jdegoes/97459c0045f373f4eaf126998d8f65dc
http://eed3si9n.com/learning-scalaz/
http://www.scala-lang.org/docu/files/ScalaTutorial.pdf
http://danielwestheide.com/scala/neophytes.html
https://www.javacodegeeks.com/2014/06/scala-maps-and-sorting.html
https://www.javacodegeeks.com/2014/11/from-java-7-futures-to-akka-actors-with-scala.html
Pattern Matching
case classes
“Case classes can be seen as plain and immutable data-holding objects that should exclusively depend on their constructor arguments.
This functional concept allows us to
use a compact initialisation syntax (Node(1, Leaf(2), None)))
decompose them using pattern matching
have equality comparisons implicitly defined
In combination with inheritance, case classes are used to mimic algebraic datatypes.
If an object performs stateful computations on the inside or exhibits other kinds of complex behaviour, it should be an ordinary class.“
scala> case class Camera(brand: String, model: String)
defined class Camera
scala> val myCamera = Camera("Canon", "5D Mark III")
myCamera: Camera = Camera(Canon,5D Mark III)
scala> myCamera. put . and tab after myCamera to see the list of methods:
brand
copy
hashCode
productArity
productIterator
toString
canEqual
equals
model
productElement
productPrefix
https://www.javacodegeeks.com/category/jvm-languages/scala
https://www.javacodegeeks.com/2016/09/developing-modern-applications-scala-console-applications.html
https://www.youtube.com/watch?v=ugHsIj60VfQ
http://www.lihaoyi.com/fastparse/
https://madusudanan.com/blog/scala-tutorials-part-3-methods/#CallByNamevsValue
https://medium.com/@sinisalouc/latest
https://leanpub.com/modern-web-development-with-scala
https://github.com/ornicar/scalachess
http://www.47deg.com/blog/scala-exercises-version-two
https://github.com/scala-exercises/
https://medium.com/from-the-couch/scala-for-human-beings-ee079f14e3a0#.c4wbwbe0y
http://rerun.me/2016/06/05/scala-notes-futures-2-promises/
https://habrahabr.ru/company/retailrocket/blog/302828/ scala + spark
https://advancedweb.hu/2015/06/11/vim-scala/
http://twitter.github.io/scala_school/
https://www.reddit.com/r/scala/comments/409lki/how_do_i_move_beyond_the_scala_basics/
https://github.com/shekhargulati/52-technologies-in-2016/blob/master/02-sbt/README.md
http://matt.might.net/articles/implementing-laziness/
https://www.youtube.com/watch?v=P8jrvyxHodU Odersky
https://www.youtube.com/watch?v=WxyyJyB_Ssc Odersky
https://www.youtube.com/watch?v=DzFt0YkZo8M
https://www.udemy.com/scala-for-java-developers-ru/
http://habrahabr.ru/company/dca/blog/260845/ Akka
http://twitter.github.io/scala_school/ru/index.html
https://engineeringgutefrage.files.wordpress.com/2015/01/gf_scala_cheatsheet.pdf
http://underscore.io/books/creative-scala/
http://madusudanan.com/blog/scala-tutorials-part-2-type-inference-in-scala/
https://github.com/alexandru/scala-best-practices/
http://habrahabr.ru/post/273611/ Scalding - for HADOOP
http://danielwestheide.com/scala/neophytes.html
https://pavelfatin.com/category/programming/
https://github.com/pavelfatin/patterns
https://www.reddit.com/r/scala/comments/3xhj9n/best_way_to_learn_scala/
https://www.reddit.com/r/scala/comments/3v4s5o/where_should_i_start_to_learn_scala/
$ brew install scala
==> Downloading https://downloads.sf.net/project/machomebrew/Bottles/scala-2.11.5.yosemite.bottle.tar.gz
curl: (35) Unknown SSL protocol error in connection to downloads.sf.net:-36
Error: Failed to download resource "scala"
Download failed: https://downloads.sf.net/project/machomebrew/Bottles/scala-2.11.5.yosemite.bottle.tar.gz
Warning: Bottle installation failed: building from source.
==> Downloading http://www.scala-lang.org/files/archive/scala-2.11.5.tgz
######################################################################## 100.0%
==> Downloading https://raw.githubusercontent.com/scala/scala-dist/v2.11.4/bash-completion/src/main/resources/completion.d/2.9.1/scala
######################################################################## 100.0%
==> Caveats
To use with IntelliJ, set the Scala home to:
/usr/local/opt/scala/idea
Bash completion has been installed to:
/usr/local/etc/bash_completion.d
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/fsc
/usr/local/bin is not writable.
You can try again using:
brew link scala
==> Summary
🍺 /usr/local/Cellar/scala/2.11.5: 46 files, 29M, built in 8 seconds
https://blog.udemy.com/scala-tutorial-getting-started-with-scala/
http://danielwestheide.com/scala/neophytes.html
https://github.com/pathikrit/scalgos
https://pavelfatin.com/design-patterns-in-scala/
https://www.youtube.com/watch?v=478W_A9E1O8 parsing
http://habrahabr.ru/company/cit/blog/269293/ scalaTest
http://habrahabr.ru/company/golovachcourses/blog/266905/
http://www.slideshare.net/Odersky/scala-days-san-francisco-45917092
http://underscore.io/blog/posts/2015/03/25/creative-scala-released.html
http://habrahabr.ru/company/golovachcourses/blog/251239/
https://github.com/anton-k/ru-neophyte-guide-to-scala
http://rrees.me/2013/03/19/horses-for-courses-choosing-scala-or-clojure/
http://twitter.github.com/scala_school/
http://habrahabr.ru/post/158209/
http://www.meetup.com/Bay-Area-Scala-Enthusiasts/events/88983192/?a=ed1_12
http://www.scala-lang.org/node/104
http://www.artima.com/scalazine/articles/steps.html
http://programming-scala.labs.oreilly.com/ch01.html
http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=scala
http://www.kogics.net/sf:kojo Scala IDE
http://daily-scala.blogspot.com/
http://coding-time.blogspot.com/2011/05/covariance-and-contravariance-simple.html
http://apocalisp.wordpress.com/
https://github.com/strangeloop/2011-slides/blob/master/TOC.md
http://www.slideshare.net/oxbow_lakes/practical-scalaz
http://www.infoq.com/presentations/Functional-Data-Structures-in-Scala
#1 Minimum and Maximum values
val numbers = Seq(11, 2, 5, 1, 6, 3, 9)
numbers.max //11
numbers.min //1
case class Book(title: String, pages: Int)
val books = Seq(
Book("Future of Scala developers", 85),
Book("Parallel algorithms", 240),
Book("Object Oriented Programming", 130),
Book("Mobile Development", 495)
)
//Book(Mobile Development,495)
books.maxBy(book => book.pages)
//Book(Future of Scala developers,85)
books.minBy(book => book.pages)
#2 Filtering
val numbers = Seq(1,2,3,4,5,6,7,8,9,10)
numbers.filter(n => n % 2 == 0)
val books = Seq(
Book("Future of Scala developers", 85),
Book("Parallel algorithms", 240),
Book("Object Oriented Programming", 130),
Book("Mobile Development", 495)
)
books.filter(book => book.pages >= 120)
Also there is a syntax sugar analogue of filter function. Its name is filterNot.
#3 Flatten O_o
val abcd = Seq('a', 'b', 'c', 'd')
val efgj = Seq('e', 'f', 'g', 'h')
val ijkl = Seq('i', 'j', 'k', 'l')
val mnop = Seq('m', 'n', 'o', 'p')
val qrst = Seq('q', 'r', 's', 't')
val uvwx = Seq('u', 'v', 'w', 'x')
val yz = Seq('y', 'z')
val alphabet = Seq(abcd, efgj, ijkl, mnop, qrst, uvwx, yz)
// List(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z)
alphabet.flatten
When flatten is helpful? if you have a collection of collections, and you want to operate with all of the elements from the collections, don’t hesitate and use flatten.
#4 difference, intersection, union.
val num1 = Seq(1, 2, 3, 4, 5, 6)
val num2 = Seq(4, 5, 6, 7, 8, 9)
//List(1, 2, 3)
num1.diff(num2)
//List(4, 5, 6)
num1.intersect(num2)
//List(1, 2, 3, 4, 5, 6, 4, 5, 6, 7, 8, 9)
num1.union(num2)
The examples are self explained. But what about the union function? It keeps duplicates.
What if we want to get rid of them? For this purpose use distinct function:
//List(1, 2, 3, 4, 5, 6, 7, 8, 9)
num1.union(num2).distinct
#5 map list elements
val numbers = Seq(1,2,3,4,5,6)
//List(2, 4, 6, 8, 10, 12)
numbers.map(n => n * 2)
val chars = Seq('a', 'b', 'c', 'd')
//List(A, B, C, D)
chars.map(ch => ch.toUpper)
A logic of map function is following: you iterate through each element of collection and apply a function to the elements.
#6 flatMap
http://alvinalexander.com/scala/collection-scala-flatmap-examples-map-flatten
Let’s assume that we want to see how uppercase and lowercase characters look in the alphabet.
val abcd = Seq('a', 'b', 'c', 'd')
//List(A, a, B, b, C, c, D, d)
abcd.flatMap(ch => List(ch.toUpper, ch))
#7 Check entire collection for a condition
If at least one of the elements doesn’t correspond to the condition, you need to do something.
val numbers = Seq(3, 7, 2, 9, 6, 5, 1, 4, 2)
//ture
numbers.forall(n => n < 10)
//false
numbers.forall(n => n > 5)
Function forall is created for this sort of tasks.
#8 Partitioning of collection
What if you have a plan to separate a collection into two new collections by some rule?
This can be done with help of partition function. So let’s put all even numbers in one collection and all odd numbers in another:
val numbers = Seq(3, 7, 2, 9, 6, 5, 1, 4, 2)
//(List(2, 6, 4, 2), List(3, 7, 9, 5, 1))
numbers.partition(n => n % 2 == 0)
#9 Fold
Another on popular operation is fold. In context of Scala you can usually think about foldLeft and foldRight. In general they do the same job but from the different sides
val numbers = Seq(1, 2, 3, 4, 5)
//15
numbers.foldLeft(0)((res, n) => res + n)
The code sample above needs some explanations. In the first pair of parentheses we put a start value.
In the second pair of parentheses we define the operation which need to be performed for each element of the numbers sequence. On the first step n = 0,
than it evolves according to the sequence elements.
another example of foldLeft. Let’s count number ow characters in sequence of words:
val words = Seq("apple", "dog", "table")
//13
words.foldLeft(0)((resultLength, word) => resultLength + word.length)
#10 Your favorite function
Given a string S, find the longest substring which contains uppercase & lowercase characters, but not numbers.
Example: dP4knqw1QAp
Answer: QAp
This function solves the problem. If the input string doesn’t contain any suitable substring UnsupportedOperationException will be thrown.
def theLongest(s: String): String = {
s.split ("[0-9]")
.filter (_.exists (ch => ch.isUpper))
.filter (_.exists (ch => ch.isLower))
.maxBy (_.length)
}
F#
http://biarity.me/2016/11/30/An-unassuming-F-study-plan/
http://www.slideshare.net/ScottWlaschin/fp-patterns-buildstufflt
http://channel9.msdn.com/posts/Understanding-the-World-with-F