gpt4 book ai didi

scala - 验证数字序列是否在允许的范围内

转载 作者:行者123 更新时间:2023-12-03 08:53:39 25 4
gpt4 key购买 nike

如何以更 scala/功能性(不像 java)的方式验证数字序列是否落入允许的数字范围?

val valuesRight = Seq(1, 2, 3, 4, 5, 6, 7)
val valuesWrong = Seq(1, 2, 5, 6, 7, 8, 9)
val allowedValues = Range(1, 8)

def containsNotAllowedValues(allowed: Range, input: Seq[Int]): Boolean = {
var containsNotAllowedValue = false
// pseudo code of how to do it in java, But how in scala / functional way?
while next element is available
validate if it is contained in allowed
if not allowed set containsNotAllowedValue to true and break the loop early
}
containsNotAllowedValue
}

containsNotAllowedValues(allowedValues, valuesRight) // expected false as no wrong element contained
containsNotAllowedValues(allowedValues, valuesWrong) // expected true as at least single wrong element is contained

最佳答案

您可以在 Seq 上使用 forall 函数。它检查给定谓词对于 Seq 中的所有元素是否都为 true。如果该函数返回 false 并带有谓词 allowed contains _,则您的 Seq 包含非法值。

def containsNotAllowedValues(allowed: Range, input: Seq[Int]): Boolean = 
!input.forall { allowed contains _ }

关于scala - 验证数字序列是否在允许的范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57304958/

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