@@ -938,12 +938,15 @@ end
938938_bool (f) = x-> f (x):: Bool
939939
940940"""
941- count(p, itr) -> Integer
942- count(itr) -> Integer
941+ count([f=identity,] itr; init=0) -> Integer
943942
944- Count the number of elements in `itr` for which predicate `p` returns `true`.
945- If `p` is omitted, counts the number of `true` elements in `itr` (which
946- should be a collection of boolean values).
943+ Count the number of elements in `itr` for which the function `f` returns `true`.
944+ If `f` is omitted, counts the number of `true` elements in `itr` (which
945+ should be a collection of boolean values). `init` optionally specifies the value
946+ to start counting from and therefore also determines the output type.
947+
948+ !!! compat "Julia 1.6"
949+ `init` keyword was added in Julia 1.6.
947950
948951# Examples
949952```jldoctest
@@ -952,32 +955,35 @@ julia> count(i->(4<=i<=6), [2,3,4,5,6])
952955
953956julia> count([true, false, true, true])
9549573
958+
959+ julia> count(>(3), 1:7, init=0x00)
960+ 0x04
955961```
956962"""
957- count (itr) = count (identity, itr)
963+ count (itr; init = 0 ) = count (identity, itr; init )
958964
959- count (f, itr) = _simple_count (f, itr)
965+ count (f, itr; init = 0 ) = _simple_count (f, itr, init )
960966
961- function _simple_count (pred, itr)
962- n = 0
967+ function _simple_count (pred, itr, init :: T ) where {T}
968+ n:: T = init
963969 for x in itr
964970 n += pred (x):: Bool
965971 end
966972 return n
967973end
968974
969- function count (:: typeof (identity), x:: Array{Bool} )
970- n = 0
975+ function _simple_count (:: typeof (identity), x:: Array{Bool} , init :: T = 0 ) where {T}
976+ n:: T = init
971977 chunks = length (x) ÷ sizeof (UInt)
972978 mask = 0x0101010101010101 % UInt
973979 GC. @preserve x begin
974980 ptr = Ptr {UInt} (pointer (x))
975981 for i in 1 : chunks
976- n += count_ones (unsafe_load (ptr, i) & mask)
982+ n = (n + count_ones (unsafe_load (ptr, i) & mask)) % T
977983 end
978984 end
979985 for i in sizeof (UInt)* chunks+ 1 : length (x)
980- n += x[i]
986+ n += x[i] % T
981987 end
982988 return n
983989end
0 commit comments