kotlin - How to transform this code using a functional approach in the Kotlin programming language
问题描述
I need to transform this code using a functional approach in the Kotlin language, while it is forbidden to use mutable collection and var variables, except for input and output
The attached code does the following
Schaeffer's bitwise stroke of the penultimate digit of all numbers (opera- walkie-talkies are performed from right to left)
fun main() {
try {
val s = readLine();
var digits: Array<Int> = emptyArray();
if (s != null) {
var words = s.split(" ");
for (c in words) {
digits += (c.toInt() / 10) % 10
}
digits.reverse();
var d = 0;
while (digits.size - 1 != d) {
println("Sheffer's stroke between ${digits[d]} и ${digits[d + 1]} = ${(digits[d] and digits[d + 1]).inv()}");
d++
}
}
} catch (s: NumberFormatException) {
println("Input error please try again!")
} catch (s: ArrayIndexOutOfBoundsException) {
println("Out of bounds of an array")
}
}
解决方案
You can do it like this:
readLine()?.let { input ->
input.split(" ")
.map { it.toInt() / 10 % 10 }
.asReversed()
.zipWithNext { a, b ->
println("Sheffer's stroke between $a и $b = ${(a and b).inv()}")
}
}
Of course you can wrap it around a try-catch
block to handle the errors.
Here's a summary of what we've did there:
?.let
- runs the given block when value of the left is not null.split(" ")
- splits the given input string with space delimiter.map
- applies given block to each element of the list and returns a new list with returned value.asReversed()
- returns a wrapper in which list is indexed from last to first (does not reallocate new memory or actually reverse the order), you can usereversed()
to copy the contents inside list and make a reversed order list.zipWithNext
- Calls the given block with two adjacent elements at a time, then returns list of returned items which isUnit
in our case and useless.
推荐阅读
- php - PHP 错误:致命错误:未捕获的 PDOException:SQLSTATE [42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;
- dart - 如何将 `ByteData` 实例写入 Dart 中的文件?
- python - 在 SqlAlchemy 中加入时如何将子查询对象转换为 ResultProxy 类?
- c# - IdentityServer3 - 错误 Microsoft.IdentityModel.Tokens.SecurityTokenInvalidSignatureException:IDX10503:签名验证失败
- mysql - 从 SQL 列中删除所有字母
- java - 操作栏后退键不起作用
- php - 使用 git 终端时,laravel homestead “找不到驱动程序”
- lua - 使用 lua 文件来要求其他 lua 文件?
- webview - 单击onesignal通知时打开android webview应用程序
- php - php exec wget无法下载大文件