リストを反復し、そこからリスト内のオブジェクトに基づいて複数のリストを生成する必要があるシナリオを考えると、命令型アプローチの使用を避けずにこれを行う方法を理解できません。より具体的に言うと、アイテム [a、b、c、d] のリストがあり、アイテムの異なる属性に基づいて 3 つの新しいリストを作成したいとします: [a1、b1、c1、d1]、[a2、 b2、c2、d2]、[a3、b3、c3、d3]。
以下の簡単な例を作成しましたが、これはおそらくJavaで行う方法ですが、命令型スタイルを避けながらこれを行う方法を誰かが推奨できるかどうか疑問に思っていますか?
case class Atom(nuc: Int, prot: Int, neut: Int)
class Splitter(list: Array[Atom]) {
val nucs: ArrayBuffer[(Int, Int)] = ArrayBuffer()
val prots: ArrayBuffer[(Int, Int)] = ArrayBuffer()
val neuts: ArrayBuffer[(Int, Int)] = ArrayBuffer()
list foreach { atom =>
nucs += (atom.nuc -> atom.nuc * 3)
prots += (atom.prot -> atom.prot * 4)
neuts += (atom.neut -> atom.neut * 5)
}
}