首页 > 解决方案 > 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")
    }
}

标签: kotlin

解决方案


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 use reversed() 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 is Unit in our case and useless.

推荐阅读