Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are if expressions and if statements in ada, also for case

Taken from 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.

I do not understand the need to have two different ways of constructing code with the if keyword. What is the reasoning behind this?

Also there case expressions and case statements. Why is this?

like image 211
Jinzu Avatar asked Dec 11 '22 03:12

Jinzu


1 Answers

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;

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);

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?

like image 67
egilhh Avatar answered Mar 03 '23 09:03

egilhh