Book Image

Getting Started with Julia

By : Ivo Balbaert
Book Image

Getting Started with Julia

By: Ivo Balbaert

Overview of this book

Table of Contents (19 chapters)
Getting Started with Julia
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
The Rationale for Julia
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
type Point
    x::Float64
    y::Float64
end

type 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 that has coordinates as the sum of the corresponding coordinates:

+(p, v)

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

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) = Point(u.x + v.x, u.y + v.y)
+(u::Vector2D, p::Point) = Point(u.x + p.x, u.y...