Last active
August 29, 2015 14:18
-
-
Save JRHeaton/36f2aa51ad542c5209b2 to your computer and use it in GitHub Desktop.
using rob rix's madness to parse lowercase/numeric tuples cuz that's what we do when we learn
This file contains 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
func flatten(x: [String]) -> String { | |
return reduce(x, "", +) | |
} | |
let x = "(1,2,(3,4,(5, potato,7)),8,(9))" | |
enum Type: Printable { | |
case Element(String) | |
case Tuple([Type]) | |
var description: String { | |
switch self { | |
case .Element(let x): return toString(x) | |
case .Tuple(let types): return toString(types) | |
} | |
} | |
} | |
let element = ignore((%" ")*) // any leading whitespace | |
++ ((%("0"..."9") | %("a"..."z"))+ --> flatten) // 1 or more elements | |
++ ignore((%",")* ++ (%" ")*) // optional comma/trailing whitespace | |
--> { Type.Element($0) } | |
let fixed = fix { tuple -> Parser<Type>.Function in | |
let tupleElement = tuple ++ ignore(%(","))* // recursive pattern + comma | |
let tupleOrNumber = (tupleElement | element)* --> { Type.Tuple($0) } // array of tuple elements or singleton array of other element | |
let p = ignore(%"(") ++ tupleOrNumber ++ ignore(%")") | |
return p | |
} | |
println(parse(fixed, x)) // Optional([1, 2, [3, 4, [5, potato, 7]], 8, [9]]) |
For the sake of making the URL available, https://github.com/robrix/Madness is the one referenced at top.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another neat library for exploring this type of parsing is https://github.com/brotchie/Parcoa if anyone is interested.