I am not familiar with compiler design or implementation problems outside of an academic introduction many years ago.
In C I might define a function thusly:
int foo(int bar) {
return bar * 2;
}
But in Rust, I would write:
fn foo(bar: i32) -> i32 {
return bar * 2;
}
Notice that my function definition in Rust required the 'fn' preamble, while no such identifier was used in the C example.
Plenty of other languages throughout the ages have exhibited this same requirement. Perl, Python, Rust, Basic, all have this requirement (sub, def, fn, sub).
Why do some programming languages require a specific preamble before the declaration of a function? Is there a technical reason that make this design attractive, or is it simply a stylistic choice?
Like in human languages, in technical languages it would be difficult to determine which language's grammar is better. In C, if you have
<thetype> <thename>(<theparameters>)
is a proper function header. If you have
<thetype> <thename>
(without the paranthesis), then it is a variable (assuming this is the full command with possibly an assignment being added).
As we can see, C's syntax does not require you to specify with an explicit function
, fn
or fun
or func
keyword that the code that follows is a function, because the syntax makes that perfectly clear given the rules of the language.
Since we have found a language where the function
(or similar) keyword is unnecessary in order to specify that the code that follows is a function, we have also proven that there is no technical necessity to use such a keyword.
Nevertheless, some other languages might be not so clear about this. For instance, in basic you can implement a Sub
(that is, a procedure) or a Function
. Here we have an explicit distinction between the two in the language's rules, but it does not seem to be a technical necessity, even if we take Basic's language rules into account in general.
One could implement a compiler that searches for the Return
keyword inside a Function
and handle the difference between the Sub
and the Function
internally. But the engineers planning the language have chosen not to do so, maybe they were preferring the language to be explicit, as other keyword usages (such as IsNot Nothing
or AndAlso
) suggests, but, since I was not involved at the planning of that particular language, I cannot be sure.
In general, to summarize the answer: there is no technical reason that would force the inventors of languages to use a function
or similar keyword explicitly, but they may choose to do so, possibly with the reason of being explicit, but the exact reason is only known by those who were part of the planning or who have been informed about this.