I first encountered the spread (...
) syntax in JavaScript, and have grown to appreciate the many things it can do, but I confess I still find it quite bizarre. Is there an equivalent in other languages, and what is it called there?
Asked
Active
Viewed 1,097 times
5

Patrick Roberts
- 49,224
- 10
- 102
- 153

Danyal Aytekin
- 4,106
- 3
- 36
- 44
-
1Groovy has a spread operator: http://groovy-lang.org/operators.html#_spread_operator. It's functionality is quite different though. – May 04 '18 at 16:29
-
1To be precise, the spread syntax is *not* an "operator". The term "operator" has a specific meaning in the expression grammar, and the spread syntax isn't part of that. – Pointy May 04 '18 at 16:33
-
1The [Go language](http://golang.org) allows this as a means of implementing variadic functions. I prefer its form, where in the "receiving" position (parameters), the `...` comes before the type ident, and in the "sending" positions (arguments), it comes after the values. `func foo(bar string, rest ...string) { /***/ }` ... `foo("bar", myStrings...)` – May 04 '18 at 16:41
3 Answers
2
Yes, in Ruby: the splat operator. It's an asterisk instead of three dots:
def foo(a, *b, **c)
[a, b, c]
end
> foo 10
=> [10, [], {}]
> foo 10, 20, 30
=> [10, [20, 30], {}]
> foo 10, 20, 30, d: 40, e: 50
=> [10, [20, 30], {:d=>40, :e=>50}]
> foo 10, d: 40, e: 50
=> [10, [], {:d=>40, :e=>50}]
(Copied from this answer)

kwyntes
- 1,045
- 10
- 27
-
2
-
1JavaScript is the only language I know that uses three dots instead of an asterisk... I think it's because [JavaScript already uses the asterisk somewhere else](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function%2A), but I don't know for sure. – kwyntes May 05 '18 at 09:05
2
Common Lisp has &rest
parameters:
(defun do-something (&rest params)
...
)

Barmar
- 741,623
- 53
- 500
- 612
-
1But can you do something like `(+ 1 2 3 ...params)` without using something like `apply`, because that would be pretty sweet. – Meow May 08 '18 at 05:21
-
1@Meow No, Lisp doesn't have that. You can do it with data using backquote: `(1 2 3 ,@params)`, but not with function parameters. – Barmar May 08 '18 at 18:17
1
PHP has it too, using the three dots: it is a new feature of PHP version 5.6. The operator looks like a ellipsis (…) character but it is not.

Cie6ohpa
- 815
- 1
- 10
- 13