Scala Collections集合のいくつかの重要な概念

1964 ワード

いくつかの重要な概念
述語は何ですか(What a predicate is)
A predicate is simply a method, function, or anonymous function that takes one or more parameters and returns a Boolean value. For instance, the following method returns true or false, so it’s a predicate:
def isEven (i: Int) = if (i % 2 == 0) true else false

述語は1つの方法で、1つの関数、1つの匿名の関数は1つ以上のパラメータを受け入れて、1つのBoolean値を返して、上のような関数の戻り値はtrueあるいはfalseで、だからそれは1つの述語です
匿名関数(What an anonymous function is):
The concept of an anonymous function is also important. here’s an example of the long form for an anonymous function:
(i: Int) => i % 2 == 0

Here’s the short form of the same function:
_ % 2 == 0

匿名関数は重要な概念であり、上の最初のセグメントのコードは完全な匿名関数の例であり、次の簡略化版の例であり、彼らは似ていないように見えますが、集合でfilterメソッドを使用すると、この短いコードは非常に強力になります.
scala> val list = List.range(1, 10)
list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
scala> val events = list.filter(_ % 2 == 0) 
events: List[Int] = List(2, 4, 6, 8)

暗黙サイクル(Implied loops)
This is a nice lead-in into the third topic: implied loops. As you can see from that example, the filter method contains a loop that applies your function to every element in the collection and returns a new collection. You could live without the filter method and write equivalent code like this:ここでは暗黙的なループを導入しました.前の例で見たようにfilterメソッドにはループが含まれており、コレクション内の各要素を巡り、新しいコレクションを返します.filterメソッドを使用して次のコードでこの機能を実装する必要はありません.
for {
    e 

But I think you’ll agree that the filter approach is both more concise and easier to read. しかし、filterは簡素で読みやすいと思います.Collection methods like filter、foreach、map、reduceLeft、and many more have loops built into their algorithms.As a result, you’ll write far fewer loops when writing Scala code than with another language like Java. filter、foreach、map、reduceLeftなどの多くの類似の集合方法は、暗黙的なループを有する.だからJAVAに比べて、Scalaは多くのサイクルを書くことができます.