Last active
August 29, 2015 14:23
-
-
Save naoty/42365babe3acc1ea9bd6 to your computer and use it in GitHub Desktop.
Simple parser combinator in Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| typealias Parser = String -> (String, String) | |
| func charParser(char: Character) -> Parser { | |
| return { text in | |
| if text[text.startIndex] == char { | |
| return (String(char), text[advance(text.startIndex, 1)..<text.endIndex]) | |
| } | |
| return ("", text) | |
| } | |
| } | |
| infix operator <|> { associativity left precedence 110 } | |
| func <|>(left: Parser, right: Parser) -> Parser { | |
| return { text in | |
| let result = left(text) | |
| if result.0.isEmpty { | |
| return right(text) | |
| } | |
| return result | |
| } | |
| } | |
| infix operator <&> { associativity left precedence 120 } | |
| func <&>(left: Parser, right: Parser) -> Parser { | |
| return { text in | |
| let leftResult = left(text) | |
| let rightResult = right(leftResult.1) | |
| return (leftResult.0 + rightResult.0, rightResult.1) | |
| } | |
| } | |
| let aParser = charParser("a") | |
| let bParser = charParser("b") | |
| let cParser = charParser("c") | |
| let hogeParser = charParser("?") | |
| let parser = aParser <&> bParser <&> (cParser <|> hogeParser) | |
| parser("abcde") //=> ("abc", "de") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment