clojure - Error while trying to get first element of sequence by index in a function call -
i've encountered problem while doing task 4clojure.com. here description of task:
write function returns last element in sequence.
i've solved using following code:
#(first (reverse %)) when wanted change first function number of index. so:
#(0 (reverse %)) i've received error:
java.lang.classcastexception: java.lang.long cannot cast clojure.lang.ifn
my question is: why receiving error? cannot it, because instance ([1 2 3 4] 0) valid , returns first element of sequence why cannot use index of array in function?
edit1: following code not work , suppose apersistentvector first there.
#((reverse %) 0) edit2: managed make work converting list returned reverse function vector. @josh
(#((vec (reverse %)) 0)[1 2 3])
if @ code apersistentvector, see:
public abstract class apersistentvector extends afn ... afn implements ifn, extends java's callable , runnable interfaces, means clojure persistent vector can called function, argument being used index retrieve. can see here:
public object invoke(object arg1) { if(util.isinteger(arg1)) return nth(((number) arg1).intvalue()); throw new illegalargumentexception("key must integer"); } the same true maps , sets; can invoked functions:
({:a 1 :b 2} :b) ;; 2 (#{:a :b} :a) ;; :a ([1 2 3 4] 0) ;; 1 however, long (your number zero) not implement ifn:
(ancestors (class 42)) => #{java.lang.comparable java.lang.number java.lang.object java.io.serializable} hence, cannot invoked function.
Comments
Post a Comment