Stream: helpdesk (published)

Topic: Destructure a Pair


view this post on Zulip Kwaku Oskin (Jun 22 2021 at 08:56):

I guess, I am missing something obvious, but is there any way to destructure a Pair in functions like mean, sum etc?

x = Dict(1 => 2, 3 => 4)

# works
mean(y -> y[2], x)

# not works
mean( (k, v) -> v, x)

Writing y[2] doesn't look very clean

view this post on Zulip Fredrik Ekre (Jun 22 2021 at 08:59):

mean( ((k, v),) -> v, x)

view this post on Zulip Kwaku Oskin (Jun 22 2021 at 09:02):

Ah, good! Thank you.
But now I am thinking, that for such short functions, y[2] is not that bad :-)

view this post on Zulip Kwaku Oskin (Jun 22 2021 at 09:02):

Too many brackets.

view this post on Zulip Alex Ames (Jun 23 2021 at 03:05):

See also first and last, as in mean(y -> last(y), x)

view this post on Zulip Mason Protter (Jun 23 2021 at 05:39):

There's also

mean(x) do (k, v)
    v
end

if the ((k, v),) -> v syntax is too hard to read

view this post on Zulip Kwaku Oskin (Jun 23 2021 at 09:33):

It's not to hard, it's just lengthy.

view this post on Zulip Kwaku Oskin (Jun 23 2021 at 09:34):

I wonder, is there any explanation, why mean((k, v) -> v, d) is not working as expected? Is it a bug or a feature?

view this post on Zulip Fredrik Ekre (Jun 23 2021 at 09:35):

(k, v) -> ... is how you define a two-argument anonymous function.

view this post on Zulip Kwaku Oskin (Jun 23 2021 at 09:41):

Ah, you are right, it's one argument-two elements function.

view this post on Zulip Kwaku Oskin (Jun 23 2021 at 09:41):

Yes, then ((k, v), ) make sense.


Last updated: Nov 22 2024 at 04:41 UTC