gpt4 book ai didi

if-statement - 为什么 ada 中的 if 表达式和 if 语句也适用于 case

转载 作者:行者123 更新时间:2023-12-04 05:25:00 25 4
gpt4 key购买 nike

取自 Introduction to Ada—If expressions :

Ada's if expressions are similar to if statements. However, there are a few differences that stem from the fact that it is an expression:

All branches' expressions must be of the same type

It must be surrounded by parentheses if the surrounding expression does not already contain them

An else branch is mandatory unless the expression following then has a Boolean value. In that case an else branch is optional and, if not present, defaults to else True.


我不明白需要有两种不同的方式来使用 if 构建代码关键词。这背后的原因是什么?
还有 case表达式和 case声明。为什么是这样?

最佳答案

我认为这最好通过引用 Ada 2012 基本原理来回答 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.



此外, if声明和 case语句通常为所有分支中的同一变量分配不同的值,仅此而已:
if Foo > 10 then
Bar := 1;
else
Bar := 2;
end if;

在这种情况下,一个 if表达式可能会增加可读性,并在代码中更清楚地说明正在发生的事情:
Bar := (if Foo > 10 then 1 else 2);

我们现在可以看到代码的维护者不再需要阅读整个 if语句以查看仅更新了一个变量。

同样适用于 case表达式,这也可以减少嵌套的需要 if表达式。

另外,我可以把问题抛给你:为什么基于 C 的语言有三元运算符 ?:除了 if 语句?

关于if-statement - 为什么 ada 中的 if 表达式和 if 语句也适用于 case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55860948/

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