[swift-evolution] pattern matching on variable-sized data type

Anton Zhilin antonyzhilin at gmail.com
Tue Sep 6 10:58:34 CDT 2016


You can process lists using pattern matching today:

enum List<T> {
    case Nil
    indirect case Cons(T, List<T>)
}
let list: List<Int> = .Cons(2, .Cons(3, .Nil))
switch list {
    case .Nil: ...
    case .Cons(let x, .Nil): ...
    case .Cons(let x, .Cons(let y, .Nil)): ...
    default: handleLongList(list)
}

The thing is, such lists are not idiomatic in Swift. Pattern matching on
Array also kind-of works:

let array: Array<Int> = ...
switch array.first {
    case .some(let first):
        processHead(first)
        processTail(array.dropFirst())
    case .none:
        handleNil()
}

Again, it’s not the most idiomatic way to do this in Swift. Also, there is
no guaranteed tail-call optimization.

2016-09-06 17:48 GMT+03:00 Jean-Denis Muys via swift-evolution <
swift-evolution at swift.org>:

Hello,
>
> I would like to suggest an additive evolution to Swift that might be in
> scope of phase 1 of Swift 4 (because it might have an impact on the ABI).
>
> The idea is to extend the pattern matching abilities of Swift to enable a
> recursive programming style that’s very common in languages such as Lisp,
> ML, or Prolog on a collection that is processed as a list. By analogy to
> ML, Swift could do that on tuples, or on arrays, or on any similar, perhaps
> new, data type. This would allow the following for example:
>
​
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160906/786e8524/attachment.html>


More information about the swift-evolution mailing list