Created
April 4, 2015 01:07
-
-
Save JRHeaton/d6229b710085625cc22d to your computer and use it in GitHub Desktop.
learning about parser combinators (this is likely wrong code)
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
| struct Parser<Input: CollectionType, Output> { | |
| typealias Function = (Input, Input.Index) -> (Output, Input.Index)? | |
| } | |
| func parseString(string: String) -> Parser<String, String>.Function { | |
| return { str, index in | |
| let end = advance(index, count(string)) | |
| if str.substringWithRange(index..<end) == string { | |
| return (string, end) | |
| } else { | |
| return nil | |
| } | |
| } | |
| } | |
| func concat<C: CollectionType, T, U>(ƒ: Parser<C, T>.Function, g: Parser<C, U>.Function) -> Parser<C, (T, U)>.Function { | |
| return { c, index in | |
| if let first = ƒ(c, index), second = g(c, first.1) { | |
| return ((first.0, second.0), second.1) | |
| } else { | |
| return nil | |
| } | |
| } | |
| } | |
| func parse<Input: CollectionType, Output>(ƒ: Parser<Input, Output>.Function, input: Input) -> Output? { | |
| return ƒ(input, input.startIndex).flatMap { $1 == input.endIndex ? $0 : nil } | |
| } | |
| let parser = concat(parseString("asdf"), parseString("asdf")) | |
| println(parse(parser, "asdfasdf")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment