【问题标题】:Parameters for a foldleft on list of futures期货列表上的左折叠参数
【发布时间】:2014-10-23 09:37:19
【问题描述】:

我想在 Futures 上试验 foldleft。我从一个简单/愚蠢的示例作为工作表开始:

import scala.concurrent._
import ExecutionContext.Implicits.global

val list = (1 to 10).toList
def doubleFuture(i: Int) = Future { println(i);i }

val twoFutures = list map doubleFuture //returns List[Future[Int]]
val res = (twoFutures foldLeft(List[Int]())
    ((theList:List[Int], aFuture:Future[Int]) =>
    {
      theList :+ 1
    }))

编译器对此不满意并指出:

Error:(11, 48) type mismatch;
 found   : (List[Int], scala.concurrent.Future[Int]) => List[Int]
 required: Int
    ((theList:List[Int], aFuture:Future[Int]) =>
                                          ^

我不明白为什么 foldleft 函数的第二个参数不是 Future[Int] 类型,因为 twoFutures 是 List[Future[Int]] 类型。 你能解释一下有什么问题吗?

谢谢!

【问题讨论】:

    标签: scala


    【解决方案1】:

    您需要在列表后使用句点 (.) 告诉编译器括号后的块或括号绑定到 foldLeft 而不是 twoFutures

    import scala.concurrent._
    import ExecutionContext.Implicits.global
    
    object FutureList {
      def main(args: Array[String]) {
        val list = (1 to 10).toList
        def doubleFuture(i: Int) = Future { println(i); i }
    
        val twoFutures = list map doubleFuture //returns List[Future[Int]]
    
        val res = twoFutures.foldLeft(List[Int]())(
          (theList, aFuture) => theList :+ 1)
    
        println(res)
    
        // Uncomment these lines to unfold the mystery
        //    val theList = List[Int]()
        //    val aFuture = Future[Int](0)
        //    twoFutures((theList: List[Int], aFuture: Future[Int]))
    
      }
    }
    

    为了解释它的含义,您可以取消注释上面的三个注释行。您将看到与没有twoFutures 列表之后的句点相同的编译错误:

     Multiple markers at this line
        - type mismatch; found : (List[Int], scala.concurrent.Future[Int]) required: 
         Int
        - type mismatch; found : (List[Int], scala.concurrent.Future[Int]) required: 
         Int
    

    输出

    2
    4
    1
    3
    5
    6
    8
    10
    7
    9
    List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    

    【讨论】:

    • 这让我想起了 ;在我做 C++ 并且我看不到的 if 之后:-) - 我认为编译器在这里可能会更有帮助。但你却是。谢谢!
    【解决方案2】:

    这个解决方案使用左折叠的点符号,即

    val res = (twoFutures.foldLeft(List[Int]())
        ((theList:List[Int], aFuture:Future[Int]) =>
        {
          theList :+ 1
        }))
    

    【讨论】:

      猜你喜欢
      • 2011-11-15
      • 2014-05-09
      • 2013-04-13
      • 2014-09-03
      • 1970-01-01
      • 2020-03-03
      • 2017-04-11
      • 2019-07-24
      • 2020-05-04
      相关资源
      最近更新 更多