Book Image

Julia 1.0 Programming - Second Edition

By : Ivo Balbaert
Book Image

Julia 1.0 Programming - Second Edition

By: Ivo Balbaert

Overview of this book

The release of Julia 1.0 is now ready to change the technical world by combining the high productivity and ease of use of Python and R with the lightning-fast speed of C++. Julia 1.0 programming gives you a head start in tackling your numerical and data problems. You will begin by learning how to set up a running Julia platform, before exploring its various built-in types. With the help of practical examples, this book walks you through two important collection types: arrays and matrices. In addition to this, you will be taken through how type conversions and promotions work. In the course of the book, you will be introduced to the homo-iconicity and metaprogramming concepts in Julia. You will understand how Julia provides different ways to interact with an operating system, as well as other languages, and then you'll discover what macros are. Once you have grasped the basics, you’ll study what makes Julia suitable for numerical and scientific computing, and learn about the features provided by Julia. By the end of this book, you will also have learned how to run external programs. This book covers all you need to know about Julia in order to leverage its high speed and efficiency for your applications.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Type unions


In geometry, a two-dimensional point and a vector are not the same, even if they both have an x and y component. In Julia, we can also define them as different types, as follows:

# see the code in Chapter 6\unions.jl
mutable struct Point
    x::Float64
    y::Float64
end

mutable struct Vector2D
    x::Float64
    y::Float64
end

Here are the two objects:

  • p = Point(2, 5) that returns Point(2.0, 5.0)

  • v = Vector2D(3, 2) that returns Vector2D(3.0, 2.0)

Suppose we want to define the sum for these types as a point which has coordinates as the sum of the corresponding coordinates:

+(p, v)

This results in an ERROR: MethodError: `+` has no method matching +(::Point, ::Vector2D) error message.

To define a + method here, first do an import Base.+

 

 

Even after defining the following, +(p, v) still returns the same error because of multiple dispatch. Julia has no way of knowing that +(p,v) should be the same as +(v,p):

+(p::Point, q::Point) = Point(p.x + q.x, p.y + q.y)
+(u::Vector2D, v::Vector2D)...