4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scala: Listで前後の値を参照した処理の記述

Last updated at Posted at 2015-02-25

ScalaでList(1, 2, 3, 4, 5)というリストがあったときに、(1, 2), (2, 3), (3, 4), (4, 5)と前後2つペアにして、List(3, 5, 7, 9)のような足し算の処理になるような式の書き方。

varとかforとかを使えばできるけどスマートじゃないし負けた気がするので、考えたらIterable#zipを使った方法を思いついた、Seqでも同じはず。

val list = List(1, 2, 3, 4, 5)

(list.init zip list.tail).map{ case (a, b) => a + b }

もっと楽な方法があれば教えて下さい。

4
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?