Day 15 / Mar 21 (Mon)¶
Misc¶
- All 10 Scala devs working together in the office. Yay! 🔥
- Honing Scala skills
- A Scala exam on April, 1st (Fri) at 10am
- Possibly remote?
Discussion: Differences Between Methods and Functions (def and val)¶
object Daniel {
val f: Int => Int = _ * 2
}
class Daniel {
def g(n: Int) = n * 2
val h: Int => Int = _ * 2
}
Daniel.f(2)
(new Daniel).g(32)
(new Daniel).h(43)
Exercise: Random Pairs¶
Write a function that generate distinct random pairs of 2 numbers from two Int
sequences (of the same length)
- scala.util.Random
randomPairs(left: Seq[Int], right: Seq[Int]): Seq[(Int, Int)]
Solution: randomPairs.sc
Polymorphic Methods¶
def randomPairs[T](left: Seq[T], right: Seq[T]): Seq[(T, T)] = {
import scala.util.Random
Random.shuffle(left).zip(Random.shuffle(right))
}
case class MyOwnClass(id: Long)
// two different ways to create a series of case class instances
val myLeft = (0 to 4).map(MyOwnClass(_))
val myRight = (5 to 9).map(n => MyOwnClass(n))
randomPairs(myLeft, myRight)
Exercise: Uppercase Every N-th Word (Pair Programming)¶
-
Use Pair programming technique to work together on a solution to the exercise.
- Use the above polymorphic method to generate pairs of two Scala devs to work together
val hakunaMatata = Seq("rafal", "damian", "daniel", "ania", "grzegorz") val theOffice = Seq("adam", "leo", "mateusz", "krzysiek", "janek") randomPairs(hakunaMatata, theOffice)
-
Develop a command-line application to uppercase every
n
-th word in a file- A file path and
n
are command-line arguments (parameters) - A brand new Scala project in IntelliJ IDEA
extends App
- Publish the project to GitHub
- A file path and
Solution: uppercase.sc
Partial Functions¶
- Pattern Matching
- Anonymous Functions
- Partial Functions (
case
functions) if
Guards- Destructuring and Case Classes
Scala Topics¶
From Scala for the Impatient book:
- 2.8 Default and Named Arguments, p. 21
- 4.7 Tuples, p. 45
- 4.8 Zipping, p. 46
More Exercises¶
From or based on Scala for the Impatient book:
-
Write a function that prints out a text in a box of
-
s (dashes),|
(pipes), and+
(pluses) e.g.+-------+ | Hello | +-------+
-
P28. Sorting a list of lists according to length of sublists
- We suppose that a list contains elements that are lists themselves. The objective is to sort the elements of the list according to their length. E.g. short lists first, longer lists later, or vice versa.
scala> lsort(List(List('a, 'b, 'c), List('d, 'e), List('f, 'g, 'h), List('d, 'e), List('i, 'j, 'k, 'l), List('m, 'n), List('o))) res0: List[List[Symbol]] = List(List('o), List('d, 'e), List('d, 'e), List('m, 'n), List('a, 'b, 'c), List('f, 'g, 'h), List('i, 'j, 'k, 'l))
Further Reading¶
- STD LIB module in Scala Exercises
Schedule¶
- 8:30 - 10:25
- 15' break
- 10:35 - 12:00
- 45' lunch break
- 12:45 - 13:40
- 15' break
- 13:55 - 14:30