Pairs in for loops?

I see x => y-style pairs pop up in new places (e.g., in replace), which can help clarify intent, and the roles of different arguments/variables, among other things. I was representing a binary relation as a set of pairs, and without thinking, I wrote a for loop that used pair syntax to unpack the elements – as in:

for (x => y) in R
    ...
end

This doesn’t work, of course, but perhaps it should? Even for, say, mapping/dictionary iteration? This is used (though with separate syntax) in PHP, for example, where you can use foreach (R as $x => $y), as opposed to the usual foreach (R as $p).

I’m not arguing that we should be able to unpack to arbitrary structs – but Pair is perhaps almost as special as Tuple…? I guess it would make sense to permit this as unpacking syntax in general, such as (x => y) = pop!(R); an issue with that is that it’s currently valid syntax…

2 Likes

(Then again, unpacking arbitrary structs – both in loops and assignments and parameter lists, using constructors that are populated by corresponding fields – would be cool, too. But in this case, we’re even talking about an operator, and not the Pair constructor … and unpacking to arbitrary functions would be taking things a tad too far xD)

I think the general case here is pattern-matching built in to the language.

I believe Jeff has expressed interest in eventually adding something like this to core Julia, but in the mean time @kevin.squire built a package for pattern matching using macros: GitHub - kmsquire/Match.jl: Advanced Pattern Matching for Julia.

Pair is a plain old struct with the infix a => b as an alternate spelling of Pair(a, b), so a solution here should probably be more general than treating Pair or => specially.

Related to your second point, here’s an example of destructuring a struct: Home · Match.jl.

1 Like

Just to make sure you’re aware, the following syntax does unpack elements:

for (x, y) in R
    ...
end
2 Likes

Yes, that’s what I’m using :slight_smile:

1 Like

I find the (existing) tuple destructuring syntax better, since it generalizes to 2+ elements naturally. I am not sure that a parallel syntax would be useful for just one special case (n=2).

It would be specifically for pairs, not iterables in general, I was thinking. But, yeah, just a special case of pattern-matching. I’ll just wait for that maybe showing up at some point :slight_smile:

I guess I formulated that a bit ambiguously. I meant specifically the Pair type.

+1
I would like that too, for consistency. I always find myself having to google for the syntax, as my first attempt is k => v.

1 Like