我怎样才能重构出所需要的其他条款? [英] How can I refactor out the required else clause?
本文介绍了我怎样才能重构出所需要的其他条款?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来有点像这样一个C#方法:
I have a C# method that looks a bit like this:
bool Eval() {
// do some work
if (conditionA) {
// do some work
if (conditionB) {
// do some work
if (conditionC) {
// do some work
return true;
}
}
}
return false;
}
在F#这结束了,因为强制else分支的看着颇有几分丑陋
In F# this ends up looking quite a bit uglier because of the mandatory else branches:
let eval() =
// do some work
if conditionA then
// do some work
if conditionB then
// do some work
if conditionC then
// do some work
true
else
false
else
false
else
false
什么是F#中写这篇的更清洁的方式?
What would be a cleaner way of writing this in F#?
推荐答案
那么,既然做一些工作已是势在必行(大概),那么我认为
Well, since 'do some work' is already imperative (presumably), then I think that
let eval() =
let mutable result = false
... // ifs
result <- true
... // no more elses
result
较短合理。 (换句话说,其他
仅供如果
返回值的表达式强制性的;因为你正在做的工作势在必行,使用不需要其他
)
is shorter and reasonable. (In other words, else
is only mandatory for if
expressions that return values; since you're doing imperative work, use if
statements that don't need an else
.)
这篇关于我怎样才能重构出所需要的其他条款?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文