Author Archives: Andrew Collier

#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.

#MonthOfJulia Day 7: Functional Programming

In computer science, functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions. In functional code, the output value of a function depends only on the arguments that are input to the function, so calling a function f twice with the same value for an argument x will produce the same result f(x) each time. Eliminating side effects, i.e. changes in state that do not depend on the function inputs, can make it much easier to understand and predict the behavior of a program, which is one of the key motivations for the development of functional programming.
Wikipedia: Functional Programming

Functional Programming is characterised by higher order functions which accept other functions as arguments. Typically a Functional Programming language has facilities for anonymous “lambda” functions and ways to apply map, reduce and filter operations. Julia ticks these boxes.

We’ve seen anonymous functions before, but here’s a quick reminder of the syntax:

julia> x -> x^2
(anonymous function)

Let’s start with map() which takes a function as its first argument followed by one or more collections. The function is then mapped onto each element of the collections. The first example below applies an anonymous function which squares its argument.

julia> map(x -> x^2, [1:5])
5-element Array{Int64,1}:
  1
  4
  9
 16
 25
julia> map(/, [16, 9, 4], [8, 3, 2])
3-element Array{Float64,1}:
 2.0
 3.0
 2.0

The analogues for this operation in Python and R are map() and mapply() or Map() respectively.

filter(), as its name would suggest, filters out elements from a collection for which a specific function evaluates to true. In the example below the function isprime() is applied to integers between 1 and 50 and only the prime numbers in that range are returned.

julia> filter(isprime, [1:50])
15-element Array{Int64,1}:
  2
  3
  5
  7
 11
 13
 17
 19
 23
 29
 31
 37
 41
 43
 47

The equivalent operation in Python and R is carried out using filter() and Filter() respectively.

The fold operation is implemented by reduce() which builds up its result by applying a bivariate function across a collection of objects and using the result of the previous operation as one of the arguments. Hmmmm. That’s a rather convoluted definition. Hopefully the link and examples below will illustrate. The related functions, foldl() and foldr(), are explicit about the order in which their arguments are associated.

julia> reduce(/, 1:4)
0.041666666666666664
julia> ((1 / 2) / 3) / 4
0.041666666666666664

The fold operation is applied with reduce() and Reduce() in Python and R respectively.

Finally there’s a shortcut to achieve both map and reduce together.

julia> mapreduce(x -> x^2, +, [1:5])
55
julia> (((1^2 + 2^2) + 3^2) + 4^2) + 5^2
55

A few extra bits and pieces about Functional Programming with Julia can be found on github.

The post #MonthOfJulia Day 7: Functional Programming appeared first on Exegetic Analytics.

#MonthOfJulia Day 6: Composite Types

I’ve had a look at the basic data types available in Julia as well as how these can be stashed in collections. What about customised-composite-DIY-build-your-own style types?

Composite types are declared with the type keyword. To illustrate we’ll declare a type for storing geographic locations, with attributes for latitude, longitude and altitude. The type immediately has two methods: a default constructor and a constructor specialised for arguments with data types corresponding to those of the type’s attributes. More information on constructors can be found in the documentation.

julia> type GeographicLocation
       	latitude::Float64
       	longitude::Float64
       	altitude::Float64
       end
julia> methods(GeographicLocation)
# 2 methods for generic function "GeographicLocation":
GeographicLocation(latitude::Float64,longitude::Float64,altitude::Float64)
GeographicLocation(latitude,longitude,altitude)

Creating instances of this new type is simply a matter of calling the constructor. The second instance below clones the type of the first instance. I don’t believe I’ve seen that being done with another language. (That’s not to say that it’s not possible elsewhere! I just haven’t seen it.)

julia> g1 = GeographicLocation(-30, 30, 15)
GeographicLocation(-30.0,30.0,15.0)
julia> typeof(g1)                              # Interrogate type
GeographicLocation (constructor with 3 methods)
julia> g2 = typeof(g1)(5, 25, 165)             # Create another object of the same type.
GeographicLocation(5.0,25.0,165.0)

We can list, access and modify instance attributes.

julia> names(g1)
3-element Array{Symbol,1}:
 :latitude 
 :longitude
 :altitude 
julia> g1.latitude
-30.0
julia> g1.longitude
30.0
julia> g1.latitude = -25                       # Attributes are mutable
-25.0

Additional “outer” constructors can provide alternative ways to instantiate the type.

julia> GeographicLocation(lat::Real, lon::Real) = GeographicLocation(lat, lon, 0)
GeographicLocation (constructor with 3 methods)
julia> g3 = GeographicLocation(-30, 30)
GeographicLocation(-30.0,30.0,0.0)

Of course, we can have collections of composite types. In fact, these composite types have essentially all of the rights and privileges of the built in types.

julia> locations = [g1, g2, g3]
3-element Array{GeographicLocation,1}:
 GeographicLocation(-25.0,30.0,15.0)
 GeographicLocation(5.0,25.0,165.0) 
 GeographicLocation(-30.0,30.0,0.0)

The GeographicLocation type declared above is a “concrete” type because it has attributes and can be instantiated. You cannot derive subtypes from a concrete type. You can, however, declare an abstract type which acts as a place holder in the type hierarchy. As opposed to concrete types, an abstract type cannot be instantiated but it can have subtypes.

julia> abstract Mammal
julia> type Cow <: Mammal
       end
julia> Mammal()                            # You can't instantiate an abstract type!
ERROR: type cannot be constructed
julia> Cow()
Cow()

The immutable keyword will create a type where the attributes cannot be modified after instantiation.

Additional ramblings and examples of composite types can be found on github. Also I’ve just received an advance copy of Learn Julia by Chris von Csefalvay which I’ll be reviewing over the next week or so.

Learn_Julia_meap

The post #MonthOfJulia Day 6: Composite Types appeared first on Exegetic Analytics.