Julia, lesson 7
Most real programs handle many values at once: a list of prices, all the words in a text, a
score for every player. Julia's two workhorse collections are the array (an ordered list)
and the dictionary (Dict, a lookup table from keys to values).
Write an array with square brackets. A one-dimensional array is called a Vector:
Indexing starts at 1, and end means the last position:
Arrays can grow and shrink. Functions whose names end in ! change the array you give them:
Julia has a function for most everyday questions:
x -> x > 3 is an anonymous function: a small function without a name, written inline.
Many collection functions take one to decide what to do with each element.
2 exercises to try what you just read.
A comprehension builds a new array from an old one in a single readable line:
The dot syntax from earlier lessons also applies a function to every element: nums .* 2 is
[8, 18, 2, 14]. To print an array's items separated by spaces, use join(nums, " ").
A Dict maps keys to values. Build one from key => value pairs:
Reading a missing key with prices["milk"] throws a KeyError, so use haskey or get when a
key might not be there. get(d, key, 0) + 1 is the classic way to count things.
Loop over a dictionary to get each key and value:
A Dict does not keep any particular order. When the output order matters, sort the keys
first: for k in sort(collect(keys(d))).
Read one line of whole numbers separated by spaces. Print the squares of the even numbers
only, from smallest to largest, separated by single spaces. If there are no even numbers, print
none.
Sample input:
Sample output:
Each input line holds one vote: the name of a candidate. Count the votes and print one line per
candidate in alphabetical order, in the form name: votes. Then print the winner (the most
votes; if there is a tie, the name that comes first alphabetically) as Winner: name.
Sample input:
Sample output:
temps = [14.2, 17.9, 11.4]
names = ["Ada", "Ben", "Cleo"]
length(temps) # 3names[1] # "Ada"
names[end] # "Cleo"
names[2:end] # ["Ben", "Cleo"], a new arrayscores = Int[] # an empty array of integers
push!(scores, 72) # add to the end
push!(scores, 95, 58)
pop!(scores) # removes and returns 58nums = [4, 9, 1, 7]
sum(nums), maximum(nums), minimum(nums) # (21, 9, 1)
sort(nums) # [1, 4, 7, 9], a new array
sort(nums, rev=true) # [9, 7, 4, 1]
9 in nums # true
count(x -> x > 3, nums) # 3
filter(x -> x % 2 == 1, nums) # [9, 1, 7]squares = [n^2 for n in nums] # [16, 81, 1, 49]
big = [n for n in nums if n > 5] # [9, 7]prices = Dict("tea" => 2.2, "coffee" => 2.8)
prices["coffee"] # 2.8
prices["juice"] = 3.5 # add or replace an entry
haskey(prices, "milk") # false
get(prices, "milk", 0.0) # 0.0, a default instead of an error
delete!(prices, "tea")for (item, price) in prices
println("$item costs $price")
end3 4 1 2 10 74 16 100Zara
Omar
Zara
Lena
Omar
ZaraLena: 1
Omar: 2
Zara: 3
Winner: Zara