8  Exercise for control flow

8.1 Meaw

meaw(): using simple for loop

function meaw(n::Int)
    for _ in 1:n
    println("meaw")
    end
end
#> meaw (generic function with 1 method)
meaw(3)
#> meaw
#> meaw
#> meaw

meaw(): one-liner

meaw(n::Int) = print("meaw\n" ^ n)
#> meaw (generic function with 1 method)
meaw(2)
#> meaw
#> meaw

8.2 Hogwarts

students = ["Hermione", "Harry", "Ron"]
#> 3-element Vector{String}:
#>  "Hermione"
#>  "Harry"
#>  "Ron"
for student in students
    println(student)
end
#> Hermione
#> Harry
#> Ron

8.2.1 Dictionary of Students

students = [
    Dict("name"=> "Hermione", "house"=> "Gryffindor", "patronus"=> "Otter"),
    Dict("name"=> "Harry", "house"=> "Gryffindor", "patronous"=> "Stag"),
    Dict("name"=> "Draco", "house"=> "Slytherin", "patronous"=> Nothing)
]
#> 3-element Vector{Dict{String}}:
#>  Dict("name" => "Hermione", "patronus" => "Otter", "house" => "Gryffindor")
#>  Dict("name" => "Harry", "patronous" => "Stag", "house" => "Gryffindor")
#>  Dict{String, Any}("name" => "Draco", "patronous" => Nothing, "house" => "Slytherin")

Iterate though array of student (row by row)

for student in students
    println(student["name"], ", ", student["house"])
end
#> Hermione, Gryffindor
#> Harry, Gryffindor
#> Draco, Slytherin

Define a function to print information from each student

function print_student_info(i::Int)
    println("Student No.", i)
    for (k, v) in students[i]
        println("- ", k, ": ", v)
    end
end
#> print_student_info (generic function with 1 method)
print_student_info(1)
#> Student No.1
#> - name: Hermione
#> - patronus: Otter
#> - house: Gryffindor
for i in 1:length(students)
    print_student_info(i)
end
#> Student No.1
#> - name: Hermione
#> - patronus: Otter
#> - house: Gryffindor
#> Student No.2
#> - name: Harry
#> - patronous: Stag
#> - house: Gryffindor
#> Student No.3
#> - name: Draco
#> - patronous: Nothing
#> - house: Slytherin

or use broadcasting

print_student_info.(1:length(students))
#> Student No.1
#> - name: Hermione
#> - patronus: Otter
#> - house: Gryffindor
#> Student No.2
#> - name: Harry
#> - patronous: Stag
#> - house: Gryffindor
#> Student No.3
#> - name: Draco
#> - patronous: Nothing
#> - house: Slytherin
#> 3-element Vector{Nothing}:
#>  nothing
#>  nothing
#>  nothing