Baby steps with Julia

Posted on Sun 04 October 2020 in julia

Hello World

In [1]:
println("hello world")
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]:
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
In [3]:
b = "a"
Out[3]:
"a"

Everything seems to return a value

In [4]:
c = 99
Out[4]:
99

Assignment can be chained

In [5]:
e = d = 101
Out[5]:
101
In [6]:
d
Out[6]:
101
In [7]:
e
Out[7]:
101

How about list comprehension?

In [8]:
x, y, z = 1, 2, 3
Out[8]:
(1, 2, 3)
In [9]:
println(x, y, z)
123
In [10]:
x, y, z = ["a", 'b', 3]
Out[10]:
3-element Array{Any,1}:
  "a"
  'b'
 3

Handling conditions

In [11]:
i = 1
if i >= 0
    println("It sure is")
end
It sure is
In [12]:
if i != 0
    println("No they're not")
end
No they're not

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
It still is
In [14]:
i = 1
       if i >= 0
println("Even this")
   end
Even this

Basic loops

Ranges can be specified easily and ranges are inclusive

In [15]:
for i in -2:3
    println(i)
end
-2
-1
0
1
2
3

Arrays look Python-like

In [16]:
my_array = [1,2,3]
Out[16]:
3-element Array{Int64,1}:
 1
 2
 3

Arrays can hold a mix of types

In [17]:
my_array = ["string",'c', 3,["a"]]

for i in my_array
    print(i, ", ")
end
string, c, 3, ["a"], 

There are dictionaries too

In [18]:
my_dict = Dict("frogger"=>"one", 2=>'1', 'c'=>"three")
Out[18]:
Dict{Any,Any} with 3 entries:
  2         => '1'
  "frogger" => "one"
  'c'       => "three"
In [19]:
for k in keys(my_dict)
    println(k)
end
2
frogger
c

Not sure what I'm getting here

In [20]:
for k in my_dict
    println(k)
end
Pair{Any,Any}(2, '1')
Pair{Any,Any}("frogger", "one")
Pair{Any,Any}('c', "three")

Function syntax is clear

In [21]:
function my_func(x)
    println(x * x)
    return -1
end
Out[21]:
my_func (generic function with 1 method)

Not sure how to avoid this output

In [23]:
y = my_func(8)
64
Out[23]:
-1
In [29]:
y = my_func(8);
64
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")
   Updating registry at `~/.julia/registries/General`
    
   Updating git-repo `https://github.com/JuliaRegistries/General.git`
[1mFetching: [========================================>]  100.0 %
  Resolving package versions...
   Updating `~/.julia/environments/v1.4/Project.toml`
  [cd3eb016] + HTTP v0.8.19
   Updating `~/.julia/environments/v1.4/Manifest.toml`
 [no changes]

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]:
"{\"name\":\"Darth Vader\",\"height\":\"202\",\"mass\":\"136\",\"hair_color\":\"none\",\"skin_color\":\"white\",\"eye_color\":\"yellow\",\"birth_year\":\"41.9BBY\",\"gender\":\"male\",\"homeworld\":\"http://swapi.dev/api/planets/1/\",\"films\":[\"http://swapi.dev/api/films/1/\",\"http://swapi.dev/api/films/2/\",\"http://swapi.dev/api/films/3/\",\"http://swapi.dev/api/films/6/\"],\"species\":[],\"vehicles\":[],\"starships\":[\"http://swapi.dev/api/starships/13/\"],\"created\":\"2014-12-10T15:18:20.704000Z\",\"edited\":\"2014-12-20T21:17:50.313000Z\",\"url\":\"http://swapi.dev/api/people/4/\"}"

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)
{
    "skin_color": "fair",
    "eye_color": "brown",
    "edited": "2014-12-20T21:17:50.349000Z",
    "films": [
        "http://swapi.dev/api/films/2/",
        "http://swapi.dev/api/films/3/",
        "http://swapi.dev/api/films/5/"
    ],
    "starships": [
        "http://swapi.dev/api/starships/21/"
    ],
    "name": "Boba Fett",
    "height": "183",
    "birth_year": "31.5BBY",
    "mass": "78.2",
    "vehicles": [],
    "created": "2014-12-15T12:49:32.457000Z",
    "hair_color": "black",
    "url": "http://swapi.dev/api/people/22/",
    "species": [],
    "gender": "male",
    "homeworld": "http://swapi.dev/api/planets/10/"
}

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]:
make_API_call (generic function with 1 method)
In [40]:
response = make_API_call("https://swapi.dev/api/vehicles/45/")
JSON.print(JSON.parse(response), 4)
{
    "edited": "2014-12-20T21:30:21.716000Z",
    "films": [
        "http://swapi.dev/api/films/5/"
    ],
    "model": "Koro-2 Exodrive airspeeder",
    "max_atmosphering_speed": "800",
    "crew": "1",
    "length": "6.6",
    "name": "Koro-2 Exodrive airspeeder",
    "passengers": "1",
    "created": "2014-12-20T17:17:33.526000Z",
    "pilots": [
        "http://swapi.dev/api/people/70/"
    ],
    "cargo_capacity": "80",
    "url": "http://swapi.dev/api/vehicles/45/",
    "vehicle_class": "airspeeder",
    "consumables": "unknown",
    "manufacturer": "Desler Gizh Outworld Mobility Corporation",
    "cost_in_credits": "unknown"
}

Looks OK so far ;)

I've barely touched the service but it's interesting...