r - 编写这种嵌套条件结构的更好方法是什么?
问题描述
我会以 R 为例:
# x is an object
# condA(x), condB(x) and condC(x) evaluate x and return TRUE or FALSE
# The conditions must be evaluated in the following orders.
# For e.g., when validating for an random object being a number larger than 5,
# you always need to evaluate whether it is numeric first,
# only after which can you evaluate whether it is larger than 5.
# Trying to evaluate both at once will cause an error if it is non-numeric.
# process1() and process2() are two different procedures
# modify1() is a modifier for x
if (condA(x)) {
if (condB(x)) {
x %<>% modify1
if (condC(x)) {
process1()
} else {
process2()
}
} else {
process2()
}
} else {
if (cond(C)) {
process1()
} else {
process2()
}
}
这样我需要多次指定每个过程,并重复评估 condC(x) 的部分,我觉得这样做很笨拙。有什么建议可以用更优雅的方式来编码这个结构,这样我只需要提到一次 process1() 和 process2() ,而不会破坏上述代码中所述的评估顺序?
更多信息:
我想这是一个普遍的问题,但也许一个例子可以促进讨论......假设如果condB(x)
评估需要修改TRUE
。
condA()
是is.character()
condB()
是exists()
condC()
是is.data.table()
modify1()
是get()
因此,如果x
是一个字符,它应该表示一个对象名称,然后验证其存在,然后转换为对象的指针。如果x
不是字符,它应该指向目标对象。然后验证目标对象(由 指向x
)以查看它是否为data.table
。如果是,process1()
,否则process2()
。
解决方案
长版:
boolean A = condA(x);
boolean B = false;
boolean C = false;
if (A) {
B = condB(x);
}
if (A && B || !A) {
C = condC(x);
}
if (C) {
process1();
} else {
process2();
}
精简版:
boolean A = condA(x);
boolean B = A && condB(x);
boolean C = (A && B || !A) && condC(x);
if (C) {
process1();
} else {
process2();
}
PS:我不确定R语言,但以上是我的想法。
推荐阅读
- python - How do I do something like numpy where(2darray ==0, 1darray, 1darray)
- ios - 如何在 SwiftUI 中进行异步更新后解雇发布者?
- windows - Can't seem to get this assembly program to output at all
- powershell - Powershell Get-Random AND Rename-Item
- python - 改进代码 - 网页抓取工作机会 - 职位、雇主、薪水、需要链接
- theory - How to use NEXT and TO in ACSL BASIC?
- laravel - Livewire - Bootstrap select not rendering
- sql-server - Connection with MSSQL
- c# - 如何在 ASP.NET Core MVC 中获得单击按钮的值?
- substrate - 在基材墨水上!如何获取调试信息?