Option[Future[Option[Int]]] => Future[Option[Int]] - scala

Given a Option[Future[Option[Int]]]:
scala> val x: Option[Future[Option[Int]]] = Some ( Future ( Some ( 10 ) ) )
x: Option[scala.concurrent.Future[Option[Int]]] =
Some(scala.concurrent.impl.Promise$DefaultPromise#446a1e84)
I want Future[Option[Int]].
I can pattern match (or use Option#getOrElse):
scala> x match {
| case Some(f) => f
| case None => Future { None }
| }
res6: scala.concurrent.Future[Option[Int]] =
scala.concurrent.impl.Promise$DefaultPromise#446a1e84
scala> res6.value
res7: Option[scala.util.Try[Option[Int]]] = Some(Success(Some(10)))
But, is there a higher-order function that will do the job?
I thought of using sequence, but I don't have an outer type of List:
> :t sequence
sequence :: Monad m => [m a] -> m [a]

Haskell's sequence isn't as generic as it could be, or as generic as Scalaz's (and I'm assuming you're okay with a Scalaz solution since you mention sequence).
Scalaz's sequence (and Haskell's sequenceA in Data.Traversable) only requires that the outer type constructor have a Traverse instance—it doesn't necessarily have to be a list. Option has a Traverse instance, so sequence will work just fine here:
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scalaz._, Scalaz._
def collapse(x: Option[Future[Option[Int]]]): Future[Option[Int]] =
x.sequence.map(_.flatten)
Scalaz also provides an orZero extension method for Option, which would allow you just to write x.orZero, since the zero of Future[Option[Int]] is Future(None).
I'd actually probably use x.getOrElse(Future.successful(None)), though, in this case—it's slightly (probably irrelevantly) more performant, but more importantly it's as clear and almost as concise as the Scalaz options.

Related

When map over a function is useful when you have andThen

With Scalaz, a function can be mapped over another function. When would I want to use map over andThen? Is there a clear advantage using map? Thanks
For example,
val f: Int => Int = (a) => a + 10
val g: Int => Int = (a) => a * 100
(f map g map {_*3})(10) == (f andThen g andThen {_*3})(10) // true
Setting aside implementation details for a moment, map is andThen for functions (under the functor instance for A => ?), and it doesn't really make a lot of sense to talk about preferring one over the other if we're talking about functions specifically and not some higher level of abstraction.
What methods like map (and type classes like Functor more generally) allow us to do is abstract over specific types or type constructors. Suppose we want to write a incrementResult method that works on both A => Int or Kleisli[Option, A, Int], for example. These types don't have anything in common in terms of inheritance (short of AnyRef, which is useless), but A => ? and Kleisli[Option, A, ?] are both functors, so we could write this:
import scalaz._, Scalaz._
def incrementResult[F[_]: Functor](f: F[Int]): F[Int] = f.map(_ + 1)
And then use it like this (note that I'm using kind-projector to simplify the type syntax a bit):
scala> val plainOldFuncTriple: Int => Int = _ * 3
plainOldFuncTriple: Int => Int = <function1>
scala> val optionKleisliTriple: Kleisli[Option, Int, Int] = Kleisli(i => Some(i * 3))
optionKleisliTriple: scalaz.Kleisli[Option,Int,Int] = Kleisli(<function1>)
scala> val f = incrementResult[Int => ?](plainOldFuncTriple)
f: Int => Int = <function1>
scala> val k = incrementResult[Kleisli[Option, Int, ?]](optionKleisliTriple)
k: scalaz.Kleisli[Option,Int,Int] = Kleisli(<function1>)
scala> f(10)
res0: Int = 31
scala> k(10)
res1: Option[Int] = Some(31)
In this case specifically there are better ways to implement this operation, but it shows the general idea—we couldn't write a single method that works for both ordinary functions and Kleisli arrows using andThen, but we can with the extra level of abstraction that map gives us.
So to answer your question—you'd use map if you want to abstract over all type constructors that have a functor instance, but if you're working specifically with functions, map is andThen, and—as long as we're still setting aside implementation details—it doesn't matter which you choose.
Footnote: the map that Scalaz's syntax package gives you for values of types that have functor instances is implemented as an extension method, so there's a tiny bit of overhead (both at compile time and runtime) involved in using map instead of andThen on a function. If you're only working with functions and don't need the extra abstraction, then, you might as well go with andThen.

Wrapping a Monad into a parser - do I need Monad Transformers and how to do it?

I have a monadic type Exp and I want to build a parser that parses into such a value. The following code works, but is there something nicer/cooler I can do?
def grid(x: Int, y: Int): Problem = ???
def expInt: Parser[Exp[Int]] = ???
def grid: Parser[Exp[Problem]] =
for{
ex ~ _ ~ ey <- "grid(" ~> expInt ~ "," ~ expInt <~ ")"
} yield for{
x <- ex
y <- ey
} yield grid(x,y)
I've heard of monad transformers, but still are a bit scared of Scalaz 7's wierd import system. Can someone answer whether
I can use monad transformers and
How this would look like in principle, using Scalaz 7 for a Scala combinator parser wrapping my own Exp Monad.
First for the easy part—the "weird" import system:
import scalaz._, Scalaz._
That's all. This will always work (barring name collisions, of course, but that's a possibility with any library and is easy to resolve), and nobody's going to look down on you for not using the new à la carte imports, which are mainly about documentation.
The basic pattern for monad transformers is that you have a WhateverT[F[_], ...] type class that has a method named runWhateverT (or just run) that returns an F[Whatever[...]].
In this case it looks like you want to end up with a Parser[Exp], which suggests that you need your own ExpT[F[_]] transformer. I won't start with details about how to implement this (which will depend on the semantics of your monad, of course), but will give an example using Scalaz's OptionT:
import scala.util.parsing.combinator._
import scalaz._, Scalaz._
object MyParser extends RegexParsers {
implicit val monad = parserMonad(this)
def oddNumber: OptionT[Parser, Int] = OptionT.optionT(
"\\d+".r ^^ (_.toInt) ^^ (i => (i % 2 != 0) option i)
)
def pairOfOdds: OptionT[Parser, (Int, Int)] = for {
_ <- literal("(").liftM[OptionT]
x <- oddNumber
_ <- literal(",").liftM[OptionT]
y <- oddNumber
_ <- literal(")").liftM[OptionT]
} yield (x, y)
def apply(s: String) = parse(pairOfOdds.run, s)
}
See my question here for some discussion about why we need the implicit val monad = ... line.
It works like this:
scala> MyParser("(13, 43)")
res0: MyParser.ParseResult[Option[(Int, Int)]] = [1.9] parsed: Some((13,43))
scala> MyParser("(13, 42)")
res1: MyParser.ParseResult[Option[(Int, Int)]] = [1.8] parsed: None
Note that oddNumber.run would give us a Parser[Option[Int]] that will parse a string of digits and return either a Some(i) (if they represent an odd number) or a None (if they're even).
We're not actually going to call oddNumber.run, though, in this case—the fact that we're using a monad transformer means that we can compose oddNumber with lifted Parser actions (the literal(...) here) in a single for comprehension.
The syntax here is ugly—we lose the nice ~ combinators and the implicit conversions from String to Parser[String], for example, but we could easily write lifted versions of those things if we wanted.

Iterable[Try[(K, V)]] to Try[Map[K, V]]

I have a method load which is relatively expensive to call. In order to allow some kind of exception handling during loading it returns a Try. I need now an implementation for the loadAll method which basically delegates to load for each of the given keys. Here is my first approach, however I don't know if this is best practices with respect to the work with Try. Is there a better way to achieve the following?
def load(key: K): Try[V] // very expensive
def loadAll(keys: Traversable[K]): Try[Map[K, V]] = {
// remove duplicate keys
val ukeys = Set.empty ++ keys
val result: Iterable[Try[(K, V)]] = ukeys map { key =>
load(key) match {
case Success(value) => Success(key, value)
case Failure(exception) => Failure(exception)
}
}
Try(result.map { _.get }.toMap)
}
You can do this using a fold to iterate over the keys, and a for comprehension to combine the Try instances:
def toSet(keys: Traversable[K]): Try[Map[K, V]] = {
keys.toSet.foldLeft( Try( Map.empty[K, V] ) ){ case (tryMap, key) =>
for ( m <- tryMap; v <- load( key ) ) yield m.updated( key, v )
}
}
It's a one-liner in vanilla Scala (assuming you've already got Try in scope):
def loadAll(keys: Traversable[K]) = Try{ keys.toSet.map((k: K) => (k,load(k).get)).toMap }
If you're interested in a scalaz solution, this is a general operation, available via Traversable functors, called sequence. Needed instances for Try reside in scalaz-contrib. Here's how it might look like:
Welcome to Scala version 2.10.1 (OpenJDK 64-Bit Server VM, Java 1.7.0_21).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import scalaz._, Scalaz._, scalaz.contrib.std.utilTry._
import scalaz._
import Scalaz._
import scalaz.contrib.std.utilTry._
scala> import scala.util.Try
import scala.util.Try
scala> val result: Iterable[Try[(Int, String)]] = Iterable.empty
result: Iterable[scala.util.Try[(Int, String)]] = List()
scala> result.toList.sequence.map(_.toMap)
res0: scala.util.Try[scala.collection.immutable.Map[Int,String]] = Success(Map())
By the way, there's a paper "The essence of the Iterator pattern", describing/deriving traverse (and sequence, as it's special case). There's a great summary of this paper by Eric Torreborre here.

More haskell-like applicative syntax in scalaz

I am experimenting with scalaz. I tried writing code in applicative code. I wrote code like this:
val max: Option[Int] = (a |#| b) { math.max(_, _) }
I didn't like this code very much. I would like to code which is closer to Haskell style, something like this:
val max: Option[Int] = { math.max(_, _) } <$> a <*> b
Is this possible. And why scalaz didn't implement it this way?
Scala's type inference, is much more limited than in Haskell (identifier overloading, which comes with the JVM being one of the reasons). Inferences flows from left to right, and the type of the arguments of a function may be deduced from previous context (if at the place of the definition, a function with arg type A is expected), but not from how they are used in the definition. Scalaz syntax makes the arguments types available. Reversing it would most of the time force you to write the function arguments types, e.g.
{math.max(_: Int, _: Int) } <$> a <*> b
You can translate the Haskell version directly into Scala, if you're willing to be a little more verbose:
import scalaz._, Scalaz._
val a = Option(1)
val b = Option(2)
val f: Int => Int => Int = x => math.max(x, _)
val c = b <*> (a map f)
Or, as a one-liner:
val c = 2.some <*> 1.some.map(x => math.max(x, _: Int))
Or:
val c = 2.some <*> (1.some map (math.max _).curried)
The order is reversed because these are method calls instead of infix operators, but it's essentially the same thing as max <$> a <*> b: we map the function over the first item, and then apply the result to the second.

Is there anything like Haskell's 'maybe' function built into Scala?

What I'm looking for is this function:
def maybe[A, B](a: Option[A])(f: A => B)(g: () => B): B = a match
{
case Some(x) => f(x)
case None => g()
}
It's in the Haskell prelude so I'm thinking it might be in the Scala standard library somewhere and I've just missed it. I hate having to recode it in projects so I'm wondering if anyone knows where it is, or if it's definitively not there. Or is there a better method for getting this functionality?
Other answers have given the map + getOrElse composition. Just for the record, you can "add" a maybe function to Option in the following way:
implicit def optionWithMaybe[A](opt: Option[A]) = new {
def maybe[B](f: A=>B)(g: =>B) = opt map f getOrElse g
}
It's worth noting that the syntax of higher-order functions in Scala is usually nicer when the function parameter comes last. Thus, a better way to organize maybe would be as follows:
def maybe[B](g: =>B)(f: A=>B) = opt map f getOrElse g
This could be used as follows:
val opt: Option[String] = ...
opt.maybe("") { _.toUpperCase }
You could do
val opt:Option[A] = // ...
val result:B = opt.map(f).getOrElse(g());
getOrElse takes a by-name parameter, so g will only be evaluated if opt is None.
The method would be called fold if it were to adhere to convention (see Either.fold which is the catamorphism for Either).
You can use scalaz, and then you have an implicit conversion to OptionW which has fold, or you can use Scala 2.10.0-M3 and use the builtin Option.fold
scala> Some(1).fold(5)(_ * 2)
res5: Int = 2
scala> (None: Option[Int]).fold(5)(_ * 2)
res7: Int = 5
Note that the scalaz fold signature is fold[X](some: A => X, none: => X), while the builtin seems to be fold[X](none: => X)(some: A => X).
I don't think there is. The best I could come up with is to chain Option's "map" and "getOrElse" together:
scala> var a: Option[String] = Some("hello")
a: Option[String] = Some(hello)
scala> a.map(_.toUpperCase).getOrElse("empty")
res19: java.lang.String = HELLO
scala> a = None
a: Option[String] = None
scala> a.map(_.toUpperCase).getOrElse("empty")
res21: java.lang.String = empty
I don't think there is. However, I'd write it to take g by name:
def maybe[A, B](a: Option[A])(f: A => B)(g: => B): B = a.map(f).getOrElse(g)
This is more Scala- and Haskell-like and a bit nicer to use.
I'd use Option.fold for this:
opt.fold(g)(f)
Note that g is by-name, just like getOrElse. Also note the inversion of the cases.