# Essentials¶

## Introduction¶

The Julia standard library contains a range of functions and macros appropriate for performing scientific and numerical computing, but is also as broad as those of many general purpose programming languages. Additional functionality is available from a growing collection of available packages. Functions are grouped by topic below.

Some general notes:

• Except for functions in built-in modules (Pkg, Collections, Graphics, Test and Profile), all functions documented here are directly available for use in programs.
• To use module functions, use import Module to import the module, and Module.fn(x) to use the functions.
• Alternatively, using Module will import all exported Module functions into the current namespace.
• By convention, function names ending with an exclamation point (!) modify their arguments. Some functions have both modifying (e.g., sort!) and non-modifying (sort) versions.

## Getting Around¶

exit([code])

Quit (or control-D at the prompt). The default exit code is zero, indicating that the processes completed successfully.

quit()

Quit the program indicating that the processes completed succesfully. This function calls exit(0) (see exit()).

atexit(f)

Register a zero-argument function to be called at exit.

isinteractive() → Bool

Determine whether Julia is running an interactive session.

whos([Module,] [pattern::Regex])

Print information about global variables in a module, optionally restricted to those matching pattern.

edit(file::String[, line])

Edit a file optionally providing a line number to edit at. Returns to the julia prompt when you quit the editor.

edit(function[, types])

Edit the definition of a function, optionally specifying a tuple of types to indicate which method to edit.

@edit()

Evaluates the arguments to the function call, determines their types, and calls the edit function on the resulting expression

less(file::String[, line])

Show a file using the default pager, optionally providing a starting line number. Returns to the julia prompt when you quit the pager.

less(function[, types])

Show the definition of a function using the default pager, optionally specifying a tuple of types to indicate which method to see.

@less()

Evaluates the arguments to the function call, determines their types, and calls the less function on the resulting expression

clipboard(x)

Send a printed form of x to the operating system clipboard (“copy”).

clipboard() → String

Return a string with the contents of the operating system clipboard (“paste”).

require(file::String...)

Load source files once, in the context of the Main module, on every active node, searching standard locations for files. require is considered a top-level operation, so it sets the current include path but does not use it to search for files (see help for include). This function is typically used to load library code, and is implicitly called by using to load packages.

When searching for files, require first looks in the current working directory, then looks for package code under Pkg.dir(), then tries paths in the global array LOAD_PATH.

Like require, except forces loading of files regardless of whether they have been loaded before. Typically used when interactively developing libraries.

include(path::String)

Evaluate the contents of a source file in the current context. During including, a task-local include path is set to the directory containing the file. Nested calls to include will search relative to that path. All paths refer to files on node 1 when running in parallel, and files will be fetched from node 1. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.

include_string(code::String)

Like include, except reads code from the given string rather than from a file. Since there is no file path involved, no path processing or fetching from node 1 is done.

help(name)

Get help for a function. name can be an object or a string.

apropos(string)

Search documentation for functions related to string.

which(f, types)

Return the method of f (a Method object) that will be called for arguments with the given types.

@which()

Evaluates the arguments to the function call, determines their types, and calls the which function on the resulting expression

methods(f[, types])

Show all methods of f with their argument types.

If types is specified, an array of methods whose types match is returned.

methodswith(typ[, showparents])

Return an array of methods with an argument of type typ. If optional showparents is true, also return arguments with a parent type of typ, excluding type Any.

@show()

Show an expression and result, returning the result

versioninfo([verbose::Bool])

Print information about the version of Julia in use. If the verbose argument is true, detailed system information is shown as well.

workspace()

Replace the top-level module (Main) with a new one, providing a clean workspace. The previous Main module is made available as LastMain. A previously-loaded package can be accessed using a statement such as using LastMain.Package.

This function should only be used interactively.

## All Objects¶

is(x, y) → Bool
===(x, y) → Bool
(x, y) → Bool

Determine whether x and y are identical, in the sense that no program could distinguish them. Compares mutable objects by address in memory, and compares immutable objects (such as numbers) by contents at the bit level. This function is sometimes called egal.

isa(x, type) → Bool

Determine whether x is of the given type.

isequal(x, y)

Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal to 0.0. For values that are not floating-point, isequal calls == (so that if you define a == method for a new type you automatically get isequal).

isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

This typically means that if you define your own == function then you must define a corresponding hash (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

Scalar types generally do not need to implement isequal separate from ==, unless they represent floating-point numbers amenable to a more efficient implementation than that provided as a generic fallback (based on isnan, signbit, and ==).

isless(x, y)

Test whether x is less than y, according to a canonical total order. Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. This is the default comparison used by sort. Non-numeric types with a canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN.

ifelse(condition::Bool, x, y)

Return x if condition is true, otherwise return y. This differs from ? or if in that it is an ordinary function, so all the arguments are evaluated first.

lexcmp(x, y)

Compare x and y lexicographically and return -1, 0, or 1 depending on whether x is less than, equal to, or greater than y, respectively. This function should be defined for lexicographically comparable types, and lexless will call lexcmp by default.

lexless(x, y)

Determine whether x is lexicographically less than y.

typeof(x)

Get the concrete type of x.

tuple(xs...)

Construct a tuple of the given objects.

ntuple(n, f::Function)

Create a tuple of length n, computing each element as f(i), where i is the index of the element.

object_id(x)

Get a unique integer id for x. object_id(x)==object_id(y) if and only if is(x,y).

hash(x[, h])

Compute an integer hash code such that isequal(x,y) implies hash(x)==hash(y). The optional second argument h is a hash code to be mixed with the result.

New types should implement the 2-argument form, typically by calling the 2-argument hash method recursively in order to mix hashes of the contents with each other (and with h). Typically, any type that implements hash should also implement its own == (hence isequal) to guarantee the property mentioned above.

finalizer(x, function)

Register a function f(x) to be called when there are no program-accessible references to x. The behavior of this function is unpredictable if x is of a bits type.

copy(x)

Create a shallow copy of x: the outer structure is copied, but not all internal values. For example, copying an array produces a new array with identically-same elements as the original.

deepcopy(x)

Create a deep copy of x: everything is copied recursively, resulting in a fully independent object. For example, deep-copying an array produces a new array whose elements are deep copies of the original elements. Calling deepcopy on an object should generally have the same effect as serializing and then deserializing it.

As a special case, functions can only be actually deep-copied if they are anonymous, otherwise they are just copied. The difference is only relevant in the case of closures, i.e. functions which may contain hidden internal references.

While it isn’t normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::ObjectIdDict) (which shouldn’t otherwise be used), where T is the type to be specialized for, and dict keeps track of objects copied so far within the recursion. Within the definition, deepcopy_internal should be used in place of deepcopy, and the dict variable should be updated as appropriate before returning.

isdefined([object, ]index | symbol)

Tests whether an assignable location is defined. The arguments can be an array and index, a composite object and field name (as a symbol), or a module and a symbol. With a single symbol argument, tests whether a global variable with that name is defined in current_module().

convert(type, x)

Try to convert x to the given type. Conversions from floating point to integer, rational to integer, and complex to real will raise an InexactError if x cannot be represented exactly in the new type.

promote(xs...)

Convert all arguments to their common promotion type (if any), and return them all (as a tuple).

oftype(x, y)

Convert y to the type of x.

widen(type | x)

If the argument is a type, return a “larger” type (for numeric types, this will be a type with at least as much range and precision as the argument, and usually more). Otherwise the argument x is converted to widen(typeof(x)).

julia> widen(Int32)
Int64

julia> widen(1.5f0)
1.5

identity(x)

The identity function. Returns its argument.

## Types¶

super(T::DataType)

Return the supertype of DataType T

issubtype(type1, type2)

True if and only if all values of type1 are also of type2. Can also be written using the <: infix operator as type1 <: type2.

<:(T1, T2)

Subtype operator, equivalent to issubtype(T1,T2).

subtypes(T::DataType)

Return a list of immediate subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

subtypetree(T::DataType)

Return a nested list of all subtypes of DataType T. Note that all currently loaded subtypes are included, including those not visible in the current module.

typemin(type)

The lowest value representable by the given (real) numeric type.

typemax(type)

The highest value representable by the given (real) numeric type.

realmin(type)

The smallest in absolute value non-subnormal value representable by the given floating-point type

realmax(type)

The highest finite value representable by the given floating-point type

maxintfloat(type)

The largest integer losslessly representable by the given floating-point type

sizeof(type)

Size, in bytes, of the canonical binary representation of the given type, if any.

eps([type])

The distance between 1.0 and the next larger representable floating-point value of type. Only floating-point types are sensible arguments. If type is omitted, then eps(Float64) is returned.

eps(x)

The distance between x and the next larger representable floating-point value of the same type as x.

promote_type(type1, type2)

Determine a type big enough to hold values of each argument type without loss, whenever possible. In some cases, where no type exists to which both types can be promoted losslessly, some loss is tolerated; for example, promote_type(Int64,Float64) returns Float64 even though strictly, not all Int64 values can be represented exactly as Float64 values.

promote_rule(type1, type2)

Specifies what type should be used by promote when given values of types type1 and type2. This function should not be called directly, but should have definitions added to it for new types as appropriate.

getfield(value, name::Symbol)

Extract a named field from a value of composite type. The syntax a.b calls getfield(a, :b), and the syntax a.(b) calls getfield(a, b).

setfield!(value, name::Symbol, x)

Assign x to a named field in value of composite type. The syntax a.b = c calls setfield!(a, :b, c), and the syntax a.(b) = c calls setfield!(a, b, c).

fieldoffsets(type)

The byte offset of each field of a type relative to the data start. For example, we could use it in the following manner to summarize information about a struct type:

julia> structinfo(T) = [zip(fieldoffsets(T),names(T),T.types)...];

julia> structinfo(StatStruct)
12-element Array{(Int64,Symbol,DataType),1}:
(0,:device,Uint64)
(8,:inode,Uint64)
(16,:mode,Uint64)
(32,:uid,Uint64)
(40,:gid,Uint64)
(48,:rdev,Uint64)
(56,:size,Int64)
(64,:blksize,Int64)
(72,:blocks,Int64)
(80,:mtime,Float64)
(88,:ctime,Float64)

fieldtype(value, name::Symbol)

Determine the declared type of a named field in a value of composite type.

isimmutable(v)

True if value v is immutable. See Immutable Composite Types for a discussion of immutability. Note that this function works on values, so if you give it a type, it will tell you that a value of DataType is mutable.

isbits(T)

True if T is a “plain data” type, meaning it is immutable and contains no references to other values. Typical examples are numeric types such as Uint8, Float64, and Complex{Float64}.

julia> isbits(Complex{Float64})
true

julia> isbits(Complex)
false

isleaftype(T)

Determine whether T is a concrete type that can have instances, meaning its only subtypes are itself and None (but T itself is not None).

typejoin(T, S)

Compute a type that contains both T and S.

typeintersect(T, S)

Compute a type that contains the intersection of T and S. Usually this will be the smallest such type or one close to it.

## Generic Functions¶

apply(f, x...)

Accepts a function and several arguments, each of which must be iterable. The elements generated by all the arguments are appended into a single list, which is then passed to f as its argument list.

julia> function f(x, y) # Define a function f
x + y
end;

julia> apply(f, [1 2]) # Apply f with 1 and 2 as arguments
3


apply is called to implement the ... argument splicing syntax, and is usually not called directly: apply(f,x) === f(x...)

method_exists(f, tuple) → Bool

Determine whether the given generic function has a method matching the given tuple of argument types.

julia> method_exists(length, (Array,))
true

applicable(f, args...) → Bool

Determine whether the given generic function has a method applicable to the given arguments.

julia> function f(x, y)
x + y
end;

julia> applicable(f, 1)
false

julia> applicable(f, 1, 2)
true

invoke(f, (types...), args...)

Invoke a method for the given generic function matching the specified types (as a tuple), on the specified arguments. The arguments must be compatible with the specified types. This allows invoking a method other than the most specific matching method, which is useful when the behavior of a more general definition is explicitly needed (often as part of the implementation of a more specific method of the same function).

|>(x, f)

Applies a function to the preceding argument. This allows for easy function chaining.

julia> [1:5] |> x->x.^2 |> sum |> inv
0.01818181818181818


## Syntax¶

eval([m::Module, ]expr::Expr)

Evaluate an expression in the given module and return the result. Every module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.

@eval()

Evaluate an expression and return the value.

evalfile(path::String)

Load the file using include, evaluate all expressions, and return the value of the last one.

esc(e::ANY)

Only valid in the context of an Expr returned from a macro. Prevents the macro hygiene pass from turning embedded variables into gensym variables. See the Non-Standard String Literals section of the Metaprogramming chapter of the manual for more details and examples.

gensym([tag])

Generates a symbol which will not conflict with other variable names.

@gensym()

Generates a gensym symbol for a variable. For example, @gensym x y is transformed into x = gensym("x"); y = gensym("y").

parse(str, start; greedy=true, raise=true)

Parse the expression string and return an expression (which could later be passed to eval for execution). Start is the index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, "(error message)"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation.

parse(str; raise=true)

Parse the whole string greedily, returning a single expression. An error is thrown if there are additional characters after the first expression. If raise is true (default), syntax errors will raise an error; otherwise, parse will return an expression that will raise an error upon evaluation.

## System¶

run(command)

Run a command object, constructed with backticks. Throws an error if anything goes wrong, including the process exiting with a non-zero status.

spawn(command)

Run a command object asynchronously, returning the resulting Process object.

DevNull

Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage: run(cat test.txt |> DevNull)

success(command)

Run a command object, constructed with backticks, and tell whether it was successful (exited with a code of 0). An exception is raised if the process cannot be started.

process_running(p::Process)

Determine whether a process is currently running.

process_exited(p::Process)

Determine whether a process has exited.

kill(p::Process, signum=SIGTERM)

Send a signal to a process. The default is to terminate the process.

open(command, mode::String="r", stdio=DevNull)

Start running command asynchronously, and return a tuple (stream,process). If mode is "r", then stream reads from the process’s standard output and stdio optionally specifies the process’s standard input stream. If mode is "w", then stream writes to the process’s standard input and stdio optionally specifies the process’s standard output stream.

open(f::Function, command, mode::String="r", stdio=DevNull)

Similar to open(command, mode, stdio), but calls f(stream) on the resulting read or write stream, then closes the stream and waits for the process to complete. Returns the value returned by f.

Starts running a command asynchronously, and returns a tuple (stdout,stdin,process) of the output stream and input stream of the process, and the process object itself.

ignorestatus(command)

Mark a command object so that running it will not throw an error if the result code is non-zero.

detach(command)

Mark a command object so that it will be run in a new process group, allowing it to outlive the julia process, and not have Ctrl-C interrupts passed to it.

setenv(command, env; dir=working_dir)

Set environment variables to use when running the given command. env is either a dictionary mapping strings to strings, or an array of strings of the form "var=val".

The dir keyword argument can be used to specify a working directory for the command.

|>(command, command)
|>(command, filename)
|>(filename, command)

Redirect operator. Used for piping the output of a process into another (first form) or to redirect the standard output/input of a command to/from a file (second and third forms).

Examples:
• run(ls |> grep xyz)
• run(ls |> "out.txt")
• run("out.txt" |> grep xyz)
>>(command, filename)

Redirect standard output of a process, appending to the destination file.

.>(command, filename)

Redirect the standard error stream of a process.

gethostname() → String

Get the local machine’s host name.

Get the IP address of the local machine, as a string of the form “x.x.x.x”.

getpid() → Int32

Get julia’s process ID.

time([t::TmStruct])

Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution. When passed a TmStruct, converts it to a number of seconds since the epoch.

time_ns()

Get the time in nanoseconds. The time corresponding to 0 is undefined, and wraps every 5.8 years.

strftime([format, ]time)

Convert time, given as a number of seconds since the epoch or a TmStruct, to a formatted string using the given format. Supported formats are the same as those in the standard C library.

strptime([format, ]timestr)

Parse a formatted time string into a TmStruct giving the seconds, minute, hour, date, etc. Supported formats are the same as those in the standard C library. On some platforms, timezones will not be parsed correctly. If the result of this function will be passed to time to convert it to seconds since the epoch, the isdst field should be filled in manually. Setting it to -1 will tell the C library to use the current system settings to determine the timezone.

TmStruct([seconds])

Convert a number of seconds since the epoch to broken-down format, with fields sec, min, hour, mday, month, year, wday, yday, and isdst.

tic()

Set a timer to be read by the next call to toc() or toq(). The macro call @time expr can also be used to time evaluation.

toc()

Print and return the time elapsed since the last tic().

toq()

Return, but do not print, the time elapsed since the last tic().

@time()

A macro to execute an expression, printing the time it took to execute and the total number of bytes its execution caused to be allocated, before returning the value of the expression.

@elapsed()

A macro to evaluate an expression, discarding the resulting value, instead returning the number of seconds it took to execute as a floating-point number.

@allocated()

A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression.

EnvHash() → EnvHash

A singleton of this type provides a hash table interface to environment variables.

ENV

Reference to the singleton EnvHash, providing a dictionary interface to system environment variables.

@unix()

Given @unix? a : b, do a on Unix systems (including Linux and OS X) and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@osx()

Given @osx? a : b, do a on OS X and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@linux()

Given @linux? a : b, do a on Linux and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

@windows()

Given @windows? a : b, do a on Windows and b elsewhere. See documentation for Handling Platform Variations in the Calling C and Fortran Code section of the manual.

## Errors¶

error(message::String)

Raise an error with the given message

throw(e)

Throw an object as an exception

rethrow([e])

Throw an object without changing the current exception backtrace. The default argument is the current exception (if called within a catch block).

backtrace()

Get a backtrace object for the current program point.

catch_backtrace()

Get the backtrace of the current exception, for use within catch blocks.

assert(cond[, text])

Raise an error if cond is false. Also available as the macro @assert expr.

@assert()

Raise an error if cond is false. Preferred syntax for writing assertions.

ArgumentError

The parameters given to a function call are not valid.

BoundsError

An indexing operation into an array tried to access an out-of-bounds element.

EOFError

No more data was available to read from a file or stream.

ErrorException

Generic error type. The error message, in the .msg field, may provide more specific details.

KeyError

An indexing operation into an Associative (Dict) or Set like object tried to access or delete a non-existent element.

An error occurred while including, requiring, or using a file. The error specifics should be available in the .error field.

MethodError

A method with the required type signature does not exist in the given generic function.

ParseError

The expression passed to the parse function could not be interpreted as a valid Julia expression.

ProcessExitedException

After a client Julia process has exited, further attempts to reference the dead child will throw this exception.

SystemError

A system call failed with an error code (in the errno global variable).

TypeError

A type assertion failure, or calling an intrinsic function with an incorrect argument type.

## Events¶

Timer(f::Function)

Create a timer to call the given callback function. The callback is passed one argument, the timer object itself. The timer can be started and stopped with start_timer and stop_timer.

start_timer(t::Timer, delay, repeat)

Start invoking the callback for a Timer after the specified initial delay, and then repeating with the given interval. Times are in seconds. If repeat is 0, the timer is only triggered once.

stop_timer(t::Timer)

Stop invoking the callback for a timer.

## Reflection¶

module_name(m::Module) → Symbol

Get the name of a module as a symbol.

module_parent(m::Module) → Module

Get a module’s enclosing module. Main is its own parent.

current_module() → Module

Get the dynamically current module, which is the module code is currently being read from. In general, this is not the same as the module containing the call to this function.

fullname(m::Module)

Get the fully-qualified name of a module as a tuple of symbols. For example, fullname(Base.Pkg) gives (:Base,:Pkg), and fullname(Main) gives ().

names(x::Module[, all=false[, imported=false]])

Get an array of the names exported by a module, with optionally more module globals according to the additional parameters.

names(x::DataType)

Get an array of the fields of a data type.

isconst([m::Module, ]s::Symbol) → Bool

Determine whether a global is declared const in a given module. The default module argument is current_module().

isgeneric(f::Function) → Bool

Determine whether a function is generic.

function_name(f::Function) → Symbol

Get the name of a generic function as a symbol, or :anonymous.

function_module(f::Function, types) → Module

Determine the module containing a given definition of a generic function.

functionloc(f::Function, types)

Returns a tuple (filename,line) giving the location of a method definition.

functionlocs(f::Function, types)

Returns an array of the results of functionloc for all matching definitions.

## Internals¶

gc()

Perform garbage collection. This should not generally be used.

gc_disable()

Disable garbage collection. This should be used only with extreme caution, as it can cause memory use to grow without bound.

gc_enable()

Re-enable garbage collection after calling gc_disable.

macroexpand(x)

Takes the expression x and returns an equivalent expression with all macros removed (expanded).

expand(x)

Takes the expression x and returns an equivalent expression in lowered form

code_lowered(f, types)

Returns an array of lowered ASTs for the methods matching the given generic function and type signature.

@code_lowered()

Evaluates the arguments to the function call, determines their types, and calls the code_lowered function on the resulting expression

code_typed(f, types)

Returns an array of lowered and type-inferred ASTs for the methods matching the given generic function and type signature.

@code_typed()

Evaluates the arguments to the function call, determines their types, and calls the code_typed function on the resulting expression

code_llvm(f, types)

Prints the LLVM bitcodes generated for running the method matching the given generic function and type signature to STDOUT.

@code_llvm()

Evaluates the arguments to the function call, determines their types, and calls the code_llvm function on the resulting expression

code_native(f, types)

Prints the native assembly instructions generated for running the method matching the given generic function and type signature to STDOUT.

@code_native()

Evaluates the arguments to the function call, determines their types, and calls the code_native function on the resulting expression

precompile(f, args::(Any..., ))

Compile the given function f for the argument tuple (of types) args, but do not execute it.