Real World Functional Programming in Scala

The key to functional programming is abstraction, and composability of abstractions. Monads, Arrows, Lenses, these are all abstractions which have proven themselves useful, mostly because they are composable. You’ve asked for a “prescriptive” answer, but I’m going to say no. Perhaps you’re not convinced that functional programming matters? I’m sure plenty of people on StackOverflow … Read more

Traversing lists and streams with a function returning a future

I cannot answer it all, but i try on some parts: Is there some reason that the “most asynchronous” behavior—i.e., don’t consume the collection before returning, and don’t wait for each future to complete before moving on to the next—isn’t represented here? If you have dependent calculations and a limited number of threads, you can … Read more

How to understand traverse, traverseU and traverseM

sequence is used to gather together applicative effects. More concretely, it lets you “flip” F[G[A]] to G[F[A]], provided G is Applicative and F is Traversable. So we can use it to “pull together” a bunch of Applicative effects (note all Monads are Applicative): List(Future.successful(1), Future.successful(2)).sequence : Future[List[Int]] // = Future.successful(List(1, 2)) List(4.set(“abc”), 5.set(“def”)).sequence : Writer[String, … Read more

Using Scalaz Stream for parsing task (replacing Scalaz Iteratees)

A scalaz-stream solution: import scalaz.std.vector._ import scalaz.syntax.traverse._ import scalaz.std.string._ val action = linesR(“example.txt”).map(_.trim). splitOn(“”).flatMap(_.traverseU { s => s.split(” “) match { case Array(form, pos) => emit(form -> pos) case _ => fail(new Exception(s”Invalid input $s”)) }}) We can demonstrate that it works: scala> action.collect.attempt.run.foreach(_.foreach(println)) Vector((no,UH), (,,,), (it,PRP), (was,VBD), (n’t,RB), (monday,NNP), (.,.)) Vector((the,DT), (equity,NN), (market,NN), (was,VBD), … Read more

Unexpected implicit resolution based on inference from return type

1) After rewriting your code as follows: case class Monoid[A](m0: A) // We only care about the zero here implicit def s[T] : Monoid[Set[T]] = Monoid(Set.empty[T]) implicit def l[T] : Monoid[List[T]] = Monoid(List.empty[T]) def mzero[A]()(implicit m: Monoid[A]) : A = m.m0 val zero = mzero[List[Int]]() val zero2: List[Int] = mzero() then becomes clearly why that … Read more

How to reduce Seq[Either[A,B]] to Either[A,Seq[B]]?

Edit: I missed that the title of your question asked for Either[Seq[A],Seq[B]], but I did read “I’d like to obtain the first error message or a concatenation of all error messages”, and this would give you the former: def sequence[A, B](s: Seq[Either[A, B]]): Either[A, Seq[B]] = s.foldRight(Right(Nil): Either[A, List[B]]) { (e, acc) => for (xs … Read more