Questions tagged «for-comprehension»

5
与对FlatMap / Map转换的理解相混淆
我真的似乎不太了解Map和FlatMap。我无法理解的是理解力是对map和flatMap的一系列嵌套调用的序列。以下示例来自Scala中的Functional Programming def bothMatch(pat:String,pat2:String,s:String):Option[Boolean] = for { f <- mkMatcher(pat) g <- mkMatcher(pat2) } yield f(s) && g(s) 转换为 def bothMatch(pat:String,pat2:String,s:String):Option[Boolean] = mkMatcher(pat) flatMap (f => mkMatcher(pat2) map (g => f(s) && g(s))) mkMatcher方法的定义如下: def mkMatcher(pat:String):Option[String => Boolean] = pattern(pat) map (p => (s:String) => p.matcher(s).matches) 图案方法如下: import java.util.regex._ def …


4
Scala上的类型不匹配以进行理解
为什么这种构造会在Scala中导致类型不匹配错误? for (first <- Some(1); second <- List(1,2,3)) yield (first,second) <console>:6: error: type mismatch; found : List[(Int, Int)] required: Option[?] for (first <- Some(1); second <- List(1,2,3)) yield (first,second) 如果我用列表切换Some,它可以很好地编译: for (first <- List(1,2,3); second <- Some(1)) yield (first,second) res41: List[(Int, Int)] = List((1,1), (2,1), (3,1)) 这也可以正常工作: for (first <- …
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.