Skip to content

Instantly share code, notes, and snippets.

@ignasi35
Created April 14, 2016 20:39
Show Gist options
  • Save ignasi35/543c08f8106ee567499a7cecc2496bc4 to your computer and use it in GitHub Desktop.
Save ignasi35/543c08f8106ee567499a7cecc2496bc4 to your computer and use it in GitHub Desktop.
Sample code for the Ironhack Meetup: Intro to scala for Ruby devs
package com.marimon.meetup
object Naive extends App {
def parse(s: String): Int = s.toInt
def div(in: Int): Int = 16 / in
def sqrt(in: Int): Double = Math.sqrt(in)
val values = List("4", "2", "-4", "0", "asdf")
values.map {
input =>
val x = parse(input)
val y = div(x)
val z = sqrt(y)
z // this is like 'return z' but return is not necessary
} foreach println
}
object Naive2 extends App {
def parse(s: String): Int = s.toInt
def div(in: Int): Int = 16 / in
def sqrt(in: Int): Int = Math.sqrt(in).toInt
val values = List("4", "2", "-4", "0", "asdf")
values.foreach {
input =>
try {
val x = parse(input)
val y = div(x)
val z = sqrt(y)
println(z) /// <-- is that a valid result always?
} catch {
case x: NumberFormatException => println("Number format Exception: " + x.getMessage) // concat string
case x: ArithmeticException => println(s"Arythmetic Exception: ${x.getMessage}") // interpolate strings
}
}
}
object Railways extends App {
import scala.util.{Failure, Success, Try}
def parse(s: String): Try[Int] = Try(s.toInt)
def div(in: Int): Try[Int] = Try(16 / in)
def sqrt(in: Int): Try[Int] =
if (in >= 0) {
Success(Math.sqrt(in).toInt)
}
else {
Failure(new IllegalArgumentException("Can't sqrt negative values."))
}
val values = List("4", "2", "-4", "0", "asdf")
// the type of the variable is already telling me something may
// be wrong with each individual item of the 'results' list.
val results: List[Try[Int]] = values.map {
input =>
for {
x <- parse(input)
y <- div(x)
z <- sqrt(y)
} yield {
z
}
}
results.foreach(println)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment