gpt4 book ai didi

kotlin - Kotlin 的函数式主函数参数解析

转载 作者:行者123 更新时间:2023-12-02 12:47:28 26 4
gpt4 key购买 nike

如果我写问答的方式不合适,请告诉我。另外,我也期待一些更好的答案。我提供的两种解决方案都不完美。

现在网上有一些Kotlin参数解析器,例如GitHub: xenomachina/kotlin-argparser , GitHub: Kotlin/kotlinx.cliGitHub: ajalt/clikt .但是我不想在我的(也许)小项目中添加这么大的文件夹。我想要的是一个简单而干净的解决方案,例如只是一个具有“流畅”流样式实现的函数。相反,这些项目都包含多个文件。

我在想的是,只需要将命令行参数解析为 Map<String, List<String>> , 使用 map.containsKey()获取 no_argument参数,并使用 map[key]获取 required_argument范围。

例如,命令行参数列表

-a -b c -d e f g -h --ignore --join k --link m n o -p "q r s"

将被解析为:
{-a=[], -b=[c], -d=[e, f, g], -h=[], --ignore=[], --join=[k], --link=[m, n, o], -p=[q r s]}

或者我们说
mapOf(
"-a" to listOf(), // POSIX style, no argument
"-b" to listOf("c"), // POSIX style, with single argument
"-d" to listOf("e", "f", "g"), // POSIX style, with multiple argument
"-h" to listOf(), // POSIX style, no argument
"--ignore" to listOf(), // GNU style, no argument
"--join" to listOf("k"), // GNU style, with single argument
"--link" to listOf("m", "n", "o"), // GNU style, with multiple argument
"-p" to listOf("q r s") // POSIX style, with single argument containing whitespaces
)

最佳答案

嗯,我的解决方案涉及不变性和折叠 last参数也一样。

fun main(args: Array<String>) {
val map = args.fold(Pair(emptyMap<String, List<String>>(), "")) { (map, lastKey), elem ->
if (elem.startsWith("-")) Pair(map + (elem to emptyList()), elem)
else Pair(map + (lastKey to map.getOrDefault(lastKey, emptyList()) + elem), lastKey)
}.first

println(map)

val expected = mapOf(
"-a" to emptyList(),
"-b" to listOf("c"),
"-d" to listOf("e", "f", "g"),
"-h" to emptyList(),
"--ignore" to emptyList(),
"--join" to listOf("k"),
"--link" to listOf("m", "n", "o"),
"-p" to listOf("q r s"))

check(map == expected)
}

输出
{-a=[], -b=[c], -d=[e, f, g], -h=[], --ignore=[], --join=[k], --link=[m, n, o], -p=[q r s]}

它还处理第一个参数是参数的情况,您可以在 map[""] 中访问它们。

关于kotlin - Kotlin 的函数式主函数参数解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53946908/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com