Skip to content

Instantly share code, notes, and snippets.

@mathewsanders
Last active April 25, 2016 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathewsanders/a855abf1b76919372648ed6aa70e54fe to your computer and use it in GitHub Desktop.
Save mathewsanders/a855abf1b76919372648ed6aa70e54fe to your computer and use it in GitHub Desktop.
Array pattern matching
// the types of items that a template can be built up from, in the future I'd be interested in expanding this
// to allow a wider range of options.
enum TemplateItem<T> {
case Exact(T) // matches only this exact element
case Either([T]) // matches any one of the elements given
case LazySequence // matches any sequence of elements
}
// create a template to describe the pattern you want to look for in the array
let moreThanTemplate: [TemplateItem<String>] = [
.Either(["more", "greater"]),
.LazySequence,
.Exact("than"),
.LazySequence
]
// I extended Array with a method with this signature:
// func matches(_: [TemplateItem<Element>]) -> [TemplateMatch<Element>]?
// given a template, it returns nil if there are no matches, otherwise an array of 'TemplateMatch'
// TemplateMatch is just a way to give some structure to results.
// Either indicating a single element, or a sequence of elements
enum TemplateMatch<T> {
case Single(T)
case Sequence([T])
}
// create a text sentence to test the parser
let words = "more large blue shapes than small squares".componentsSeparatedByString(" ")
// if matches is non-nil then the `words` array matches the `moreThanTemplate` format
if let matches = words.matches(moreThanTemplate) {
// check that the order if match items is as expected and at the same time assign components
if case let (.Single, .Sequence(fragment1), .Single, .Sequence(fragment2)) = (matches[0], matches[1], matches[2], matches[3]) {
print("more", fragment1, "than", fragment2)
// more ["large", "blue", "shapes"] than ["small", "squares"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment