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?
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.
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.
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.
Try using count
:
(count '(1 2 3)) => 3 (count [1 2 3]) => 3
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With