2017-01-04 3 views
-1

Was genau macht die letzte Zeile?Was macht list.count (x => x * x> 1)?

val list = List(-1,0,2,3,5) 
list.count(x => x * x > 1) 

Das Ergebnis ist 3.

+6

Haben Sie die API-Dokumentation für [count] (http://www.scala-lang.org/api/current/scala/collection/immutable/List.html#count (p: A => Boolesch): Int)? –

Antwort

11

Was genau die letzte Zeile ist zu tun?

Es zählt die Anzahl der Elemente in der Auflistung, die für das Prädikat x * x > 1 zutreffen. Die Elemente sind 2, 3 und 5, daher ist das Ergebnis 3.

1

count() nimmt Prädikat. Die Elemente, für das Prädikat true zurück, werden also hier gezählt sind Sie einfaches Zählen Elemente, für die

n * n > 1 

Ihre Liste enthält: -1,0,2,3,5

-1 * -1 = 1 
0 * 0 = 0 
2 * 2 = 4 > 1 
3 * 3 = 9 > 1 
5 * 5 = 25 > 1 

Und das Warum ist das Ergebnis 3 :)