evhub / coconut

Simple, elegant, Pythonic functional programming.
http://coconut-lang.org
Apache License 2.0
4.04k stars 120 forks source link

Destructuring first and last item #835

Closed MichalMarsalek closed 5 months ago

MichalMarsalek commented 5 months ago

It's often tempting to write

first, *_, last = collection

to extract the first and the last items from a collection. The intended operation should only fail when the collection is empty, however, when written like this, it requires at least 2 items in the collection. Can Coconut be changed to handle the case where there is exactly one item in which case it should be assigned to both first and last?

evhub commented 5 months ago

No, for a couple of reasons.

First, I think there's good reason to fail the match for the one-element sequence, which is that the actual syntax x, *xs, y (or [x] + xs + [y]) could never be used to construct a one-element tuple/list, so it would be counterintuitive if that syntax as a pattern was able to match a one-element sequence.

Second, since Python added its own match syntax, Coconut has aimed for strict compatibility with Python match syntax everywhere Coconut does pattern-matching, and in Python x, *xs, y can only match two-element sequences and above.

If you'd like a simple match syntax that will match either case, try

(first, *_, last) or (first and last) = collection

which you can even wrap into a view pattern if you want

def first_and_last((first, *_, last) or first and last) = (first, last)

first_and_last -> (first, last) = collection