# Introducing Julia/The REPL
### The REPL

The julia program starts the interactive REPL, the Read/Evaluate/Print/Loop, by default. It lets you type expressions in Julia code and see the results of the evaluation printed on the screen immediately. It:
* Reads what you type;
* Evaluates it;
* Prints out the return value; then
* Loops back and does it all over again.
The REPL is a great place to start experimenting with the language. But it's not the best environment to do serious programming work of any scale – for that, a text editor, or interactive notebook environment (e.g. IJulia/Jupyter) is a better choice. But there are advantages to using the REPL: it's simple, and should work without any installation or configuration. There's a built-in help system, too.

#### Using the REPL

You type some Julia code and then press Return/Enter. Julia evaluates what you typed and returns the result:
If you're using the Jupyter (IPython) notebook, you probably have to type Control-Enter, or Shift-Enter.
If you don't want to see the result of the expression printed, use a semicolon at the end of the expression:
Also, if you want to access the value of the last expression you typed on the REPL, it's stored within the variable ans:
If you don't complete the expression on the first line, continue typing until you finish. For example:
now Julia waits patiently until you finish the expression:
and then you'll see the answer:

#### Help and searching for help

Type a question mark ?
and you'll immediately switch to Help mode, and the prompt changes to yellow (in the terminal):
Now you can type the name of something (function names should be written without parentheses):
Notice that the help system has tried to find all the words that match the letters you typed, and shows you what it found.
If you want to search the documentation, you can use apropos and a search string:
You'll see a list of functions whose names or descriptions contain the string.
and so on.

#### Shell mode

If you type a semicolon
you immediately switch to shell mode:
(And the prompt changes to red). The commands available within this mode are the ones used by your system's command-line shell. In shell mode you can type any shell (i.e., non-Julia) command and see the result:
How you leave shell mode depends on your Julia version:
* In Julia 1.6 and later, shell mode is "sticky" (persistent). Press Backspace as the first character, or CTRL+C, to go back to the julia> prompt
* In earlier Julia versions, the prompt switches immediately back to julia>, so you have to type a semicolon every time you want to give a shell command.

#### Package mode

If you type a right bracket as the first character:
you immediately switch to Package mode:
This is where you carry out package management tasks such as adding packages, testing them, and so on.
To leave package mode press Backspace or CTRL+C on an otherwise empty line.

#### Orientation

Here are some other useful interactive functions and macros available at the REPL-prompt:
* varinfo – prints information about the exported global variables in a module
* @which – tells you which method will be called for a function and particular arguments:
* versioninfo – gets Julia version and platform information:
There's also a quick way to find out the version:
* edit("pathname") – launch the default editor and open the file pathname for editing
* @edit rand – launch the default editor and open the file containing the definition of the built-in function rand
* less("filename-in-current-directory") – displays the file in the pager
* clipboard("stuff") – copies "stuff" to the system clipboard
* clipboard – pastes the contents of the clipboard into the current REPL line
* dump(x) – displays information about a Julia object x on the screen
* names(x) – gets an array of the names exported by the module x
* fieldnames(typeof(x)) – gets an array of the data fields that belong to a symbol of type x

#### The <TAB> key: autocompletion

The TAB key is usually able to complete – or suggest a completion for – something whose name you start typing. For example, if I type w and then press the TAB key (press twice when there are multiple options), all the functions that are currently available beginning with 'w' are listed:
This works both for Julia entities and in shell and package modes. Here, for example, is how I can navigate to a directory from inside Julia:
Remember you can get help about functions using ? and typing in its full name (or using TAB-completion).
TAB-completion also works for Unicode-symbols: eg type \alp and press TAB to get \alpha and then press TAB again to get α. And for Emoji: eg type \:fe and press TAB to get \:ferris_wheel: and then press TAB again to get 🎡.

#### History

You can look back through a record of your previous commands using the Up and Down arrow keys (and you can quit and restart without erasing that history). So you don't have to type a long multi-line expression again, because you can just recall it from history. And if you've typed loads of expressions, you can search through them, both back and forwards, by pressing Ctrl-R and Ctrl-S.

#### Fancy editing

Julia's REPL supports features that make command-line entry more efficient, and these features are bound to particular key combinations. For example, Alt+bgoes back one word, while Alt+fgoes forward one word. A complete list of key bindings, together with instructions for customizing them, can be found in the REPL documentation. Note that some editors, like VS Code, may override certain key combinations.

#### Scope and performance

One warning about the REPL. The REPL operates at the global scope level of Julia. Usually, when writing longer code, you would put your code inside a function, and organise functions into modules and packages. Julia's compiler works much more effectively when your code is organized into functions, and your code will run much faster as a result. There are also some things that you can't do at the top level – such as specify types for the values of variables.

#### Changing the prompt and customising your Julia session

The following Julia file runs every time you start up Julia (unless you use the startup-file=no option).
This lets you load any package that you know you are going to want later. For example, if you want to customise your REPL session automatically, you can install the Julia package OhMyREPL.jl (https://github.com/KristofferC/OhMyREPL.jl) which lets you customize the REPL's appearance and behaviour, then, in the startup file:
If you just want to set the prompt every time you start a Julia session, you could just add these instructions:
This just sets the current REPL prompt to show the Julia version number that your session is using.

### Julia and mathematics

You can use Julia as a powerful calculator, using the REPL. It's good practice, too. (This is a tradition in introductions to interactive programming languages, and it's a good way to meet the language.)

#### Typing numbers

Half the world uses a comma (,) to divide long numbers into groups of three, the other half uses a period (.). (And the rest of us use scientific notation...) In Julia you can use an underscore (_) to separate groups of digits:
although you won't see one in the response.
To use scientific notation, just type "e" (or "E") and don't add any spaces:
To type imaginary numbers, use im:

#### Operators as functions

An equivalent form for adding numbers is:
The operators that you usually use between values are ordinary Julia functions, and can be used in the same way as other functions. Similarly:
can be written as
and
can be written as
Some maths constants are provided:
You can find other maths constants in the MathConstants module:
All the usual operators are available:
Notice the precedence of the operators. In this case it's:
If you want to check the precedence of operators, enclose the expression in :( and ):
(More on this in Metaprogramming).
Multiplication is usually written *, but this can be omitted when multiplying a variable by a number literal:
This makes equations much easier to write.
You'll sometimes need parentheses to control the evaluation order:
Some others to watch out for include:
* ^ power
* % remainder
To make rational numbers, use two slashes (//):
Technically, / means "right division." There's also left division "\". For numbers, x/y = y\x. However, for vectors and matrices, x = A\y solves A*x = y and x = y/A solves x*A = y.
The standard arithmetic operators also have special updating versions, which you can use to update variables quickly:
For example, after defining a variable x:
you can add 2 to it:
then multiply it by 100:
and then reduce it to its modulus 11 value:
There are element-wise operators which work on arrays. This means that you can multiply two arrays element by element:
Arrays are fundamental to Julia, and so have their own chapter in this book.
If you divide two integers using /, the answer is always a floating-point number. If you've used Python version 2, you'll remember that Python returns an integer result. Python (3) returns a float now.
Julia offers an integer division operator ÷ (type \div TAB, or use the function version div. This should be used when you want an integer result rather than the floating-point returned by /.
Notice that Julia doesn't convert the answer to an integer type, even if the result is effectively an integer.
This is to avoid type instability problems, which can slow down your code.

#### Integer overflow

If you think your calculations are going to burst out of the 64-bit restriction, choose Big Integers by applying the big function to store the operands as big numbers:
To get the fastest execution speeds for your Julia programs, you should be aware of how your data and variables can be stored without introducing 'type instability'.

#### Number bases

These handy utility functions might come in useful when using the REPL as a calculator.
The bitstring function shows the literal binary representation of a number, as stored:
Notice that the floating point 'version' is, as you would expect, stored differently.
To go from a binary string back to decimal, you can use parse, which accepts a target type and number base:
For working in number bases other than the default 10, use the string function to convert integers to strings:
Whereas digits(number, base=b) returns an array of the digits of number in the given base:

#### Variables

In this expression:
x is a variable, a named storage location for a data object. In Julia, variables can be named pretty much how you like, although don't start variable names with numbers or punctuation. You can use Unicode characters, if you want.
To assign a value, use a single equals sign.
To test equality, you should use the == operator or isequal function.
In Julia, you can also assign multiple variables at the same time:
Notice that the return value of this expression is a parenthesis-bounded comma-separated ordered list of elements: tuple for short.

##### Multiplying numbers and variables

It's worth repeating that you can preface a variable name with a number to multiply them, without having to use an asterisk (*). For example:

#### Special characters

The Julia REPL provides easy access to special characters, such as Greek alphabetic characters, subscripts, and special maths symbols. If you type a backslash, you can then type a string (usually the equivalent LATEX string) to insert the corresponding character. For example, if you type:
Julia replaces the \sqrt with a square root symbol:
Some other examples:
| \pi | π |
| \Gamma | Γ |
| \mercury | ☿ |
| \degree | ° |
| \cdot | ⋅ |
| \in | ∈ |
There's a full list in the Julia source code. As a general principle, in Julia you're encouraged to look at the source code, so there are useful built-in functions for looking at Julia source files. For example, on macOS these symbols are stored in:
less runs the file through a pager (ie the less command in Unix). If you're brave, try using edit rather than less. This launches an editor and opens the file.
It's also possible to use Emoji and other Unicode characters in the REPL.
For emoji, type the Emoji character name, between colons, after the backslash, then press <TAB>:
which changes to:
You can find a list at https://docs.julialang.org/en/latest/manual/unicode-input/#Unicode-Input-1.
Entering Unicode symbols that aren't in this list is possible but more OS-dependent: on macOS you 'hold down' the Ctrl/Alt key while typing the Unicode hex digits (with the Unicode Hex Input keyboard enabled); on Windows it's Ctrl+Shift+u followed by the hex digits.)

#### Maths functions

Because Julia is particularly suited for scientific and technical computing, there are many mathematical functions that you can use immediately, and you often don't have to import them or use prefixes – they're already available.
The trigonometry functions expect values in radians:
but there are degree-based versions too: sind(90) finds the sine of 90 degrees. Use deg2rad and rad2deg to convert between degrees and radians.
There are also lots of log functions:
and the accurate hypot function:
The norm function (after loading via "using LinearAlgebra") returns the "p"-norm of a vector or the operator norm of a matrix. Here's divrem:
There are dozens of others.
There's a system-wide variable called ans that remembers the most recent result, so that you can use it in the next expression.

##### Exercise

Guess, then find out using the help system, what mod2pi and isapprox do.
Descriptions of all the functions provided as standard with Julia are described here:

#### Random numbers

rand – gets one random Float64 between 0 and 1
rand(2, 2) – an array of Float64s with dimensions 2, 2
rand(type, 2, 2) – an array of values of this type with dims 2, 2
rand(range, dims) – array of numbers in a range (including both ends) with specified dimensions:
(See the Arrays chapter for more about range objects.)
The rand function can generate a true or false value if you tell it to, by passing the Bool keyword:
or a bunch of trues and falses:

##### Random numbers in a distribution

randn gives you one random number in a normal distribution with mean 0 and standard deviation 1. randn(n) gives you n such numbers:
If you've installed the Plots plotting package, you can plot this:

#### Seeding the random number generator

The Random package contains many more random functions, such as randperm, shuffle, and seed!.
Before you use random numbers, you can seed the random number generator with a specific value. This ensures that subsequent random numbers will follow the same sequence, if they start from the same seed. You can seed the generator using the seed! or MersenneTwister functions.
Once you've added the Random package, you can do:
After restarting Julia, the same seed guarantees the same random numbers.

### Simple keyboard input

Here's an example of how you'd write and run a function that reads input from the keyboard:
This works in a Julia REPL session; when called, the function waits for the user to type a string on the keyboard and press Return/Enter.