public struct State { public let rest: String public let value: T } public prefix func ^(string: String)(_ input: String) -> State? { return input.characters.startsWith(string.characters) ? State(rest: input.from(string.characters.count), value: string) : nil } public prefix func ^(strings: [String])(_ input: String) -> State? { return strings.indexOf { input.characters.startsWith($0.characters) } .flatMap { index in let string = strings[index] return (^string)(input) } } public prefix func ^(strings: S) -> String -> State? { return ^strings.map { String($0) } } /// A convenience for use while developing parsers. public func never(_: String) -> State? { return nil } public func parseWhile(predicate: Character -> Bool)(_ input: String) -> State? { return input.characters.count > 0 && predicate(input.characters[input.startIndex]) ? parseWhile(predicate)(input.from(1)).map { State(rest: $0.rest, value: input.to(1) + $0.value) } ?? State(rest: input.from(1), value: input.to(1)) : nil } public postfix func * (parser: String -> State?) -> String -> State<[T]>? { return (Array.cons <^> (parser <*> { (parser*)($0) })) <|> pure([]) } public postfix func + (parser: String -> State?) -> String -> State<[T]>? { return (Array.cons <^> (parser <*> parser*)) } public func interpolate(element: String -> State?, _ separator: String -> State?) -> String -> State<[Element]>? { return Array.cons <^> (element <*> (separator *> element)*) <|> pure([]) } public func <*> (left: String -> State?, right: String -> State?)(_ input: String) -> State<(T, U)>? { return left(input).flatMap { l in right(l.rest).map { r in State(rest: r.rest, value: (l.value, r.value)) } } } public func <* (left: String -> State?, right: String -> State?) -> String -> State? { return left >>- { const($0) <^> right } } public func *> (left: String -> State?, right: String -> State?) -> String -> State? { return left >>- const(right) } public func <|> (left: String -> State?, right: String -> State?)(_ input: String) -> State? { return left(input) ?? right(input) } public func <^> (left: T -> U, right: String -> State?) -> String -> State? { return right >>- { pure(left($0)) } } public func >>- (left: String -> State?, right: T -> String -> State?)(_ input: String) -> State? { return left(input).flatMap { state in right(state.value)(state.rest) } } public func pure(value: A)(_ input: String) -> State? { return State(rest: input, value: value) }