[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Unpack Operator
- From: Paige DePol <lual@...>
- Date: Sat, 10 Feb 2018 12:49:31 -0600
Benoît de Chezelles <benoit.dechezelles@gmail.com> wrote:
> I'm not sure what you mean, but what you're suggesting is possible in
> Crystal, for
> example the code:
So the "splat" qualifier is actually an operator as well? I missed the
line that sort of intimated at this possibility and thought that the
symbol was a variable qualifier for function parameters only.
Additionally, a call argument can have a splat (*) or double splat (**).
A splat expands a Tuple into positional arguments, while a double splat
expands a NamedTuple into named arguments. Multiple argument splats and
double splats are allowed.
So this splat and double splat are essentially unpack operators, which
was the original title and discussion topic of this thread. Nice!
> #-----------------------
> def foo(x, y, z, a = 1, b = 2, c = 3)
> puts "#{x}, #{y}, #{z}, #{a}, #{b}, #{c}"
> end
>
> foo 1, 2, 3, 4, 5, 6
Okay, my reading of the documentation last night lead me to believe there
should be an error that there was no named argument 'a', so how is 4, 5, 6
being assigned to a, b, c in this example?
Oh wait, it's because in this case a, b, c aren't named parameters they are
just positional ones with default values. I see. My bad. Sigh!
So then that does make sense, sorry Sean, I totally was thinking that a, b,
c were named arguments not positional parameters in these specific examples.
As there is no way to easily determine where positional and named parameters
start and stop that is why they use a solo 'splat' marker.
> foo x: 1, y: 2, z: 3, a: 4, b: 5, c: 6
> foo *{1, 2, 3, 4, 5, 6}
> foo **{x: 5, y: 6, z: 7}
So in Crystal you can create tuples using the same syntax we use
for tables in Lua then? Good to know, guess I should have clicked
on the links for Tuple and NamedTuple! And in these cases the
created tuple is just being created and unpacked... that doesn't
seem the most terribly efficient method for passing arguments.
> puts "You could mix things up"
>
> (live at https://carc.in/#/r/3jwq)
Thanks for the live example, that helped to clarify things. The
previous post of mine would have all made sense were the a, b ,c
arguments named and not positional... I still like the syntax
though having to have a solo splat on all functions without any
positional arguments is a bit of a wart.
Obviously, I missed the importance of the solo splat as a way
to separate the two styles of parameters. Because a, b, c had
default parameters I was thinking they were named parameters.
Again, Sean, sorry... I had just misunderstood the syntax s
your examples were correct and my clarifications were not! :(
~Paige