Scala: Producing the intermediate results of a fold

前端 未结 4 1012
忘了有多久
忘了有多久 2020-12-28 08:52

I\'ve come across the problem of maintaining a state throughout a map operation several times. Imagine the following task:

Given a List[Int], map each element to the

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 09:31

    The scan answers are the best ones, but it's worth noting that one can make the fold look nicer and/or be shorter than in your question. First, you don't need to use pattern matching:

    a.foldLeft(List(0)){ (l,i) => (l.head + i) :: l }.reverse
    

    Second, note that foldLeft has an abbreviation:

    (List(0) /: a){ (l,i) => (l.head + i) :: l }.reverse
    

    Third, note that you can, if you want, use a collection that can append efficiently so that you don't need to reverse:

    (Vector(0) /: a){ (v,i) => v :+ (v.last + i) }
    

    So while this isn't nearly as compact as scanLeft:

    a.scanLeft(0)(_ + _)
    

    it's still not too bad.

提交回复
热议问题