Baby steps with Julia
Posted on Sun 04 October 2020 in julia
Hello World¶
In [1]:
println("hello world")
OK, so I managed to copy and paste a solution the venerable "Hello World" program. Similar syntax to Python, different function name. No semicolons so far too ;)
Quotes have different meanings¶
In [2]:
a = 'a'
Out[2]:
In [3]:
b = "a"
Out[3]:
Everything seems to return a value¶
In [4]:
c = 99
Out[4]:
Assignment can be chained¶
In [5]:
e = d = 101
Out[5]:
In [6]:
d
Out[6]:
In [7]:
e
Out[7]:
How about list comprehension?¶
In [8]:
x, y, z = 1, 2, 3
Out[8]:
In [9]:
println(x, y, z)
In [10]:
x, y, z = ["a", 'b', 3]
Out[10]:
Handling conditions¶
In [11]:
i = 1
if i >= 0
println("It sure is")
end
In [12]:
if i != 0
println("No they're not")
end
Whitespace not so important¶
There's not a semi colon in sight but whitespace isn't important
In [13]:
if i >= 0
println("It still is")
end
In [14]:
i = 1
if i >= 0
println("Even this")
end
Basic loops¶
Ranges can be specified easily and ranges are inclusive
In [15]:
for i in -2:3
println(i)
end
Arrays look Python-like¶
In [16]:
my_array = [1,2,3]
Out[16]:
Arrays can hold a mix of types¶
In [17]:
my_array = ["string",'c', 3,["a"]]
for i in my_array
print(i, ", ")
end
There are dictionaries too¶
In [18]:
my_dict = Dict("frogger"=>"one", 2=>'1', 'c'=>"three")
Out[18]:
In [19]:
for k in keys(my_dict)
println(k)
end
Not sure what I'm getting here¶
In [20]:
for k in my_dict
println(k)
end
Function syntax is clear¶
In [21]:
function my_func(x)
println(x * x)
return -1
end
Out[21]:
Not sure how to avoid this output¶
In [23]:
y = my_func(8)
Out[23]:
In [29]:
y = my_func(8);
In [31]:
y;
Packages are installed like this¶
This I found a little counter intuitive coming from Python. Packages are added from inside the shell rather than having an external package manager like pip.
In [33]:
using Pkg
In [36]:
Pkg.add("HTTP")
Or you can use the inbuilt Pkg shell¶
Press "]" to enter when in the Julia shell
(@v1.4) pkg> add HTTP
Resolving package versions...
Updating `~/.julia/environments/v1.4/Project.toml`
[cd3eb016] + HTTP v0.8.19
Updating `~/.julia/environments/v1.4/Manifest.toml`
[cd3eb016] + HTTP v0.8.19
[83e8ac13] + IniFile v0.5.0
Using a package¶
Using is like importing. This shows how to make a simple request using the HTTP package
In [37]:
using HTTP
response = HTTP.get("https://swapi.dev/api/people/4/")
response = String(response.body)
Out[37]:
Pretty printing JSON¶
In [38]:
using JSON
response = HTTP.get("https://swapi.dev/api/people/22/")
response = String(response.body)
JSON.print(JSON.parse(response), 4)
Creating a function¶
Also shows simple error handling mechanism
In [39]:
function make_API_call(url)
try
response = HTTP.get(url)
return String(response.body)
catch e
return "Something is borked: $e"
end
end
Out[39]:
In [40]:
response = make_API_call("https://swapi.dev/api/vehicles/45/")
JSON.print(JSON.parse(response), 4)
Looks OK so far ;)¶
I've barely touched the service but it's interesting...