Quiz 1.9: Custom types
Q1: Type theory
Which of the following sentences are correct ?
RESOLUTION
Please look again the corresponding segment for clarifications.
The correct answers are:
- After a Type has been defined, it can no longer be redefine
- Unless explicitly declared as mutable, composite types once created can no longer be modified
x = MyType(1,2,3)performs two operations: first it instantiates an object of typeMytypeand then it assigns this object to the variablex- Objects can not be instantiated out of an abstract type
Q2: Type theory (2)
Given the following code snippet:
abstract type Aoo end
struct Foo
f1::Int64
f2::String
endWhich of the following commands, taken individually, would rise an error?
RESOLUTION
Concerning the commands raising an error: (1) the default constructor takes only positional arguments (in the order the type has been defined); (2) it is not possible to instantiate objects from an abstract type; (3) it is not possible to modify an immutable object
The correct answers are:
o = Foo(f1=1,f2="aaa")o = Aoo()o = Foo(2,"bbb"); o.f1 +=1
Q3: "Types" of types
Given the following code snippet:
struct Foo{T<:Number}
f1::T
f2::T
endWhich properties are correct for Foo?
RESOLUTION
Concerning the wrong sentences: (1) Foo is immutable, as it has not explicitly being declared mutable,(2) A parent/child relation in the template parameter type (here Int64 being a child of Number) doesn't extent to an equivalent parent/child relation in the main parametric type. This has important consequences. If you want to define a function foo whose parameter x is a vector of numbers (integers, floats,...) rather than define your function as foo(x::Vector{Number}) use instead foo(x::Vector{T}) where {T<: Number}. Even better, use AbstractVector unless you really need to constrain the parameter to being a Vector.
The correct answers are:
Foois concreteFoois compositeFoois parametricFoo{Int64}is a bits type
Q4: Constructor of a parameteric type
Given the following code snippet:
struct Foo{T<:Number}
f1::T
f2::T
function Foo(x::T,y::T) where {T<:Number}
return XXXX(x,y)
end
endTo what XXXX should be replaced for the giiven inner constructor to work (don't use spaces)?
RESOLUTION
Inner constructor use the keyword new. In this case, because we are dealing with a parametric type, the correct syntax is new{T}(...arguments...)
The correct answer is: new{T}