简体   繁体   中英

How does [ ] work in a function in Clojure?

How does [] work in a function in Clojure?

(def square (fn [x] (* x x)))
(square 10) ; -> 100

As I understand from the above, we pass 10 in the place of x. Shouldn't I be able to do the following?

(def square (fn [x y] (* x y)))
(square 5 10) ; -> 50

In Clojure, [] is used to represent the argument list. That is to say, the anonymous function defined in square takes a single argument and multiplies it against itself.

You can absolutely extend that, but you're probably going to want to change the name of the function to better reflect what it's actually doing instead.

(def multiply (fn [x y] (* x y)))

Some comments on Makoto's answer .

You don't need to name a function in order to use it:

((fn [x] (* x x)) 10) ; 100

((fn [x y] (* x y)) 5 10) ; 50

Anonymous functions often crop up as arguments to higher order function s such as map .

Clojure (and other Lisps) separate the act of making a function as a thing from the act of naming it. def does the naming. A subsequent def for a name erases/obliterates/overwrites an earlier one.

Nor do you need to explicate a function in order to name it. Instead of

(def multiply (fn [x y] (* x y)))

just write

(def multiply *)

There's a lovely explanation of this (for Common Lisp) in Paul Graham's On Lisp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM