Added Sequence.count(predicate)

Returns the number of elements in the sequence that pass the
`predicate`.

It could also have been implemented as:

  count(f) { reduce(0) {|a, b| f.call(b) ? a + 1 : a } }

But I considered the simple version more readable.

Also documented Sequence.count.
This commit is contained in:
Thorbjørn Lindeijer
2015-03-19 21:10:05 +01:00
parent 5e1ddb7db5
commit 94804fe1a0
7 changed files with 52 additions and 2 deletions
+6
View File
@@ -0,0 +1,6 @@
var a = [1, 2, 3]
IO.print(a.count {|x| x > 3 }) // expect: 0
IO.print(a.count {|x| x > 1 }) // expect: 2
IO.print([].count {|x| true }) // expect: 0
@@ -0,0 +1,3 @@
var a = [1, 2, 3]
IO.print(a.count {|x| "truthy" }) // expect: 3
@@ -0,0 +1,3 @@
var a = [1, 2, 3]
a.count("string") // expect runtime error: String does not implement 'call(_)'.