Functions in Python

C has functions, so generating code is simple. On the other hand, functions in PyJ add complexity because there will be a function definition and also a function call. A function definition has the syntax:

<function> ::= “function” “(” { <identifier>

{ “,” <identifier>} } “)” <statement>+ “end”

There is the key word function, a parameter list within parentheses, a set of statements, and an end. The parameter list is just a comma separated set of identifiers, but could be empty. There must be at least one statement in the body of the function.

Here is an annotation of the code that parses a function:

This code omits code generation and a couple of other things.

A function call can be a statement:

funcx( y )

or an expression

y = funcx(z)

A function returns a value, but it can be ignored. In the first case, the situa­tion is handled by the statement function, which requires information that syntax does not provide – the kind of identifier seen. Here, is the syntax of an assignment statement and a call statement:

<assignment statement> ::= <identifier> “=” <expression>

<call statement> ::= <identifier> “(” { <expression list> “)”

Both of these begin with an identifier. How do we know what kind of state­ment we’re looking at? The next symbol is “=” in one case and “(“ in the other, so we could look ahead. This compiler has a table of names and their associated type. A variable has type FLOAT and a function has type FUNC, and so the parser does something different depending on the type of the identifier.

The compiler does not check whether the number of parameters defined is the same as the number passed.

Source: Parker James R. (2021), Python: An Introduction to Programming, Mercury Learning and Information; Second edition.

Leave a Reply

Your email address will not be published. Required fields are marked *