for-comprehension

How to convert this map/flatMap into a for comprehension in Scala?

ぃ、小莉子 提交于 2019-12-18 11:53:19
问题 How to convert this map/flatMap into a for comprehension, and please explain how it works, thanks. def compute2(maybeFoo: Option[Foo]): Option[Int] = maybeFoo.flatMap { foo => foo.bar.flatMap { bar => bar.baz.map { baz => baz.compute } } } 回答1: Your code can be translated into this: def compute2(maybeFoo: Option[Foo]): Option[Int] = for { foo <- maybeFoo bar <- foo.bar baz <- bar.baz } yield baz.compute Quotes from Programming in Scala, Second Edition: Generally, a for expression is of the

Confused with the for-comprehension to flatMap/Map transformation

╄→尐↘猪︶ㄣ 提交于 2019-12-17 03:22:05
问题 I really don't seem to be understanding Map and FlatMap. What I am failing to understand is how a for-comprehension is a sequence of nested calls to map and flatMap. The following example is from Functional Programming in Scala def bothMatch(pat:String,pat2:String,s:String):Option[Boolean] = for { f <- mkMatcher(pat) g <- mkMatcher(pat2) } yield f(s) && g(s) translates to def bothMatch(pat:String,pat2:String,s:String):Option[Boolean] = mkMatcher(pat) flatMap (f => mkMatcher(pat2) map (g => f

Generalised lazy permutations in Scala

独自空忆成欢 提交于 2019-12-13 08:30:05
问题 I want to create a generic permutations function. def permutation(size: Int): Stream[List[Int]] = ... permutation(1) # same as: for { x <- (1 to 10).toStream } yield List(x) permutation(2) # same as: for { x <- (1 to 10).toStream; y <- (1 to 10).toStream; } yield List(x,y) Can I get dynamically nested for-comprehensions behavior on the fly for arbitrary depth . 回答1: I think this gives a generalised version of what you are asking for: def permutation[X](iter: Iterable[X], len: Int) = { def acc

Scala async/callback code rewriting

混江龙づ霸主 提交于 2019-12-12 10:42:43
问题 Simple code that should check user by pass, user is active and after that update last login datetime. def authenticate() = Action.async { implicit request => loginForm.bindFromRequest.fold( errors => Future.successful(BadRequest(views.html.logon(errors))), usersData =>{ val cursor = this.collection.find(BSONDocument("name" -> usersData._1)).one[Account].map(_.filter(p=>p.password == hashedPass(usersData._2, usersData._1))) cursor.flatMap(p => p match { case None => Future.successful

Scala Pattern: For Comprehension that Yields a Future[A]

橙三吉。 提交于 2019-12-12 04:24:59
问题 What is the pattern used in Scala to deal with the scenario: You have a bunch of futures (they can be whatever, but for the sake of example...) val aF = Future { true } val bF = Future { Option(3) } val cF = Future { myObject } and you have some function that returns a future def fooF: Future[SomeObject] I want to do something like: for { a <- aF b <- bF c <- cF } yield { if (a) { // do stuff with b & c fooF } else { Future.successful(SomeObject) } } I want to return a value of Future

Strange (?) for comprehension evaluation in Scala

这一生的挚爱 提交于 2019-12-10 16:30:15
问题 Now, it took me a while to figure out why my recursion is somehow managing to blow the stack. Here it is, the part causing this problem: scala> for { | i <- List(1, 2, 3) | j = { println("why am I evaluated?"); 10 } if false | } yield (i, j) why am I evaluated? why am I evaluated? why am I evaluated? res0: List[(Int, Int)] = List() Isn't this, like, insane? Why at all evaluate j = ... if it ends in if false and so will never be used? What happens when instead of { println ... } you have a

Can I use for-comprehenion / yield to create a map in Scala?

試著忘記壹切 提交于 2019-12-08 23:39:26
问题 Can I "yield" into a Map? I've tried val rndTrans = for (s1 <- 0 to nStates; s2 <- 0 to nStates if rnd.nextDouble() < trans_probability) yield (s1 -> s2); (and with , instead of -> ) but I get the error TestCaseGenerator.scala:42: error: type mismatch; found : Seq.Projection[(Int, Int)] required: Map[State,State] new LTS(rndTrans, rndLabeling) I can see why, but I can't see how to solve this :-/ 回答1: scala> (for(i <- 0 to 10; j <- 0 to 10) yield (i -> j)) toMap res1: scala.collection

Why does this list-of-futures to future-of-list transformation compile and work?

旧时模样 提交于 2019-12-07 03:29:13
问题 Disclaimer: the code snippet below relates to one of ongoing Coursera courses. Let's consider it's posted just for a learning purpose and should not be used for submitting as a solution for one's homework assignment. As the comment below states, we need to transform a list of Futures to a single Future of a list. More than that, the resulting Future should fail if at least one of input futures failed. I met the following implementation and I don't understand it completely. /** Given a list of

What are the scoping rules for vals in Scala for-comprehensions

六月ゝ 毕业季﹏ 提交于 2019-12-07 03:06:05
问题 When I use a val in a for-comprehension, I get the warning: warning: val keyword in for comprehension is deprecated despite the production in the syntax appendix of the spec. This suggests that when I do something like for (x <- xs; a = x) I'm not really introducing a variable, such as if I do something like for (x <- xs) yield { implicit val a = x; /* more */ } where, as usual, the brace starts a new scope where I can introduce a new val, or even a new implicit. What am I really doing with

Use 4 (or N) collections to yield only one value at a time (1xN) (i.e. zipped for tuple4+)

半城伤御伤魂 提交于 2019-12-07 02:32:28
问题 scala> val a = List(1,2) a: List[Int] = List(1, 2) scala> val b = List(3,4) b: List[Int] = List(3, 4) scala> val c = List(5,6) c: List[Int] = List(5, 6) scala> val d = List(7,8) d: List[Int] = List(7, 8) scala> (a,b,c).zipped.toList res6: List[(Int, Int, Int)] = List((1,3,5), (2,4,6)) Now: scala> (a,b,c,d).zipped.toList <console>:12: error: value zipped is not a member of (List[Int], List[Int], List[Int], List[Int]) (a,b,c,d).zipped.toList ^ I've searched for this elsewhere, including this