count - Clojure Standard Library

For a quick intro to this series of blog posts check out Clojure Standard Library - Intro. It includes a lot of useful info, including notes about presentation of examples and more.


This posts function:

count

Quick Overview

Description

clojure.core/count is a function that simply returns the number of items that are in a collection.

Examples

(count [1 2 3 4])
; => 4
(count '(1 2 3 4))
; => 4
(count {:one 1 :two 2 :three 3})
; => 3

How To Use

Parameters and Return Values

The interface for count really is very simple. It has a single parameter, coll, which accepts a collection (or string, array, Java Collection, Java Map) who’s items you wish to be counted. count returns a single integer that represents the number of items in the supplied collection.

If you supply it with nil or an empty collection it will return 0.

Ex:

(count "count this")
; => 10
(count ["count" "this" "also"])
; => 3
(count {:all ["of" :us]})
; => 1
(count { :all ["of" :us] :please nil})
; => 2
(count [])
; => 0
(count nil)
; => 0

Expanded Description

Examining Simplified Source Code

(defn count                      ; Name
  [coll]                         ; Parameters
  (clojure.lang.RT/count coll))  ; Function Body

1

Breaking It Down:

The count function basically acts as an alias to the method count from the Java class RT, as clojure.lang.RT/count does all of the actual work.

In case you are not familiar with Java interop in Clojure, clojure.lang.RT/count is a way of accessing the staticmethod count, which is a part of the Java class RT. The expression is structured like this: (ClassName/staticMethod arguments*). 2

If you would like to view the implementation of clojure.lang.RT/count go to clojure/src/jvm/clojure/lang/RT.java in the Clojure GitHub repository and search for public static int count.


Copyright (C) 2016 Steven Cutting - License

  1. To simplify things I removed the metadata map that contained a few things well beyond the scope of this post. To view the full version of count (as of the time this post was written), I have saved a copy here. For the most recent version follow the source link on the clojuredocs count page↩︎

  2. For more information on Java interop in Clojure checkout clojure.org↩︎