Stream: helpdesk (published)

Topic: what is the lonely `,` doing in the parameter list?


view this post on Zulip Peter Goodall (Jul 20 2021 at 05:39):

scalex(α) = ((x,y),) -> (α*x, y)

view this post on Zulip Brenhin Keller (Jul 20 2021 at 05:42):

Ah, that , in the outer parens denotes that you want to construct a tuple:

julia> ((1,2),)
((1, 2),)

julia> typeof(ans)
Tuple{Tuple{Int64, Int64}}

julia> ((1,2))
(1, 2)

julia> typeof(ans)
Tuple{Int64, Int64}

view this post on Zulip Brenhin Keller (Jul 20 2021 at 05:46):

And in the context of this function definition seems to denote that you mean to pull a tuple of (x,y) _out_ of the argument to scalex. I.e.:

julia> scalex(α) = ((x,y),) -> (α*x, y)
scalex (generic function with 1 method)

julia> scalex(5)([1,2])
(5, 2)

julia> scalex(α) = (x,y) -> (α*x, y)
scalex (generic function with 1 method)

julia> scalex(5)(1,2)
(5, 2)

julia> scalex(5)([1,2])
ERROR: MethodError: no method matching (::var"#5#6"{Int64})(::Vector{Int64})
Closest candidates are:
  (::var"#5#6")(::Any, ::Any) at REPL[16]:1
Stacktrace:
 [1] top-level scope
   @ REPL[18]:1

view this post on Zulip Peter Goodall (Jul 20 2021 at 05:54):

i can see it happening, but not why.

  1. Is it related to the function being a lambda expressions on the arguments?
  2. Why use a lambda expression here?

I was just tinkering with tuple arguments and the splat operator, and was going really well until I saw that comma:
f₈(x,y,z) = 5sin(xy) + 2y/4z
f₈(v)=f₈(v...)
and
f₉((x,y,z)) = 5sin(xy) + 2y/4z
f₉(x,y,z)=f₉((x,y,z))
w = (1,2,3)
f₉(w...),f₉(w)

view this post on Zulip Brenhin Keller (Jul 20 2021 at 06:10):

Yeah, so

((x,y),) -> (α*x, y)

is just fancy lambda syntax equivalent to

function (tpl)
    x,y = tpl
    return α*x, y
end

and the whole thing is equivalent to

function scalex(α)
    function (tpl)
       x,y = tpl
       return α*x, y
    end
end

view this post on Zulip Peter Goodall (Jul 20 2021 at 06:43):

OK thanks... I can see the tuple literal with the lonely , being equivalent to the function parameters declaration.

view this post on Zulip Patrick Toche (Jul 27 2021 at 04:37):

A tuple of one element takes a trailing comma. Otherwise the parentheses would be interpreted as grouping operations together.


Last updated: Nov 06 2024 at 04:40 UTC