19
Applicative order Vs Normal order
Yeah, the Topic is a little weird. You ever heard static language and dynamic language. So, this topic looks like the same static vs dynamic language.
In Functional programming, the evaluation of an expression rewrites the canonical form into the order(Evaluation Order).
What is rewriting the function??
It’s replacing the function body with the function call.
Eg Code Block:
//if the function the double the number
double x = x + x;
//if we call this function with a number
double 4
//It replaces by the body of the function "x + x" with argument
double 4 => 4 + 4
//so the answer is 8
There's two important order rewriting.
1.Normal order
->It rewrites or execute leftmost occurrence of a function.
2.Applicative order
->It rewrites or execute innermost occurrence of a function.
//the function double the number
double x = x + x;
//the function average the two number
average x y = (x + y) / 2;
To avoid confusing the concept, let re-express operator function "+" , "*" and "/".
//so the function double change into
double x = plus x x //change expression num1 + num2
//so the function average change into
average x y = divide (plus x y) 2 //change expression num1 / num2
Let evaluate double(average 2 4)
Normal order execute leftmost part of function.
double (average 2 4) =>
plus (average 2 4) (average 2 4) =>
plus (divide (plus 2 4) 2) (average 2 4) =>
plus (divide 6 2) (average 2 4) =>
plus 3 (average 2 4) =>
plus 3 (divide (plus 2 4) 2) =>
plus 3 (divide 6 2) =>
plus 3 3 =>
6
Applicative Order execute innermost part of function.
double (average 2 4) =>
double (divide (plus 2 4) 2) =>
double (divide 6 2) =>
double 3 =>
plus 3 3 =>
6
So, We see. Normal order evaluate many steps and it is a delay evaluation. It is lazy evaluation.
Applicative Order takes the few steps.
So, This is Applicative order languages vs normal order languages.
19