Skip to content

The ? operator from regex #41

Answered by alexbbrown
alexbbrown asked this question in Q&A
Discussion options

You must be logged in to vote

Experimenting, I find the answer is: Use the Optional.parser

Here's a worked example of a parser that can accept [1,2,3] or [1,3]:

typealias Input = ArraySlice<Int>

let n = { (v: Int) in
    Prefix<Input>(minLength: 1) {
        $0 == v
    }.map { $0.first! }
}

let data: Input = [1,3]

let parser = n(1)
    .take(Optional.parser(of: n(2)))
    .take(n(3))

let parsed = parser.parse(data)

XCTAssertNotNil(parsed.output)

print(parsed) // output: Optional((1, nil, 3)), rest: ArraySlice([]))

output: does not fail, Optional((1, nil, 3)), rest: ArraySlice([])


feel free to copy this code.

Replies: 1 comment 5 replies

Comment options

You must be logged in to vote
5 replies
@stephencelis
Comment options

@alexbbrown
Comment options

@stephencelis
Comment options

@alexbbrown
Comment options

@stephencelis
Comment options

Answer selected by alexbbrown
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants