0% found this document useful (0 votes)
244 views24 pages

Getting Started With Julia - Sample Chapter

Chapter No. 1 Installing the Julia Platform Enter the exciting world of Julia, a high-performance language for technical computing For more information: http://bit.ly/1GxlecD

Uploaded by

Packt Publishing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
244 views24 pages

Getting Started With Julia - Sample Chapter

Chapter No. 1 Installing the Julia Platform Enter the exciting world of Julia, a high-performance language for technical computing For more information: http://bit.ly/1GxlecD

Uploaded by

Packt Publishing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Fr

ee

Julia is a new open source programming language that is


used in the field of data science computing. It was created
to solve the dilemma between high-level slow code and
fast but low-level code, and the necessity to use both to
achieve high performance. This book will give you a head
start to tackle your numerical and data problems with
Julia. Your journey will begin by learning how to set up a
running Julia platform before exploring its various built-in
types. You will then move on to cover the different functions
and constructs in Julia. The book will then walk you through
the two important collection typesarrays and matrices.
Over the course of the book, you will also be introduced to
homoiconicity, the meta-programming concept in Julia.
Towards the concluding part of the book, you will also learn
how to run external programs. This book will cover all you
need to know about Julia to leverage its high speed and
efficiency.

What you will learn from this book


Set up your Julia environment to achieve
the highest productivity
Solve your tasks in a high-level dynamic
language and use types for your data only
when needed
Create your own types to extend the built-in
type system
Visualize your data in IJulia with plotting
packages

Apply Julia to tackle problems concurrently


and in a distributed environment

This book is for you if you are a data scientist or working on


any technical or scientific computation projects. The book
assumes you have a basic working knowledge of high-level
dynamic languages such as MATLAB, R, Python, or Ruby.

Integrate with other languages such as


C, Python, and MATLAB

C o m m u n i t y

E x p e r i e n c e

D i s t i l l e d

Getting started with Julia


Ivo Balbaert

$ 29.99 US
18.99 UK

P U B L I S H I N G

pl

Explore the use of built-in macros for testing,


debugging, benchmarking, and more

Who this book is written for

community experience distilled

Getting Started with Julia Programming

Getting Started with


Julia Programming

Sa
m

Enter the exciting world of Julia, a high-performance language for


technical computing

Prices do not include


local sales tax or VAT
where applicable

Visit www.PacktPub.com for books, eBooks,


code, downloads, and PacktLib.

Ivo Balbaert

In this package, you will find:

The author biography


A preview chapter from the book, Chapter 1 "Installing the Julia Platform"
A synopsis of the books content
More information on Getting Started with Julia

About the Author


Ivo Balbaert is currently a lecturer in (web) programming and databases at CVO
Antwerpen (www.cvoantwerpen.be), a community college in Belgium. He received a
PhD degree in applied physics from the University of Antwerp in 1986. He worked for 20
years in the software industry as a developer and consultant in several companies, and
for 10 years as a project manager at the University Hospital of Antwerp. From 2000
onward, he switched to partly teaching and developing software (KHM Mechelen,
CVO Antwerp).
He also wrote an introductory book in Dutch about developing in Ruby and Rails,
Programmeren met Ruby en Rails, Van Duuren Media. In 2012, he authored a book on
the Go programming language, The Way To Go, iUniverse. In 2013, in collaboration
with Dzenan Ridzanovic, he authored Learning Dart and Dart Cookbook, both by
Packt Publishing.
I would like to thank the technical reviewers Pascal Bugnion, Michael Otte,
and Dustin Stansbury for the many useful remarks that improved the text.

Getting Started with Julia


Julia is a new programming language that was developed at MIT in the Applied
Computing Group under the supervision of Prof. Alan Edelman. Its development
started in 2009, and it was first presented publicly in February 2012. It is still a fairly
young language when you look at the current Version number (0.3), but its foundation is
stable; the core language has had no backwards incompatible changes since Version 0.1.
It is based on clear and solid principles, and its popularity is steadily increasing in the
technical, data scientist, and high-performance computing arenas. In the section The
Rationale for Julia, we present an overview of the principles on which Julia is based
and compare them to other languages.

What This Book Covers


Chapter 1, Installing the Julia Platform, guides you with the installation of all the
necessary components required for a Julia environment. It teaches you how to work with
Julia's console (the REPL) and discusses some of the more elaborate development editors
you can use.
Chapter 2, Variables, Types, and Operations, discusses the elementary built-in types in
Julia, and the operations that can be performed on them, so that you are prepared to start
writing the code with them.
Chapter 3, Functions, explains why functions are the basic building blocks of Julia, and
how to effectively use them.
Chapter 4, Control Flow, shows Julia's elegant control constructs, how to perform error
handling, and how to use coroutines (called Tasks in Julia) to structure the execution of
your code.
Chapter 5, Collection Types, explores the different types that group individual values,
such as arrays and matrices, tuples, dictionaries, and sets.
Chapter 6, More on Types, Methods, and Modules, digs deeper into the type concept and
explains how this is used in multiple dispatch to get C-like performance. Modules, a
higher code organizing concept, are discussed as well.
Chapter 7, Metaprogramming in Julia, touches on the deeper layers of Julia, such as
expressions and reflection capabilities, and demonstrates the power of macros.

Chapter 8, I/O, Networking, and Parallel Computing, shows how to work with data in
files and databases using DataFrames. We can explore the networking capabilities, and
shows how to set up a parallel computing environment with Julia.
Chapter 9, Running External Programs, looks at how Julia interacts with the command
line and other languages and also discusses performance tips.
Chapter 10, The Standard Library and Packages, digs deeper into the standard library
and demonstrates the important packages for visualization of data.
Appendix, List of Macros and Packages, provides you with handy reference lists of the
macros and packages used in this book.

Installing the Julia Platform


This chapter guides you through the download and installation of all the necessary
components of Julia. The topics covered in this chapter are as follows:

Installing Julia

Working with Julia's shell

Start-up options and Julia scripts

Packages

Installing and working with Julia Studio

Installing and working with IJulia

Installing Sublime-IJulia

Installing Juno

Other editors and IDEs

Working of Julia

By the end of this chapter, you will have a running Julia platform. Moreover,
you will be able to work with Julia's shell as well as with editors or integrated
development environments with a lot of built-in features to make development
more comfortable.

Installing the Julia Platform

Installing Julia
The Julia platform in binary (that is, executable) form can be downloaded from
http://julialang.org/downloads/. It exists for three major platforms (Windows,
Linux, and OS X) in 32- and 64-bit format, and is delivered as a package or in
an archive format. You should use the current official stable release when doing
serious professional work with Julia (at the time of writing, this is Version 0.3). If
you would like to investigate the latest developments, install the upcoming version
(which is now Version 0.4). The previous link contains detailed and platformspecific instructions for the installation. We will not repeat these instructions here
completely, but we will summarize some important points.

Windows version usable from Windows XP


SP2 onwards
You need to keep the following things in mind if you are using the Windows OS:
1. As a prerequisite, you need the 7zip extractor program, so first download
and install http://www.7-zip.org/download.html.
2. Now, download the julia-n.m.p-win64.exe file to a temporary folder
(n.m.p is the version number, such as 0.2.1 or 0.3.0; win32/win64 are
respectively the 32- and 64-bit version; a release candidate file looks like
julia-0.4.0-rc1-nnnnnnn-win64 (nnnnnnn is a checksum number such
as 0480f1b).
3. Double-click on the file (or right-click, and select Run as Administrator if
you want Julia installed for all users on the machine). Clicking OK on the
security dialog message, and then choosing the installation directory (for
example, c:\julia) will extract the archive into the chosen folder, producing
the following directory structure, and taking some 400 MB of disk space:

[ 16 ]

Chapter 1

The Julia folder structure in Windows

4. A menu shortcut will be created which, when clicked, starts the Julia
command-line version or Read Evaluate Print Loop (REPL), as shown
in the following screenshot:

The Julia REPL

[ 17 ]

Installing the Julia Platform

5. On Windows, if you have chosen C:\Julia as your installation directory,


this is the C:\Julia\bin\julia.exe file. Add C:\Julia\bin to your PATH
variable if you want the REPL to be available on any Command Prompt. The
default installation folder on Windows is: C:\Users\UserName\AppData\
Local\Julia-n.m.p (where n.m.p is the version number, such as 0.3.2).
6. More information on Julia in the Windows OS can be found at https://
github.com/JuliaLang/julia/blob/master/README.windows.md.

Ubuntu version
For Ubuntu systems (Version 12.04 or later), there is a Personal
Package Archive (PPA) for Julia (can be found at https://launchpad.
net/~staticfloat/+archive/ubuntu/juliareleases) that makes the installation
painless. All you need to do to get the stable version is to issue the following
commands in a terminal session:
sudo add-apt-repository ppa:staticfloat/juliareleases
sudo add-apt-repository ppa:staticfloat/julia-deps
sudo apt-get update
sudo apt-get install julia

If you want to be at the bleeding edge of development, you can download the nightly
builds instead of the stable releases. The nightly builds are generally less stable,
but will contain the most recent features. To do so, replace the first of the preceding
commands with:
sudo add-apt-repository ppa:staticfloat/julianightlies

This way, you can always upgrade to a more recent version by issuing the following
commands:
sudo apt-get update
sudo apt-get upgrade

The Julia executable lives in /usr/bin/julia (given by the JULIA_HOME variable or


by the which julia command) and the standard library is installed in /usr/share/
julia/base, with shared libraries in /usr/lib/x86_64-linux-gnu/Julia.
For other Linux versions, the best way to get Julia running is to build from source
(refer to the next section).

[ 18 ]

Chapter 1

OS X
Installation for OS X is straightforwardusing the standard software installation
tools for the platform. Add /Applications/Julia-n.m.app/Contents/Resources/
julia/bin/Julia to make Julia available everywhere on your computer.
If you want code to be run whenever you start a Julia session, put it in /home/.
juliarc.jl on Ubuntu, ~/.juliarc.jl on OS X, or c:\Users\username\.
juliarc.jl on Windows. For instance, if this file contains the following code:
println("Greetings! ! ?")

Then, Julia starts up in its shell (or REPL as it is usually called) with the following
text in the screenshot, which shows its character representation capabilities:

Using .juliarc.jl

Building from source


Perform the following steps to build Julia from source:
1. Download the source code, rather than the binaries, if you intend to
contribute to the development of Julia itself, or if no Julia binaries are
provided for your operating system or particular computer architecture.
Building from source is quite straightforward on Ubuntu, so we will outline
the procedure here. The Julia source code can be found on GitHub at
https://github.com/JuliaLang/julia.git.
2. Compiling these will get you the latest Julia version, not the stable version (if
you want the latter, download the binaries, and refer to the previous section).

[ 19 ]

Installing the Julia Platform

3. Make sure you have git installed; if not, issue the command:
sudo apt-get -f install git

4. Then, clone the Julia sources with the following command:


git clone git://github.com/JuliaLang/julia.git

This will download the Julia source code into a julia directory in the
current folder.
5. The Julia building process needs the GNU compilation tools g++, gfortran,
and m4, so make sure that you have installed them with the following
command:
sudo apt-get install gfortran g++ m4

6. Now go to the Julia folder and start the compilation process as follows:
cd julia
make

7. After a successful build, Julia starts up with the ./julia command.


8. Afterwards, if you want to download and compile the newest version,
here are the commands to do this in the Julia source directory:
git pull
make clean
make

For more information on how to build Julia on Windows, OS X, and other systems,
refer to https://github.com/JuliaLang/julia/.
Using parallelization
If you want Julia to use n concurrent processes, compile the source
with make -j n.

There are two ways of using Julia. As described in the previous section, we can
use the Julia shell for interactive work. Alternatively, we can write programs in a
text file, save them with a .jl extension, and let Julia execute the whole program
sequentially.

[ 20 ]

Chapter 1

Working with Julia's shell


We started with Julia's shell in the previous section (refer to the preceding two
screenshots) to verify the correctness of the installation, by issuing the julia
command in a terminal session. The shell or REPL is Julia's working environment,
where you can interact with the Just in Time (JIT) compiler to test out pieces of code.
When satisfied, you can copy and paste this code into a file with a .jl extension,
such as program.jl. Alternatively, you can continue the work on this code from
within a text editor or an IDE, such as the ones we will point out later in this chapter.
After the banner with Julia's logo has appeared, you get a julia> prompt for the
input. To end this session, and get to the OS Command Prompt, type CTRL + D or
quit(), and hit ENTER. To evaluate an expression, type it and press ENTER to show
the result, as shown in the following screenshot:

Working with the REPL (1)

If, for some reason, you don't need to see the result, end the expression with a
; (semicolon) such as 6 * 7. In both the cases, the resulting value is stored, for
convenience, in a variable named ans that can be used in expressions, but only
inside the REPL. You can bind a value to a variable by entering an assignment as
a = 3. Julia is dynamic, and we don't need to enter a type for a, but we do need to
enter a value for the variable, so that Julia can infer its type. Using a variable b that
is not bound to the a value, results in the ERROR: b not defined message. Strings
are delineated by double quotes (""), as in b = "Julia". The following screenshot
illustrates these workings with the REPL:

Working with the REPL (2)

[ 21 ]

Installing the Julia Platform

Previous expressions can be retrieved in the same session by working with the
up and down arrow keys. The following key bindings are also handy:

To clear or interrupt a current command, press CTRL + C

To clear the screen (but variables are kept in memory), press CTRL + L

To reset the session so that variables are cleared, enter the command

workspace() in the REPL

Commands from the previous sessions can still be retrieved, because they are stored
(with a timestamp) in a.julia_history file (in /home/$USER on Ubuntu, c:\Users\
username on Windows, or ~/.julia_history on OS X). Ctrl + R (produces a
(reverse-i-search) ': prompt) searches through these commands.
Typing ? starts up the help mode (help?>) to give quick access to Julia's
documentation. Information on function names, types, macros, and so on, is given
when typing in their name. Alternatively, to get more information on a variable
a, type help(a), and to get more information on a function such as sort, type
help(sort). To find all the places where a function such as println is defined or
used, type apropos("println"), which gives the following output:
Base.println(x)
Base.enumerate(iter)
Base.cartesianmap(f, dims)

Thus, we can see that it is defined in the Base module, and is used in two other
functions. Different complete expressions on the same line have to be separated by a
; (semicolon) and only the last result is shown. You can enter multi-line expressions
as shown in the following screenshot. If the shell detects that the statement is
syntactically incomplete, it will not attempt to evaluate it. Rather, it will wait for the
user to enter additional lines until the multi-line statement can be evaluated.

Working with the REPL (3)

[ 22 ]

Chapter 1

A handy autocomplete feature also exists. Type one or more letters, press the Tab key
twice, and then a list of functions starting with these letters appears. For example:
type so, press the Tab key twice, and then you get the list as: sort sort! sortby
sortby! sortcols sortperm sortrows.
If you start a line with ;, the rest of the line is interpreted as a system shell command
(try for example, ls, cd, mkdir, whoami, and so on). The Backspace key returns to the
Julia prompt.
A Julia script can be executed in the REPL by calling it with include. For example,
for hello.jl, which contains the println("Hello, Julia World!") command,
the command is as follows:
julia> include("hello.jl")

The preceding command prints the output as follows:


Hello, Julia World!

Experiment a bit with different expressions to get some feeling for this environment.
You can get more information at http://docs.julialang.org/en/
latest/manual/interacting-with-julia/#key-bindings.

Startup options and Julia scripts


Without any options, the julia command starts up the REPL environment. A
useful option to check your environment is julia v. This shows Julia's version,
for example, julia-version 0.3.2+2. (The versioninfo()function in REPL
is more detailed, the VERSION constant gives you only the version number:
v"0.3.2+2"). An option that lets you evaluate expressions on the command line
itself is e, for example:
julia -e 'a = 6 * 7;
println(a)'

The preceding commands print out 42 (on Windows, use " instead of the '
character).
Some other options useful for parallel processing will be discussed in Chapter 9,
Running External Programs. Type julia h for a list of all options.

[ 23 ]

Installing the Julia Platform

A script.jl file with Julia source code can be started from the command line with
the following command:
julia script.jl arg1 arg2 arg3

Here arg1, arg2, and arg3 are optional arguments to be used in the script's code.
They are available from the global constant ARGS. Take a look at the args.jl file
as follows:
for arg in ARGS
println(arg)
end

The julia args.jl 1 Dart C command prints out 1, Dart, and C on consecutive
lines.
A script file also can execute other source files by including them in the REPL; for
example, main.jl contains include("hello.jl") that will execute the code from
hello.jl when called with julia main.jl.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files
e-mailed directly to you.

Packages
Most of the standard library in Julia (can be found in /share/julia/base relative
to where Julia was installed) is written in Julia itself. The rest of Julia's code
ecosystem is contained in packages that are simply Git repositories. They are most
often authored by external contributors, and already provide functionality for such
diverse disciplines such as bioinformatics, chemistry, cosmology, finance, linguistics,
machine learning, mathematics, statistics, and high-performance computing. A
searchable package list can be found at http://pkg.julialang.org/. Official Julia
packages are registered in the METADATA.jl file in the Julia Git repository, available
on GitHub at https://github.com/JuliaLang/METADATA.jl.

[ 24 ]

Chapter 1

Julia's installation contains a built-in package manager Pkg for installing additional
Julia packages written in Julia. The downloaded packages are stored in a cache ready
to be used by Julia given by Pkg.dir(), which are located at c:\users\username\.
julia\vn.m\.cache, /home/$USER/.julia/vn.m/.cache, or ~/.julia/vn.m/.
cache. If you want to check which packages are installed, run the Pkg.status()
command in the Julia REPL, to get a list of packages with their versions, as shown in
the following screenshot:

Packages list

The Pkg.installed() command gives you the same information, but in a dictionary
form and is usable in code. Version and dependency management is handled
automatically by Pkg. Different versions of Julia can coexist with incompatible
packages, each version has its own package cache.
If you get an error with Pkg.status() such as
ErrorException("Unable to read directory METADATA."),
issue a Pkg.init() command to create the package repository folders,
and clone METADATA from Git. If the problem is not easy to find or the
cache becomes corrupted somehow, you can just delete the .julia
folder, enter Pkg.init(), and start with an empty cache. Then, add
the packages you need.

[ 25 ]

Installing the Julia Platform

Adding a new package


Before adding a new package, it is always a good idea to update your package
database for the already installed packages with the Pkg.update()command.
Then, add a new package by issuing the Pkg.add("PackageName") command, and
execute using PackageName in code or in the REPL. For example, to add 2D plotting
capabilities, install the Winston package with Pkg.add("Winston "). To make a
graph of 100 random numbers between 0 and 1, execute the following commands:
using Winston
plot(rand(100))

The rand(100) function is an array with 100 random numbers. This produces the
following output:

A plot of white noise with Winston

After installing a new Julia version, update all the installed packages by running
Pkg.update() in the REPL. For more detailed information, you can refer to
http://docs.julialang.org/en/latest/manual/packages/.

[ 26 ]

Chapter 1

Installing and working with Julia Studio


Julia Studio is a free desktop app for working with Julia that runs on Linux,
Windows, and OS X (http://forio.com/labs/julia-studio/). It works with
the 0.3 release on Windows (Version 0.2.1 for Linux and OS X, at this time, if you
want Julia Studio to work with Julia v0.3 on Linux and OS X, you have to do the
compilation of the source code of the Studio yourself). It contains a sophisticated
editor and integrated REPL, version control with Git, and a very handy side pane
with access to the command history, filesystem, packages, and the list of edited
documents. It is created by Forio, a company that makes software for simulations,
data explorations, interactive learning, and predictive analytics. In the following
screenshot, you can see some of Julia Studio's features, such as the Console section
and the green Run button (or F5) in the upper-right corner. The simple program
fizzbuzz.jl prints for the first 100 integers for "fizz" if the number is a multiple
of 3, "buzz" if a multiple of 5, and "fizzbuzz" if it is a multiple of 15.

Julia Studio

[ 27 ]

Installing the Julia Platform

Notice the # sign that indicates the beginning of comments, the elegant and familiar
for loop and if elseif construct, and how they are closed with end. The 1:100
range is a range; mod returns the remainder of the division; the function mod(i, n)
can also be written as an i % n operator. Using four spaces for indentation is a
convention. Recently, Forio also developed Epicenter, a computational platform for
hosting the server-side models (also in Julia), and building interactive web interfaces
for these models.

Installing and working with IJulia


IJulia (https://github.com/JuliaLang/IJulia.jl) is a combination of the
IPython web frontend interactive environment (http://ipython.org/) with a
Julia-language backend. It allows you to work with IPython's powerful graphical
notebook (which combines code, formatted text, math, and multimedia in a single
document) with qtconsole and regular REPL. Detailed instructions for installation
are found at the GitHub page for IJulia (https://github.com/JuliaLang/IJulia.
jl) and in the Julia at MIT notes (https://github.com/stevengj/julia-mit/
blob/master/README.md). Here is a summary of the steps:
1. Install Version 1.0 or later of IPython via easy_install or pip (on OS X and
Windows, this is included in the Anaconda Python installation). On Linux,
use apt-get install ipython. (For more information, refer to the IPython
home page).
2. Install PyQt4 or PySide for qtconsole.
3. Install the IJulia package from the REPL with Pkg.add("IJulia").
4. Install the PyPlot package with Pkg.add("PyPlot").
You can work with IJulia in either of two ways:

Start an IPython notebook in your web browser by typing the following


command in a console:
ipython notebook --profile julia

Start qtconsole with:


ipython qtconsole --profile Julia

[ 28 ]

Chapter 1

The IJulia dashboard on Ubuntu

Verify that you have started IJulia. You must see IJ and the Julia logo in the upperleft corner of the browser window. Julia code is entered in the input cells (input can
be multiline) and then executed with Shift + Enter. Here is a small example:

An IJulia session example

[ 29 ]

Installing the Julia Platform

In the first input cell, the value of b is calculated from a:


a = 5
b = 2a^2 + 30a + 9

In the second input cell, we use PyPlot (this requires the installation of matplotlib;
for example, on Linux, this is done by sudo apt-get install pythonmatplotlib).
The linspace(0, 5) command defines an array of 100 equally spaced values
between 0 and 5, y is defined as a function of x and is then shown graphically
with the plot as follows:
using PyPlot
x = linspace(0, 5)
y = cos(2x + 5)
plot(x, y, linewidth=2.0, linestyle="--")
title("a nice cosinus")
xlabel("x axis")
ylabel("y axis")

Save a notebook in file format (with the extension .ipynb) by downloading it from
the menu. If working in an IPython notebook is new for you, you can take a look at
the demo at http://ipython.org/notebook.html to get started. After installing a
new Julia version, always run Pkg.build("IJulia") in the REPL in order to rebuild
the IJulia package with this new version.

Installing Sublime-IJulia
The popular Sublime Text editor (http://www.sublimetext.com/3) now has a
plugin based on IJulia (https://github.com/quinnj/Sublime-IJulia) authored
by Jacob Quinn. It gives you syntax highlighting, autocompletion, and an in-editor
REPL, which you basically just open like any other text file, but it runs Julia code for
you. You can also select some code from a code file and send it to the REPL with the
shortcut CTRL + B, or send the entire file there. Sublime-IJulia provides a frontend to
the IJulia backend kernel, so that you can start an IJulia frontend in a Sublime view
and interact with the kernel. Here is a summary of the installation, for details you
can refer to the preceding URL:
1. From within the Julia REPL, install the ZMQ and IJulia packages.
2. From within Sublime Text, install the Package Control package
(https://sublime.wbond.net/installation).
[ 30 ]

Chapter 1

3. From within Sublime Text, install the IJulia package from the Sublime
command palette.
4. Ctrl + Shift + P opens up a new IJulia console. Start entering commands,
and press Shift + Enter to execute them. The Tab key provides
command completion.

Installing Juno
Another promising IDE for Julia and a work in progress by Mike Innes and Keno
Fisher is Juno, which is based on the Light Table environment. The docs at http://
junolab.org/docs/installing.html provides detailed instructions for installing
and configuring Juno. Here is a summary of the steps:
1. Get LightTable from http://lighttable.com.
2. Start LightTable, install the Juno plugin through its plugin manager, and
restart LightTable.
Light Table works extensively with a command palette that you can open by
typing Ctrl + SPACE, entering a command, and then selecting it. Juno provides
an integrated console, and you can evaluate single expressions in the code editor
directly by typing Ctrl + Enter at the end of the line. A complete script is evaluated
by typing Ctrl + Shift + Enter.

Other editors and IDEs


For terminal users, the available editors are as follows:

Vim together with Julia-vim works great (https://github.com/


JuliaLang/julia-vim)

Emacs with julia-mode.el from the https://github.com/JuliaLang/


julia/tree/master/contrib directory

On Linux, gedit is very good. The Julia plugin works well and provides
autocompletion. Notepad++ also has Julia support from the contrib directory
mentioned earlier.
The SageMath project (https://cloud.sagemath.com/) runs Julia in the cloud
within a terminal and lets you work with IPython notebooks. You can also work and
teach with Julia in the cloud using the JuliaBox platform (https://juliabox.org/).

[ 31 ]

Installing the Julia Platform

How Julia works


(You can safely skip this section on a first reading.)
Julia works with an LLVM JIT compiler framework that is used for just-in-time
generation of machine code. The first time you run a Julia function, it is parsed
and the types are inferred. Then, LLVM code is generated by the JIT (just-in-time)
compiler, which is then optimized and compiled down to native code. The second
time you run a Julia function, the native code already generated is called. This is
the reason why, the second time you call a function with arguments of a specific
type, it takes much less time to run than the first time (keep this in mind when
doing benchmarks of Julia code). This generated code can be inspected. Suppose,
for example, we have defined a f(x) = 2x + 5 function in a REPL session. Julia
responds with the message, f (generic function with 1 method); the code is dynamic
because we didn't have to specify the type of x or f. Functions are by default generic
because they are ready to work with different data types for their variables. The
code_llvm function can be used to see the JIT bytecode, for example, the version
where the x argument is of type Int64:
julia> code_llvm(f, (Int64,))
define i64 @"julia_f;1065"(i64) {
top:
%1 = shl i64 %0, 1, !dbg !3248
%2 = add i64 %1, 5, !dbg !3248
ret i64 %2, !dbg !3248
}

The code_native function can be used to see the assembly code generated for the
same type of x:
julia> code_native(f, (Int64,))
.text
Filename: none
Source line: 1
push
RBP
mov
RBP, RSP
Source line: 1
lea
RAX, QWORD PTR [RCX + RCX + 5]
pop
RBP
ret

[ 32 ]

Chapter 1

Compare this with the code generated when x is of type Float64:


julia> code_native(f, (Float64,))
.text
Filename: none
Source line: 1
push
RBP
mov
RBP, RSP
Source line: 1
vaddsd XMM0, XMM0, XMM0
movabs RAX, 48532256
vaddsd XMM0, XMM0, QWORD PTR [RAX]
pop
RBP
ret

Julia code is fast because it generates specialized versions of functions for each data
type. Julia implements automatic memory management. The user doesn't have
to worry about allocating and keeping track of the memory for specific objects.
Automatic deletion of objects that are not needed any more (and hence, reclamation
of the memory associated with those objects) is done using a garbage collector (GC).
The garbage collector runs at the same time as your program. Exactly when a specific
object is garbage collected is unpredictable. In Version 0.3, the GC is a simple markand-sweep garbage collector; this will change to an incremental mark-and-sweep GC
in Version 0.4. You can start garbage collection yourself by calling gc(), or if it runs
in the way you can disable it by calling gc_disable().
The standard library is implemented in Julia itself. The I/O functions rely on the libuv
library for efficient, platform-independent I/O. The standard library is also contained
in a package called Base, which is automatically imported when starting Julia.

Summary
By now, you should have been able to install Julia in a working environment you
prefer. You should also have some experience with working in the REPL. We will
put this to good use starting in the next chapter, where we will meet the basic data
types in Julia, by testing out everything in the REPL.

[ 33 ]

Get more information Getting Started with Julia

Where to buy this book


You can buy Getting Started with Julia from the Packt Publishing website.
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet
book retailers.
Click here for ordering and shipping details.

www.PacktPub.com

Stay Connected:

You might also like