Parameter passing techniques:
From what I can gather on these two techniques.
Call By Reference:
The address location of the variable is being passed into the function, thus within the local scope of the function, any changes to the value of the local variable will change the value of the original variable, since they are pointing to the same place.
Call By Name:
The actual variable is being passed into the function. Any changes to the value of the variable inside the local scope of the function will also be reflected on the outside of the function.
It seems to me, these two parameter passing techniques accomplish the same thing? Both of them act on the original variables contents. Do I have my definitions wrong? Am I thinking about this in the wrong way?
The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.
Example 2: Function Call by Reference – Swapping numbers As you can see the values of the variables have been changed after calling the swapnum() function because the swap happened on the addresses of the variables num1 and num2.
Call By-NameCall by-name evaluation is similar to call by-value, but it has the advantage that a function argument won't be evaluated until the corresponding value is used inside the function body. Both strategies are reduced to the final value as long as: The reduced expression consists of pure functions.
Call-by-name is slightly different than you describe. In pseudo code, imagine:
function foo(index, value-increment)
sum = 0
loop index = 1 to 3
sum = sum + value-increment
return sum
x = 3
foo(x, 1 / x)
If our foo
call is by reference, the second argument, 1 / x
, is evaluated only once giving us effectively: 1/3 + 1/3 + 1/3. It is a strict evaluation - each argument is fully evaluated before the function is applied.
If we call by name, 1 / x
is not strictly evaluated. Instead, it's evaluated in the loop as it's needed. Effectively, the loop becomes:
loop x = 1 to 3
sum = sum + 1 / x
or 1/1 + 1/2 + 1/3.
Take a look at thunks, though thunks don't always mean call-by-name. Haskell has the idea of thunks but uses call-by-need where 1 / x
wouldn't be evaluated until it was needed but then would be evaluated only once (not to mention Haskell wouldn't have a mutable loop variable).
Other resources:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With