gpt4 book ai didi

if-statement - 做 "if none of the above"的优雅方式是什么?

转载 作者:行者123 更新时间:2023-12-01 03:49:18 24 4
gpt4 key购买 nike

我确定你去过那里。你想说“如果flib这样做,如果flob这样做,如果flab做饮食等”,其中任何数量都可以是真的,那么最后你想要一个“如果你没有做任何一个”。

例如(下面的例子是用 Swift 编写的,因为我一直在玩它,但我认为大多数语言的情况都是一样的):

let thing = 101
var isInteresting = false
if (thing % 3 == 0) {
println("\"\(thing)\" is a multiple of three.")
isInteresting = true
}
if (thing > 100) {
println("\"\(thing)\" is greater than one hundred.")
isInteresting = true
}
if (thing > 1000) {
println("\"\(thing)\" is greater than one thousand.")
isInteresting = true
}
if !isInteresting {
println("\"\(thing)\" is boring.")
}

我发现跟踪一个 bool 值来告诉我我是否做了什么有点笨拙。

我想出的唯一其他方法是:
let thing = 101
let isAMultipleOfThree = (thing % 3 == 0)
let isGreaterThan100 = (thing > 100)
let isGreaterThan1000 = (thing > 1000)

if isAMultipleOfThree {
println("\"\(thing)\" is a multiple of three.")
}
if isGreaterThan100 {
println("\"\(thing)\" is greater than one hundred.")
}
if isGreaterThan1000 {
println("\"\(thing)\" is greater than one thousand.")
}
if !(isAMultipleOfThree || isGreaterThan100 || isGreaterThan1000 ) {
println("\"\(thing)\" is boring.")
}

但如果有更糟糕的事情(如果你添加一个新条款,你需要记住在三个地方添加它。

所以我的问题是,有没有一种简洁、简洁的方法来做到这一点?

我梦想着一个虚构的类似开关的语句:
switchif {   //Would have fallthrough where every case condition is checked
case thing % 3 == 0:
println("\"\(thing)\" is a multiple of three.")
case thing >100 :
println("\"\(thing)\" is greater than one hundred.")
case thing > 1000:
println("\"\(thing)\" is greater than one thousand.")
none: //Unlike 'default' this would only occur if none of the above did
println("\"\(thing)\" is boring.")
}

最佳答案

这是一个没有完美答案的好问题。但是,除了您建议的那些想法之外,还有另一个想法:将测试机制封装在一个过程中,以允许调用代码至少更精简一些。

具体来说,对于您的示例,调用代码可以是这样的:

if (! doInterestingStuff(101)) {
println("\"\(thing)\" is boring.");
}

如果将测试封装成一个过程:
  public boolean doInterestingStuff(int thing) {
var isInteresting = false

if (thing % 3 == 0) {
println("\"\(thing)\" is a multiple of three.")
isInteresting = true
}
if (thing > 100) {
println("\"\(thing)\" is greater than one hundred.")
isInteresting = true
}
if (thing > 1000) {
println("\"\(thing)\" is greater than one thousand.")
isInteresting = true
}

return isInteresting
}

关于if-statement - 做 "if none of the above"的优雅方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24324754/

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