2

I'm new to Clojure and trying to learn the basics. One thing that tripped me up is understanding the correlation between the data structures and the functions they use.

For instance, if I create a new Vector:

(def my-vec [1 2 3])

Then when I try to call my-vec:

(my-vec)

I get:

ArityException Wrong number of args (0) passed to: PersistentVector  clojure.lang.AFn.throwArity (AFn.java:437)

I know that I can pass an argument and it appears to be calling get but how do I know? What args does PersistentVector take and where do I find documentation about it?

I tried:

(doc PersistentVector)

But that returns nil.

4 Answers 4

4

Documentation can be found under IPersistentVector here: http://clojure.org/data_structures

In particular: Vectors implement IFn, for invoke() of one argument, which they presume is an index and look up in themselves as if by nth, i.e. vectors are functions of their indices.

Sign up to request clarification or add additional context in comments.

2 Comments

That helps! So when I do (my-vec) or (my-vec 1) it calls invoke() which for IPersistentVector calls nth?
1

If you pass a number to a Clojure vector the vector will use that number as an index into it's self and return the value at that index:

user> (def my-vec [1 2 3 4 5])
#'user/my-vec
user> (my-vec 2)
3

this allows you to write expressions like this which grab several keys out of a vec

user> (map my-vec [1 3 4])
(2 4 5)

3 Comments

Hmmm I guess someone got confused with your statement 'look that number up' and that caused a down vote.. Please make it clear that the number is an index and not a value in vector
fixed :) though i suspect someone just down-voted all the answers in this question
Sorry Arthur. I down voted this because it doesn't answer my actual question. My question wasn't about why I was getting an error. It was about how do I find what function is getting called. invoke() is the magic piece that I didn't know about.
-1

You can think of a vector as mapping indexes 0, 1, 2, ..., N to values, one at each index. Abstractly, it's a special case of a map where the keys are integers starting from 0. That notion helps to see the consistency in Clojure between maps and vectors when used as functions:

(<ILookup-able-collection> <key-for-lookup>)

JavaScript does something similar, allowing you to use [] syntax for lookup on arrays or objects.

Comments

-2

my-vec isn't a function, so you should call: my-vec not (my-vec)

Try: (nth my-vec i) for get i-th element of this vector.

link: nth

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.