[swift-evolution] Pattern matching with Arrays
Erica Sadun
erica at ericasadun.com
Thu Dec 22 21:49:38 CST 2016
On Dec 22, 2016, at 8:43 PM, Robert Widmann via swift-evolution <swift-evolution at swift.org> wrote:
>
> Do you think there’s room for a more general Pattern Synonyms-like <https://ghc.haskell.org/trac/ghc/wiki/PatternSynonyms> feature that could extend this to things that look tuple-y? We had a short conversation on Twitter 'round about the release of Swift 1.2 about Swiftz’s HList <https://github.com/typelift/Swiftz/blob/master/Sources/HList.swift#L185> implementation and my desire to be able to destructure them into tuples for native pattern matching.
>
> ~Robert Widmann
>
>> On Dec 22, 2016, at 9:46 AM, Joe Groff via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>
>>>
>>> On Dec 17, 2016, at 9:43 PM, Mathew Sanders via swift-evolution <swift-evolution at swift.org <mailto:swift-evolution at swift.org>> wrote:
>>>
>>> I've just joined the list (hi!) so not sure if this has been discussed in the past.
>>>
>>> Curious to hear if a future version of Swift might ever include some sort of pattern-matching extended to Arrays. Maybe something like the following:
>>>
>>> let numbers: [Int]
>>>
>>> switch numbers {
>>> case []:
>>> // to match an empty array
>>>
>>> case [1, 2, 3]:
>>> // to match array with specific values
>>>
>>> case [_, _, _]:
>>> // to match array with 3 Ints
>>>
>>> case let [first, last]:
>>> // match a 2 element array and bind first and last elements
>>>
>>> case let [first, next...]:
>>> // to match array with at least one element
>>> // bind first element, and bind other elements (could be empty)
>>> // first: Int, next: [Int]
>>> }
>>>
>>> I love the pattern matching on tuples, and would love to see if extend to Arrays as well, but not sure if it fits with future goals for the language.
>>
>> Yeah, this is something I've wanted to add for a while, along with pattern matching for dictionaries, which together with array matching I think would make a lot of JSON/plist wrangling much more pleasant. Since it's an additive feature, it's taken a backseat to more pressing source- and ABI-breaking changes we've wanted to get out of the way first.
I'd be excited to see a feature like this for arrays, dictionaries, and array-like items such as strings. I know that this cannot be addressed for a while, but I'd love to see the idea formalized a bit and placed on a list somewhere so it doesn't just disappear into the aether.
It's a pity we don't have a formal registry for "Some Day" items like this that get mentioned on-list, but don't properly fit into Jira or the SE pull-request queue.
-- E
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20161222/b3fc9887/attachment.html>
More information about the swift-evolution
mailing list