Created
November 24, 2015 22:06
-
-
Save ignasi35/640225ae98df60841a8d to your computer and use it in GitHub Desktop.
Betabeers Nov 2015 - Intro to scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.marimon | |
case class Address(streetName: String, | |
number: Int, | |
zipCode: String, | |
city: String) | |
case class Person(name: String, | |
surname: String, | |
address: Option[Address]) | |
case class Family(surname: String, | |
members: Set[Person]) | |
object Sample extends App { | |
val home = | |
Address("Emperor Dr", 42, "WDE 3R", "Coruscant") | |
val padme = Person("Padme", "skywalker", Some(home)) | |
val alderaan = | |
Address("Avenue de la Reine", 1, "08001", "OrganaVille Sur Mer") | |
val leia = Person("leia", "organa", Some(home)) | |
val luke = Person("luke", "skywalker", None) | |
val anakin = Person("anakin", "skywalker", None) | |
val skywalkers = Family("Vader", Set(anakin, padme, luke, leia)) | |
val shuffled = scala.util.Random.shuffle(skywalkers.members) | |
val paired = skywalkers.members zip shuffled | |
val validSecretSanta = !paired.exists(pair => pair._1 == pair._2) | |
println(s" Is this a valid Secret Santa? $validSecretSanta") | |
paired foreach println | |
val square = (x: Int) => x * x | |
val sqrt = (x: Int) => scala.math.sqrt(x).toInt | |
val intoAString = (x: Int) => "*" * x | |
val prettify = (s: String) => s.toCharArray.foldLeft("")((acc, c2) => acc + " " + c2) | |
println( | |
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).map(square) | |
) | |
val myFunc = square andThen | |
sqrt andThen | |
intoAString andThen | |
prettify andThen { | |
_.tail | |
} | |
List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) | |
.map(myFunc) | |
.foreach(println) | |
import java.net.URL | |
import java.util.concurrent.TimeUnit | |
import scala.concurrent.duration.Duration | |
import scala.concurrent.{Await, Future} | |
import scala.util.Success | |
import scala.concurrent.ExecutionContext.Implicits.global | |
val futures = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).map { i => | |
Future { | |
new URL("http://httpbin.org/delay/" + scala.util.Random.nextInt(i)).getContent | |
i | |
}.andThen { case Success(x) => println(x) } | |
} | |
Await.result(Future.sequence(futures), Duration(10, TimeUnit.SECONDS)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment