Question 1. Which of the following defines a variable x with value 10 in Julia?
Auto-evaluation
We have included in this page a series of quizzes to help reinforce your learning. These quizzes are designed not only to test your understanding but also to provide you with an opportunity for self-reflection. After each quiz, take a moment to review your answers, reflect on what you’ve learned, and identify areas where you may need further clarification. Do not hesitate to reach out to your lecturer if any questions come up.
Core Syntax
Question 2. Which keyword is used to define a function in Julia?
Question 3. Which symbol is used for element-wise operations in Julia (e.g., squaring each element of a vector)?
Question 4. What is the output of this code?
a = [1, 2, 3]
b = a
b[1] = 10
println(a)
Question 5. What does the end keyword do in Julia?
Question 6. Which expression returns the number of elements in a vector v?
Question 7. What does === do in Julia?
Question 8. What is the output of the following code?
result = 0
for i in 1:10
if i == 5
break
end
result += i
end
println(result)
Question 9. What is the output of the following code?
result = Int[]
for i in 1:6
if i % 2 == 0
continue
end
push!(result, i)
end
println(result)
Question 10. Which of the following is a valid for loop in Julia?
Question 11. What is the output of the following code?
a = [1, 2, 3]
b = [1, 2, 3]
println(a == b)
println(a === b)
Question 12. What is the output of the following code?
x = 7
result = x > 5 ? "big" : "small"
println(result)
Question 13. What is the output of the following code?
v = [1, 2, 3]
println(v .^ 2)
Type Hierarchies
Question 1. What is the purpose of an abstract type in Julia?
Question 2. Which of the following types is a concrete type?
Question 3. What does the isconcretetype function return for AbstractFloat?
Question 4. What will the following code return?
typeof(42)
Question 5. What is the purpose of the isa operator in Julia?
Question 6. What will be the result of the following code?
Int64 <: Real
Question 7. What will the following code return?
isconcretetype(Int64)
isconcretetype(AbstractFloat)
Question 8. What does the <: operator check in Julia?
Question 9. What is the result of the following code?
subtypes(Real)
Question 10. What does the supertype function return for Float64?
supertype(Float64)
Question 11. What is the output of the following code?
println(42 isa Int64)
println(42 isa Real)
println(Int64 <: Real)
println(42 <: Real)
Question 12. Starting from Float64, what is the correct chain of supertypes up to Any?
Type Conversion and Promotion
Question 1. What does the convert function do in Julia?
Question 2. What is the output of the following code?
println(round(Int, 3.14))
println(floor(Int, 3.14))
println(convert(Float64, 5))
println(string(123))
Question 3. What happens when an integer is assigned to a Float64 variable in Julia?
y::Float64 = 10
println(y)
Question 4. What does the promote function do in Julia?
a, b = promote(3, 4.5)
println(a)
println(b)
println(typeof(a))
println(typeof(b))
Question 5. What will happen if we try to add an Int and a String in Julia?
println(3 + "Hello")
Question 6. What are the types of a, b, and c after the following promote call?
a, b, c = promote(1, 2.0, 3//1)
println(typeof(a), " ", typeof(b), " ", typeof(c))
Question 7. What is the output of the following code?
println(floor(Int, -2.3))
println(round(Int, -2.5))
Special Types
Question 1. What does the Nothing type represent in Julia?
Question 2. What is the result of calling the following function in Julia?
# Example of a function that returns `Nothing`
function print_message(msg::String)
println(msg)
return nothing # Explicitly returns `nothing`
end
result = print_message("Hello!")
println(result === nothing) # Output: true
Question 3. What happens to Julia’s compiler when a function’s return type is inferred as Any?
Question 4. What does the following code do in Julia?
data = [1, 2, missing, 4, 5]
for item in data
if item === missing
println("Missing data detected.")
else
println("Value: ", item)
end
end
Question 5. What is the purpose of the skipmissing function in Julia?
using Statistics
# Example array with missing values
data = [1, 2, missing, 4, 5, missing, 7]
# Summing values while skipping missing entries
sum_no_missing = sum(skipmissing(data))
println("Sum without missing values: ", sum_no_missing) # Output: 19
# Calculating the mean while skipping missing values
mean_no_missing = mean(skipmissing(data))
println("Mean without missing values: ", mean_no_missing) # Output: 3.8
Question 6. What is the output of the following code?
data = Union{Int, Missing}[1, missing, 3]
println(typeof(data[2]))
println(ismissing(data[2]))
Question 7. What is the output of the following code?
function find_value(d::Dict, key)
return get(d, key, nothing)
end
result = find_value(Dict("a" => 1), "b")
println(result === nothing)
println(typeof(result))
Union Types
Question 1. What is a Union type in Julia?
Question 2. What is the output of the following code?
function process_number(x::Union{Int, Float64})
println("The input is: ", x)
end
process_number(5) # Works with an Int
process_number(3.14) # Works with a Float64
Question 3. Which of the following scenarios would benefit from using a Union type?
# Example using Union to handle multiple types in a function
function add_one(x::Union{Int, Float64})
return x + 1
end
println(add_one(3)) # Output: 4 (Int)
println(add_one(2.5)) # Output: 3.5 (Float64)
Question 4. Two methods exist for process. Which one is called by process(3//1)?
function process(x::Union{Int, Float64})
return x * 2
end
function process(x::Real)
return x + 1
end
println(process(3//1))
Question 5. What is the output of the following code?
function add_one(x::Union{Int, Float64})
return x + 1
end
println(add_one(Int8(3)))
Question 6. What does Int <: Union{Int, Float64} return, and what does it mean?
Type Annotations and Declarations
Question 1. What is the primary purpose of type annotations in Julia?
Question 2. Which of the following correctly applies a type annotation to a variable?
Question 3. What will happen if the following code is executed?
function add(a::Int, b::Int)
return a + b
end
add(3, "4")
Question 4. In Julia, what will the following code output?
function multiply(a::Int, b::Int)::Int
return a * b
end
multiply(3, 4)
Question 5. What happens when the following function is called with f("hello")?
function f(x::T) where T <: Real
return x * 2
end
f("hello")
Parametric Types
Question 1. What is the output of the following code?
struct MyPair{T, S}
first::T
second::S
end
p = MyPair(1, 2.0)
println(typeof(p))
Question 2. What is the role of T and S in the Pair struct example?
struct Pair{T, S}
first::T
second::S
end
pair1 = Pair(1, "apple")
pair2 = Pair(3.14, true)
Question 3. What happens when you instantiate Pair(1, 'apple') in the provided code?
pair1 = Pair(1, "apple")
Question 4. What is the benefit of using parametric types like AbstractContainer{T}?
abstract type AbstractContainer{T} end
struct VectorContainer{T} <: AbstractContainer{T}
data::Vector{T}
end
struct SetContainer{T} <: AbstractContainer{T}
data::Set{T}
end
Question 5. What does the print_container_info function do?
function print_container_info(container::AbstractContainer{T}) where T
println("Container holds values of type: ", T)
end
Question 6. What is the purpose of AbstractContainer{T} in the code example?
abstract type AbstractContainer{T} end
Question 7. What would be the output of print_container_info(vec) if vec is VectorContainer([1, 2, 3])?
vec = VectorContainer([1, 2, 3])
Question 8. How does using parametric types help with code reusability?
Question 9. What is the output of the following code?
struct RealPair{T <: Real}
first::T
second::T
end
println(typeof(RealPair(1, 2)))
println(typeof(RealPair(1.0, 2.0)))
Question 10. What happens when RealPair("a", "b") is called?
Errors and Exception Handling
Question 1. Which error type is raised when an index is out of bounds in an array?
Question 2. What does the following code do in Julia?
function divide(a, b)
if b == 0
throw(DivideError())
end
return a / b
end
Question 3. What happens when the following try/catch block is executed?
try
println(divide(10, 0)) # Will raise an error
catch e
println("Error: ", e) # Handles the error
end
Question 4. What is the purpose of the finally block in Julia’s exception handling?
Question 5. What is the output of the following code?
function safe_file_read(filename::String)
file = nothing
try
file = open(filename, "r")
data = read(file, String)
return data
catch e
println("An error occurred: ", e)
finally
if file !== nothing
close(file)
println("File closed.")
end
end
end
# Test with a valid file
println(safe_file_read("example.txt"))
# Test with an invalid file
println(safe_file_read("nonexistent.txt"))
Question 6. Which of the following is an appropriate use case for the finally block?
Question 7. What happens when try is used with finally but without catch?
try
error("oops")
finally
println("cleanup")
end
Question 8. What type of error is thrown by sqrt(-1.0) in Julia?
Performance
Question 1. What does it mean for a function in Julia to be type stable?
Question 2. Which Julia macro is commonly used to check for type stability?
Question 3. Which of the following best describes a type-unstable function?
Question 4. Consider the function:
function g(x)
return x > 10 ? 10 : "small"
end
Question 5. In Julia, which type causes the biggest problems for type inference when used as a return type?
Question 6. Which of the following is volatile (non permanent) memory?
Question 7. Which component temporarily stores instructions and data for quick access by the CPU?
Question 8. The basic unit of data in computer hardware is:
Question 9. Consider two functions below. Which one is type-stable when called with an Int argument?
function f1(x)
return x > 0 ? x : 0.0
end
function f2(x)
return x > 0 ? x : zero(x)
end
Question 10. A function returns Union{Int, Float64} depending on its input value. What is the main performance consequence?
Functions
Question 1. Which of the following is the correct syntax for a keyword argument with a default value?
Question 2. What is the output of the following code?
function greet(name; greeting="Hello")
println("$greeting, $name!")
end
greet("Alice")
greet("Bob", greeting="Hi")
Question 3. By convention, what does a trailing ! in a Julia function name indicate?
Question 4. What is the output of the following code?
function sum_all(args...)
total = 0
for x in args
total += x
end
return total
end
println(sum_all(1, 2, 3))
println(sum_all(10))
Question 5. What is the output of the following code?
function double(x)
x * 2
end
println(double(5))
println(double("hi"))
Question 6. What is the output of the following code?
v = [3, 1, 2]
sort(v)
println(v)
sort!(v)
println(v)
Question 7. What is the output of the following code?
f(x) = x^2
v = [1, 2, 3, 4]
println(f.(v))
Question 8. Three methods are defined for describe. Which method is called by describe(3.14)?
describe(x::Int) = println("integer: ", x)
describe(x::Float64) = println("float: ", x)
describe(x) = println("other: ", x)
describe(3.14)
describe(42)
describe("hello")
Data Structures
Question 1. How do you create a Dict mapping "a" to 1 and "b" to 2 in Julia?
Question 2. What is the output of the following code?
d = Dict("x" => 10, "y" => 20)
d["z"] = 30
println(length(d))
println(get(d, "w", -1))
Question 3. What is the difference between v[2:4] and @view v[2:4]?
Question 4. What is the output of the following code?
A = [1 2; 3 4]
B = [5 6; 7 8]
println(A * B)
println(A .* B)
Question 5. What does the \\ operator do when applied to a matrix A and vector b?
Question 6. What is the output of the following code?
A = [2.0 1.0; 1.0 3.0]
b = [5.0, 10.0]
x = A \ b
println(round.(x, digits=4))
Question 7. What is the output of the following code?
d = Dict("score" => 0)
function update!(d, key, val)
d[key] = val
end
update!(d, "score", 42)
println(d["score"])
Question 8. What is the output of the following code?
v = [10, 20, 30, 40, 50]
w = v[2:4]
w[1] = 999
println(v[2])
Composite Types
Question 1. What is the key difference between struct and mutable struct in Julia?
Question 2. What is the output of the following code?
struct Point
x::Float64
y::Float64
end
p = Point(3.0, 4.0)
println(p.x)
println(fieldnames(Point))
Question 3. What happens when you try to modify a field of an immutable struct?
struct Circle
radius::Float64
end
c = Circle(5.0)
c.radius = 10.0
Question 4. What is the output of the following code?
mutable struct Counter
count::Int
end
c = Counter(0)
c.count += 1
c.count += 1
println(c.count)
Question 5. What is the output of the following code?
struct LinearTransform
slope::Float64
intercept::Float64
end
(lt::LinearTransform)(x) = lt.slope * x + lt.intercept
lt = LinearTransform(2.0, 3.0)
println(lt(5))
Question 6. An inner constructor is defined below. What happens when SafeValue(-5) is called?
struct SafeValue
value::Float64
function SafeValue(v)
v < 0 && error("Value must be non-negative")
new(v)
end
end
SafeValue(-5)
Question 7. What does fieldnames(Point) return for struct Point; x::Float64; y::Float64; end?
Question 8. What is the output of the following code?
struct Box{T}
value::T
end
b1 = Box(42)
b2 = Box(3.14)
println(typeof(b1))
println(typeof(b2))
println(Box{Int} <: Box{Real})
Scoping, Closures and Modules
Question 1. What is the output of the following code?
x = 10
function f()
x = 20
println(x)
end
f()
println(x)
Question 2. What is the output of the following code?
function make_adder(n)
return x -> x + n
end
add5 = make_adder(5)
println(add5(3))
println(add5(10))
Question 3. What is the output of the following code?
function make_counter()
count = 0
increment! = () -> (count += 1; count)
return increment!
end
counter = make_counter()
println(counter())
println(counter())
println(counter())
Question 4. What does the export keyword do inside a module?
Question 5. What is the output of the following code?
module MyMath
export square
square(x) = x^2
cube(x) = x^3
end
using .MyMath
println(square(4))
println(MyMath.cube(3))
Question 6. What is the output of the following code?
x = 1
for i in 1:3
x = x + i
end
println(x)