Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named parameters functions in Clojure

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?

like image 253
Chiron Avatar asked Sep 17 '26 06:09

Chiron


1 Answers

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).

like image 60
dfan Avatar answered Sep 19 '26 05:09

dfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!