Skip to content

Instantly share code, notes, and snippets.

@tristanwietsma
Last active May 17, 2019 03:01
Show Gist options
  • Save tristanwietsma/385ec9242d9cbbac5fcf to your computer and use it in GitHub Desktop.
Save tristanwietsma/385ec9242d9cbbac5fcf to your computer and use it in GitHub Desktop.
Scala for the Impatient

Exercise 1

scala> 3.
%   +   >    >>>            isInstanceOf   toDouble   toLong     unary_+   |
&   -   >=   ^              toByte         toFloat    toShort    unary_-
*   /   >>   asInstanceOf   toChar         toInt      toString   unary_~

Exercise 2

scala> import math._
import math._

scala> var root3 = math.sqrt(3)
root3: Double = 1.7320508075688772

scala> math.pow(root3, 2)
res1: Double = 2.9999999999999996

scala> 3 - res1
res2: Double = 4.440892098500626E-16

Exercise 3

res variables are var.

Exercise 4

scala> "crazy" * 3
res2: String = crazycrazycrazy

From StringOps in the docs, "*" returns the string concatenated n times.

Exercise 5

10 max 2 returns the max of the two numbers (10). Defined in RichInt.

Exercise 6

scala> val two = BigInt("2")
two: scala.math.BigInt = 2

scala> two.pow(1024)
res2: scala.math.BigInt = 179769313486231590772930519078902473361797697894230657273430081157732675805500963132708477322407536021120113879871393357658789768814416622492847430639474124377767893424865485276302219601246094119453082952085005768838150682342462881473913110540827237163350510684586298239947245938479716304835356329624224137216

Exercise 7

scala> import scala.util.Random
import scala.util.Random

scala> import BigInt._
import BigInt._

scala> probablePrime(100, Random)
res0: scala.math.BigInt = 752657953138039345657544035981

Exercise 8

scala> val num = probablePrime(100, Random)
num: scala.math.BigInt = 793354810523066938087955098157

scala> num.toString(36)
res1: String = 24x0gg5vc0a3svf3srot

Exercise 9

scala> val x = "Me"
x: String = Me

scala> x(0)
res2: Char = M

scala> x.length
res3: Int = 2

scala> x(x.length-1)
res4: Char = e

Or, use the builtins:

scala> x.tail
res8: String = e

scala> x.head
res9: Char = M

Exercise 10

take n returns the first n chars; drop n returns the chars remaining after n chars. +Right does the same operation from the opposite end of the array.

scala> val test = "some word"
test: String = some word

scala> test take 3
res14: String = som

scala> test drop 3
res15: String = e word

scala> test takeRight 3
res16: String = ord

scala> test dropRight 3
res17: String = some w

Also works on other collections:

scala> 1 to 10 take 3
res19: scala.collection.immutable.Range = Range(1, 2, 3)

scala> 1 to 10 drop 3
res20: scala.collection.immutable.Range = Range(4, 5, 6, 7, 8, 9, 10)

Exercise 1

scala> def signum(x: Int): Int = {
     | if (x > 0) 1
     | else if (x < 0) return -1
     | else 0
     | }
signum: (x: Int)Int

scala> signum(1)
res0: Int = 1

scala> signum(-1)
res1: Int = -1

scala> signum(0)
res2: Int = 0

Alternatively, with pattern matching:

scala> def signum2(x: Int): Int = {
     | x match {
     | case x if x > 0 => return 1
     | case x if x < 0 => return -1
     | case _ => return 0
     | }
     | }
signum2: (x: Int)Int

scala> signum2(10)
res3: Int = 1

scala> signum2(-10)
res4: Int = -1

scala> signum2(0)
res5: Int = 0

Equivalent, but cleaner:

scala> def signum3(x: Int): Int = {
     | return x match {
     | case x if x > 0 => 1
     | case x if x < 0 => -1
     | case _ => 0
     | }
     | }

Exercise 2

This is literally nothing.

scala> var x = {}
x: Unit = ()

Exercise 3

Dumb question. x is Unit.

Exercise 4

scala> for(i <- 1 to 10; j = 11 - i) println(j);
10
9
8
7
6
5
4
3
2
1

or this...

scala> for(i <- 10 to 1 by -1) println(i);
10
9
8
7
6
5
4
3
2
1

Exercise 5

scala> def countdown(n: Int) = for(i <- n to 0 by -1) println(i)
countdown: (n: Int)Unit

scala> countdown(3)
3
2
1
0

Exercise 6

For-loop...

scala> var prod = BigInt(1);
prod: scala.math.BigInt = 1

scala> for(i <- "Hello") prod *= BigInt(i)

scala> prod
res24: scala.math.BigInt = 9415087488

Exercise 7

Functional way...

scala> "Hello" map (i => BigInt(i))
res20: scala.collection.immutable.IndexedSeq[scala.math.BigInt] = Vector(72, 101, 108, 108, 111)

scala> "Hello" map (i => BigInt(i)) product
res21: scala.math.BigInt = 9415087488

Exercise 8

scala> def StringProd(x: String): BigInt = {
     | return x map (i => BigInt(i)) product
     | }
StringProd: (x: String)BigInt

scala> StringProd("Hello")
res25: BigInt = 9415087488

Exercise 9

scala> def StringProdRecurse(x: String): BigInt = {
     | if(x.length == 1) return BigInt(x(0))
     | return BigInt(x.head) * StringProdRecurse(x.drop(1))
     | }
StringProdRecurse: (x: String)BigInt

scala> StringProdRecurse("Hello")
res0: BigInt = 9415087488

Exercise 10

scala> def x10(x: Double, n: Int): Double = (x, n) match {
     | case (x, n) if (n % 2 == 0 & n > 0) => x10(x, n/2) * x10(x, n/2)
     | case (x, n) if (n % 2 == 1 & n > 0) => x * x10(x, n-1)
     | case (x, n) if (n == 0) => 1
     | case (x, n) if (n < 0) => 1 / x10(x, -n)
     | }
x10: (x: Double, n: Int)Double

scala> x10(10, 1)
res0: Double = 10.0

scala> x10(10, 12)
res1: Double = 1.0E12

scala> x10(10, 2)
res2: Double = 100.0

scala> x10(10, -2)
res3: Double = 0.01

Exercise 1

scala> val n = Random.nextInt(10)
n: Int = 9

scala> val arr = new Array[Int](n).map(_ match {case _ => Random.nextInt(n)})
arr: Array[Int] = Array(2, 5, 2, 4, 4, 2, 4, 3, 8)

Exercise 2

scala> val x = (1 until 6).toArray
x: Array[Int] = Array(1, 2, 3, 4, 5)

scala> for(i <- 0 to 2*(x.length / 2)-1 by 2) {
     | val first = x(i)
     | x(i) = x(i+1)
     | x(i+1) = first
     | }

scala> x
res15: Array[Int] = Array(2, 1, 4, 3, 5)

Exercise 3

scala> x.grouped(2)
res2: Iterator[scala.collection.immutable.IndexedSeq[Int]] = non-empty iterator

scala> (for {b <- x.grouped(2); c <- b.reverse} yield c).toArray
res3: Array[Int] = Array(2, 1, 4, 3, 5)

Exercise 4

scala> val x = (-4 until 5).toArray
x: Array[Int] = Array(-4, -3, -2, -1, 0, 1, 2, 3, 4)

scala> x.filter(_ > 0) ++ x.filter(_ <= 0)
res19: Array[Int] = Array(1, 2, 3, 4, -4, -3, -2, -1, 0)

Exercise 5

cala> val x = (0 until 10).map(_.toDouble)
x: scala.collection.immutable.IndexedSeq[Double] = Vector(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0)

scala> x.sum
res20: Double = 45.0

scala> x.sum / x.length
res21: Double = 4.5

Exercise 6

scala> (0 until 10).toArray.sorted.reverse
res26: Array[Int] = Array(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

Exercise 7

scala> arr
res29: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 3, 1, 2, 3, -7)

scala> arr.toSet.toArray
res31: Array[Int] = Array(1, 2, 3, -7)

Exercise 9

scala> import java.util.TimeZone.getAvailableIDs
import java.util.TimeZone.getAvailableIDs

scala> getAvailableIDs.filter(_.startsWith("America")).map(_.drop(8))
res38: Array[String] = Array(Adak, Atka, Anchorage, Juneau, Nome, Sitka, Yakutat, Dawson, Ensenada, Los_Angeles, Metlakatla, Santa_Isabel, Tijuana, Vancouver, Whitehorse, Boise, Cambridge_Bay, Chihuahua, Creston, Dawson_Creek, Denver, Edmonton, Hermosillo, Inuvik, Mazatlan, Ojinaga, Phoenix, Shiprock, Yellowknife, Bahia_Banderas, Belize, Cancun, Chicago, Costa_Rica, El_Salvador, Guatemala, Indiana/Knox, Indiana/Tell_City, Knox_IN, Managua, Matamoros, Menominee, Merida, Mexico_City, Monterrey, North_Dakota/Beulah, North_Dakota/Center, North_Dakota/New_Salem, Rainy_River, Rankin_Inlet, Regina, Resolute, Swift_Current, Tegucigalpa, Winnipeg, Atikokan, Bogota, Cayman, Coral_Harbour, Detroit, Fort_Wayne, Grand_Turk, Guayaquil, Havana, Indiana/Indianapolis, Indiana/Marengo, Indiana/Petersburg...

Exercise 1

scala> val prices = Map("das" -> 113.00, "laptop" -> 1899.99)
prices: scala.collection.immutable.Map[String,Double] = Map(das -> 113.0, laptop -> 1899.99)

scala> val discount = for ((k,price) <- prices) yield (k, 0.9*price)
discount: scala.collection.immutable.Map[String,Double] = Map(das -> 101.7, laptop -> 1709.991)

scala> discount
res3: scala.collection.immutable.Map[String,Double] = Map(das -> 101.7, laptop -> 1709.991)

Exercise 2

echo "A B C A B C A B A A" > example.txt

import scala.io.Source

object Ex2 {
  def main(args: Array[String]) {
    val source = Source.fromFile(args(0), "UTF-8")
    val counts = scala.collection.mutable.Map[String, Int]()
    for (line <- source.getLines) {
      val words = line.split(" ")
      for(i <- 0 until words.length){
        val c = if (counts.contains(words(i))) counts(words(i)) else 0
        counts(words(i)) = c + 1
      }
    }
    println(counts)
  }
}

Exercise 3

import scala.io.Source

object Ex3 {
  def main(args: Array[String]) {
    val source = Source.fromFile(args(0), "UTF-8")
    var counts = Map[String, Int]() withDefault {_ => 0}
    for (line <- source.getLines) {
      val words = line.split(" ")
      for(i <- 0 until words.length){
        val c = counts(words(i)) + 1
        counts = counts - words(i) + (words(i) -> c)
      }
    }
    println(counts)
  }
}

Exercise 4

import scala.io.Source

object Ex4 {
  def main(args: Array[String]) {
    val source = Source.fromFile(args(0), "UTF-8")
    var counts = collection.immutable.SortedMap[String, Int]() withDefault {_ => 0}
    for (line <- source.getLines) {
      val words = line.split(" ")
      for(i <- 0 until words.length){
        val c = counts(words(i)) + 1
        counts = counts - words(i) + (words(i) -> c)
      }
    }
    println(counts)
  }
}

Exercise 5

import scala.io.Source
import java.util.TreeMap

object Ex5 {
  def main(args: Array[String]) {
    val source = Source.fromFile(args(0), "UTF-8")
    var counts = new TreeMap[String, Int]
    for (line <- source.getLines) {
      val words = line.split(" ")
      for (i <- 0 until words.length) {
        if (!(counts containsKey words(i))) counts put (words(i), 0)
        counts put (words(i), (counts get words(i)) + 1)
      }
    }
    println(counts)
  }
}

Exercise 6

import java.util.Calendar.{ MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
import collection.mutable.LinkedHashMap

object Ex6 {
  def main(args: Array[String]) {
    val m = new LinkedHashMap[String, Int]()
    m put ("Monday", MONDAY)
    m put ("Tuesday", TUESDAY)
    m put ("Wednesday", WEDNESDAY)
    m put ("Thursday", THURSDAY)
    m put ("Friday", FRIDAY)
    m put ("Saturday", SATURDAY)
    m put ("Friday", FRIDAY)
    println(m)
  }
}

Exercise 7

Exercise 8

Exercise 9

Exercise 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment