Quiz 1.3: Variables and objects
Q1: Passing functions as argument to other functions (callbacks)
Which is the output of the following snippet?:
foo(x) = x+1
boo(x) = x+2
zoo(foo,x) = foo(x) + 1
zoo.(boo,[1,2,3])
RESOLUTION
The code first defines two functions, foo
and boo
, then it defines the function zoo
whose first parameter is a function object and then it calls the function with the function boo
and the value 1
. It doesn't matter that the argument name is foo
like the foo
function, that is only a local variable within the zoo
function. What is actually passed (as an object) is the bool
function, so that is the one what will be used to evaluate the result. Note that functions in Julia are Fist-class citizens of the language: they can be passed as arguments to other functions (as done here), returned by other functions, assigned as objects to any identifier or stored in data structures.
The correct answers are:
- The vector
[4,5,6]
Q2: Effects of different way of copying objects
Given the following snippet:
foo = [[1,2],3]
goo = foo[1]
goo[1] = 10
zoo = copy(foo)
zoo[1][1] = foo[1][1]+10
zoo[1] = 100
doo = deepcopy(foo)
doo[1] = foo[1][1]+100
Which is the value of doo[1]
?
RESOLUTION
The object "stored" as first element of the array foo
is assigned to the name binding goo
too. It is hence the same object that is mutated in the third line command. zoo
creates a new array object, but this different object store the same object as first element. zoo[1][1] = foo[1][1]+10
hence mutates itself (it is equivalent to zoo[1][1] += 10
), while the following line reassignes the first element of the (independent) array referenced by zoo
to an other totally different object (an integer). foo[1][1]
hence is first mutated to 10
using goo
and then is further increased of 10
using zoo
. When used to compute the value of doo[1]
it is hence 120
.
The correct answer is: 120