Tag Archives: julialang

#MonthOfJulia Day 10: Modules

Julia Module

Modules allow you to encapsulate your code and variables. In the words of the Julia documentation:

Modules in Julia are separate global variable workspaces. Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else’s. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting).
Modules, Julia Documentation

To illustrate the concept, let’s define two new modules:

julia> module AfrikaansModule
       __init__() = println("Initialising the Afrikaans module.")
       greeting() = "Goeie môre!"
       bonappetit() = "Smaaklike ete"
       export greeting
       end
Initialising the Afrikaans module.
julia> module ZuluModule
       greeting() = "Sawubona!"
       bonappetit() = "Thokoleza ukudla"
       end

If an __init__() function is present in the module then it’s executed when the module is defined. Is it my imagination or does the syntax for that function have an uncanny resemblance to something in another popular scripting language?

The greeting() function in the above modules does not exist in the global namespace (which is why the first function call below fails). But you can access functions from either of the modules by explicitly giving the module name as a prefix.

julia> greeting()
ERROR: greeting not defined
julia> AfrikaansModule.greeting()
"Goeie môre!"
julia> ZuluModule.greeting()
"Sawubona!"

The Afrikaans module exports the greeting() function, which becomes available in the global namespace once the module has been loaded.

julia> using AfrikaansModule
julia> greeting()
"Goeie môre!"

But it’s still possible to import into the global namespace functions which have not been exported.

julia> import ZuluModule.bonappetit
julia> bonappetit()
"Thokoleza ukudla"

In addition to functions, modules can obviously also encapsulate variables.

That’s pretty much the essence of it although there are a number of subtleties detailed in the official documentation. Well worth a look if you want to suck all the marrow out of Julia’s modules. As usual the code for today’s flirtation can be found on github.

The post #MonthOfJulia Day 10: Modules appeared first on Exegetic Analytics.

#MonthOfJulia Day 9: Input/Output

Your code won’t be terribly interesting without ways of getting data in and out. Ways to do that with Julia will be the subject of today’s post.

Julia-Logo-IO

Console IO

Direct output to the Julia terminal is done via print() and println(), where the latter appends a newline to the output.

julia> print(3, " blind "); print("mice!n")
3 blind mice!
julia> println("Hello World!")
Hello World!

Terminal input is something that I never do, but it’s certainly possible. readline() will read keyboard input until the first newline.

julia> response = readline();
Yo!
julia> response
"Yo!n"

Reading and Writing with a Stream

Writing to a file is pretty standard. Below we create a suitable name for a temporary file, open a stream to that file, write some text to the stream and then close it.

filename = tempname()
fid = open(filename, "w")
write(fid, "Some temporary text...")
close(fid)

print() and println() can also be used in the same way as write() for sending data to a stream. STDIN, STDOUT and STDERR are three predefined constants for standard console streams.

There are various approaches to reading data from files. One of which would be to use code similar to the example above. Another would be to do something like this (I’ve truncated the output because it really is not too interesting after a few lines):

julia> open("/etc/passwd") do fid
           readlines(fid)
       end
46-element Array{Union(UTF8String,ASCIIString),1}:
 "root:x:0:0:root:/root:/bin/bashn"                                               
 "daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologinn"                               
 "bin:x:2:2:bin:/bin:/usr/sbin/nologinn"                                          
 "sys:x:3:3:sys:/dev:/usr/sbin/nologinn"                                          
 "sync:x:4:65534:sync:/bin:/bin/syncn"    

Here readlines() returns the entire contents of the file as an array, where each element corresponds to a line of content. readall() would return everything in a single string. A somewhat different approach would be to use eachline() which creates an iterator allowing you to process each line of the file individually.

Delimited Files

Data can be read from a delimited file using readdlm(), where the delimiter is specified explicitly. For a simple Comma Separated Value (CSV) file it’s more direct to simply use readcsv().

julia> passwd = readdlm("/etc/passwd", ':');
julia> passwd[1,:]
1x7 Array{Any,2}:
 "root"  "x"  0.0  0.0  "root"  "/root"  "/bin/bash"

The analogues writedlm() and writcecsv() are used for writing delimited data.

These functions will be essential if you are going to use Julia for data analyses. There is also functionality for reading and writing data in a variety of other formats like xls and xlsx, HDF5, Matlab and Numpy data files and WAV audio files.

File Manipulation

Julia implements a full range of file manipulation methods (documented here), most of which have names similar to their UNIX counterparts.

A few other details of my dalliance with Julia’s input/output functionality can be found on github.

The post #MonthOfJulia Day 9: Input/Output appeared first on Exegetic Analytics.

#MonthOfJulia Day 8: Iteration, Conditionals and Exceptions

Yesterday I had a look at Julia’s support for Functional Programming. Naturally it also has structures for conventional program flow like conditionals, iteration and exception handling.

Conditionals

Conditionals allow you to branch the course of execution on the basis of one or more logical outcomes.

julia> n = 8;
julia> if (n > 7)                          # The parentheses are optional.
           println("high")
       elseif n < 3
           println("low")
       else
           println("medium")
       end
high

The ternary conditional operator provides a compact syntax for a conditional returning one of two possible values.

julia> if n > 3 0 else 1 end               # Conditional.
0
julia> n > 3 ? 0 : 1                       # Ternary conditional.
0

I’m still a little gutted that R does not have a ternary operator. Kudos to Python for at least having something similar, even if the syntax is somewhat convoluted.

Iteration

There are a few different ways of achieving iteration in Julia. The simplest of these is the humble for loop.

julia> for n in [1:10]
           println("number $n.")
       end
number 1.
number 2.
number 3.
number 4.
number 5.
number 6.
number 7.
number 8.
number 9.
number 10.

In the code above we used the range operator, :, to construct an iterable sequence of integers between 1 and 10. This might be a good place to take a moment to look at ranges, which might not work in quite the way you’d expect. To get the range to actually expand into an array you need to enclose it in [], otherwise it remains a Range object.

julia> typeof(1:7)
UnitRange{Int64} (constructor with 1 method)
julia> typeof([1:7])
Array{Int64,1}
julia> 1:7
1:7
julia> [1:7]
7-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
 7

A for loop can iterate over any iterable object, including strings and dictionaries. Using enumerate() in conjunction with a for loop gives a compact way to number items in a collection.

The while construct gives a slightly different approach to iteration and is probably most useful when combined with continue and break statements which can be used to skip over iterations or prematurely exit from the loop.

Exceptions

The details of exception handling are well covered in the documentation, so I’ll just provide a few examples. Functions generate exceptions when something goes wrong.

julia> factorial(-1)
ERROR: DomainError
 in factorial_lookup at combinatorics.jl:26
 in factorial at combinatorics.jl:35
julia> super(DomainError)
Exception

All exceptions are derived from the Exception base class.

An exception is explicitly launched via throw(). To handle the exception in an elegant way you’ll want to enclose that dodgy bit of code in a try block.

julia> !(n) = n < 0 ? throw(DomainError()) : n < 2 ? 1 : n * !(n-1)
! (generic function with 7 methods)
julia> !10
3628800
julia> !0
1
julia> !-1
ERROR: DomainError
 in ! at none:1
julia> try
           !-1
       catch
           println("Well, that did't work!")
       end
Well, that did't work!

Exceptional conditions can be flagged by the error() function. Somewhat less aggressive are warn() and info().

I’ve dug a little deeper into conditionals, loops and exceptions in the code on github.

The post #MonthOfJulia Day 8: Iteration, Conditionals and Exceptions appeared first on Exegetic Analytics.