Julia Intermediate Introduction
Julia Intermediate is the next stage of learning Julia. It goes deeper into how Julia picks a method and how to write methods that work well.
One name can have several methods
One method handles whole numbers. Another method handles text.
describe(x::Int) = "whole number"
describe(x::String) = "text"
println(describe(7))
println(describe("hi"))A struct groups values for a method
A struct groups two whole numbers. A method uses both numbers to find an area.
struct Rect
w::Int
h::Int
end
area(r::Rect) = r.w * r.h
println(area(Rect(3, 4)))A short sum uses a list of numbers
A short sum uses a list of whole numbers. The result is the sum of their squares.
println(sum(x * x for x in [1, 2, 3]))Example
describe(x::Int) = "whole number"
describe(x::String) = "text"
describe(x::Float64) = "decimal number"
println(describe(5))
println(describe("hi"))
println(describe(2.5))
println(length([describe(5), describe("hi")]))Key points
- Multiple dispatch: Julia picks a method from the types of its arguments.
- Types: a type describes what kind of value something is.
- Functions: a function can have several methods for different argument types.
- Structs: a struct groups related values under one type.
- Course shape: each lesson shows short code, its result, and a small exercise.
In this example, three methods describe three kinds of values. Three calls print their descriptions. A final line prints the length of a list of two descriptions.
Note
every example in this course runs as a complete script.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· JuliaHub
Exercise
Julia picks a method from what?