Last active
March 6, 2017 09:34
-
-
Save pyldin601/1bd1089cfa33b964426b36311312d44d to your computer and use it in GitHub Desktop.
String Parser 2
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
fun <T> List<T>.headTail(): Pair<T, List<T>> = Pair(first(), drop(1)) | |
typealias Result = List<Pair<String, Int>> | |
fun iterString(rest: List<Char>, stringAcc: String, numberAcc: String, acc: Result): Result { | |
if (rest.isEmpty()) { | |
throw IllegalStateException() | |
} | |
val (head, tail) = rest.headTail() | |
if (head.isLetter()) { | |
return iterString(tail, stringAcc + head, numberAcc, acc) | |
} | |
return iterNumber(tail, stringAcc, "" + head, acc) | |
} | |
fun iterNumber(rest: List<Char>, stringAcc: String, numberAcc: String, acc: Result): Result { | |
if (rest.isEmpty()) { | |
return acc + Pair(stringAcc, numberAcc.toInt()) | |
} | |
val (head, tail) = rest.headTail() | |
if (head.isLetter()) { | |
return iterString(tail, "" + head, "", acc + Pair(stringAcc, numberAcc.toInt())) | |
} | |
return iterNumber(tail, stringAcc, numberAcc + head, acc) | |
} | |
fun parseString(string: String): Result { | |
return iterString(string.toList(), "", "", listOf()) | |
} | |
fun main(args: Array<String>) { | |
println(parseString("abc2edf4ee7")) | |
assert("[(abc, 2), (edf, 4), (ee, 7)]" == parseString("abc2edf4ee7").toString()) | |
assert("[(foo, 45), (bar, 99), (baz, 100)]" == parseString("foo45bar99baz100").toString()) | |
assert("[(bit, 0), (been, 1), (b, 0)]" == parseString("bit000been1b0").toString()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment