In Clojure, what does `&` mean in function/macro signature?
Asked Answered
A

3

10

I saw the usage of & in Clojure function signature like this (http://clojure.github.io/core.async/#clojure.core.async/thread):

(thread & body)

And this:

(doseq seq-exprs & body)

Does that means the function/macro can accept a list as variable? I also find * is often used to mean multiple parameters can be accepted, like this:

(do exprs*)

Does anyone have ideas about the difference between & and * in function/macro signature? Is there any documentation to explain this syntax?

Anybody answered 15/2, 2016 at 15:20 Comment(0)
M
14

In clojure binding forms (let, fn, loop, and their progeny), you can bind the rest of a binding vector to a sequence with a trailing &. For instance,

(let [[a b & xs] (range 5)] xs) ;(2 3 4)

Uses of * and other uses of & are conventions for documenting the structure of argument lists.

Melodize answered 15/2, 2016 at 15:44 Comment(0)
W
16

It means that there can be multiple parameters after the ampersand, and they will be seen as a seq by the function. Example:

(defn g [a & b]
  (println a b))

Then if you call:

 (g 1 2 3 4)

it will print out 1 (2 3 4) (a is 1, b is a sequence containing 2, 3 and 4).

Warram answered 15/2, 2016 at 15:43 Comment(1)
oh, so it is like the ...rest parameter in JavaScript? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…Solicitude
M
14

In clojure binding forms (let, fn, loop, and their progeny), you can bind the rest of a binding vector to a sequence with a trailing &. For instance,

(let [[a b & xs] (range 5)] xs) ;(2 3 4)

Uses of * and other uses of & are conventions for documenting the structure of argument lists.

Melodize answered 15/2, 2016 at 15:44 Comment(0)
P
1

Does anyone have ideas about the difference between & and * in function/macro signature? Is there any documentation to explain this syntax?

There is no real difference between exprs* and & body. The former some sort of informal description inspired by regular expression and the latter more how it is often written in the code.

Pyridine answered 8/3, 2023 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.