Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created October 28, 2018 19:18
Show Gist options
  • Save dengjonathan/4b823d98f1ca92c9177dc06861a8e86a to your computer and use it in GitHub Desktop.
Save dengjonathan/4b823d98f1ca92c9177dc06861a8e86a to your computer and use it in GitHub Desktop.
Playing around to try to fully grok Scala map/ flatMap behavior
import scala.concurrent.{Await, Future, ExecutionContext}
import scala.util.Try
import ExecutionContext.Implicits.global
object rnn {
val seed = "5"
def fetch = Future {
Thread.sleep(100)
seed
}
def parse(stringifiedNumber: String) = Try(stringifiedNumber.toInt)
def getPrize(luckyNum: Int) = Future {
Thread.sleep(100)
if (luckyNum > 2) {
"A pony!"
} else {
"nothing!"
}
}
// How do I convert the type of the monad?
// I understand if I convert directly to Try type, then I am losing the abstraction over latency
// that future provides
// so it would actually not be useful to convert Future[String] => Try[Number] but
// the most accurate type for modelling this domain is Future[Try[Number]]
def getNum = fetch.flatMap(stringifiedNum => stringifiedNum match {
case str => parse(str)
})
def fetchAndFetch = fetch flatMap ((_: String) => fetch)
def getNumMap = fetch map parse
def drawNumberAndGetPrize = fetch map parse map {
_ match {
case Success(parsedNum) => Option(getPrize(parsedNum))
case Failure => Option.empty[String]
}
}
// why is this one not the same as the `drawNumberAndGetPrize` above?
def drawNumberAndGetPrice2 = for {
// my aassumption is this is the flatMap part
stringifiedNum <- fetch
parsedInt <- parse(stringifiedNum)
// and this yyield statement is the map part
} yield parsedInt match {
case Success(parsedNum) => getPrize(parsedNum)
case Failure => Option.empty[String]
}
}
//rnn.getNum
val int = rnn.getNumV2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment