scala関数コンボレータ

2330 ワード

1、map
リスト内の各要素に関数を計算し、同じ数の要素を含むリストを返します.
scala> numbers.map(_ * 2)res3: Array[Int] = Array(2, 4, 6, 8)
2、foreach
mapと同様にシーケンス内の各要素に対して操作し、異なるのは戻り値がないことです.
scala> numbers.foreach(println(_))1234
3、filter
入力された関数がfalseを返す要素を削除します.Booleanタイプを返す関数は一般的に断言関数と呼ばれます.
scala> numbers.filter(_ % 2 == 0)res5: Array[Int] = Array(2, 4)
4、zip
2つのリストの要素を要素ペアからなるリストに合成します.
scala> Array(1, 2, 3).zip(Array("one", "two", "three"))res6: Array[(Int, java.lang.String)] = Array((1,one), (2,two), (3,three))
5、partition

scala> val numbers = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

scala> numbers.partition(_ % 2 == 0)
res7: (Array[Int], Array[Int]) = (Array(2, 4, 6, 8, 10),Array(1, 3, 5, 7, 9))

6、find

scala> numbers.find(_ > 5)
res8: Option[Int] = Some(6)

7、drop&dropWhile

drop のi を
scala> numbers.drop(3)res9: Array[Int] = Array(4, 5, 6, 7, 8, 9, 10) dropWhile の する の を
scala> numbers.dropWhile(_ % 2 != 0)res11: Array[Int] = Array(2, 3, 4, 5, 6, 7, 8, 9, 10)
8、foldLeft
scala> numbers.foldLeft(0)((a, b) => a + b)res12: Int = 55
0は です
scala> numbers.foldLeft(0){(a, b) => println("a: "+ a + "b: "+ b); a + b}a: 0 b: 1a: 1 b: 2a: 3 b: 3a: 6 b: 4a: 10 b: 5a: 15 b: 6a: 21 b: 7a: 28 b: 8a: 36 b: 9a: 45 b: 10res16: Int = 55
9、foldRight
は とは
10、flatten
flattenはネストされた を することができます
scala> Array(Array(1, 2), Array(3, 4))res17: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4))
scala> Array(Array(1, 2), Array(3, 4)).flattenres18: Array[Int] = Array(1, 2, 3, 4)
11、flatMap
mapとflattenの を み わせています.flatMapはネストされたリストを できる を し、 り を します.
scala> val test = Array(Array(1, 2), Array(3, 4))test: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4))
scala> test.flatMap(x => x.map(_ * 2))
res20: Array[Int] = Array(2, 4, 6, 8)