if语句应该与ocaml中的else语句关联吗? [英] Should an if statement be associated with else statement in ocaml?
问题描述
在ocaml中,我希望每个条件都有许多嵌套的if语句和一个返回值.这样的代码变得越来越复杂.
In ocaml, I want to have many nested if statements and a return value on each of the conditions. The code is becoming complicated like this.
let func arg1 arg2 =
if condition1 then arg1+arg2
else
(
//code1
if condition2 then arg1*arg2
else
(
//code2
if condition3 then arg1+arg2
else
(
//code3
)
)
)
我可以有这样的代码来代替这样的嵌套语句吗?
Instead of such nested statements can I have code like this?
let func arg1 arg2 =
if condition1 then arg1+arg2
//code1
if condition2 then arg1*arg2
//code2
if condition3 then arg1+arg2
//code3
推荐答案
OCaml是一种强类型和静态类型的语言,这意味着在编译时会检查每个表达式的类型.
OCaml is a strongly and statically typed language, which means that the type of every expression is checked at compile-time.
看看下面的代码片段.
if condition then true_value else false_value
在编译过程中,类型检查器将检查以下内容:
During compilation, the type-checker will check for the following:
-
condition
必须具有类型bool
; -
true_value
必须与false_value
具有相同的类型; - 整个表达式的类型与
true_value
和false_value
相同.
condition
must have typebool
;true_value
must have the same type asfalse_value
;- The whole expression has the same type as
true_value
andfalse_value
.
如果这些语句中的任何一个都不为真,则编译将失败并出现类型错误.
If any one of these statements is not true, then the compilation fails with a type error.
现在,让我们看一个没有else
的if
语句.
Now, let's take a look at a if
statement, without a else
.
if condition then true_value
如果条件为假,则表达式的计算结果为()
,这是类型为unit
的唯一值.使用前面的语句2和3,true_value
在此处可以具有的唯一类型是unit
.这意味着您不能将int
或string
或任何其他内容用作true_value
.
If the condition is false, then the expression evaluates to ()
, the only value of type unit
. Using statements 2 and 3 from before, the only type that true_value
can have here is unit
. That means that you can't use int
or string
or anything as the true_value
.
通常,深度嵌套的if-else
语句被视为代码异味:它可能表明您的代码需要重构.例如,OCaml提供模式匹配.取决于实际代码的样子,这可能是解决方法.
Usually, deeply nested if-else
statements is considered a code smell: it may indicate that your code needs refactoring. For instance, OCaml offers pattern-matching. Depending on what your actual code looks like, it may be the way to go.
这篇关于if语句应该与ocaml中的else语句关联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!