Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure length of sequence

I could have sworn I had alength working previously, but I don't quite know what I am doing wrong right now:

user=> (alength '(1 2 3)) IllegalArgumentException No matching method found: alength  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79) user=> (alength [1 2 3]) IllegalArgumentException No matching method found: alength  clojure.lang.Reflector.invokeMatchingMethod (Reflector.java:79) user=> (doc alength) ------------------------- clojure.core/alength ([array])   Returns the length of the Java array. Works on arrays of all   types. nil 

What should I be doing to get the length of a list/array in Clojure?

like image 661
wrongusername Avatar asked Dec 26 '11 01:12

wrongusername


People also ask

What is Lazyseq in Clojure?

Lazy Sequences in Clojure Clojure reference explains laziness as: Most of the sequence library functions are lazy, i.e. functions that return seqs do so incrementally, as they are consumed, and thus consume any seq arguments incrementally as well.

What is a Clojure sequence?

Clojure defines many algorithms in terms of sequences (seqs). A seq is a logical list, and unlike most Lisps where the list is represented by a concrete, 2-slot structure, Clojure uses the ISeq interface to allow many data structures to provide access to their elements as sequences.

How do you do if else in Clojure?

In Clojure, the condition is an expression which evaluates it to be either true or false. If the condition is true, then statement#1 will be executed, else statement#2 will be executed. The general working of this statement is that first a condition is evaluated in the 'if' statement.


2 Answers

Try using count:

(count '(1 2 3)) => 3 (count [1 2 3]) => 3 
like image 81
Óscar López Avatar answered Sep 24 '22 00:09

Óscar López


As the docstring says, alength works on Java™ arrays, such as a String[] or Integer[], which is definitely an incompatible type with Clojure lists or vectors, for which you want to use count:

user=> (def x '(1 2 3)) #'user/x user=> (def xa (to-array x)) #'user/xa user=> (class x) clojure.lang.PersistentList user=> (class xa) [Ljava.lang.Object; user=> (alength xa) 3 user=> (alength x)  java.lang.IllegalArgumentException: No matching method found: alength (NO_SOURCE_FILE:0) user=> (count x) 3 

[Ljava.lang.Object; is the weird way toString is defined to output for native Object arrays.

like image 40
skuro Avatar answered Sep 21 '22 00:09

skuro