3.7 Additional libraries

OK, there is one more thing I want to briefly talk about, and it is libraries (sometimes called packages).

A library is a piece of code developed by someone else. At the time I’m writing these words there are over 10’000 libraries (aka packages) in Julia (see here) available under different licenses. If the package is under MIT license (a lot of them are) then basically you may use it freely, but without any warranty.

To install a package you use Pkg, i.e. Julia’s built in package manager. Click the link in the previous sentence to see how to do it (be aware that installation may take some time).

In general there are two ways to use a package in your project:

  1. by typing using Some_pkg_name
  2. by typing import Some_pkg_name

Personally, I prefer the latter. Actually, I use it in the form import Some_pkg_name as Abbreviated_pkg_name (you will see why in a moment).

Let’s see how it works. Remember the getSum and getAvg functions that we wrote ourselves. Well, it turns out Julia got a built-in sum and Statistics package got a mean function. To use it I type at the top of my file (it is a good practice to do so):

import Statistics as Stats

Now I can access any of its functions by preceding them with Stats (my abbreviation) and . like so

Stats.mean([1, 2, 3])

2.0

And that’s it. It just works.

Note that if you type import Statistics instead of import Statistics as Stats then in order to use mean you will have to type Statistics.mean([1, 2, 3]). So in general it is a good idea to give some shorter name for an imported package.

Oh yeah, one more thing. In order to know what are the functions in a library and how to use them you should check the library’s documentation.

OK, enough theory, time for some practice.



CC BY-NC-SA 4.0 Bartlomiej Lukaszuk