Day 11 / Mar 15 (Tue)¶
Goal¶
- Developing Scala applications
Exercises¶
Converter¶
Create Converter
class that converts Farenheits to Celcius.
Palindrome¶
Define palindrome
method using pattern matching and recursion.
def palindrome(s: String): Boolean = ???
Review a solution in solutions/day011-palindrome.sc
.
longest¶
// Exercise 4 page 103
// Create a function that takes a list of strings
// and returns the longest string in the list
// Hint: Use foldLeft
def longest(ss: List[String]): String = {
// ss.maxBy(_.length)
val maxStringCandidate = ""
ss.foldLeft(maxStringCandidate) { (longestString, s) =>
if (longestString.length < s.length) s else longestString
}
}
// longest(List("abc","420","a8c33"))
// 1. (maxStringCandidate, "abc") => "abc"
// 2. ("abc", "420") => "abc"
// 3. ("abc", "a8c33") => "a8c33"
Size of The Longest Element¶
longest
that returns the size of the longest element (not the element itself).
// longestSize(List("trzy")) == 4
def longestSize(ss: List[String]): Int = {
val maxLenCandidate = 0
ss.foldLeft(maxLenCandidate)((b, s) =>
if (b < s.length) s.length else b
)
}
Longest Strings¶
longest
that returns the longest string(s) in the list (all that are of the longest size).
case class LongestAllPair(size: Int, ns: List[String])
def longestAll(ss: List[String]): List[String] = {
val candidate = LongestAllPair(-1, List.empty[String])
ss.foldLeft(candidate)((b, s) =>
// s.length > "b" save s (and remove the acc)
// s.length == "b" add s to whatever you collected so far
// if s.length < "b" then drop s
if (b.size == -1) {
LongestAllPair(s.length, List(s))
} else if (b.size < s.length) {
LongestAllPair(s.length, List(s))
} else if (b.size == s.length) {
LongestAllPair(b.size, s +: b.ns)
} else {
b
}
).ns
}
longestAll(List("", "", "")) == List("", "", "")
longestAll(List("one", "two", "no")) == List("one", "two")
Handling Command Line¶
Write a command-line application that prints out the minimum and maximum numbers out of numbers from command line.
object Main extends App {
if (args.isEmpty) {
println("ERROR: No arguments. Exiting...")
sys.exit(0)
}
println(s"Number of arguments on command line: ${args.length}")
// Ints assumed
val ns = args.map(_.toInt).sorted
println(s"Given the following arguments: ${ns.mkString(", ")}")
println(s"Maximum value: ${ns.max}")
println(s"Minimum value: ${ns.min}")
}
Scala Topics¶
Case Class¶
class Person(val name: String) {
override def toString = {
name
}
}
object Person {
def apply(name: String): Person = new Person(name)
}
val jacek = new Person("Jacek")
jacek.name // "Jacek"
jacek.toString
case class MyPerson(name: String)
Schedule¶
- 8:30 - 10:10
- 10:25 - 12:00