代码之家  ›  专栏  ›  技术社区  ›  Aavik

scala:scala如何将foldLeft转换为curring函数

  •  0
  • Aavik  · 技术社区  · 6 年前

    下面的例子中,有人能解释一下在foldleft中是如何发生电流的吗?

    val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    >numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    val numberFunc = numbers.foldLeft(List[Int]())_
    >numberFunc: ((List[Int], Int) => List[Int]) => List[Int] 
    

    我的理解是:

    (List[Int], Int) - (accumulator which in this case is empty List, each element of the numbers list)
    => List[Int]     - which is the output numberFunc list.
    => List[Int]     - what does this represent? 
    

    谢谢。

    1 回复  |  直到 6 年前
        1
  •  3
  •   Andrey Tyukin    6 年前

    一步一步地:

    • foldLeft 在一 List[A] 有签名 foldLeft[B](b: B)(f: (B, A) => B): B
    • 因此,一般来说, list: List[A] b: B ,课程表达式 list.foldLeft(b) _ 会有类型 ((B, A) => B) => B
    • numbers 具有类型 List[Int] 因此 A 被推断为 Int
    • List[Int]() 具有类型 列表[int] 因此 B 被推断为 列表[int]
    • 替代 int 对于 列表[int] 对于 在里面 (b,a)=>b)=>b ,你得到 (List[Int], Int) => List[Int]) => List[Int] . 这正是编译器给你的。

    大写:

      (numberFunc :                       // `numberFunc` is a function that
         (                                // given a function that
           (List[Int], Int)               //   takes an accumulator and an int
           =>                             //   and produces 
           List[Int]                      //   an updated list of ints
         )
         =>                               // produces
         List[Int]                        // a list of ints
      )