Julia Tutorial

Welcome to Julia!

Julia is a new language focused on technical and numerical computing, and similar to systems such as Octave (or MATLAB), IDL, SciLab, and Python+NumPy+SciPy.

Although Julia's current focus is technical computing, due to a well-considered design and an extensive mathematical library, Julia has also been used to write such things as web servers, and microframeworks, raytracers and a Quake rendering engine.

This tutorial is organized as follows:

  • Why Julia?
  • Community and contribution
  • Basics: introduction to the language
  • Numbers, Arithmetic, and Arrays
  • Types and Multiple Dispatch

Why Julia?

Julia has been designed from the ground up for the needs of modern technical computing.

  • Julia's efficient front-end and LLVM-based JIT compiler provide compelling performance within 2x of C on a range of benchmarks.
  • Therefore, the transition from "correct" to "fast" can be accomplished within a single language, drastically simplifying the development experience.
  • Optional type annotations and multiple dispatch combine to form a powerful paradigm for both mathematical and general programming.
  • Scalable computing is included from the start, with powerful distributed array primitives and interfaces to a growing number of computation platforms.
  • Julia is fun: express powerful ideas in concise code with judicious use of anonymous functions, operator overloading, Unicode operators, duck-typing, excellent shell support, and much more!

Community and contribution

As a young, open-source language and community, there are nearly unlimited opportunities for contribution. The community strives to be welcoming to new contributors in any capacity. Some suggested areas to pursue contribution:

  • documentation: as with any open-source project, good documentation is critical for continued growth (and as such, contributions are deeply appreciated!)

  • packages: there are a huge number of "greenfield" packages just waiting to be written (or implemented in pure Julia). Come build something new, just the way you've always wanted it!

  • library: Because Julia's library is written in the language itself, the barrier-to-entry for contributions to the core repository is much lower than other projects written in a mix of languages. Pull requests are always welcome! Here is one list of potential areas to contribute.

  • core: the core of Julia is written in high-quality, terse, highly-readable C. Julia's code generation is written in C++ (with extern C entry points) in order to interface with the LLVM JIT engine. There are many optimizations left to be written (for even better performance), and anyone with the skills and interest is welcome and encouraged to contribute.

Julia Activity Hubs

Basics

Hello, world!

We start with the canonical introductory program:


In [3]:
println("Hello, world!")


Hello, world!

Simple enough, right? Now, let's make a function:


In [1]:
function sayhello(name)
    println("Hello, ", name)
end


Out[1]:
sayhello (generic function with 1 method)

...and call it:


In [2]:
sayhello("friend!")


Hello, friend!

The "Hello, world" example could be written on the command line as:

julia -e 'println("Hello, world")

Or as a script, by placing the command in hello.jl and running:

> julia hello.jl

To write text without appending a newline, use print():


In [6]:
print(1)
print("   2")


1   2

IJulia Notes

This tutorial can be run in IJulia, and viewed statically using the IPython notebook viewer (IJulia is built on the remarkable IPython software)

In IJulia, each In [#] line denotes an individual cell containing one or more lines of Julia code, which may be executed by pressing Shift-Enter. Program output or errors will be displayed immediately below the input cell, and the return value of the last command in the cell will be printed in Out[#] box.

In [1]: println("Hello, world!")
Hello, world!                         <-- standard output is captured and printed sans Out[] prefix.

In [3]: "Hello, friend!"
Out[3]: "Hello, friend!"              <-- expression values are printed in the Out[] cell

Variables

Variables allow storage and reuse of the results of earlier calculations. There are very few limits on variable names, and variable names may be written in Unicode, as will be demonstrated shortly.

Naming variables and Assigning them values

Use a single equal = sign to assign variables.


In [1]:
i = 2.0


Out[1]:
2.0

We can define complex variables using the special symbol im denoting the imaginary unit:


In [2]:
e = 1+1im


Out[2]:
1 + 1im

Julia contains a set of built-in constants, which may be used in computation or assigned to other variable names:


In [3]:
supercalifragilisticexpialidocious = pi

supercalifragilisticexpialidocious/2


Out[3]:
1.5707963267948966

The cell above calculates pi/2 using the special variable supercalifragilisticexpialidocious that we have set as equal pi, and prints the result to Out [ ].

You can even use names of built-in variables and functions, if you so choose. (This is usually not a good idea since it is very easy to write confusing code; Julia will warn you against overwriting built-ins, but will not stop you in this case)

You cannot, however, use the names of Julia keywords for your variable names.


In [13]:
end=0.5im


syntax: unexpected end
at In[13]:1

Comparison

Julia supports the standard set of comparison operators:

<  >  ==  <=  >=

In [10]:
supercalifragilisticexpialidocious == pi


Out[10]:
true

In [3]:
pi == 3.2    # Sorry, Indiana


Out[3]:
false

In [5]:
pi < 3.2


Out[5]:
true

Inexact comparisons should use isapprox


In [16]:
isapprox(exp(im * pi) + 1, 0)


Out[16]:
true

Characters and strings

A single character is denoted with single-quote marks, and characters may be input by ASCII or Unicode value using the char function:


In [17]:
'a' == char(97) # ASCII 97 is 'a'


Out[17]:
true

Strings and escaped characters

Strings are denoted by double-quote signs, as in many other languages. Some characters may only be printed as escape sequences. An escape sequence starts with a backslash \ and ends with a single character that follows it.

Here are two very common examples:


In [20]:
println("1\n2") #Newline


1
2

In [21]:
println("1\t2") #Tab


1	2

To print the baskslash character itself, it must be escaped with another backslash.


In [17]:
println("1\\2") #backslash


1\2

The dollar sign has special meaning in Julia and must be escaped to print correctly.


In [18]:
println("\$")


$

What happens if we don't escape it?


In [19]:
println("$pi")


π = 3.1415926535897...

The dollar sign performs string interpolation, splicing the value of the variable name after the $ into the output. Attempting to splice a non-existent variable results in an error:


In [20]:
println("$α")


α not defined
at In[20]:1

Unicode support (or: fancy characters)

Julia supports Unicode for string contents as well as variable names. So variables:


In [21]:
α =  7.29735257E-3


Out[21]:
0.00729735257

and formulae:


In [22]:
z = 3+4im
ξ = 1/z


Out[22]:
0.09090909090909091

May be written with any appropriate character.

Or even using non-Latin alphabets!


In [23]:
アルコール = 0.1337
アルコール^2


Out[23]:
0.017875690000000003

On some operating systems and browsers, you may even be able to print pizza!:


In [24]:
print(char(0x1f355))
print(" = ")
print('\U263A')


🍕 = ☺

Regular expressions

Julia includes a Perl-compatible regular expression support. A regular expression is declared using the special syntax: r prefixed immediately before the regex string:


In [25]:
re = r".*(brown fox).*(lazy dog)"


Out[25]:
r".*(brown fox).*(lazy dog)"

In [26]:
m = match(re, "The quick brown fox jumped over the lazy dog.")


Out[26]:
RegexMatch("The quick brown fox jumped over the lazy dog", 1="brown fox", 2="lazy dog")

In [27]:
m.captures[1]


Out[27]:
"brown fox"

In [28]:
m.captures[2]


Out[28]:
"lazy dog"

Control Flow

if/else

Parentheses are optional:


In [29]:
if false
    println("Twilight zone...")
    
elseif ( 1 == 2 )
    println("We can actually do math, right?")
    
else
  println("All is well. Both conditions are false.")
end


All is well. Both conditions are false.

for loops


In [30]:
for i in 1:10
    print(i, " ")
end


1 2 3 4 5 6 7 8 9 10 

Breaking it down:

  • the expression i in 1:10 returns an iterator over the range 1 to 10
  • for loop executes the enclosing codeblock for all values of i
  • instead of println, we use simply print, which does not add a newline after each output

We can also skip elements using the continue keyword:


In [31]:
for i in 1:10
    (i > 5 && i < 9) && continue
    
    print(i, " ")
end


1 2 3 4 5 9 10 

Exercise

Write the for loop above as a while loop instead.


In [ ]:

Input and output

So how do we get data out of and into Julia? Here is the simplest possible example:


In [119]:
# opening a file:

vecfile = open("/tmp/myvector.txt", "w")


Out[119]:
IOStream(<file /tmp/myvector.txt>)

Notice that the open function returns a variable with the type IOStream. This is important, because the behavior of other functions will be influenced by the type of this variable.

Exercise

Write a function that prints the comma-separated numbers from 1 to 5, in increments of .5, to the file handle vecfile defined above.

  • HINT 1: the print function is overloaded, and will accept an IOStream as the first argument.
  • HINT 2: the range syntax accepts a middle argument specifying step-size: start:step:end
  • Bonus: don't print the final comma.

In [23]:
function writenumbers(fhandle)
  # implementation goes here
end


Out[23]:
writenumbers (generic function with 1 method)

In [121]:
writenumbers(vecfile)

Be sure to clean up the file handle:


In [122]:
close(vecfile)

Reading it back

Now that we have a file, let's read the data back in:


In [26]:
f_in = open("/tmp/myvector.txt", "r")
myvec1 = split( readall(f_in), "," )


Out[26]:
10-element Array{String,1}:
 "1.0"
 "1.5"
 "2.0"
 "2.5"
 "3.0"
 "3.5"
 "4.0"
 "4.5"
 "5.0"
 ""   

Since this is a CSV file, we could also use the built-in readcsv function:


In [27]:
seekstart(f_in)
myvec1 = readcsv( f_in )


Out[27]:
1x9 Array{Float64,2}:
 1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0

We have used the built-in function seekstart to go back to the beginning of the file, so that we don't have to open it again.

Data structures

Julia includes a number of useful data structures; here are two important examples:

Lists

Here we define a list containing a strange, heterogenous grab bag of stuff:


In [28]:
allmixedup = { 1, pi, "foo", myvec1, "biggles", sayhello }


Out[28]:
6-element Array{Any,1}:
     1                                                                  
 π = 3.1415926535897...                                                 
      "foo"                                                             
      1x9 Array{Float64,2}:
 1.0  1.5  2.0  2.5  3.0  3.5  4.0  4.5  5.0
      "biggles"                                                         
      sayhello                                                          

Square brackets, [ ], are used to retrieve the contents at a specific index.

Note: Julia uses 1-based indexing just like Fortran. Everything will be ok.


In [30]:
allmixedup[1]


Out[30]:
1

In [31]:
allmixedup[5]


Out[31]:
"biggles"

In [38]:
allmixedup[6]


Out[38]:
sayhello (generic function with 1 method)

As demonstrated above, can store a reference to a function like any other object!

List elements can be set by assigning to an index:


In [126]:
push!(allmixedup, "another random string")


Out[126]:
7-element Array{Any,1}:
     1                       
 π = 3.1415926535897...      
      "foo"                  
      [""]                   
      "biggles"              
      sayhello               
      "another random string"

Exercise

call the sayhello function by using the reference stored in allmixedup.


In [32]:

Dictionaries (aka: maps or associative arrays)

Julia provides an efficient associative array implementation and, like Python, there is a compact comprehension syntax to define a mapping set:


In [41]:
mymap = { 1 => "one", "two" => 2, "sayhello" => sayhello, sayhello => "function called `sayhello`"}


Out[41]:
{"sayhello"=>sayhello,sayhello=>"function called `sayhello`",1=>"one","two"=>2}

(mymap above accepts any type of object, but as will be seen, dictionary key and value types may be restricted)

Key-value pairs may also be assigned individually:


In [42]:
mymap[7.3] = "seven point 3"


Out[42]:
"seven point 3"

Map indexing is similar to lists:


In [43]:
mymap[1]


Out[43]:
"one"

In [44]:
mymap["two"]


Out[44]:
2

In [45]:
mymap["sayhello"]


Out[45]:
sayhello (generic function with 1 method)

In [46]:
mymap[sayhello]


Out[46]:
"function called `sayhello`"

In [47]:
mymap[7.3]


Out[47]:
"seven point 3"

Numbers, Arithmetic, and Arrays

Numbers

Numbers are the soul of Julia, so it is fitting that all numeric types are defined in the language itself. For example, the 64-bit integer is declared as follows (in src/base/base.jl, for the curious):


In [48]:
bitstype 64  Int64   <: Signed

This means that you can define your own data types in pure Julia, and expect the same performance profile as "core" types!

One goal of Julia is to be fast enough that moving to another language for performance should never be necessary.

Binary Representations

We can write numeric literals in binary representation:


In [49]:
0b10 == 2    # There are 10 kinds of programmers...


Out[49]:
true

Julia is also quite willing to expose the when you want to see them. Binary representations are one example, and can be easily inspected:


In [50]:
[ 0  bits(0);  1  bits(1);  2  bits(2);  3  bits(3);  7  bits(7);  8  bits(8);
  16 bits(16); 17 bits(17); 32 bits(32); 33 bits(33); 35 bits(35); 64 bits(64);]


Out[50]:
12x2 Array{Any,2}:
  0  "0000000000000000000000000000000000000000000000000000000000000000"
  1  "0000000000000000000000000000000000000000000000000000000000000001"
  2  "0000000000000000000000000000000000000000000000000000000000000010"
  3  "0000000000000000000000000000000000000000000000000000000000000011"
  7  "0000000000000000000000000000000000000000000000000000000000000111"
  8  "0000000000000000000000000000000000000000000000000000000000001000"
 16  "0000000000000000000000000000000000000000000000000000000000010000"
 17  "0000000000000000000000000000000000000000000000000000000000010001"
 32  "0000000000000000000000000000000000000000000000000000000000100000"
 33  "0000000000000000000000000000000000000000000000000000000000100001"
 35  "0000000000000000000000000000000000000000000000000000000000100011"
 64  "0000000000000000000000000000000000000000000000000000000001000000"

Integers

Literal values without a decimal point are interpreted as integers:


In [51]:
x = 1


Out[51]:
1

In [52]:
typeof(x)


Out[52]:
Int64

Julia has both signed and unsigned Integer types for 8, 16, 32, 64, and 128-bits.

Each Integer type can hold a specific and finite range of values:


In [33]:
[ typemin(Uint8) typemax(Uint8) ;
  typemin(Int8)  typemax(Int8)  ;
  typemin(Int64) typemax(Int64) ; ]


Out[33]:
3x2 Array{Int64,2}:
                    0                  255
                 -128                  127
 -9223372036854775808  9223372036854775807

Floating point

Literals entered with a decimal point are intepreted as floating-point numbers:


In [54]:
y = 2.0


Out[54]:
2.0

In [55]:
[ 2.  typeof(2.);
  .5  typeof(.5); ]


Out[55]:
2x2 Array{Any,2}:
 2.0  Float64
 0.5  Float64

Note that 0 == -0, but they do not have the same binary representation:


In [56]:
0 == -0


Out[56]:
true

In [57]:
[ " 0" bits(0.0)  ;
  "-0" bits(-0.0) ; ]


Out[57]:
2x2 Array{ASCIIString,2}:
 " 0"  "0000000000000000000000000000000000000000000000000000000000000000"
 "-0"  "1000000000000000000000000000000000000000000000000000000000000000"

Julia does arithmetic using machine numbers which can represent only finite ranges and with finite precision (as compared to the idealized $\mathbb{R}$eal numbers). The eps function returns the smallest difference that can be represented by a given type:


In [34]:
[  1.0                    bits(1.0)
   repr(1.0 + eps(1.0))   bits(1.0 + eps(Float64)) ]


Out[34]:
2x2 Array{Any,2}:
 1.0                    …  "0011111111110000000000000000000000000000000000000000000000000000"
  "1.0000000000000002"     "0011111111110000000000000000000000000000000000000000000000000001"

Wrap around

Exceeding the maximum representable type (typemax) for a given type results in wrap-around:


In [40]:
typemax(Int64)


Out[40]:
9223372036854775807

In [41]:
typemax(Int64) + 1


Out[41]:
-9223372036854775808

For more information on numerical representations and accurate computation with machine math, please see the excellent discussion in the Julia manual (and links therein).

Complex numbers

As seen earlie, the imaginary unit is called im in Julia.


In [4]:
z=3+4im


Out[4]:
3 + 4im

After defining a complex variable, addition and multiplication "just work":


In [5]:
z+z


Out[5]:
6 + 8im

In [6]:
z*z'    # z' denotes the conjugate of z (complex, of course)


Out[6]:
25 + 0im

Arithmetic

Operators and conversions

Operations on heterogenous types result in promotion to the most representative common type:


In [64]:
x + y


Out[64]:
3.0

In [65]:
typeof(x + y)


Out[65]:
Float64

In [66]:
0x1 + 2


Out[66]:
3

In [67]:
[ typeof(0x1)   typeof(0x1 + 2) ]


Out[67]:
1x2 Array{DataType,2}:
 Uint8  Int64

For the sake of completeness, here is a review of all of the standard arithmetic operators:


In [68]:
rtmc = [  1+1   -2   1/2   2/3   3\2   2^3   x%y   y^4 ]


Out[68]:
1x8 Array{Float64,2}:
 2.0  -2.0  0.5  0.666667  0.666667  8.0  1.0  16.0

The rtmc assignment above is an example of array declaration, with array elements computed in place using the specified inputs and operations.

Again, Julia converts all operations to the most representative type for given arguments. For example, division between integers results in a floating point number:


In [69]:
[ 2/3  typeof(2/3) ]


Out[69]:
1x2 Array{Any,2}:
 0.666667  Float64

This rule is applied consistently even if the result could be represented exactly by the common type of the input variables:


In [70]:
[ 4/2 typeof(4/2) ]


Out[70]:
1x2 Array{Any,2}:
 2.0  Float64

Array creation

Let's look at several compact ways to create an array, noting in particular the use of array comprehension:


In [71]:
a = ones(5)


Out[71]:
5-element Array{Float64,1}:
 1.0
 1.0
 1.0
 1.0
 1.0

In [72]:
b = [ 5:9 ]    # 5-9, inclusive


Out[72]:
5-element Array{Int64,1}:
 5
 6
 7
 8
 9

In [73]:
c = eye(4)     # returns the 4x4 identity matrix


Out[73]:
4x4 Array{Float64,2}:
 1.0  0.0  0.0  0.0
 0.0  1.0  0.0  0.0
 0.0  0.0  1.0  0.0
 0.0  0.0  0.0  1.0

In [74]:
d = ones(4,4)   # returns a 4x4 matrix of ones


Out[74]:
4x4 Array{Float64,2}:
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0
 1.0  1.0  1.0  1.0

Array arithmetic

We can do arithmetic with array elements:


In [75]:
a[1] + b[1]


Out[75]:
6.0

And with entire arrays, such as addition:


In [76]:
a + b


Out[76]:
5-element Array{Float64,1}:
  6.0
  7.0
  8.0
  9.0
 10.0

... scalar multiplication:


In [77]:
5 * b


Out[77]:
5-element Array{Int64,1}:
 25
 30
 35
 40
 45

... and exponentiation:


In [78]:
b .^ 2


Out[78]:
5-element Array{Int64,1}:
 25
 36
 49
 64
 81

This last one is important: the .^ operator denotes element-wise operation. As a general convention in Julia, element-wise operators are denoted with a dot prefixed to the operator symbol.

Types and Multiple Dispatch

Julia has a powerful type system, and variables carry type information that is automatically inferred at the time of assignment (and helpfully printed by IJulia):


In [79]:
rtmc = [  1   1+1   -2   1/2   2/3   3\2   2^3   x%y   y^4 ]


Out[79]:
1x9 Array{Float64,2}:
 1.0  2.0  -2.0  0.5  0.666667  0.666667  8.0  1.0  16.0

Although it is fully possible to program in Julia without explicit type declarations, the type system is fundamental to higher-level and generic programming. Let's make a quick review of some types encountered so far:


In [80]:
typeof('a')


Out[80]:
Char

In [81]:
typeof("Quick brown fox")


Out[81]:
ASCIIString (constructor with 1 method)

In [82]:
typeof(1)


Out[82]:
Int64

In [83]:
typeof(1.0)


Out[83]:
Float64

In [84]:
typeof([1.0 2.0 3.0])


Out[84]:
Array{Float64,2}

In [85]:
typeof([ 1 => "2", 2 => "2"])


Out[85]:
Dict{Int64,ASCIIString} (constructor with 2 methods)

In [86]:
typeof(allmixedup)


Out[86]:
Array{Any,1}

This last one is special: the Any type is the root of the type hierarchy in Julia.

Example: typed dictionaries

We can explicitly specify the accepted key-value types in a dictionary constructor:


In [87]:
int_to_string = Dict{Int,String}()


Out[87]:
Dict{Int64,String}()

Or, we can ask Julia to select inferred types by using square bracket [ ] comprehension instead of the curly bracket { } comprehension used earlier:


In [88]:
int_to_string = [ 1 => "1", 2 => "2"]


Out[88]:
[2=>"2",1=>"1"]

In [89]:
typeof(int_to_string)


Out[89]:
Dict{Int64,ASCIIString} (constructor with 2 methods)

Assigning an Integer-String pair works:


In [90]:
int_to_string[3] = "foo"


Out[90]:
"foo"

But, unsurprisingly, assigning a String-String pair does not:


In [91]:
int_to_string["item3"] = "baz"


no method convert(Type{Int64},ASCIIString)
at In[91]:1
 in setindex! at dict.jl:412

These last lines failed becase int_to_string expects only Integers as keys, and only strings as values.

Composite types

Julia provides a mechanism to define custom composite (aggregate) types, reminescent of structs in C, and plain-old-data classes in C++.


In [92]:
type LP
    c # Types are optional
    A::Matrix{Float64}
    b::Vector{Float64}
end

randlp(n,m) = LP(rand(n),rand(n,m),rand(m))

mylp = randlp(10,5)

println(mylp.c)


.41658206875707227
.5017688328770391
.4950271332072449
.47894020363889234
.4810285428763976
.5129626979895638
.4894621516145241
.04926848192609756
.35015060687983346
.57393984978873
Warning: imported binding for Int64 overwritten in module Main

Parametric Types

Parametric types take one (or more) type arguments which are used in the final construction of constituent fields:


In [93]:
type LP2{T}
    c::Vector{T}
    A::Matrix{T}
    b::Vector{T}
end

We can construct derived types by specifying the element type in the constructor, between { } curly brackets following the type name:


In [94]:
lp = LP2{Float64}(mylp.c,mylp.A,mylp.b)    # dbl precision


Out[94]:
LP2{Float64}([0.41658206875707227,0.5017688328770391,0.4950271332072449,0.47894020363889234,0.4810285428763976,0.5129626979895638,0.4894621516145241,0.04926848192609756,0.35015060687983346,0.57393984978873],10x5 Array{Float64,2}:
 0.31356   0.421467     0.855788  0.184812   0.522469 
 0.523827  0.000162772  0.80338   0.990524   0.435689 
 0.903068  0.412541     0.208929  0.249097   0.0109994
 0.73804   0.00372301   0.880434  0.287483   0.962761 
 0.41663   0.475956     0.716943  0.748487   0.642943 
 0.561952  0.594682     0.408093  0.375726   0.554211 
 0.428398  0.390269     0.264798  0.655475   0.473286 
 0.759091  0.60214      0.232885  0.922757   0.946042 
 0.179187  0.204381     0.995682  0.0101273  0.592077 
 0.674353  0.806467     0.180198  0.677089   0.871963 ,[0.599648906039072,0.5608212204969416,0.9780278280294874,0.11913449426512002,0.2961395431294518])

Multiple dispatch

Recall the IJulia output after the definition of sayhello in the first section:

In [146]: function sayhello(name)
              println("Hello, ", name)
          end
Out[146]: sayhello (generic function with 1 method)

Notice the line (generic function with 1 method).

What happens if we define another version of this function with a different argument type?


In [95]:
sayhello(friendnumber::Number) = println("Hello, numerical friend ", friendnumber)


Out[95]:
sayhello (generic function with 2 methods)

Aha! No error. Instead, IJulia tells us that sayhello now refers to a function with two methods. Compare the output when we call this function with different types of arguments:


In [96]:
sayhello("Bob")


Hello, Bob

In [97]:
sayhello(3)


Hello, numerical friend 3

In [98]:
sayhello(4.0)


Hello, numerical friend 4.0

When we call sayhello with a String argument, the original definition with unspecified type is used. When we call sayhello with any numerical type, the new Number-specific version is called.

We can make another, even more specific definition; compare the output now with different argument types:


In [99]:
sayhello(fpfriend::FloatingPoint) = println("Hello, floating point friend ", fpfriend)


Out[99]:
sayhello (generic function with 3 methods)

In [100]:
sayhello(4)


Hello, numerical friend 4

In [101]:
sayhello(5.0)


Hello, floating point friend 5.0

Why does this work? Julia's multiple dispatch chooses the most specific method for a given argument. Float64 is a subtype of Number (twice removed), so the Float64 version is used for a floating point argument, but the earlier Number version is still used for other numeric types.

Float64 is a subtype of the abstract FloatingPoint type:


In [102]:
super(Float64)


Out[102]:
FloatingPoint

which is in turn a subtype of Number:


In [103]:
issubtype(Float64, Number)


Out[103]:
true

Exercise

Write a function to print the type hierarchy for a given type. Hint: use the super function as shown above.


In [26]:
function hierarchy(t::Type)

end


Out[26]:
hierarchy (generic function with 1 method)

In [27]:
hierarchy(Int64)

Expected output:

In[]: hierarchy(Int64)

Signed
Integer
Real
Number
Any

Array functions

We can use type annotated functions to define different behavior for various types of arrays:


In [1]:
function array_sum(x::Array{Float64, 1})
    y = 0
    for i in 1:length(x)
        y += x[i] + 2
    end
    return y
end

function array_sum(x::Array{Int64, 1})
    y = 0
    for i in 1:length(x)
        y += x[i] + 1
    end
    return y
end


Out[1]:
array_sum (generic function with 2 methods)

In [2]:
array_sum([ 1, 2, 3, 4, 5 ])  # array of integers


Out[2]:
20

In [107]:
array_sum([ 1.0, 2, 3, 4, 5 ]) # array of floats


Out[107]:
25.0

Exercise

Write a function that takes a vector and normalizes it in place by its L2 norm:

$\|x\|_2 = \sqrt{\sum\limits_{i=1}^n{|x_i|^2}}$

Hints:

  • Use for loops.
  • square root function: sqrt
  • use element-wise operators to calculate the norm

In [28]:
function vec_norm(ar::Array{Float64,1})

end


Out[28]:
vec_norm (generic function with 1 method)

Expected output

In [8]: vec_norm([1.0, 1.0, 1.0])
Out[8]:
3-element Array{Float64,1}:
 0.57735
 0.57735
 0.57735

Extra Topics

Calling C code

Julia provides a facility to call C (and Fortran!) libraries with no runtime overhead.


In [109]:
path = ccall( (:getenv, "libc"), Ptr{Uint8}, (Ptr{Uint8},), "PATH")


Out[109]:
Ptr{Uint8} @0x00007fff4dc88553

In [110]:
bytestring(path)


Out[110]:
"/home/isaiah/bin:/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

Plotting

There are several plotting options available for Julia. Gadfly Winston PyPlot

Here is a demonstration of PyPlot, as integrated with the IJulia notebook:


In [111]:
using PyPlot
x = -3pi:.01:3pi
plot(x, sin(x))


Out[111]:
1-element Array{Any,1}:
 PyObject <matplotlib.lines.Line2D object at 0xa8a2550>

Code blocks

Julia supports two kinds of code blocks. The first is delimited by:


In [112]:
begin 
    # and
    "hello"
end


Out[112]:
"hello"

And the second is delimted by parentheses, with expressions separated by a semi-colon ; between each expression:


In [113]:
expression = 1
( this = 1; is = 2; println(a[1]); valid = expression )


1.0
Out[113]:
1

The final expression in a code block determines the resulting value, if any. Code blocking style can be used to great effect

Generated Code

Julia provides access to several levels of transformed code between the initial input and the executable, including type-annotated expressions, LLVM Intermediate Representation, and finally the resulting machine code for any function.


In [114]:
function plus(x::Float64, y::Float64)
    return x + y
end


Out[114]:
plus (generic function with 1 method)

In [115]:
code_typed(plus, (Float64, Float64))


Out[115]:
1-element Array{Any,1}:
 :($(Expr(:lambda, {:x,:y}, {{},{{:x,Float64,0},{:y,Float64,0}},{}}, quote  # In[114], line 2:
        return top(box)(Float64,top(add_float)(x::Float64,y::Float64))::Float64
    end)))

In [116]:
code_llvm(plus, (Float64, Float64))


define double @julia_plus(double, double) {
top:
  %2 = fadd double %0, %1, !dbg !15456
  ret double %2, !dbg !15456
}

In [117]:
code_native(plus, (Float64, Float64))


	.text
Filename: In[114]
Source line: 2
	push	RBP
	mov	RBP, RSP
Source line: 2
	vaddsd	XMM0, XMM0, XMM1
	pop	RBP
	ret