1.

Explain with example Pure and impure functions?

Answer»

Pure functions:

Pure functions are functions which will give exact result when the same arguments are passed. For example the mathematical function sin (0) always results 0. This means that every time you call the function with the same arguments, you will always get the same result. A function can be a pure function provided it should not have any external variable which will alter the behaviour of that variable.

Let us see an example

let square x

return: x * x

The above function square is a pure function because it will not give different results for same input. There are various theoretical advantages of having pure functions. One advantage is that if a function is pure, then if it is called several times with the same arguments, the compiler only needs to actually call the function once. Let’s see an example let i: = 0; if i < strlen (s) then – Do something which doesn’t affect s ++ i 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. Impure functions: The variables used inside the function may cause side effects through the functions which are not passed with any arguments.

In such cases the function is called impure function. When a function depends on variables or functions outside of its definition block, you can never be sure that the function will behave the same every time it’s called. For example the mathematical function random Q will give different outputs for the same function call, let Random number let a : = random( ) if a > 10 then

return: a

else

return: 10 

Flere the function Random is impure as it is not sure what will be the result when we call the function.



Discussion

No Comment Found