3

This code discussing named arguments in Clojure from "The Joy of Clojure":

(defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}] 
   (float (/ (- (p2 1) (p1 1))
             (- (p2 0) (p1 0)))))

(slope :p1 [4 15] :p2 [3 21])

The function itself, I understand it -no problem with destructuring- but I don't understand the calling.
Are we passing four arguments to slope? how vectors are getting assigned to :p1 and :p2?

1 Answer 1

8

You are passing four arguments to slope, yes. The [] part of slope specifies the parameters, in which & means "slurp all additional parameters into this form", which then specifies that it is looking for arguments that form a map with keys p1 and p2 (and gives default values if either doesn't exist).

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

2 Comments

I got that but when calling: (slope :p1 [4 15] :p2 [3 21]) how p1 gets the value [4 15] and p2 [3 21] ?
p1 got the value [4 15] because the arguments :p1 [4 15] :p2 [3 21] are treated as a map, and the parameter block in slope says to bind the variables p1 and p2 to their corresponding values in that map.

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.