Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Julia as a Second Language
Julia as a Second Language
Julia as a Second Language
Ebook863 pages3 hours

Julia as a Second Language

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Learn the awesome Julia programming language by building fun projects like a rocket launcher, a password keeper, and a battle simulator.

Julia as a Second Language covers:
  • Data types like numbers, strings, arrays, and dictionaries
  • Immediate feedback with Julia’s read-evaluate-print-loop (REPL)
  • Simplify code interactions with multiple dispatch
  • Sharing code using modules and packages
  • Object-oriented and functional programming styles

Julia as a Second Language introduces Julia to readers with a beginning-level knowledge of another language like Python or JavaScript. You’ll learn by coding engaging hands-on projects that encourage you to apply what you’re learning immediately. Don’t be put off by Julia’s reputation as a scientific programming language—there’s no data science or numerical computing knowledge required. You can get started with what you learned in high school math classes.

About the Technology

Originally designed for high-performance data science, Julia has become an awesome general purpose programming language. It offers developer-friendly features like garbage collection, dynamic typing, and a flexible approach to concurrency and distributed computing. It is the perfect mix of simplicity, flexibility and performance.

About the Book

Julia as a Second Language introduces Julia by building on your existing programming knowledge. You’ll see Julia in action as you create a series of interesting projects that guide you from Julia’s basic syntax through its advanced features. Master types and data structures as you model a rocket launch. Use dictionaries to interpret Roman numerals. Use Julia’s unique multiple dispatch feature to send knights and archers into a simulated battle. Along the way, you’ll even compare the object-oriented and functional programming styles–Julia supports both!

What’s Inside
  • Data types like numbers, strings, arrays, and dictionaries
  • Immediate feedback with Julia’s read-evaluate-print-loop (REPL)
  • Simplify code interactions with multiple dispatch
  • Share code using modules and packages

About the Reader

For readers comfortable with another programming language like Python, JavaScript, or C#.

About the Author

Erik Engheim is a writer, conference speaker, video course author, and software developer.

Table of Contents

PART 1 - BASICS
1 Why Julia?
2 Julia as a calculator
3 Control flow
4 Julia as a spreadsheet
5 Working with text
6 Storing data in dictionaries
PART 2 - TYPES
7 Understanding types
8 Building a rocket
9 Conversion and promotion
10 Representing unknown values
PART 3 - COLLECTIONS
11 Working with strings
12 Understanding Julia collections
13 Working with sets
14 Working with vectors and matrices
PART 4 - SOFTWARE ENGINEERING
15 Functional programming in Julia
16 Organizing and modularizing your code
PART 5 - GOING IN DEPTH
17 Input and output
18 Defining parametric types
LanguageEnglish
PublisherManning
Release dateMay 2, 2023
ISBN9781638351900
Julia as a Second Language
Author

Erik Engheim

Erik Engheim is a writer, conference speaker, video course author and software developer. He has spent much of his career developing 3D modeling software for reservoir modeling and simulation in the Norwegian gas and oil industry. Erik also spent several years as an iOS and Android developer.

Related to Julia as a Second Language

Related ebooks

Programming For You

View More

Related articles

Reviews for Julia as a Second Language

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Julia as a Second Language - Erik Engheim

    inside front cover

    IBC-01

    Type hierarchy for numbers in Julia, showing abstract and concrete number types in dark gray and light gray, respectively

    IBC-02

    Type hierarchy for arrays and ranges in Julia. The dark gray types are abstract while the light gray are concrete types.

    Julia as a Second Language

    General purpose programming with a taste of data science

    ERIK ENGHEIM

    To comment go to liveBook

    Manning

    Shelter Island

    For more information on this and other Manning titles go to

    www.manning.com

    Copyright

    For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity.

    For more information, please contact

    Special Sales Department

    Manning Publications Co.

    20 Baldwin Road

    PO Box 761

    Shelter Island, NY 11964

    Email: orders@manning.com

    ©2023 by Manning Publications Co. All rights reserved.

    No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

    Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

    ♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

    ISBN: 9781617299711

    dedication

    To my grandparents, who paid for my first computer: an Amiga 1000.

    contents

    front matter

    preface

    acknowledgments

    about this book

    about the author

    about the cover illustration

    Part 1 Basics

    1 Why Julia?

    1.1 What is Julia?

    Pros and cons of statically and dynamically typed languages

    1.2 Julia combines elegance, productivity, and performance

    1.3 Why Julia was created

    Scientists need the interactive programming that dynamically typed languages offer

    Developers in other fields also need the interactivity a dynamically typed language offers

    1.4 Julia’s higher performance solves the two-language problem

    1.5 Julia is for everyone

    1.6 What can I build with Julia?

    Julia in the sciences

    Nonscience uses of Julia

    1.7 Where Julia is less ideal

    1.8 What you will learn in this book

    2 Julia as a calculator

    2.1 The Julia command line

    2.2 Using constants and variables

    Assigning and binding values to variables

    Using the ans variable

    What is a literal coefficient?

    2.3 Different number types and their bit length in Julia

    Writing numbers using different number formats

    2.4 Floating-point numbers

    Performing operations on integers and floating-point numbers

    2.5 Defining functions

    Storing function definitions in a file

    Working with functions in the REPL

    Functions everywhere

    Functions to work with numbers

    2.6 How to use numbers in practice

    3 Control flow

    3.1 Navigation and trigonometry

    3.2 Boolean expressions

    Compound statements

    3.3 Looping

    Flowchart

    Making a mathematical table for the sine function

    Range objects

    For loops

    3.4 Multiline functions

    Implementing the sine trigonometric function

    3.5 Implementing factorial

    3.6 Factorial with recursion

    3.7 If statements

    If-else statements

    Elseif clause

    3.8 Throwing exceptions to handle errors

    3.9 Control flow vs. data flow

    3.10 Counting rabbits

    Base case

    Iteration vs. recursion

    To return or not return

    4 Julia as a spreadsheet

    4.1 Analyzing pizza sales

    4.2 Different types of arrays

    4.3 Performing operations on arrays

    4.4 Working with the statistics module

    4.5 Accessing elements

    4.6 Creating arrays

    4.7 Mapping values in an array

    4.8 Introducing characters and strings

    4.9 Storing pizza data in tuples

    4.10 Filtering pizzas based on predicates

    Combining higher-order functions

    4.11 Mapping and reducing an array

    Sine table with map and reduce

    4.12 Counting matches with Boolean arrays

    5 Working with text

    5.1 Making a pretty pizza sales table

    Print, println, and printstyled

    Printing multiple elements

    Printing multiple pizzas

    Align with lpad and rpad

    Adding lines

    5.2 Printing a trigonometric table

    5.3 Reading and writing pizza sales to CSV files

    Writing pizza sales to a file

    Reading pizza sales from a file

    5.4 Interacting with the user

    6 Storing data in dictionaries

    6.1 Parsing Roman numerals

    6.2 Using the Dict type

    6.3 Looping over characters

    6.4 Enumerating values and indices

    6.5 Explaining the conversion process

    6.6 Using dictionaries

    Creating dictionaries

    Element access

    6.7 Why use a dictionary?

    6.8 Using named tuples as dictionaries

    When do you use a named tuple?

    Tying it all together

    Part 2 Types

    7 Understanding types

    7.1 Creating composite types from primitive types

    7.2 Exploring type hierarchies

    7.3 Creating a battle simulator

    Defining warrior types

    Adding behavior to warriors

    Using multiple dispatch to invoke methods

    7.4 How Julia selects method to call

    Contrasting Julia’s multiple dispatch with object-oriented languages

    How is multiple dispatch different from function overloading?

    8 Building a rocket

    8.1 Building a simple rocket

    8.2 Maintaining invariants in your code

    8.3 Making objects with constructor functions

    8.4 Differences between outer and inner constructors

    8.5 Modeling rocket engines and payloads

    8.6 Assembling a simple rocket

    8.7 Creating a rocket with multiple stages and engines

    8.7 Launching a rocket into space

    9 Conversion and promotion

    9.1 Exploring Julia’s number promotion system

    9.2 Understanding number conversion

    9.3 Defining custom units for angles

    Defining angle constructors

    Defining arithmetic operations on angles

    Defining accessors to extract degrees, minutes, and seconds

    Displaying DMS angles

    Defining type conversions

    Making pretty literals

    Type promotions

    10 Representing unknown values

    10.1 The nothing object

    10.2 Using nothing in data structures

    What is a parametric type?

    Using union types to end the wagon train

    10.3 Missing values

    10.4 Not a number

    10.5 Undefined data

    10.6 Putting it all together

    Part 3 Collections

    11 Working with strings

    11.1 UTF-8 and Unicode

    Understanding the relation between code points and code units

    11.2 String operations

    Converting from camel case to snake case

    Converting between numbers and strings

    String interpolation and concatenation

    sprintf formatting

    11.3 Using string interpolation to generate code

    11.4 Working with nonstandard string literals

    DateFormat strings

    Raw strings

    Using regular expressions to match text

    Making large integers with BigInt

    MIME types

    12 Understanding Julia collections

    12.1 Defining interfaces

    12.2 Propellant tank interface example

    12.3 Interfaces by convention

    12.4 Implementing engine cluster iteration

    Making clusters iterable

    12.5 Implementing rocket stage iteration

    Adding support for map and collect

    12.6 Comparison of linked lists and arrays

    Adding and removing elements

    12.7 Utility of custom types

    13 Working with sets

    13.1 What kind of problems can sets help solve?

    13.2 What is a set?

    Comparing properties of sets and arrays

    13.3 How to use set operations

    13.4 How to use sets in your code

    13.5 Searching for products using set operations

    Defining and using enumerations

    Creating test data to perform queries on

    Searching for screws

    Putting screw objects into sets

    Looking up screws using dictionaries

    13.6 Search in bug tracker using sets

    13.7 Relational databases and sets

    14 Working with vectors and matrices

    14.1 Vectors and matrices in mathematics

    14.2 Constructing a matrix from rows and columns

    14.3 The size, length, and norm of an array

    14.4 Slicing and dicing an array

    14.5 Combining matrices and vectors

    14.6 Creating matrices

    Part 4 Software engineering

    15 Functional programming in Julia

    15.1 How does functional programming differ from object-oriented programming?

    15.2 How and why you should learn to think functionally

    15.3 Avoid deeply nested calls with function chaining

    Understanding anonymous functions and closures

    Using the pipe operator |>

    Conveniently produce new functions using partial application

    15.4 Implementing Caesar and substitution ciphers

    Implementing the Caesar cipher

    Implementing substitution ciphers

    15.5 Creating a cipher-algorithm-agnostic service

    15.6 Building an encryption service using object-oriented programming

    15.7 Building an encryption service using functional programming

    Defining a functional Caesar cipher

    Defining a functional substitution cipher

    Implementing a functional password-keeper service

    16 Organizing and modularizing your code

    16.1 Setting up a work environment

    Using a package in the REPL

    How modules relate to packages

    16.2 Creating your own package and module

    Generating a package

    Adding code to your package

    16.3 Modifying and developing a package

    16.4 Tackling common misconceptions about modules

    16.5 Testing your package

    Part 5 Going in depth

    17 Input and output

    17.1 Introducing Julia’s I/O system

    17.2 Reading data from a process

    17.3 Reading and writing to a socket

    17.4 Parsing a CSV file

    Loading rocket engine data

    Saving rocket engine data

    18 Defining parametric types

    18.1 Defining parametric methods

    18.2 Defining parametric types

    18.3 Type safety benefits from parametric types

    18.4 Performance benefits from parametric types

    18.5 Memory benefits of parametric types

    appendix A Installing and configuring the Julia environment

    appendix B Numerics

    index

    front matter

    preface

    I began programming as a teenager, learning from fun books containing comic strips with wizards and turtles. I read magazines that showed me how to make my own simple games or cause silly effects to appear on the screen. I had fun.

    But when I went to university, my books began discussing bank accounts, balances, sales departments, employees, and employers. I wondered if my life as a programmer would mean putting on a gray suit and writing code handling payroll systems. Oh, the horror!

    At least half of my class hated programming with a passion. I could not blame them. Why did programming books have to be so boring, functional, and sensible?

    Where was the sense of adventure and fun? Fun is underrated. Who cares if a book is silly and has stupid jokes if it makes you learn and enjoy learning?

    That is one of the reasons I wrote this book. I wanted the reader to enjoy learning programming—not through cracking jokes but by working through programming examples that are interesting and fun to do.

    I promise you, there will be no examples modeling a sales department. Instead, we will do things like simulate rocket launches, pretend to be Caesar sending a secret message to his army commanders using old Roman encryption techniques, and many others.

    The second important reason why I wanted to write this book is because people keep asking me, Julia? Isn’t that a language only for science and scientists? Julia has had major success in this area, which is why the Julia community today is full of brainy people working on hard problems, such as developing new drugs and modeling the spread of infectious diseases, climate change, or the economy.

    But no, you don’t need to be a genius or a scientist to use Julia. Julia is a wonderful general purpose programming language for everyone! I am not a scientist, and I have enjoyed using it for over 9 years now. With Julia, you will find that you can solve problems more quickly and elegantly than you have done in the past. And as a cherry on top, computationally intensive code will run blisteringly fast.

    acknowledgments

    This book has lived through several incarnations. At one point, it was a self-published book. Later, chance brought me in touch with Manning Publications, and we agreed to work on publishing my book. Back then, I did not realize how much work I was getting myself into. In my mind, I would do minor revisions to the existing book, but from all the feedback I got, I realized I had to make many revisions.

    At times I felt like giving up. However, despite the difficulties, I believe the extensive system Manning has set up to aid us authors has helped me make a significantly better book. For that, I must thank Nicole Butterfield, who got me to sign on with Manning. I have had two Manning editors: Lesley Trites, in the early phase of the book, and Marina Michaels, who with her considerable experience and steady hand has helped get me over the finish line. I would like to extend a thanks to Milan Ćurčić, my technical development editor, who helped me a lot with his feedback in determining when material was understandable (or not) to my target audience. My copyeditor Christian Berk was invaluable for me as a non-native English speaker in correcting any odd constructs or grammar I may have written.

    Furthermore, I’d like to thank the reviewers who took the time to read my manuscript at various stages during its development and who provided invaluable feedback: Alan Lenton, Amanda Debler, Andy Robinson, Chris Bailey, Daniel Kenney, Darrin Bishop, Eli Mayost, Emanuele Piccinelli, Ganesh Swaminathan, Geert Van Laethem, Geoff Barto, Ivo Balbaert, Jeremy Chen, John Zoetebier, Jonathan Owens, Jort Rodenburg, Katia Patkin, Kevin Cheung, Krzysztof Jȩdrzejewski, Louis Luangkesorn, Mark Thomas, Maura Wilder, Mike Baran, Nikos Kanakaris, Ninoslav Čerkez, Orlando Alejo Méndez Morales, Patrick Regan, Paul Silisteanu, Paul Verbeke, Samvid Mistry, Simone Sguazza, Steve Grey-Wilson, Timothy Wolodzko, and Thomas Heiman.

    Special thanks go to Maurizio Tomasi, technical proofreader, for his careful review of the code one last time, shortly before the book went into production. Finally, thank you to the creators of Julia. You have created the programming language for the future, which I believe will transform the computer industry. That may sound like hyperbole, but I truly believe Julia is a major milestone in the evolution of programming languages.

    about this book

    Julia as a Second Language is an introduction to the Julia programming language for software developers. It not only covers the syntax and semantics of the language but also tries to teach the reader how to think and work like a Julia developer through extensive focus on interactive coding in a read-evaluate-print-loop (REPL) based environment.

    Who should read this book?

    Julia as a Second Language is written for developers curious about the Julia programming language but who do not necessarily have a scientific or mathematical background. The book is also a good starting point for anyone who wants to explore data science or scientific computing, as Julia is a language very well designed for such work. However, that does not exclude other uses. Any developer who would like to program in a modern, high performance language that makes them more productive would benefit from this book.

    How this book is organized

    The book is organized into five parts, consisting of 18 chapters.

    Part 1 covers the basics of the language.

    Chapter 1 explains what kind of language Julia is, why it got created, and the advantages of using the Julia programming language.

    Chapter 2 discusses working with numbers in Julia. It shows how you can use the Julia REPL environment as a very sophisticated calculator.

    Chapter 3 explains control flow statements, such as if statements, while loops, and for loops, by implementing a trigonometry function and calculating the Fibonacci numbers.

    Chapter 4 explains how to work with collections of numbers using the array type. Readers will work through an example involving pizza sales data.

    Chapter 5 is about working with text. This chapter walks you through making nicely formatted displays of pizza sales data with colors as well as reading and writing pizza data to files.

    Chapter 6 discusses how a program to convert Roman numerals to decimal numbers can be implemented using the dictionary collection type.

    Part 2 covers the Julia type system in greater detail.

    Chapter 7 explains type hierarchies in Julia and how you can define your own composite types. This is one of the most important chapters because it also explains multiple dispatch, which is one of the most important and unique features in Julia.

    Chapter 8 introduces a rocket simulation code example we will use through several chapters. This chapter is focused on defining types for different rocket parts.

    Chapter 9 gets into depth on numerical conversion and promotion in Julia by building up a code example dealing with different units for degrees. This chapter helps cement an understanding of the multiple dispatch system in Julia.

    Chapter 10 explains how you can represent objects that are nonexistent, missing, or undefined in Julia.

    Part 3 revisits collection types, such as arrays, dictionaries, and strings covered in part 1, but this time digs into more details.

    Chapter 11 goes into much more detail about strings, including topics such as Unicode and UTF-8 usage in Julia as well as their effects on your use of strings.

    Chapter 12 explains traits common to all Julia collections, such as iterating over elements and building your own collections.

    Chapter 13 walks through several code examples to show how sets and set operations are used to organize and search for data in many types of applications.

    Chapter 14 shows how you can work with and combine arrays of different dimensions, such as vectors and matrices.

    Part 4 focuses on methods for organizing your code at different levels, including modularizing at the function level all the way up to packages, files, and directories.

    Chapter 15 digs deeper into using functions in Julia, with emphasis on how functional programming differs from object-oriented programming.

    Chapter 16 is about organizing your code into modules, using third-party packages, and creating your own packages for sharing code with others.

    Part 5 digs into details that were hard to explain without the previous chapters as a foundation.

    Chapter 17 builds on chapter 5. You will get into the details of the Julia I/O system by reading and writing rocket engines to files, sockets, and pipes in CSV format.

    Chapter 18 explains how a parametric data type can be defined and why parametric types are beneficial for performance, memory usage, and correctness.

    About the code

    This book contains many examples of source code, both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this. Code annotations accompany many of the listings, highlighting important concepts.

    In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the sourcecode have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts.

    Much of the code you write is in the Julia REPL (read-evaluate-print-loop) environment or in a Unix shell. In these cases, you see a prompt such as julia>, shell>, help?> or $. These should not be included when you type. However, Julia is normally able to filter out the prompt if you paste code examples into your terminal window.

    Code meant to be written into a file will usually not be shown with a prompt. However, you can typically paste this code into the Julia REPL if you like.

    You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/julia-as-a-second-language. The complete code for the examples in the book is available for download from the Manning website at https://www.manning.com/books/julia-as-a-second-language, and from GitHub at https://github.com/ordovician/code-samples-julia-second-language.

    Julia version 1.7 or higher is recommended to run the example code in this book.

    liveBook discussion forum

    Purchase of Julia as a Second Language includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/julia-as-a-second-language/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion.

    Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print.

    Other online resources

    Need additional help? The Julia language has an active Slack workspace/community with over 10,000 members, many of whom you can communicate with in real time. Find information about registration at https://julialang.org/slack.

    Julia Discourse (https://discourse.julialang.org) is the go-to place for Julia-related questions.

    The Julia community page at https://julialang.org/community has info about YouTube channels, upcoming Julia events, GitHub, and Twitter.

    Official documentation of the Julia language and standard library can be found at https://docs.julialang.org/en/v1/.

    about the author

    Engheim_author

    Erik Engheim

    is a writer, conference speaker, video course author, and software developer. He has spent much of his career developing 3D modeling software for reservoir modeling and simulation in the Norwegian gas and oil industry. Erik also spent several years as an iOS and Android developer. Erik has programmed in Julia and written and made videos about Julia since 2013.

    about the cover illustration

    The figure on the cover of Julia as a Second Language is Paysanne Anglaise, or English peasant woman, taken from a collection by Jacques Grasset de Saint-Sauveur, published in 1788. Each illustration is finely drawn and colored by hand.

    In those days, it was easy to identify where people lived and what their trade or station in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional culture centuries ago, brought back to life by pictures from collections such as this one.

    Part 1 Basics

    These chapters cover all of Julia at a basic level. Later chapters will expand on topics covered in this part. You will learn about working with numbers, arrays, if statements, for loops, text strings, basic I/O, and storing and retrieving data from dictionaries. Subsequent parts of the text then discuss these topics in greater depth.

    1 Why Julia?

    This chapter covers

    The type of problems Julia solves

    The benefits of a fast, dynamically typed language

    How Julia increases programmer productivity

    You can choose from hundreds of programming languages—many of them much more popular than Julia. So why pick Julia?

    How would you like to write code faster than you have done before? How about building systems with a fraction of the number of lines of code you normally require? Surely, such productivity will come at the cost of deplorable performance and high memory consumption. Nope. In fact, Julia is the language of choice for next-generation climate models, which have extreme performance and memory requirements.

    I know such accolades may come across like a bad sales pitch from a used car salesman, but there is no denying that Julia, in many ways, is a revolutionary programming language. You may ask, If Julia is so great, then why isn’t everybody using it? Why are so many people still using the C programming language? Familiarity, packages, libraries, and community matter. Mission-critical software built up in large organizations isn’t just transitioned away from on a whim.

    Many of you reading this book may not care about having the more efficient and productive programming language. Instead, what you care about is what you can build with it. The simple answer is: anything. Julia is a general-purpose programming language.

    That may not be a satisfactory answer. You could build anything with JavaScript too, in principle. Yet you know JavaScript dominates frontend web development. You could write anything with Lua as well, but it is mostly used as a scripting language for computer games. Your primary interest in reading this book may be the kind of job Julia can land you.

    Presently, the Julia community is strongest within scientific computing, data science, and machine learning. But learning Julia is also a bet on the future. A language with such strong capabilities will not remain within a small niche. If you read on, it will become clearer what Julia is and why it has such potential. I will also cover areas where Julia is not ideal.

    1.1 What is Julia?

    Julia is a general-purpose, multi-platform programming language that is

    Suited for numerical analysis and computational science

    Dynamically typed

    High performance and just-in-time compiled

    Using automatic memory management (garbage collection)

    Composable

    That’s a lot, and some of these things sound like contradictions. So how can Julia be a general-purpose language and also tailored toward numerical programming? It’s general-purpose because, like Python, Julia can be used for almost anything. It’s numerical because, like MATLAB, it is well suited for numerical programming. But it isn’t limited to numerical programming; it’s good for other uses as well. By composable I mean that Julia makes it easy to express many object-oriented and functional programming patterns facilitating code reuse.

    1.1.1 Pros and cons of statically and dynamically typed languages

    Let’s focus on one aspect of Julia: the fact that it’s dynamically typed. Usually, programming languages are divided into two broad categories:

    Dynamically typed

    Statically typed

    In static languages, expressions have types; in dynamic languages, values have types.

    —Stefan Karpinski Julia Creator

    Examples of statically typed languages are C/C++, C#, Java, Swift, Go, Rust, Pascal, and Fortran. In a statically typed language, type checks are performed on all your code before your program is allowed to run.

    Examples of dynamically typed languages are Python, Perl, Ruby, JavaScript, MATLAB, and LISP. Dynamically typed languages perform type checks while the program is running. Unfortunately, dynamically typed languages tend to be very slow.

    In dynamic languages values such as numbers, characters, and strings have attached tags that say what type they are. These tags allow programs written in a dynamically typed language to check type correctness at runtime.

    Julia is unusual in that it is both a dynamically typed language and high performance. To many, this is a contradiction. This unique trait of Julia is made possible because the language was explicitly designed for just-in-time (JIT) compilation and uses a feature called multiple-dispatch for all function calls. Languages such as C/C++ and Fortran use ahead-of-time (AOT) compilation. A compiler translates the whole program into machine code before it can run. Other languages, such as Python, Ruby, and Basic, use an interpreter. With interpreted languages, a program reads each line of source code and interprets it at runtime to carry out the instructions given. Now that you have an idea of what kind of language Julia is, I can begin discussing the appeal of Julia.

    Language design and JIT compilation

    In principle, a programming language is decoupled from the method used to run it. Yet you will find that I talk about Julia as a JIT-compiled language and Fortran as an AOT compiled language. Strictly speaking, this is imprecise. For instance, Julia can run through an interpreter as well. However, most languages have been designed for a particular form of execution. Julia was designed for JIT compilation.

    1.2 Julia combines elegance, productivity, and performance

    While performance is one of the key selling points of Julia, what caught my attention back in 2013 when I first discovered it was how well thought out, powerful, and easy to use it was. I had a program I had rewritten in several languages to compare how expressive, easy to use, and productive each language was. With Julia, I managed to make the most elegant, compact, and easily readable variant of this code ever. Since then, I have tried many programming languages but have never gotten close to what I achieved with Julia. Here are some one-liners that exemplify the expressiveness of Julia.

    Listing 1.1 Julia one-liners

    filter(!isempty, readlines(filename)) # strip out empty lines

    filter(endswith(.png), readdir())  # get PNG files

    findall(==(4), [4, 8, 4, 2, 5, 1])    # find every index of the number 4

    Having been programming since the 1990s, I have had periods where I have felt I had enough of programming; Julia helped me regain my joy for programming. Part of the reason is that once you master Julia, you will feel that you have a language in your toolbox that works as a member of your team rather than against you. I think many of us have had the experience of working on a problem we have a good idea of how to solve, but the language we are using is getting in our way. The limitations of the language force us to add one hack after another. With Julia, I can build software the way I want without the language putting up obstacles.

    Another aspect that adds to your productivity and sense of fun is that Julia comes bundled with a rich standard library. You hit the ground running. You can get a lot done without hunting all over the web for some library to do what you want. Julia has you covered, whether you want to do linear algebra, statistics, HTTP, or string manipulation or you want to work with different date formats. And if the capability you want isn’t in the standard library, Julia has a tightly integrated package manager that makes adding third-party libraries a walk in the park. Programming with Julia almost makes you feel guilty or spoiled because you can build rich and elegant abstractions without taking a performance hit.

    Another essential advantage of Julia is that it is easy to learn. This ease of learning can help Julia gain a larger community over time. To understand why Julia is easy to learn, consider the famous Hello world program written in Julia:

    print(Hello world)

    When run, this code writes the text Hello world to the screen. While trivial, many languages require a lot of complex scaffolding to do something that simple. The following is a Java program which does the same thing:

    public class Main {

        public static void main(String[] args) {

            System.out.print(hello world);

        }

    }

    That exposes the beginner to a lot more concepts all at once, which can be overwhelming. Julia is easier to learn because you can focus on learning one concept at a time. You can learn to write a function without ever seeing a type definition. With a lot of functionality available out of the box, you don’t even need to know how to import external libraries to write helpful code.

    1.3 Why Julia was created

    To truly understand what Julia brings to the table, you need to understand better why Julia was created in the first place. The creators of the Julia programming language wanted to solve what they have called the two-language problem.

    This problem refers to the fact that a lot of software is written using two different programming languages, each with different characteristics. In the scientific domain, machine learning and data analysis dynamic languages are often preferred. However, these languages usually don’t give good enough performance. Thus solutions often have to be rewritten in higher-performance, statically typed languages. But why does this preference exist? Why not write everything in a traditional high-performance, statically typed language?

    1.3.1 Scientists need the interactive programming that dynamically typed languages offer

    Scientists began writing software, including large weather simulations, in Fortran¹ and neural networks² in C or C++.³ These languages offer the kind of performance you need to tackle these large-scale problems. However, these languages come at a price. They tend to be rigid, verbose, and lacking in expressiveness—all of which reduce programmer productivity.

    The fundamental problem, however, is that these languages are not suited for interactive programming. What do I mean by that? Interactive programming is the ability to write code and get immediate feedback.

    Interactive programming matters a lot in data science and machine learning. In a typical data analysis process, data is explored by a developer loading large amounts of data into an interactive programming environment. Then the developer performs various analyses of this data. These analyses could include finding averages and maximum values or plotting a histogram. The results of the first analysis tell the programmer what the next steps should be.

    Figure 1.1 shows this process in a dynamically typed language. You start by running the code, which loads the data, which you can then observe. However, you don’t have to go through this whole process after you

    Enjoying the preview?
    Page 1 of 1