12 CS Unit 1
12 CS Unit 1
In the above function definition variable ‘b’ is the parameter and the value which is passed to the
variable ‘b’ is the argument. The precondition (requires) and postcondition (returns) of the
function is given. Note we have not mentioned any types: (data types). Some language compiler
solves this type (data type) inference problem algorithmically, but some require the type to be
mentioned.
In the above function definition if expression can return 1 in the then branch, shows that as per
the typing rule the entire if expression has type int. Since the if expression is of type ‘int’, the
function's return type also be ‘int’. ‘b’ is compared to 0 with the equality operator, so ‘b’ is also
a type of ‘int’. Since ‘a’ is multiplied with another expression using the * operator, ‘a’ must be
an int.
(ii) Parameter with Type
(requires: b> 0 )
(returns: a to the power of b )
let rec pow (a: int) (b: int) : int :=
if b=0 then 1
else a * pow a (b-1)
When we write the type annotations for ‘a’ and ‘b’ the parentheses are mandatory. Generally we
can leave out these annotations, because it's simpler to let the compiler infer them. There are
times we may want to explicitly write down types. This is useful on times when you get a type
error from the compiler that doesn't make sense. Explicitly annotating the types can help with
debugging such an error message.
If it is compiled, strlen (s) is called each time and strlen needs to iterate over the whole of ‘s’. If
the compiler is smart enough to work out that strlen is a pure function and that ‘s’ is not updated
in the loop, then it can remove the redundant extra calls to strlen and make the loop to execute
only one time. From these what we can understand, strlen is a pure function because the function
takes one variable as a parameter, and accesses it to find its length. This function reads external
memory but does not change it, and the value returned derives from the external memory
accessed.
8. Differentiate pure and impure function.