Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Last active August 29, 2015 14:18
Show Gist options
  • Save JRHeaton/36f2aa51ad542c5209b2 to your computer and use it in GitHub Desktop.
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
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]])
@robrix
Copy link

robrix commented Apr 4, 2015

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