Skip to content
Snippets Groups Projects
Commit 64445e13 authored by Michele Nottoli's avatar Michele Nottoli
Browse files

Working on 3.

parent 38f51081
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:4fe99eff-729a-4d93-ab82-487e5143bae5 tags: %% Cell type:markdown id:4fe99eff-729a-4d93-ab82-487e5143bae5 tags:
# Advanced Data Types # Advanced Data Types
%% Cell type:markdown id:7969b8f9-335a-4bd2-82f7-1d9795234ed5 tags: %% Cell type:markdown id:7969b8f9-335a-4bd2-82f7-1d9795234ed5 tags:
## Dictionaries ## Dictionaries
%% Cell type:markdown id:ea8518c1-8e1d-4532-8055-e04c3aa3e7c4 tags: %% Cell type:markdown id:ea8518c1-8e1d-4532-8055-e04c3aa3e7c4 tags:
A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item. A dictionary contains a collection of indices, which are called keys, and a collection of values. Each key is associated with a single value. The association of a key and a value is called a key-value pair or sometimes an item.
The function `Dict` creates a new dictionary with no items. Because Dict is the name of a built-in function, you should avoid using it as a variable name. The function `Dict` creates a new dictionary with no items. Because Dict is the name of a built-in function, you should avoid using it as a variable name.
%% Cell type:code id:59ae8d17-a6f6-4210-95bc-0e7492bc8a7a tags: %% Cell type:code id:59ae8d17-a6f6-4210-95bc-0e7492bc8a7a tags:
``` julia ``` julia
eng2de = Dict() eng2de = Dict()
``` ```
%% Cell type:code id:28490ea3-c4d3-4e4d-915f-612ad36c9472 tags: %% Cell type:code id:28490ea3-c4d3-4e4d-915f-612ad36c9472 tags:
``` julia ``` julia
eng2de["one"] = "ein"; eng2de["one"] = "ein";
``` ```
%% Cell type:markdown id:f2aff40c-6dcb-421a-b67f-1662c5bf4702 tags: %% Cell type:markdown id:f2aff40c-6dcb-421a-b67f-1662c5bf4702 tags:
You can also initialize a dictionary with items as: You can also initialize a dictionary with items as:
%% Cell type:code id:92fc203b-4ba8-432a-a541-c4ccf3292195 tags: %% Cell type:code id:92fc203b-4ba8-432a-a541-c4ccf3292195 tags:
``` julia ``` julia
eng2de = Dict("one" => "ein", "two" => "zwei", "three" => "drei") eng2de = Dict("one" => "ein", "two" => "zwei", "three" => "drei")
``` ```
%% Cell type:markdown id:c52d24af-ec90-4b8c-bdd9-988129a7fa81 tags: %% Cell type:markdown id:c52d24af-ec90-4b8c-bdd9-988129a7fa81 tags:
Dictionaries are mutable, meaning that it is always possible to modify their elements, add new key-value pairs or removing existing ones. Dictionaries are mutable, meaning that it is always possible to modify their elements, add new key-value pairs or removing existing ones.
%% Cell type:code id:22b295dc-994e-4bbc-ac8d-da5ab9e73493 tags: %% Cell type:code id:22b295dc-994e-4bbc-ac8d-da5ab9e73493 tags:
``` julia ``` julia
eng2de["four"] = "VIER" eng2de["four"] = "VIER"
@show eng2de @show eng2de
eng2de["four"] = "vier" eng2de["four"] = "vier"
@show eng2de @show eng2de
delete!(eng2de, "four") delete!(eng2de, "four")
@show eng2de; @show eng2de;
``` ```
%% Cell type:markdown id:01513ad2-3083-4c89-adca-ccc8a88d93d4 tags: %% Cell type:markdown id:01513ad2-3083-4c89-adca-ccc8a88d93d4 tags:
In general, the order of the key-value pairs is unpredictable. However this is not important, as the values are always accessed using the keys. In general, the order of the key-value pairs is unpredictable. However this is not important, as the values are always accessed using the keys.
%% Cell type:code id:e9e4c5b9-9539-4294-a6ec-0a29fb76bf7b tags: %% Cell type:code id:e9e4c5b9-9539-4294-a6ec-0a29fb76bf7b tags:
``` julia ``` julia
eng2de["two"] eng2de["two"]
``` ```
%% Cell type:markdown id:9944dbbd-478b-4ae1-ac89-e16be08a0868 tags: %% Cell type:markdown id:9944dbbd-478b-4ae1-ac89-e16be08a0868 tags:
If the key isn’t in the dictionary, you get an exception: If the key isn’t in the dictionary, you get an exception:
%% Cell type:code id:8221269b-7a8f-4cfd-ab8e-0aa4fd6c962d tags: %% Cell type:code id:8221269b-7a8f-4cfd-ab8e-0aa4fd6c962d tags:
``` julia ``` julia
eng2de["four"] eng2de["four"]
``` ```
%% Cell type:markdown id:a545abaa-78dc-4625-84e9-03b1c8beaaf8 tags: %% Cell type:markdown id:a545abaa-78dc-4625-84e9-03b1c8beaaf8 tags:
The `length` function works on dictionaries; it returns the number of key-value pairs: The `length` function works on dictionaries; it returns the number of key-value pairs:
%% Cell type:code id:0e242667-b921-4242-bdcc-cbcac14909b2 tags: %% Cell type:code id:0e242667-b921-4242-bdcc-cbcac14909b2 tags:
``` julia ``` julia
length(eng2de) length(eng2de)
``` ```
%% Cell type:markdown id:8e42655b-f2a0-41f0-be90-015ebfeafdb9 tags: %% Cell type:markdown id:8e42655b-f2a0-41f0-be90-015ebfeafdb9 tags:
The function `keys` returns a collection with the keys of the dictionary: The function `keys` returns a collection with the keys of the dictionary:
%% Cell type:code id:3236f973-d3fa-42ba-a1c0-41e0002446cb tags: %% Cell type:code id:3236f973-d3fa-42ba-a1c0-41e0002446cb tags:
``` julia ``` julia
keys(eng2de) keys(eng2de)
``` ```
%% Cell type:markdown id:acfa7044-5695-4af8-b4bc-320c8a48a220 tags: %% Cell type:markdown id:acfa7044-5695-4af8-b4bc-320c8a48a220 tags:
Now you can use the `∈` operator to see whether something appears as a key in the dictionary: Now you can use the `∈` operator to see whether something appears as a key in the dictionary:
%% Cell type:code id:1fdeb10c-0d84-4c22-b734-d68e2eafe375 tags: %% Cell type:code id:1fdeb10c-0d84-4c22-b734-d68e2eafe375 tags:
``` julia ``` julia
@show "one" keys(eng2de) @show "one" keys(eng2de)
@show "four" keys(eng2de); @show "four" keys(eng2de);
``` ```
%% Cell type:markdown id:986919d6-4f27-4fad-b222-20697bf6af40 tags: %% Cell type:markdown id:986919d6-4f27-4fad-b222-20697bf6af40 tags:
To see whether something appears as a value in a dictionary, you can use the function `values`, which returns a collection of values, and then use the `∈` operator: To see whether something appears as a value in a dictionary, you can use the function `values`, which returns a collection of values, and then use the `∈` operator:
%% Cell type:code id:ab90dad1-61d0-4dbd-b829-a354c13fcb71 tags: %% Cell type:code id:ab90dad1-61d0-4dbd-b829-a354c13fcb71 tags:
``` julia ``` julia
@show "ein" values(eng2de) @show "ein" values(eng2de)
@show "vier" values(eng2de); @show "vier" values(eng2de);
``` ```
%% Cell type:markdown id:049c9dfd-1e51-4898-98e5-a4b812d0bba2 tags: %% Cell type:markdown id:049c9dfd-1e51-4898-98e5-a4b812d0bba2 tags:
### Loops over dictionaries ### Loops over dictionaries
You can traverse the keys of the dictionary in a `for` statement. You can traverse the keys of the dictionary in a `for` statement.
%% Cell type:code id:e7062d3f-2125-4ecd-ab13-d04944a71fe1 tags: %% Cell type:code id:e7062d3f-2125-4ecd-ab13-d04944a71fe1 tags:
``` julia ``` julia
function print_dictionary(dic) function print_dictionary(dic)
for key in keys(dic) for key in keys(dic)
println(key, " ", dic[key]) println(key, " ", dic[key])
end end
end end
print_dictionary(eng2de) print_dictionary(eng2de)
``` ```
%% Cell type:markdown id:cf27195c-e601-49ca-b03d-63162bf59bce tags: %% Cell type:markdown id:cf27195c-e601-49ca-b03d-63162bf59bce tags:
Again, the keys are in no particular order. To traverse the keys in alphabetically sorted order, you can combine `sort` and `collect`: Again, the keys are in no particular order. To traverse the keys in alphabetically sorted order, you can combine `sort` and `collect`:
%% Cell type:code id:6d52aeba-3c7e-405c-bcfe-d76e37e94f51 tags: %% Cell type:code id:6d52aeba-3c7e-405c-bcfe-d76e37e94f51 tags:
``` julia ``` julia
function print_dictionary_sorted(dic) function print_dictionary_sorted(dic)
for key in sort(collect(keys(dic))) for key in sort(collect(keys(dic)))
println(key, " ", dic[key]) println(key, " ", dic[key])
end end
end end
print_dictionary_sorted(eng2de) print_dictionary_sorted(eng2de)
``` ```
%% Cell type:markdown id:8daa9d3e-19de-4415-ba6c-6aeb174b38fa tags: %% Cell type:markdown id:8daa9d3e-19de-4415-ba6c-6aeb174b38fa tags:
### Exercises ### Exercises
- Write a function that given a string as input counts how many times each letter appears. Use a dictionary. - Write a function that given a string as input counts how many times each letter appears. Use a dictionary.
%% Cell type:code id:aba1978b-e675-48a7-89aa-75553db70537 tags: %% Cell type:code id:aba1978b-e675-48a7-89aa-75553db70537 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:3a9b281f-6cc0-4d39-b9e2-d816823f9873 tags: %% Cell type:markdown id:3a9b281f-6cc0-4d39-b9e2-d816823f9873 tags:
## Tuples and named tuples ## Tuples and named tuples
%% Cell type:markdown id:a722109e-86cc-44e3-9256-a3e93a1668f5 tags: %% Cell type:markdown id:a722109e-86cc-44e3-9256-a3e93a1668f5 tags:
A tuple is a sequence of values. The values can be of any type, and they are indexed by integers. The tuples are immutable and each element can have its own type. A tuple is a sequence of values. The values can be of any type, and they are indexed by integers. The tuples are immutable and each element can have its own type.
%% Cell type:code id:8502cf2e-8bea-4707-811c-f4e6e1de3c8f tags: %% Cell type:code id:8502cf2e-8bea-4707-811c-f4e6e1de3c8f tags:
``` julia ``` julia
t = 'a', 'b', 'c', 'd', 'e' t = 'a', 'b', 'c', 'd', 'e'
``` ```
%% Cell type:markdown id:d01f5647-a240-4620-9a3a-782835aca39c tags: %% Cell type:markdown id:d01f5647-a240-4620-9a3a-782835aca39c tags:
Although it is not necessary, it is common to enclose tuples in parentheses: Although it is not necessary, it is common to enclose tuples in parentheses:
%% Cell type:code id:bfa31b99-bf9d-49bb-babc-fe8a65248429 tags: %% Cell type:code id:bfa31b99-bf9d-49bb-babc-fe8a65248429 tags:
``` julia ``` julia
t = ('a', 'b', 'c', 'd', 'e') t = ('a', 'b', 'c', 'd', 'e')
``` ```
%% Cell type:markdown id:3fa935e0-0611-4b8a-982c-329c33a74f99 tags: %% Cell type:markdown id:3fa935e0-0611-4b8a-982c-329c33a74f99 tags:
To create a tuple with a single element, you have to include a final comma: To create a tuple with a single element, you have to include a final comma:
%% Cell type:code id:cb1bea15-2b80-43b2-be8e-27507d550fca tags: %% Cell type:code id:cb1bea15-2b80-43b2-be8e-27507d550fca tags:
``` julia ``` julia
t1 = ('a',) t1 = ('a',)
@show typeof(t1) @show typeof(t1)
t2 = ('a') t2 = ('a')
@show typeof(t2); @show typeof(t2);
``` ```
%% Cell type:markdown id:193457ac-4e4b-4e58-8c28-6d8b4331d532 tags: %% Cell type:markdown id:193457ac-4e4b-4e58-8c28-6d8b4331d532 tags:
Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple: Another way to create a tuple is the built-in function tuple. With no argument, it creates an empty tuple:
%% Cell type:code id:952acafe-ca5d-4b58-8969-224b0fe3a28f tags: %% Cell type:code id:952acafe-ca5d-4b58-8969-224b0fe3a28f tags:
``` julia ``` julia
t3 = tuple() t3 = tuple()
@show typeof(t3) @show typeof(t3)
t4 = tuple(1, 'a', π) t4 = tuple(1, 'a', π, 12.0)
@show typeof(t4); @show typeof(t4);
``` ```
%% Cell type:markdown id:729c3597-1a35-4a26-ae7a-6dadee31daeb tags: %% Cell type:markdown id:729c3597-1a35-4a26-ae7a-6dadee31daeb tags:
Using the bracket operator it is possible to access an element. Note, differently from other programming languages (for example C, C++, Python) in Julia the first element is 1. Using the bracket operator it is possible to access an element. Note, differently from other programming languages (for example C, C++, Python) in Julia the first element is 1.
%% Cell type:code id:9817c28f-428d-4d5b-8384-608f9b4d763d tags: %% Cell type:code id:9817c28f-428d-4d5b-8384-608f9b4d763d tags:
``` julia ``` julia
t4[2] t4[2]
``` ```
%% Cell type:markdown id:2519be57-8c10-4878-a772-017b099f6a4c tags:
It is also possible to get multiple elements by using slices.
%% Cell type:code id:c48ac07f-3a4e-4bb8-9551-2973ea8d2f9c tags:
``` julia
@show t4[1:3];
```
%% Cell type:markdown id:aeda8602-f9da-4173-a692-54e2e9a0e178 tags: %% Cell type:markdown id:aeda8602-f9da-4173-a692-54e2e9a0e178 tags:
But if you try to modify one of the elements of the tuple, you get an error: But if you try to modify one of the elements of the tuple, you get an error:
%% Cell type:code id:cfc94cc9-832c-45d2-85b8-aaf789f33f6a tags: %% Cell type:code id:cfc94cc9-832c-45d2-85b8-aaf789f33f6a tags:
``` julia ``` julia
t4[2] = 'b' t4[2] = 'b'
``` ```
%% Cell type:markdown id:b9f13b5c-9e61-46b9-a47d-f90199bd7bd2 tags: %% Cell type:markdown id:b9f13b5c-9e61-46b9-a47d-f90199bd7bd2 tags:
Because tuples are immutable, you can’t modify the elements. Because tuples are immutable, you can’t modify the elements.
%% Cell type:markdown id:a10cb9a7-8f44-44f8-831f-178b780e4ac9 tags: %% Cell type:markdown id:a10cb9a7-8f44-44f8-831f-178b780e4ac9 tags:
Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x ÷ y and then x % y. It is better to compute them both at the same time. Strictly speaking, a function can only return one value, but if the value is a tuple, the effect is the same as returning multiple values. For example, if you want to divide two integers and compute the quotient and remainder, it is inefficient to compute x ÷ y and then x % y. It is better to compute them both at the same time.
The built-in function `divrem` takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple: The built-in function `divrem` takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:
%% Cell type:code id:d1dde137-036f-4b93-8010-13b3e835ebd8 tags: %% Cell type:code id:d1dde137-036f-4b93-8010-13b3e835ebd8 tags:
``` julia ``` julia
t = divrem(7, 3) t = divrem(7, 3)
``` ```
%% Cell type:markdown id:ea615dbd-effb-4442-b160-20e7c9b6c22e tags: %% Cell type:markdown id:ea615dbd-effb-4442-b160-20e7c9b6c22e tags:
Alternatively, we can use tuple assignment to store the elements separately: Alternatively, we can use tuple assignment to store the elements separately:
%% Cell type:code id:c4969556-7945-43c9-8b96-1ea1032cbb3c tags: %% Cell type:code id:c4969556-7945-43c9-8b96-1ea1032cbb3c tags:
``` julia ``` julia
q, r = divrem(7, 3) q, r = divrem(7, 3)
@show q r; @show q r;
``` ```
%% Cell type:markdown id:4574e191-aaa8-4834-8837-54947d6ddf30 tags: %% Cell type:markdown id:4574e191-aaa8-4834-8837-54947d6ddf30 tags:
### Gather and scatter ### Gather and scatter
Functions can take a variable number of arguments. A parameter name that ends with `...` gathers arguments into a tuple. For example, `printall` takes any number of arguments and prints them one by line: Functions can take a variable number of arguments. A parameter name that ends with `...` gathers arguments into a tuple. For example, `printall` takes any number of arguments and prints them one by line:
%% Cell type:code id:43f8c7ad-5ac2-425e-a50f-c45624bb3d8a tags: %% Cell type:code id:43f8c7ad-5ac2-425e-a50f-c45624bb3d8a tags:
``` julia ``` julia
function printall(args...) function printall(args...)
for arg in args for arg in args
println(arg) println(arg)
end end
end end
printall(1) printall(1)
printall(1, 2.0, '3') printall(1, 2.0, '3')
``` ```
%% Cell type:markdown id:eb662374-fe83-49d7-a5be-d9582d037ad1 tags: %% Cell type:markdown id:eb662374-fe83-49d7-a5be-d9582d037ad1 tags:
The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the `...` operator. For example, `divrem` takes exactly two arguments; it doesn’t work with a tuple: The complement of gather is scatter. If you have a sequence of values and you want to pass it to a function as multiple arguments, you can use the `...` operator. For example, `divrem` takes exactly two arguments; it doesn’t work with a tuple:
%% Cell type:code id:bf55fc10-8432-41e3-bd6c-2244c8c96513 tags: %% Cell type:code id:bf55fc10-8432-41e3-bd6c-2244c8c96513 tags:
``` julia ``` julia
t = (7, 3) t = (7, 3)
divrem(t) divrem(t)
``` ```
%% Cell type:markdown id:d05def39-3244-4acd-a082-a7ee532f8f1d tags: %% Cell type:markdown id:d05def39-3244-4acd-a082-a7ee532f8f1d tags:
But if you scatter the tuple, it works: But if you scatter the tuple, it works:
%% Cell type:code id:e7df53bc-6b2d-4501-9ca8-61e3cb79eb1a tags: %% Cell type:code id:e7df53bc-6b2d-4501-9ca8-61e3cb79eb1a tags:
``` julia ``` julia
t = (7, 3) t = (7, 3)
divrem(t...) divrem(t...)
``` ```
%% Cell type:markdown id:2cf01c32-9d1b-4e83-9375-f737e51c58ed tags: %% Cell type:markdown id:2cf01c32-9d1b-4e83-9375-f737e51c58ed tags:
### Dictionaries and Tuples ### Dictionaries and Tuples
%% Cell type:markdown id:00e97ccc-8e64-4eef-84be-85a266eb3490 tags: %% Cell type:markdown id:00e97ccc-8e64-4eef-84be-85a266eb3490 tags:
Dictionaries can be used as iterators that iterate the key-value pairs. You can use it in a `for` loop like this: Dictionaries can be used as iterators that iterate the key-value pairs. You can use it in a `for` loop like this:
%% Cell type:code id:ed483334-36d0-4700-b178-cd9dc5f12189 tags: %% Cell type:code id:ed483334-36d0-4700-b178-cd9dc5f12189 tags:
``` julia ``` julia
d = Dict('a'=>1, 'b'=>2, 'c'=>3); d = Dict('a'=>1, 'b'=>2, 'c'=>3);
for (key, value) in d for (key, value) in d
println(key, " ", value) println(key, " ", value)
end end
``` ```
%% Cell type:markdown id:dcb05236-810a-410b-aaa0-0cb431e3e64f tags: %% Cell type:markdown id:dcb05236-810a-410b-aaa0-0cb431e3e64f tags:
It is common to use tuples as keys in dictionaries. For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write: It is common to use tuples as keys in dictionaries. For example, a telephone directory might map from last-name, first-name pairs to telephone numbers. Assuming that we have defined last, first and number, we could write:
%% Cell type:markdown id:e5462d35-fa68-42d8-ba00-c5dd1747c557 tags: %% Cell type:markdown id:e5462d35-fa68-42d8-ba00-c5dd1747c557 tags:
`directory[last, first] = number` `directory[last, first] = number`
%% Cell type:markdown id:9980d710-392b-4716-b44d-98e6c5c8b838 tags: %% Cell type:markdown id:9980d710-392b-4716-b44d-98e6c5c8b838 tags:
### Named tuples ### Named tuples
%% Cell type:markdown id:e514c4bd-c17c-44f4-a89f-88154cc1bf6c tags: %% Cell type:markdown id:e514c4bd-c17c-44f4-a89f-88154cc1bf6c tags:
Named tuples are a special type of tuple in Julia where each element has a specific name associated with it. This allows you to access elements by their names, making the code more readable and self-explanatory. Named tuples are a special type of tuple in Julia where each element has a specific name associated with it. This allows you to access elements by their names, making the code more readable and self-explanatory.
%% Cell type:code id:78fb5959-407a-4128-9287-bb9d455f22dc tags: %% Cell type:code id:78fb5959-407a-4128-9287-bb9d455f22dc tags:
``` julia ``` julia
person = (name = "Michele", age = 28, city = "Stuttgart") person = (name = "Michele", age = 28, city = "Stuttgart")
``` ```
%% Cell type:markdown id:63075b2d-ef86-48e4-8f84-981f81fdece0 tags: %% Cell type:markdown id:63075b2d-ef86-48e4-8f84-981f81fdece0 tags:
Named tuples are immutable, however it is possible to update the content, or to add new elements, by creating a new version. For example: Named tuples are immutable, however it is possible to update the content, or to add new elements, by creating a new version. For example:
%% Cell type:code id:ecd22e07-5ba3-4f11-bc77-d967a6fc3fe8 tags: %% Cell type:code id:ecd22e07-5ba3-4f11-bc77-d967a6fc3fe8 tags:
``` julia ``` julia
updated_person = (person..., age = 29) updated_person = (person..., age = 29)
updated_person = (person..., number = "0711 ...") updated_person = (person..., number = "0711 ...")
``` ```
%% Cell type:code id:3409d1a3-85da-470c-bc5b-4ba9ecb53591 tags: %% Cell type:markdown id:347fe4ea-5b63-4fb8-91bc-2b7b8a0c6a30 tags:
### Exercises
- Write a function `swap_first_last` that takes a tuple and returns a new tuple with the first and last elements swapped. Tip: use a combination of the `...` operator and of this slice `[2:end-1]`.
%% Cell type:code id:3721b654-b182-426d-b799-a69e0b53a550 tags:
``` julia
```
%% Cell type:markdown id:647530cd-480a-414f-a8ec-1375e05a9e1b tags:
## Structs
%% Cell type:markdown id:00b9bdb1-86ad-47f6-b8c3-88e85878eaff tags:
At this point you know how to use functions to organize code and built-in types to organize data. The next step is to learn how to build your own types to organize both code and data.
We have used many of Julia’s built-in types; now we are going to define a new type. As an example, we will create a type called Point that represents a point in two-dimensional space.
There are several ways we might represent points in Julia:
- We could store the coordinates separately in two variables, x and y.
- We could store the coordinates as elements in an tuple.
- We could create a new type to represent points as objects.
Here we will investigate the third option.
%% Cell type:markdown id:9aa53d46-033b-4559-a5d8-e95357a257a5 tags:
A programmer-defined composite type is also called a struct. The struct definition for a point looks like this:
%% Cell type:code id:c2e3f646-2d82-46a4-a265-01b919412c6d tags:
``` julia
struct Point
x::Real
y::Real
end
```
%% Cell type:markdown id:fb9be134-9730-4dbd-9e05-51dd94e9d8e0 tags:
The header indicates that the new struct is called Point. The body defines the attributes or fields of the struct. The Point struct has two fields: x and y.
A struct is like a factory for creating objects. To create a point, you call Point as if it were a function having as arguments the values of the fields. When Point is used as a function, it is called a constructor. The constructor returns an instance of the object.
%% Cell type:code id:197339a2-0d8b-4882-bab2-80ba56410f21 tags:
``` julia
p = Point(3.0, 4.0)
@show p;
```
%% Cell type:markdown id:b0134aa7-f356-4d71-9d46-959bd3cfe89a tags:
The type speficication (`::Real`) is optional, but can be helpful to enforce correct usage of the struct.
%% Cell type:code id:849f1460-d228-4b22-a797-1077d75d1a2d tags:
``` julia
p = Point("a", 4.0)
```
%% Cell type:markdown id:e3011b23-816d-4aa2-be61-7eb8f4aee9d1 tags:
The values of the fields can be accessed using the `.` operator.
%% Cell type:code id:00d090e4-d74d-4fad-ae8b-369c1046e48b tags:
``` julia
@show p.x p.y;
@show distance = sqrt(p.x^2 + p.y^2);
```
%% Cell type:markdown id:08748a8c-f76c-4f14-b3d2-9db99fb28e87 tags:
Structs are however by default immutable, after construction the fields can not change value:
%% Cell type:code id:91bd6248-a358-43e3-90cc-6b8398445aaf tags:
``` julia
p.x = 2
```
%% Cell type:markdown id:629c1004-5d0f-4093-b546-473c94c91b44 tags:
Where required, mutable composite types can be declared with the keyword mutable struct. Here is the definition of a mutable point:
%% Cell type:code id:804c2c32-7a84-4261-88d8-1bad6ba5e18c tags:
``` julia
mutable struct MPoint
x::Real
y::Real
end
p = MPoint(3.0, 4.0)
p.x = 2.0
@show p;
```
%% Cell type:markdown id:1bd558dd-e6c3-4dc0-9476-768c59178708 tags:
A third option is to let some fields of an unmutable struct to be mutable. For example a dictionary inside an unmutable struct can be modified.
%% Cell type:code id:62cab9ae-5e58-401c-bc93-17720914e530 tags:
``` julia
struct Book
title::String
author::String
properties::Dict{String, Any}
end
book = Book("Der Hobbit", "J.R.R. Tolkien", Dict("available" => false))
@show book
book.properties["available"] = true
@show book;
```
%% Cell type:markdown id:31e2098b-5079-4cb5-bf64-a7a78754af32 tags:
You can pass an instance as an argument in the usual way. For example:
%% Cell type:code id:e6113221-0c03-484a-99e0-f7d4fab70f03 tags:
``` julia
function printpoint(p)
println("($(p.x), $(p.y))")
end
printpoint(p)
```
%% Cell type:code id:d5c6fa9e-c31d-4aff-a3fd-db3449904519 tags:
``` julia
function printbook(book)
println("Title: $(book.title)")
println("Author: $(book.author)")
available = book.properties["available"]
println("Available: $(available)")
end
printbook(book)
```
%% Cell type:markdown id:3b12a004-81d9-4bbc-9e2e-d2c281dcbe18 tags:
Functions can return instances as return values.
%% Cell type:code id:9c57c9f7-c4fd-4263-a55f-62f123aaaa8a tags:
``` julia
function find_center(point1, point2)
x = (point1.x + point2.x)/2.0
y = (point1.y + point2.y)/2.0
return Point(x, y)
end
point1 = Point(0.0, 0.0)
point2 = Point(10.0, 10.0)
@show find_center(point1, point2);
```
%% Cell type:markdown id:078b31ab-11e1-4596-8271-f0d33418eab8 tags:
### Exercise
- Write a function called `point_distance` which takes two points as arguments and returns the Euclidean distance between them.
%% Cell type:code id:b5957a05-e396-41c3-9b8f-f14f089115ab tags:
``` julia
```
%% Cell type:markdown id:0fb1f6bc-e6e5-4897-bbb6-880e40e3bf20 tags:
### References and values
Each object (instance of a struct) is stored at some memory address. The operator `===` checks if two variables point to the same memory address of the object. For example
book_copy = book
@show book_copy === book;
%% Cell type:markdown id:636b6713-f4ed-4220-a159-2918bd44f78e tags:
This means that any change made to `book_copy` will also modify `book`.
%% Cell type:code id:a9c46bac-d234-4616-a604-63bdf03b1393 tags:
``` julia
book.properties["available"] = true
book_copy.properties["available"] = false
@show book;
```
%% Cell type:markdown id:6bcbf983-40fa-4fc8-8eca-7cd7c45778dc tags:
If a new, distinct, object is needed (in other words, a copy by value), we can use the function `deepcopy`.
%% Cell type:code id:c36d23c8-2292-4568-aef4-7416c6f3e538 tags:
``` julia
book_copy = deepcopy(book)
@show book_copy === book;
```
%% Cell type:markdown id:02cc3ec7-e712-4c4b-abf5-9bfc98e68a91 tags:
Finally, the `==` operator between structs defaults to the `===` operator as Julia has no way of knowing how to compare custom structs. However, it is always possible to reimplement the `==` operator for our custom types.
%% Cell type:code id:3372eb89-cde6-4040-aa51-b4e76af97851 tags:
``` julia
import Core
function ==(book1::Book, book2::Book)
return book1.title == book2.title && book1.author == book2.author
end
```
%% Cell type:code id:03594f56-48ee-4152-a42f-8e3588c3ab2e tags:
``` julia ``` julia
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment