为什么在ada中使用if表达式和if语句,也用于大小写

Jin*_*nzu 3 if-statement ada

摘自Ada简介-如果表达式

Ada的if表达式类似于if语句。但是,由于它是一个表达式,因此存在一些差异:

所有分支的表达式必须具有相同的类型

必须用括号包围,如果周围的表达没有包含他们

一个else分支是强制性的,除非表达以下then具有一个布尔值。在这种情况下,else分支是可选的,如果不存在,则默认为else True

我不明白需要使用两种不同的方法来构造带有if关键字的代码。这背后的原因是什么?

也有case表达式和case语句。为什么是这样?

egi*_*lhh 5

I think this is best answered by quoting the Ada 2012 Rationale Chapter 3.1:

One of the key areas identified by the WG9 guidance document [1] as needing attention was improving the ability to write and enforce contracts. These were discussed in detail in the previous chapter. When defining the new aspects for preconditions, postconditions, type invariants and subtype predicates it became clear that without more flexible forms of expressions, many functions would need to be introduced because in all cases the aspect was given by an expression. However, declaring a function and thus giving the detail of the condition, invariant or predicate in the function body makes the detail of the contract rather remote for the human reader. Information hiding is usually a good thing but in this case, it just introduces obscurity. Four forms are introduced, namely, if expressions, case expressions, quantified expressions and expression functions. Together they give Ada some of the flexible feel of a functional language.

In addition, if statements and case statements often assigns different values to the same variable in all branches, and nothing else:

if Foo > 10 then
   Bar := 1;
else
   Bar := 2;
end if;
Run Code Online (Sandbox Code Playgroud)

In this case, an if expression may increase readability and more clearly state in the code what's going on:

Bar := (if Foo > 10 then 1 else 2);
Run Code Online (Sandbox Code Playgroud)

We can now see that there's no longer a need for the maintainer of the code to read a whole if statement in order to see that only a single variable is updated.

Same goes for case expressions, which can also reduce the need for nesting if expressions.

Also, I can throw the question back to you: Why does C-based languages have the ternary operator ?: in addition to if statements?