From 0abf0334b579ba066efa97971afbd7644dfd5e05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=96=D0=BC?= =?UTF-8?q?=D1=8B=D0=BB=D0=B5=D0=B2?= Date: Sat, 7 Dec 2024 23:20:09 +0300 Subject: [PATCH 1/2] parse int error handling impl --- src/main/kotlin/CustomAdt.kt | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/kotlin/CustomAdt.kt b/src/main/kotlin/CustomAdt.kt index c30e0c4..7d404e9 100644 --- a/src/main/kotlin/CustomAdt.kt +++ b/src/main/kotlin/CustomAdt.kt @@ -9,7 +9,18 @@ sealed interface ParseResult { object CustomAdt { fun parseInt(str: String): ParseResult { - TODO() + var res = 0 + val sign = if (str.startsWith("-")) -1 else 1 + val symbolsToSkip = if (sign == -1) 1 else 0 + + for ((i, char) in str.withIndex().drop(symbolsToSkip)) { + if (char !in '0'..'9') + return ParseResult.Failure(i, char) + + res = res * 10 + (char - '0') + } + + return ParseResult.Success(res * sign) } } \ No newline at end of file From 49c9a13b1ce1ff6f1c7e9f68dab73bb120a4aa3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B5=D0=B9=20=D0=96=D0=BC?= =?UTF-8?q?=D1=8B=D0=BB=D0=B5=D0=B2?= Date: Sun, 8 Dec 2024 20:49:41 +0300 Subject: [PATCH 2/2] parse int error handling functional impl --- src/main/kotlin/CustomAdt.kt | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/src/main/kotlin/CustomAdt.kt b/src/main/kotlin/CustomAdt.kt index 7d404e9..5c09f41 100644 --- a/src/main/kotlin/CustomAdt.kt +++ b/src/main/kotlin/CustomAdt.kt @@ -8,19 +8,20 @@ sealed interface ParseResult { object CustomAdt { - fun parseInt(str: String): ParseResult { - var res = 0 - val sign = if (str.startsWith("-")) -1 else 1 - val symbolsToSkip = if (sign == -1) 1 else 0 + fun parseInt(input: String): ParseResult { + val (sign, elementsToSkip) = if (input.startsWith("-")) -1 to 1 else 1 to 0 - for ((i, char) in str.withIndex().drop(symbolsToSkip)) { - if (char !in '0'..'9') - return ParseResult.Failure(i, char) - - res = res * 10 + (char - '0') - } - - return ParseResult.Success(res * sign) + return input.withIndex() + .drop(elementsToSkip) + .map { (index, char) -> + if (char in '0'..'9') { + char - '0' + } else { + return ParseResult.Failure(index, char) + } + } + .fold(0) { acc, digit -> acc * 10 + digit } + .let { result -> ParseResult.Success(result * sign) } } } \ No newline at end of file