-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for Argument Splats #47
Comments
Yes, but not in the same way as Ruby. The problem is, we need to know the number and type of arguments at compile time. For example def foo(x, y)
x + y
end
a = [1, 2, 3]
foo *a This in Ruby gives wrong number of arguments at runtime, of course. But how can Crystal know that at compile time? (Crystal is not a dynamic language) The answer is: this will not be possible in Crystal. Instead, we will have a Tuple type. A tuple has a fixed size and each element has a (possible different) type. The syntax will probably be:
You can't add elements to a tuple and (most probably) you can't modify it: it's (most probably) immutable. Because of this the compiler can know the types and length of a tuple and you can use a splat to pass a tuple to a method. For example:
Although this severly reduces the power of the programming language, it allows to pass along splat arguments:
Well... this is just an idea we have, it's not finished and we are still not sure about it. But for sure splats will never work with arrays types. |
Let me see if I understand: def foo(*a)
a
end
x = foo(1,2,3)
p x #=> {1,2,3}
p x.class #=> Tuple |
Yes, exactly. In fact, now that you mention it, doing that makes it unnecessary to have a special syntax for tuples. def tuple(*args)
args
end
x = tuple 1, 2, 3 This is also how it is done in the D programming language: http://dlang.org/tuple.html template Tuple(E...)
{
alias E Tuple;
}
auto tuple = Tuple!(1, 2 , 3); It's also similar to the way you can create a Proc in Ruby: def proc(&block)
block
end
p = proc { ... } Hacky :-P |
👍 Awesome. Looking forward to putting them little tuples to work. |
@trans I just pushed a couple of commits that implement this :-) Since it's so new you might find bugs in it. Also, don't try to combine default values with splats, I'm sure it doesn't work. But, at least, we can do more things now. Soon... named arguments :-D |
All of this, plus named arguments, work since version 0.4 |
Sweet!!! I'll start porting as soon. |
Just beware that splats aren't supported in |
Seeing what Ruby code I can port to Crystal. I see that argument splats cause a compile error
unexpected token: *
Will support for these be coming?
The text was updated successfully, but these errors were encountered: