Essentials

Introduction

Julia Base 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:

  • 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.

The behaviors of Base and standard libraries are stable as defined in SemVer only if they are documented; i.e., included in the Julia documentation and not marked as unstable. See API FAQ for more information.

Getting Around

Base.exit — Function

  1. exit(code=0)

Stop the program with an exit code. The default exit code is zero, indicating that the program completed successfully. In an interactive session, exit() can be called with the keyboard shortcut ^D.

source

Base.atexit — Function

  1. atexit(f)

Register a zero-argument function f() to be called at process exit. atexit() hooks are called in last in first out (LIFO) order and run before object finalizers.

Exit hooks are allowed to call exit(n), in which case Julia will exit with exit code n (instead of the original exit code). If more than one exit hook calls exit(n), then Julia will exit with the exit code corresponding to the last called exit hook that calls exit(n). (Because exit hooks are called in LIFO order, “last called” is equivalent to “first registered”.)

source

Base.isinteractive — Function

  1. isinteractive() -> Bool

Determine whether Julia is running an interactive session.

source

Base.summarysize — Function

  1. Base.summarysize(obj; exclude=Union{...}, chargeall=Union{...}) -> Int

Compute the amount of memory, in bytes, used by all unique objects reachable from the argument.

Keyword Arguments

  • exclude: specifies the types of objects to exclude from the traversal.
  • chargeall: specifies the types of objects to always charge the size of all of their fields, even if those fields would normally be excluded.

See also sizeof.

Examples

  1. julia> Base.summarysize(1.0)
  2. 8
  3. julia> Base.summarysize(Ref(rand(100)))
  4. 848
  5. julia> sizeof(Ref(rand(100)))
  6. 8

source

Base.require — Function

  1. require(into::Module, module::Symbol)

This function is part of the implementation of using / import, if a module is not already defined in Main. It can also be called directly to force reloading a module, regardless of whether it has been loaded before (for example, when interactively developing libraries).

Loads a source file, 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 for package code in the global array LOAD_PATH. require is case-sensitive on all platforms, including those with case-insensitive filesystems like macOS and Windows.

For more details regarding code loading, see the manual sections on modules and parallel computing.

source

Base.compilecache — Function

  1. Base.compilecache(module::PkgId)

Creates a precompiled cache file for a module and all of its dependencies. This can be used to reduce package load times. Cache files are stored in DEPOT_PATH[1]/compiled. See Module initialization and precompilation for important notes.

source

Base.__precompile__ — Function

  1. __precompile__(isprecompilable::Bool)

Specify whether the file calling this function is precompilable, defaulting to true. If a module or file is not safely precompilable, it should call __precompile__(false) in order to throw an error if Julia attempts to precompile it.

source

Base.include — Function

  1. Base.include([mapexpr::Function,] [m::Module,] path::AbstractString)

Evaluate the contents of the input source file in the global scope of module m. Every module (except those defined with baremodule) has its own definition of include omitting the m argument, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. 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. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files.

The optional first argument mapexpr can be used to transform the included code before it is evaluated: for each parsed expression expr in path, the include function actually evaluates mapexpr(expr). If it is omitted, mapexpr defaults to identity.

Julia 1.5

Julia 1.5 is required for passing the mapexpr argument.

source

Base.MainInclude.include — Function

  1. include([mapexpr::Function,] path::AbstractString)

Evaluate the contents of the input source file in the global scope of the containing module. Every module (except those defined with baremodule) has its own definition of include, which evaluates the file in that module. Returns the result of the last evaluated expression of the input file. 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. This function is typically used to load source interactively, or to combine files in packages that are broken into multiple source files. The argument path is normalized using normpath which will resolve relative path tokens such as .. and convert / to the appropriate path separator.

The optional first argument mapexpr can be used to transform the included code before it is evaluated: for each parsed expression expr in path, the include function actually evaluates mapexpr(expr). If it is omitted, mapexpr defaults to identity.

Use Base.include to evaluate a file into another module.

Julia 1.5

Julia 1.5 is required for passing the mapexpr argument.

source

Base.include_string — Function

  1. include_string([mapexpr::Function,] m::Module, code::AbstractString, filename::AbstractString="string")

Like include, except reads code from the given string rather than from a file.

The optional first argument mapexpr can be used to transform the included code before it is evaluated: for each parsed expression expr in code, the include_string function actually evaluates mapexpr(expr). If it is omitted, mapexpr defaults to identity.

Julia 1.5

Julia 1.5 is required for passing the mapexpr argument.

source

Base.include_dependency — Function

  1. include_dependency(path::AbstractString)

In a module, declare that the file specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if this file changes.

This is only needed if your module depends on a file that is not used via include. It has no effect outside of compilation.

source

Base.which — Method

  1. which(f, types)

Returns the method of f (a Method object) that would be called for arguments of the given types.

If types is an abstract type, then the method that would be called by invoke is returned.

See also: parentmodule, and @which and @edit in InteractiveUtils.

source

Base.methods — Function

  1. methods(f, [types], [module])

Return the method table for f.

If types is specified, return an array of methods whose types match. If module is specified, return an array of methods defined in that module. A list of modules can also be specified as an array.

Julia 1.4

At least Julia 1.4 is required for specifying a module.

See also: which and @which.

source

Base.@show — Macro

  1. @show exs...

Prints one or more expressions, and their results, to stdout, and returns the last result.

See also: show, @info, println.

Examples

  1. julia> x = @show 1+2
  2. 1 + 2 = 3
  3. 3
  4. julia> @show x^2 x/2;
  5. x ^ 2 = 9
  6. x / 2 = 1.5

source

ans — Keyword

  1. ans

A variable referring to the last computed value, automatically set at the interactive prompt.

source

Base.active_project — Function

  1. active_project()

Return the path of the active Project.toml file. See also Base.set_active_project.

source

Base.set_active_project — Function

  1. set_active_project(projfile::Union{AbstractString,Nothing})

Set the active Project.toml file to projfile. See also Base.active_project.

source

Keywords

This is the list of reserved keywords in Julia: baremodule, begin, break, catch, const, continue, do, else, elseif, end, export, false, finally, for, function, global, if, import, let, local, macro, module, quote, return, struct, true, try, using, while. Those keywords are not allowed to be used as variable names.

The following two-word sequences are reserved: abstract type, mutable struct, primitive type. However, you can create variables with names: abstract, mutable, primitive and type.

Finally: where is parsed as an infix operator for writing parametric method and type definitions; in and isa are parsed as infix operators; and outer is parsed as a keyword when used to modify the scope of a variable in an iteration specification of a for loop or generator expression. Creation of variables named where, in, isa or outer is allowed though.

module — Keyword

  1. module

module declares a Module, which is a separate global variable workspace. Within a module, you can control which names from other modules are visible (via importing), and specify which of your names are intended to be public (via exporting). Modules allow you to create top-level definitions without worrying about name conflicts when your code is used together with somebody else’s. See the manual section about modules for more details.

Examples

  1. module Foo
  2. import Base.show
  3. export MyType, foo
  4. struct MyType
  5. x
  6. end
  7. bar(x) = 2x
  8. foo(a::MyType) = bar(a.x) + 1
  9. show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
  10. end

source

export — Keyword

  1. export

export is used within modules to tell Julia which functions should be made available to the user. For example: export foo makes the name foo available when using the module. See the manual section about modules for details.

source

import — Keyword

  1. import

import Foo will load the module or package Foo. Names from the imported Foo module can be accessed with dot syntax (e.g. Foo.foo to access the name foo). See the manual section about modules for details.

source

using — Keyword

  1. using

using Foo will load the module or package Foo and make its exported names available for direct use. Names can also be used via dot syntax (e.g. Foo.foo to access the name foo), whether they are exported or not. See the manual section about modules for details.

source

baremodule — Keyword

  1. baremodule

baremodule declares a module that does not contain using Base or local definitions of eval and include. It does still import Core. In other words,

  1. module Mod
  2. ...
  3. end

is equivalent to

  1. baremodule Mod
  2. using Base
  3. eval(x) = Core.eval(Mod, x)
  4. include(p) = Base.include(Mod, p)
  5. ...
  6. end

source

function — Keyword

  1. function

Functions are defined with the function keyword:

  1. function add(a, b)
  2. return a + b
  3. end

Or the short form notation:

  1. add(a, b) = a + b

The use of the return keyword is exactly the same as in other languages, but is often optional. A function without an explicit return statement will return the last expression in the function body.

source

macro — Keyword

  1. macro

macro defines a method for inserting generated code into a program. A macro maps a sequence of argument expressions to a returned expression, and the resulting expression is substituted directly into the program at the point where the macro is invoked. Macros are a way to run generated code without calling eval, since the generated code instead simply becomes part of the surrounding program. Macro arguments may include expressions, literal values, and symbols. Macros can be defined for variable number of arguments (varargs), but do not accept keyword arguments. Every macro also implicitly gets passed the arguments __source__, which contains the line number and file name the macro is called from, and __module__, which is the module the macro is expanded in.

Examples

  1. julia> macro sayhello(name)
  2. return :( println("Hello, ", $name, "!") )
  3. end
  4. @sayhello (macro with 1 method)
  5. julia> @sayhello "Charlie"
  6. Hello, Charlie!
  7. julia> macro saylots(x...)
  8. return :( println("Say: ", $(x...)) )
  9. end
  10. @saylots (macro with 1 method)
  11. julia> @saylots "hey " "there " "friend"
  12. Say: hey there friend

source

return — Keyword

  1. return

return x causes the enclosing function to exit early, passing the given value x back to its caller. return by itself with no value is equivalent to return nothing (see nothing).

  1. function compare(a, b)
  2. a == b && return "equal to"
  3. a < b ? "less than" : "greater than"
  4. end

In general you can place a return statement anywhere within a function body, including within deeply nested loops or conditionals, but be careful with do blocks. For example:

  1. function test1(xs)
  2. for x in xs
  3. iseven(x) && return 2x
  4. end
  5. end
  6. function test2(xs)
  7. map(xs) do x
  8. iseven(x) && return 2x
  9. x
  10. end
  11. end

In the first example, the return breaks out of test1 as soon as it hits an even number, so test1([5,6,7]) returns 12.

You might expect the second example to behave the same way, but in fact the return there only breaks out of the inner function (inside the do block) and gives a value back to map. test2([5,6,7]) then returns [5,12,7].

When used in a top-level expression (i.e. outside any function), return causes the entire current top-level expression to terminate early.

source

do — Keyword

  1. do

Create an anonymous function and pass it as the first argument to a function call. For example:

  1. map(1:10) do x
  2. 2x
  3. end

is equivalent to map(x->2x, 1:10).

Use multiple arguments like so:

  1. map(1:10, 11:20) do x, y
  2. x + y
  3. end

source

begin — Keyword

  1. begin

begin...end denotes a block of code.

  1. begin
  2. println("Hello, ")
  3. println("World!")
  4. end

Usually begin will not be necessary, since keywords such as function and let implicitly begin blocks of code. See also ;.

begin may also be used when indexing to represent the first index of a collection or the first index of a dimension of an array.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Array{Int64,2}:
  3. 1 2
  4. 3 4
  5. julia> A[begin, :]
  6. 2-element Array{Int64,1}:
  7. 1
  8. 2

source

end — Keyword

  1. end

end marks the conclusion of a block of expressions, for example module, struct, mutable struct, begin, let, for etc.

end may also be used when indexing to represent the last index of a collection or the last index of a dimension of an array.

Examples

  1. julia> A = [1 2; 3 4]
  2. 2×2 Array{Int64, 2}:
  3. 1 2
  4. 3 4
  5. julia> A[end, :]
  6. 2-element Array{Int64, 1}:
  7. 3
  8. 4

source

let — Keyword

  1. let

let statements create a new hard scope block and introduce new variable bindings each time they run. Whereas assignments might reassign a new value to an existing value location, let always creates a new location. This difference is only detectable in the case of variables that outlive their scope via closures. The let syntax accepts a comma-separated series of assignments and variable names:

  1. let var1 = value1, var2, var3 = value3
  2. code
  3. end

The assignments are evaluated in order, with each right-hand side evaluated in the scope before the new variable on the left-hand side has been introduced. Therefore it makes sense to write something like let x = x, since the two x variables are distinct and have separate storage.

source

if — Keyword

  1. if/elseif/else

if/elseif/else performs conditional evaluation, which allows portions of code to be evaluated or not evaluated depending on the value of a boolean expression. Here is the anatomy of the if/elseif/else conditional syntax:

  1. if x < y
  2. println("x is less than y")
  3. elseif x > y
  4. println("x is greater than y")
  5. else
  6. println("x is equal to y")
  7. end

If the condition expression x < y is true, then the corresponding block is evaluated; otherwise the condition expression x > y is evaluated, and if it is true, the corresponding block is evaluated; if neither expression is true, the else block is evaluated. The elseif and else blocks are optional, and as many elseif blocks as desired can be used.

In contrast to some other languages conditions must be of type Bool. It does not suffice for conditions to be convertible to Bool.

  1. julia> if 1 end
  2. ERROR: TypeError: non-boolean (Int64) used in boolean context

source

for — Keyword

  1. for

for loops repeatedly evaluate a block of statements while iterating over a sequence of values.

Examples

  1. julia> for i in [1, 4, 0]
  2. println(i)
  3. end
  4. 1
  5. 4
  6. 0

source

while — Keyword

  1. while

while loops repeatedly evaluate a conditional expression, and continue evaluating the body of the while loop as long as the expression remains true. If the condition expression is false when the while loop is first reached, the body is never evaluated.

Examples

  1. julia> i = 1
  2. 1
  3. julia> while i < 5
  4. println(i)
  5. global i += 1
  6. end
  7. 1
  8. 2
  9. 3
  10. 4

source

break — Keyword

  1. break

Break out of a loop immediately.

Examples

  1. julia> i = 0
  2. 0
  3. julia> while true
  4. global i += 1
  5. i > 5 && break
  6. println(i)
  7. end
  8. 1
  9. 2
  10. 3
  11. 4
  12. 5

source

continue — Keyword

  1. continue

Skip the rest of the current loop iteration.

Examples

  1. julia> for i = 1:6
  2. iseven(i) && continue
  3. println(i)
  4. end
  5. 1
  6. 3
  7. 5

source

try — Keyword

  1. try/catch

A try/catch statement allows intercepting errors (exceptions) thrown by throw so that program execution can continue. For example, the following code attempts to write a file, but warns the user and proceeds instead of terminating execution if the file cannot be written:

  1. try
  2. open("/danger", "w") do f
  3. println(f, "Hello")
  4. end
  5. catch
  6. @warn "Could not write file."
  7. end

or, when the file cannot be read into a variable:

  1. lines = try
  2. open("/danger", "r") do f
  3. readlines(f)
  4. end
  5. catch
  6. @warn "File not found."
  7. end

The syntax catch e (where e is any variable) assigns the thrown exception object to the given variable within the catch block.

The power of the try/catch construct lies in the ability to unwind a deeply nested computation immediately to a much higher level in the stack of calling functions.

source

finally — Keyword

  1. finally

Run some code when a given block of code exits, regardless of how it exits. For example, here is how we can guarantee that an opened file is closed:

  1. f = open("file")
  2. try
  3. operate_on_file(f)
  4. finally
  5. close(f)
  6. end

When control leaves the try block (for example, due to a return, or just finishing normally), close(f) will be executed. If the try block exits due to an exception, the exception will continue propagating. A catch block may be combined with try and finally as well. In this case the finally block will run after catch has handled the error.

source

quote — Keyword

  1. quote

quote creates multiple expression objects in a block without using the explicit Expr constructor. For example:

  1. ex = quote
  2. x = 1
  3. y = 2
  4. x + y
  5. end

Unlike the other means of quoting, :( ... ), this form introduces QuoteNode elements to the expression tree, which must be considered when directly manipulating the tree. For other purposes, :( ... ) and quote .. end blocks are treated identically.

source

local — Keyword

  1. local

local introduces a new local variable. See the manual section on variable scoping for more information.

Examples

  1. julia> function foo(n)
  2. x = 0
  3. for i = 1:n
  4. local x # introduce a loop-local x
  5. x = i
  6. end
  7. x
  8. end
  9. foo (generic function with 1 method)
  10. julia> foo(10)
  11. 0

source

global — Keyword

  1. global

global x makes x in the current scope and its inner scopes refer to the global variable of that name. See the manual section on variable scoping for more information.

Examples

  1. julia> z = 3
  2. 3
  3. julia> function foo()
  4. global z = 6 # use the z variable defined outside foo
  5. end
  6. foo (generic function with 1 method)
  7. julia> foo()
  8. 6
  9. julia> z
  10. 6

source

const — Keyword

  1. const

const is used to declare global variables whose values will not change. In almost all code (and particularly performance sensitive code) global variables should be declared constant in this way.

  1. const x = 5

Multiple variables can be declared within a single const:

  1. const y, z = 7, 11

Note that const only applies to one = operation, therefore const x = y = 1 declares x to be constant but not y. On the other hand, const x = const y = 1 declares both x and y constant.

Note that “constant-ness” does not extend into mutable containers; only the association between a variable and its value is constant. If x is an array or dictionary (for example) you can still modify, add, or remove elements.

In some cases changing the value of a const variable gives a warning instead of an error. However, this can produce unpredictable behavior or corrupt the state of your program, and so should be avoided. This feature is intended only for convenience during interactive use.

source

struct — Keyword

  1. struct

The most commonly used kind of type in Julia is a struct, specified as a name and a set of fields.

  1. struct Point
  2. x
  3. y
  4. end

Fields can have type restrictions, which may be parameterized:

  1. struct Point{X}
  2. x::X
  3. y::Float64
  4. end

A struct can also declare an abstract super type via <: syntax:

  1. struct Point <: AbstractPoint
  2. x
  3. y
  4. end

structs are immutable by default; an instance of one of these types cannot be modified after construction. Use mutable struct instead to declare a type whose instances can be modified.

See the manual section on Composite Types for more details, such as how to define constructors.

source

mutable struct — Keyword

  1. mutable struct

mutable struct is similar to struct, but additionally allows the fields of the type to be set after construction. See the manual section on Composite Types for more information.

source

abstract type — Keyword

  1. abstract type

abstract type declares a type that cannot be instantiated, and serves only as a node in the type graph, thereby describing sets of related concrete types: those concrete types which are their descendants. Abstract types form the conceptual hierarchy which makes Julia’s type system more than just a collection of object implementations. For example:

  1. abstract type Number end
  2. abstract type Real <: Number end

Number has no supertype, whereas Real is an abstract subtype of Number.

source

primitive type — Keyword

  1. primitive type

primitive type declares a concrete type whose data consists only of a series of bits. Classic examples of primitive types are integers and floating-point values. Some example built-in primitive type declarations:

  1. primitive type Char 32 end
  2. primitive type Bool <: Integer 8 end

The number after the name indicates how many bits of storage the type requires. Currently, only sizes that are multiples of 8 bits are supported. The Bool declaration shows how a primitive type can be optionally declared to be a subtype of some supertype.

source

where — Keyword

  1. where

The where keyword creates a type that is an iterated union of other types, over all values of some variable. For example Vector{T} where T<:Real includes all Vectors where the element type is some kind of Real number.

The variable bound defaults to Any if it is omitted:

  1. Vector{T} where T # short for `where T<:Any`

Variables can also have lower bounds:

  1. Vector{T} where T>:Int
  2. Vector{T} where Int<:T<:Real

There is also a concise syntax for nested where expressions. For example, this:

  1. Pair{T, S} where S<:Array{T} where T<:Number

can be shortened to:

  1. Pair{T, S} where {T<:Number, S<:Array{T}}

This form is often found on method signatures.

Note that in this form, the variables are listed outermost-first. This matches the order in which variables are substituted when a type is “applied” to parameter values using the syntax T{p1, p2, ...}.

source

— Keyword

  1. ...

The “splat” operator, ..., represents a sequence of arguments. ... can be used in function definitions, to indicate that the function accepts an arbitrary number of arguments. ... can also be used to apply a function to a sequence of arguments.

Examples

  1. julia> add(xs...) = reduce(+, xs)
  2. add (generic function with 1 method)
  3. julia> add(1, 2, 3, 4, 5)
  4. 15
  5. julia> add([1, 2, 3]...)
  6. 6
  7. julia> add(7, 1:100..., 1000:1100...)
  8. 111107

source

; — Keyword

  1. ;

; has a similar role in Julia as in many C-like languages, and is used to delimit the end of the previous statement.

; is not necessary at the end of a line, but can be used to separate statements on a single line or to join statements into a single expression.

Adding ; at the end of a line in the REPL will suppress printing the result of that expression.

In function declarations, and optionally in calls, ; separates regular arguments from keywords.

While constructing arrays, if the arguments inside the square brackets are separated by ; then their contents are vertically concatenated together.

In the standard REPL, typing ; on an empty line will switch to shell mode.

Examples

  1. julia> function foo()
  2. x = "Hello, "; x *= "World!"
  3. return x
  4. end
  5. foo (generic function with 1 method)
  6. julia> bar() = (x = "Hello, Mars!"; return x)
  7. bar (generic function with 1 method)
  8. julia> foo();
  9. julia> bar()
  10. "Hello, Mars!"
  11. julia> function plot(x, y; style="solid", width=1, color="black")
  12. ###
  13. end
  14. julia> [1 2; 3 4]
  15. 2×2 Matrix{Int64}:
  16. 1 2
  17. 3 4
  18. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
  19. shell> echo hello
  20. hello

source

\= — Keyword

  1. =

= is the assignment operator.

  • For variable a and expression b, a = b makes a refer to the value of b.
  • For functions f(x), f(x) = x defines a new function constant f, or adds a new method to f if f is already defined; this usage is equivalent to function f(x); x; end.
  • a[i] = v calls setindex!(a,v,i).
  • a.b = c calls setproperty!(a,:b,c).
  • Inside a function call, f(a=b) passes b as the value of keyword argument a.
  • Inside parentheses with commas, (a=1,) constructs a NamedTuple.

Examples

Assigning a to b does not create a copy of b; instead use copy or deepcopy.

  1. julia> b = [1]; a = b; b[1] = 2; a
  2. 1-element Array{Int64, 1}:
  3. 2
  4. julia> b = [1]; a = copy(b); b[1] = 2; a
  5. 1-element Array{Int64, 1}:
  6. 1

Collections passed to functions are also not copied. Functions can modify (mutate) the contents of the objects their arguments refer to. (The names of functions which do this are conventionally suffixed with ‘!’.)

  1. julia> function f!(x); x[:] .+= 1; end
  2. f! (generic function with 1 method)
  3. julia> a = [1]; f!(a); a
  4. 1-element Array{Int64, 1}:
  5. 2

Assignment can operate on multiple variables in parallel, taking values from an iterable:

  1. julia> a, b = 4, 5
  2. (4, 5)
  3. julia> a, b = 1:3
  4. 1:3
  5. julia> a, b
  6. (1, 2)

Assignment can operate on multiple variables in series, and will return the value of the right-hand-most expression:

  1. julia> a = [1]; b = [2]; c = [3]; a = b = c
  2. 1-element Array{Int64, 1}:
  3. 3
  4. julia> b[1] = 2; a, b, c
  5. ([2], [2], [2])

Assignment at out-of-bounds indices does not grow a collection. If the collection is a Vector it can instead be grown with push! or append!.

  1. julia> a = [1, 1]; a[3] = 2
  2. ERROR: BoundsError: attempt to access 2-element Array{Int64, 1} at index [3]
  3. [...]
  4. julia> push!(a, 2, 3)
  5. 4-element Array{Int64, 1}:
  6. 1
  7. 1
  8. 2
  9. 3

Assigning [] does not eliminate elements from a collection; instead use filter!.

  1. julia> a = collect(1:3); a[a .<= 1] = []
  2. ERROR: DimensionMismatch: tried to assign 0 elements to 1 destinations
  3. [...]
  4. julia> filter!(x -> x > 1, a) # in-place & thus more efficient than a = a[a .> 1]
  5. 2-element Array{Int64, 1}:
  6. 2
  7. 3

source

?: — Keyword

  1. a ? b : c

Short form for conditionals; read “if a, evaluate b otherwise evaluate c“. Also known as the ternary operator.

This syntax is equivalent to if a; b else c end, but is often used to emphasize the value b-or-c which is being used as part of a larger expression, rather than the side effects that evaluating b or c may have.

See the manual section on control flow for more details.

Examples

  1. julia> x = 1; y = 2;
  2. julia> x > y ? println("x is larger") : println("y is larger")
  3. y is larger

source

Standard Modules

Main — Module

  1. Main

Main is the top-level module, and Julia starts with Main set as the current module. Variables defined at the prompt go in Main, and varinfo lists variables in Main.

  1. julia> @__MODULE__
  2. Main

source

Core — Module

  1. Core

Core is the module that contains all identifiers considered “built in” to the language, i.e. part of the core language and not libraries. Every module implicitly specifies using Core, since you can’t do anything without those definitions.

source

Base — Module

  1. Base

The base library of Julia. Base is a module that contains basic functionality (the contents of base/). All modules implicitly contain using Base, since this is needed in the vast majority of cases.

source

Base Submodules

Base.Broadcast — Module

  1. Base.Broadcast

Module containing the broadcasting implementation.

source

Base.Docs — Module

  1. Docs

The Docs module provides the @doc macro which can be used to set and retrieve documentation metadata for Julia objects.

Please see the manual section on documentation for more information.

source

Base.Iterators — Module

Methods for working with Iterators.

source

Base.Libc — Module

Interface to libc, the C standard library.

source

Base.Meta — Module

Convenience functions for metaprogramming.

source

Base.StackTraces — Module

Tools for collecting and manipulating stack traces. Mainly used for building errors.

source

Base.Sys — Module

Provide methods for retrieving information about hardware and the operating system.

source

Base.Threads — Module

Multithreading support.

source

Base.GC — Module

  1. Base.GC

Module with garbage collection utilities.

source

All Objects

Core.:=== — Function

  1. ===(x,y) -> Bool
  2. ≡(x,y) -> Bool

Determine whether x and y are identical, in the sense that no program could distinguish them. First the types of x and y are compared. If those are identical, mutable objects are compared by address in memory and immutable objects (such as numbers) are compared by contents at the bit level. This function is sometimes called “egal”. It always returns a Bool value.

Examples

  1. julia> a = [1, 2]; b = [1, 2];
  2. julia> a == b
  3. true
  4. julia> a === b
  5. false
  6. julia> a === a
  7. true

source

Core.isa — Function

  1. isa(x, type) -> Bool

Determine whether x is of the given type. Can also be used as an infix operator, e.g. x isa type.

Examples

  1. julia> isa(1, Int)
  2. true
  3. julia> isa(1, Matrix)
  4. false
  5. julia> isa(1, Char)
  6. false
  7. julia> isa(1, Number)
  8. true
  9. julia> 1 isa Number
  10. true

source

Base.isequal — Function

  1. isequal(x, y)

Similar to \==, except for the treatment of floating point numbers and of missing values. isequal treats all floating-point NaN values as equal to each other, treats -0.0 as unequal to 0.0, and missing as equal to missing. Always returns a Bool value.

isequal is an equivalence relation - it is reflexive (=== implies isequal), symmetric (isequal(a, b) implies isequal(b, a)) and transitive (isequal(a, b) and isequal(b, c) implies isequal(a, c)).

Implementation

The default implementation of isequal calls ==, so a type that does not involve floating-point values generally only needs to define ==.

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

This typically means that types for which a custom == or isequal method exists must implement a corresponding hash method (and vice versa). Collections typically implement isequal by calling isequal recursively on all contents.

Furthermore, isequal is linked with isless, and they work together to define a fixed total ordering, where exactly one of isequal(x, y), isless(x, y), or isless(y, x) must be true (and the other two false).

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 ==).

Examples

  1. julia> isequal([1., NaN], [1., NaN])
  2. true
  3. julia> [1., NaN] == [1., NaN]
  4. false
  5. julia> 0.0 == -0.0
  6. true
  7. julia> isequal(0.0, -0.0)
  8. false
  9. julia> missing == missing
  10. missing
  11. julia> isequal(missing, missing)
  12. true

source

  1. isequal(x)

Create a function that compares its argument to x using isequal, i.e. a function equivalent to y -> isequal(y, x).

The returned function is of type Base.Fix2{typeof(isequal)}, which can be used to implement specialized methods.

source

Base.isless — Function

  1. isless(x, y)

Test whether x is less than y, according to a fixed total order (defined together with isequal). isless is not defined on all pairs of values (x, y). However, if it is defined, it is expected to satisfy the following:

  • If isless(x, y) is defined, then so is isless(y, x) and isequal(x, y), and exactly one of those three yields true.
  • The relation defined by isless is transitive, i.e., isless(x, y) && isless(y, z) implies isless(x, z).

Values that are normally unordered, such as NaN, are ordered after regular values. missing values are ordered last.

This is the default comparison used by sort.

Implementation

Non-numeric types with a total order should implement this function. Numeric types only need to implement it if they have special values such as NaN. Types with a partial order should implement <. See the documentation on Alternate orderings for how to define alternate ordering methods that can be used in sorting and related functions.

Examples

  1. julia> isless(1, 3)
  2. true
  3. julia> isless("Red", "Blue")
  4. false

source

Base.ifelse — Function

  1. 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. In some cases, using ifelse instead of an if statement can eliminate the branch in generated code and provide higher performance in tight loops.

Examples

  1. julia> ifelse(1 > 2, 1, 2)
  2. 2

source

Core.typeassert — Function

  1. typeassert(x, type)

Throw a TypeError unless x isa type. The syntax x::type calls this function.

Examples

  1. julia> typeassert(2.5, Int)
  2. ERROR: TypeError: in typeassert, expected Int64, got a value of type Float64
  3. Stacktrace:
  4. [...]

source

Core.typeof — Function

  1. typeof(x)

Get the concrete type of x.

See also eltype.

Examples

  1. julia> a = 1//2;
  2. julia> typeof(a)
  3. Rational{Int64}
  4. julia> M = [1 2; 3.5 4];
  5. julia> typeof(M)
  6. Matrix{Float64} (alias for Array{Float64, 2})

source

Core.tuple — Function

  1. tuple(xs...)

Construct a tuple of the given objects.

See also Tuple, NamedTuple.

Examples

  1. julia> tuple(1, 'b', pi)
  2. (1, 'b', π)
  3. julia> ans === (1, 'b', π)
  4. true
  5. julia> Tuple(Real[1, 2, pi]) # takes a collection
  6. (1, 2, π)

source

Base.ntuple — Function

  1. ntuple(f::Function, n::Integer)

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

Examples

  1. julia> ntuple(i -> 2*i, 4)
  2. (2, 4, 6, 8)

source

  1. ntuple(f, ::Val{N})

Create a tuple of length N, computing each element as f(i), where i is the index of the element. By taking a Val(N) argument, it is possible that this version of ntuple may generate more efficient code than the version taking the length as an integer. But ntuple(f, N) is preferable to ntuple(f, Val(N)) in cases where N cannot be determined at compile time.

Examples

  1. julia> ntuple(i -> 2*i, Val(4))
  2. (2, 4, 6, 8)

source

Base.objectid — Function

  1. objectid(x) -> UInt

Get a hash value for x based on object identity. objectid(x)==objectid(y) if x === y.

See also hash, IdDict.

source

Base.hash — Function

  1. hash(x[, h::UInt]) -> UInt

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. Types supporting subtraction (operator -) should also implement widen, which is required to hash values inside heterogeneous arrays.

See also: objectid, Dict, Set.

source

Base.finalizer — Function

  1. finalizer(f, x)

Register a function f(x) to be called when there are no program-accessible references to x, and return x. The type of x must be a mutable struct, otherwise the behavior of this function is unpredictable.

f must not cause a task switch, which excludes most I/O operations such as println. Using the @async macro (to defer context switching to outside of the finalizer) or ccall to directly invoke IO functions in C may be helpful for debugging purposes.

Examples

  1. finalizer(my_mutable_struct) do x
  2. @async println("Finalizing $x.")
  3. end
  4. finalizer(my_mutable_struct) do x
  5. ccall(:jl_safe_printf, Cvoid, (Cstring, Cstring), "Finalizing %s.", repr(x))
  6. end

A finalizer may be registered at object construction. In the following example note that we implicitly rely on the finalizer returning the newly created mutable struct x.

Example

  1. mutable struct MyMutableStruct
  2. bar
  3. function MyMutableStruct(bar)
  4. x = new(bar)
  5. f(t) = @async println("Finalizing $t.")
  6. finalizer(f, x)
  7. end
  8. end

source

Base.finalize — Function

  1. finalize(x)

Immediately run finalizers registered for object x.

source

Base.copy — Function

  1. 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.

See also copy!, copyto!.

source

Base.deepcopy — Function

  1. 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.

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::IdDict) (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.

source

Base.getproperty — Function

  1. getproperty(value, name::Symbol)
  2. getproperty(value, name::Symbol, order::Symbol)

The syntax a.b calls getproperty(a, :b). The syntax @atomic order a.b calls getproperty(a, :b, :order) and the syntax @atomic a.b calls getproperty(a, :b, :sequentially_consistent).

Examples

  1. julia> struct MyType
  2. x
  3. end
  4. julia> function Base.getproperty(obj::MyType, sym::Symbol)
  5. if sym === :special
  6. return obj.x + 1
  7. else # fallback to getfield
  8. return getfield(obj, sym)
  9. end
  10. end
  11. julia> obj = MyType(1);
  12. julia> obj.special
  13. 2
  14. julia> obj.x
  15. 1

See also getfield, propertynames and setproperty!.

source

Base.setproperty! — Function

  1. setproperty!(value, name::Symbol, x)
  2. setproperty!(value, name::Symbol, x, order::Symbol)

The syntax a.b = c calls setproperty!(a, :b, c). The syntax @atomic order a.b = c calls setproperty!(a, :b, c, :order) and the syntax @atomic a.b = c calls getproperty(a, :b, :sequentially_consistent).

See also setfield!, propertynames and getproperty.

source

Base.propertynames — Function

  1. propertynames(x, private=false)

Get a tuple or a vector of the properties (x.property) of an object x. This is typically the same as fieldnames(typeof(x)), but types that overload getproperty should generally overload propertynames as well to get the properties of an instance of the type.

propertynames(x) may return only “public” property names that are part of the documented interface of x. If you want it to also return “private” fieldnames intended for internal use, pass true for the optional second argument. REPL tab completion on x. shows only the private=false properties.

See also: hasproperty, hasfield.

source

Base.hasproperty — Function

  1. hasproperty(x, s::Symbol)

Return a boolean indicating whether the object x has s as one of its own properties.

Julia 1.2

This function requires at least Julia 1.2.

See also: propertynames, hasfield.

source

Core.getfield — Function

  1. getfield(value, name::Symbol, [order::Symbol])
  2. getfield(value, i::Int, [order::Symbol])

Extract a field from a composite value by name or position. Optionally, an ordering can be defined for the operation. If the field was declared @atomic, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as @atomic, this parameter must be :not_atomic if specified. See also getproperty and fieldnames.

Examples

  1. julia> a = 1//2
  2. 1//2
  3. julia> getfield(a, :num)
  4. 1
  5. julia> a.num
  6. 1
  7. julia> getfield(a, 1)
  8. 1

source

Core.setfield! — Function

  1. setfield!(value, name::Symbol, x, [order::Symbol])
  2. setfield!(value, i::Int, x, [order::Symbol])

Assign x to a named field in value of composite type. The value must be mutable and x must be a subtype of fieldtype(typeof(value), name). Additionally, an ordering can be specified for this operation. If the field was declared @atomic, this specification is mandatory. Otherwise, if not declared as @atomic, it must be :not_atomic if specified. See also setproperty!.

Examples

  1. julia> mutable struct MyMutableStruct
  2. field::Int
  3. end
  4. julia> a = MyMutableStruct(1);
  5. julia> setfield!(a, :field, 2);
  6. julia> getfield(a, :field)
  7. 2
  8. julia> a = 1//2
  9. 1//2
  10. julia> setfield!(a, :num, 3);
  11. ERROR: setfield!: immutable struct of type Rational cannot be changed

source

Core.isdefined — Function

  1. isdefined(m::Module, s::Symbol, [order::Symbol])
  2. isdefined(object, s::Symbol, [order::Symbol])
  3. isdefined(object, index::Int, [order::Symbol])

Tests whether a global variable or object field is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index. Optionally, an ordering can be defined for the operation. If the field was declared @atomic, the specification is strongly recommended to be compatible with the stores to that location. Otherwise, if not declared as @atomic, this parameter must be :not_atomic if specified.

To test whether an array element is defined, use isassigned instead.

See also @isdefined.

Examples

  1. julia> isdefined(Base, :sum)
  2. true
  3. julia> isdefined(Base, :NonExistentMethod)
  4. false
  5. julia> a = 1//2;
  6. julia> isdefined(a, 2)
  7. true
  8. julia> isdefined(a, 3)
  9. false
  10. julia> isdefined(a, :num)
  11. true
  12. julia> isdefined(a, :numerator)
  13. false

source

Base.@isdefined — Macro

  1. @isdefined s -> Bool

Tests whether variable s is defined in the current scope.

See also isdefined for field properties and isassigned for array indexes or haskey for other mappings.

Examples

  1. julia> @isdefined newvar
  2. false
  3. julia> newvar = 1
  4. 1
  5. julia> @isdefined newvar
  6. true
  7. julia> function f()
  8. println(@isdefined x)
  9. x = 3
  10. println(@isdefined x)
  11. end
  12. f (generic function with 1 method)
  13. julia> f()
  14. false
  15. true

source

Base.convert — Function

  1. convert(T, x)

Convert x to a value of type T.

If T is an Integer type, an InexactError will be raised if x is not representable by T, for example if x is not integer-valued, or is outside the range supported by T.

Examples

  1. julia> convert(Int, 3.0)
  2. 3
  3. julia> convert(Int, 3.5)
  4. ERROR: InexactError: Int64(3.5)
  5. Stacktrace:
  6. [...]

If T is a AbstractFloat type, then it will return the closest value to x representable by T.

  1. julia> x = 1/3
  2. 0.3333333333333333
  3. julia> convert(Float32, x)
  4. 0.33333334f0
  5. julia> convert(BigFloat, x)
  6. 0.333333333333333314829616256247390992939472198486328125

If T is a collection type and x a collection, the result of convert(T, x) may alias all or part of x.

  1. julia> x = Int[1, 2, 3];
  2. julia> y = convert(Vector{Int}, x);
  3. julia> y === x
  4. true

See also: round, trunc, oftype, reinterpret.

source

Base.promote — Function

  1. promote(xs...)

Convert all arguments to a common type, and return them all (as a tuple). If no arguments can be converted, an error is raised.

See also: [promote_type], [promote_rule].

Examples

  1. julia> promote(Int8(1), Float16(4.5), Float32(4.1))
  2. (1.0f0, 4.5f0, 4.1f0)

source

Base.oftype — Function

  1. oftype(x, y)

Convert y to the type of x (convert(typeof(x), y)).

Examples

  1. julia> x = 4;
  2. julia> y = 3.;
  3. julia> oftype(x, y)
  4. 3
  5. julia> oftype(y, x)
  6. 4.0

source

Base.widen — Function

  1. widen(x)

If x is a type, return a “larger” type, defined so that arithmetic operations + and - are guaranteed not to overflow nor lose precision for any combination of values that type x can hold.

For fixed-size integer types less than 128 bits, widen will return a type with twice the number of bits.

If x is a value, it is converted to widen(typeof(x)).

Examples

  1. julia> widen(Int32)
  2. Int64
  3. julia> widen(1.5f0)
  4. 1.5

source

Base.identity — Function

  1. identity(x)

The identity function. Returns its argument.

See also: one, oneunit, and LinearAlgebra‘s I.

Examples

  1. julia> identity("Well, what did you expect?")
  2. "Well, what did you expect?"

source

Properties of Types

Type relations

Base.supertype — Function

  1. supertype(T::DataType)

Return the supertype of DataType T.

Examples

  1. julia> supertype(Int32)
  2. Signed

source

Core.Type — Type

  1. Core.Type{T}

Core.Type is an abstract type which has all type objects as its instances. The only instance of the singleton type Core.Type{T} is the object T.

Examples

  1. julia> isa(Type{Float64}, Type)
  2. true
  3. julia> isa(Float64, Type)
  4. true
  5. julia> isa(Real, Type{Float64})
  6. false
  7. julia> isa(Real, Type{Real})
  8. true

source

Core.DataType — Type

  1. DataType <: Type{T}

DataType represents explicitly declared types that have names, explicitly declared supertypes, and, optionally, parameters. Every concrete value in the system is an instance of some DataType.

Examples

  1. julia> typeof(Real)
  2. DataType
  3. julia> typeof(Int)
  4. DataType
  5. julia> struct Point
  6. x::Int
  7. y
  8. end
  9. julia> typeof(Point)
  10. DataType

source

Core.:<: — Function

  1. <:(T1, T2)

Subtype operator: returns true if and only if all values of type T1 are also of type T2.

Examples

  1. julia> Float64 <: AbstractFloat
  2. true
  3. julia> Vector{Int} <: AbstractArray
  4. true
  5. julia> Matrix{Float64} <: Matrix{AbstractFloat}
  6. false

source

Base.:>: — Function

  1. >:(T1, T2)

Supertype operator, equivalent to T2 <: T1.

source

Base.typejoin — Function

  1. typejoin(T, S)

Return the closest common ancestor of T and S, i.e. the narrowest type from which they both inherit.

source

Base.typeintersect — Function

  1. typeintersect(T::Type, S::Type)

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

source

Base.promote_type — Function

  1. promote_type(type1, type2)

Promotion refers to converting values of mixed types to a single common type. promote_type represents the default promotion behavior in Julia when operators (usually mathematical) are given arguments of differing types. promote_type generally tries to return a type which can at least approximate most values of either input type without excessively widening. 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.

See also: promote, promote_typejoin, promote_rule.

Examples

  1. julia> promote_type(Int64, Float64)
  2. Float64
  3. julia> promote_type(Int32, Int64)
  4. Int64
  5. julia> promote_type(Float32, BigInt)
  6. BigFloat
  7. julia> promote_type(Int16, Float16)
  8. Float16
  9. julia> promote_type(Int64, Float16)
  10. Float16
  11. julia> promote_type(Int8, UInt16)
  12. UInt16

Don’t overload this directly

To overload promotion for your own types you should overload promote_rule. promote_type calls promote_rule internally to determine the type. Overloading promote_type directly can cause ambiguity errors.

source

Base.promote_rule — Function

  1. 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.

source

Base.promote_typejoin — Function

  1. promote_typejoin(T, S)

Compute a type that contains both T and S, which could be either a parent of both types, or a Union if appropriate. Falls back to typejoin.

See instead promote, promote_type.

Examples

  1. julia> Base.promote_typejoin(Int, Float64)
  2. Real
  3. julia> Base.promote_type(Int, Float64)
  4. Float64

source

Base.isdispatchtuple — Function

  1. isdispatchtuple(T)

Determine whether type T is a tuple “leaf type”, meaning it could appear as a type signature in dispatch and has no subtypes (or supertypes) which could appear in a call.

source

Declared structure

Base.ismutable — Function

  1. ismutable(v) -> Bool

Return true if and only if value v is mutable. See Mutable 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.

See also isbits, isstructtype.

Examples

  1. julia> ismutable(1)
  2. false
  3. julia> ismutable([1,2])
  4. true

Julia 1.5

This function requires at least Julia 1.5.

source

Base.isimmutable — Function

  1. isimmutable(v) -> Bool

Warning

Consider using !ismutable(v) instead, as isimmutable(v) will be replaced by !ismutable(v) in a future release. (Since Julia 1.5)

Return true iff value v is immutable. See Mutable 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.

Examples

  1. julia> isimmutable(1)
  2. true
  3. julia> isimmutable([1,2])
  4. false

source

Base.isabstracttype — Function

  1. isabstracttype(T)

Determine whether type T was declared as an abstract type (i.e. using the abstract keyword).

Examples

  1. julia> isabstracttype(AbstractArray)
  2. true
  3. julia> isabstracttype(Vector)
  4. false

source

Base.isprimitivetype — Function

  1. isprimitivetype(T) -> Bool

Determine whether type T was declared as a primitive type (i.e. using the primitive keyword).

source

Base.issingletontype — Function

  1. Base.issingletontype(T)

Determine whether type T has exactly one possible instance; for example, a struct type with no fields.

source

Base.isstructtype — Function

  1. isstructtype(T) -> Bool

Determine whether type T was declared as a struct type (i.e. using the struct or mutable struct keyword).

source

Base.nameof — Method

  1. nameof(t::DataType) -> Symbol

Get the name of a (potentially UnionAll-wrapped) DataType (without its parent module) as a symbol.

Examples

  1. julia> module Foo
  2. struct S{T}
  3. end
  4. end
  5. Foo
  6. julia> nameof(Foo.S{T} where T)
  7. :S

source

Base.fieldnames — Function

  1. fieldnames(x::DataType)

Get a tuple with the names of the fields of a DataType.

See also propertynames, hasfield.

Examples

  1. julia> fieldnames(Rational)
  2. (:num, :den)
  3. julia> fieldnames(typeof(1+im))
  4. (:re, :im)

source

Base.fieldname — Function

  1. fieldname(x::DataType, i::Integer)

Get the name of field i of a DataType.

Examples

  1. julia> fieldname(Rational, 1)
  2. :num
  3. julia> fieldname(Rational, 2)
  4. :den

source

Core.fieldtype — Function

  1. fieldtype(T, name::Symbol | index::Int)

Determine the declared type of a field (specified by name or index) in a composite DataType T.

Examples

  1. julia> struct Foo
  2. x::Int64
  3. y::String
  4. end
  5. julia> fieldtype(Foo, :x)
  6. Int64
  7. julia> fieldtype(Foo, 2)
  8. String

source

Base.fieldtypes — Function

  1. fieldtypes(T::Type)

The declared types of all fields in a composite DataType T as a tuple.

Julia 1.1

This function requires at least Julia 1.1.

Examples

  1. julia> struct Foo
  2. x::Int64
  3. y::String
  4. end
  5. julia> fieldtypes(Foo)
  6. (Int64, String)

source

Base.fieldcount — Function

  1. fieldcount(t::Type)

Get the number of fields that an instance of the given type would have. An error is thrown if the type is too abstract to determine this.

source

Base.hasfield — Function

  1. hasfield(T::Type, name::Symbol)

Return a boolean indicating whether T has name as one of its own fields.

See also fieldnames, fieldcount, hasproperty.

Julia 1.2

This function requires at least Julia 1.2.

Examples

  1. julia> struct Foo
  2. bar::Int
  3. end
  4. julia> hasfield(Foo, :bar)
  5. true
  6. julia> hasfield(Foo, :x)
  7. false

source

Core.nfields — Function

  1. nfields(x) -> Int

Get the number of fields in the given object.

Examples

  1. julia> a = 1//2;
  2. julia> nfields(a)
  3. 2
  4. julia> b = 1
  5. 1
  6. julia> nfields(b)
  7. 0
  8. julia> ex = ErrorException("I've done a bad thing");
  9. julia> nfields(ex)
  10. 1

In these examples, a is a Rational, which has two fields. b is an Int, which is a primitive bitstype with no fields at all. ex is an ErrorException, which has one field.

source

Base.isconst — Function

  1. isconst(m::Module, s::Symbol) -> Bool

Determine whether a global is declared const in a given module m.

source

  1. isconst(t::DataType, s::Union{Int,Symbol}) -> Bool

Determine whether a field s is declared const in a given type t.

source

Memory layout

Base.sizeof — Method

  1. sizeof(T::DataType)
  2. sizeof(obj)

Size, in bytes, of the canonical binary representation of the given DataType T, if any. Or the size, in bytes, of object obj if it is not a DataType.

See also summarysize.

Examples

  1. julia> sizeof(Float32)
  2. 4
  3. julia> sizeof(ComplexF64)
  4. 16
  5. julia> sizeof(1.0)
  6. 8
  7. julia> sizeof(collect(1.0:10.0))
  8. 80

If DataType T does not have a specific size, an error is thrown.

  1. julia> sizeof(AbstractArray)
  2. ERROR: Abstract type AbstractArray does not have a definite size.
  3. Stacktrace:
  4. [...]

source

Base.isconcretetype — Function

  1. isconcretetype(T)

Determine whether type T is a concrete type, meaning it could have direct instances (values x such that typeof(x) === T).

See also: isbits, isabstracttype, issingletontype.

Examples

  1. julia> isconcretetype(Complex)
  2. false
  3. julia> isconcretetype(Complex{Float32})
  4. true
  5. julia> isconcretetype(Vector{Complex})
  6. true
  7. julia> isconcretetype(Vector{Complex{Float32}})
  8. true
  9. julia> isconcretetype(Union{})
  10. false
  11. julia> isconcretetype(Union{Int,String})
  12. false

source

Base.isbits — Function

  1. isbits(x)

Return true if x is an instance of an isbitstype type.

source

Base.isbitstype — Function

  1. isbitstype(T)

Return true if type T is a “plain data” type, meaning it is immutable and contains no references to other values, only primitive types and other isbitstype types. Typical examples are numeric types such as UInt8, Float64, and Complex{Float64}. This category of types is significant since they are valid as type parameters, may not track isdefined / isassigned status, and have a defined layout that is compatible with C.

See also isbits, isprimitivetype, ismutable.

Examples

  1. julia> isbitstype(Complex{Float64})
  2. true
  3. julia> isbitstype(Complex)
  4. false

source

Base.fieldoffset — Function

  1. fieldoffset(type, i)

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

  1. julia> structinfo(T) = [(fieldoffset(T,i), fieldname(T,i), fieldtype(T,i)) for i = 1:fieldcount(T)];
  2. julia> structinfo(Base.Filesystem.StatStruct)
  3. 13-element Vector{Tuple{UInt64, Symbol, Type}}:
  4. (0x0000000000000000, :desc, Union{RawFD, String})
  5. (0x0000000000000008, :device, UInt64)
  6. (0x0000000000000010, :inode, UInt64)
  7. (0x0000000000000018, :mode, UInt64)
  8. (0x0000000000000020, :nlink, Int64)
  9. (0x0000000000000028, :uid, UInt64)
  10. (0x0000000000000030, :gid, UInt64)
  11. (0x0000000000000038, :rdev, UInt64)
  12. (0x0000000000000040, :size, Int64)
  13. (0x0000000000000048, :blksize, Int64)
  14. (0x0000000000000050, :blocks, Int64)
  15. (0x0000000000000058, :mtime, Float64)
  16. (0x0000000000000060, :ctime, Float64)

source

Base.datatype_alignment — Function

  1. Base.datatype_alignment(dt::DataType) -> Int

Memory allocation minimum alignment for instances of this type. Can be called on any isconcretetype.

source

Base.datatype_haspadding — Function

  1. Base.datatype_haspadding(dt::DataType) -> Bool

Return whether the fields of instances of this type are packed in memory, with no intervening padding bytes. Can be called on any isconcretetype.

source

Base.datatype_pointerfree — Function

  1. Base.datatype_pointerfree(dt::DataType) -> Bool

Return whether instances of this type can contain references to gc-managed memory. Can be called on any isconcretetype.

source

Special values

Base.typemin — Function

  1. typemin(T)

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

Examples

  1. julia> typemin(Float16)
  2. -Inf16
  3. julia> typemin(Float32)
  4. -Inf32

source

Base.typemax — Function

  1. typemax(T)

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

See also: floatmax, typemin, eps.

Examples

  1. julia> typemax(Int8)
  2. 127
  3. julia> typemax(UInt32)
  4. 0xffffffff
  5. julia> typemax(Float64)
  6. Inf
  7. julia> floatmax(Float32) # largest finite floating point number
  8. 3.4028235f38

source

Base.floatmin — Function

  1. floatmin(T = Float64)

Return the smallest positive normal number representable by the floating-point type T.

Examples

  1. julia> floatmin(Float16)
  2. Float16(6.104e-5)
  3. julia> floatmin(Float32)
  4. 1.1754944f-38
  5. julia> floatmin()
  6. 2.2250738585072014e-308

source

Base.floatmax — Function

  1. floatmax(T = Float64)

Return the largest finite number representable by the floating-point type T.

See also: typemax, floatmin, eps.

Examples

  1. julia> floatmax(Float16)
  2. Float16(6.55e4)
  3. julia> floatmax(Float32)
  4. 3.4028235f38
  5. julia> floatmax()
  6. 1.7976931348623157e308
  7. julia> typemax(Float64)
  8. Inf

source

Base.maxintfloat — Function

  1. maxintfloat(T=Float64)

The largest consecutive integer-valued floating-point number that is exactly represented in the given floating-point type T (which defaults to Float64).

That is, maxintfloat returns the smallest positive integer-valued floating-point number n such that n+1 is not exactly representable in the type T.

When an Integer-type value is needed, use Integer(maxintfloat(T)).

source

  1. maxintfloat(T, S)

The largest consecutive integer representable in the given floating-point type T that also does not exceed the maximum integer representable by the integer type S. Equivalently, it is the minimum of maxintfloat(T) and typemax(S).

source

Base.eps — Method

  1. eps(::Type{T}) where T<:AbstractFloat
  2. eps()

Return the machine epsilon of the floating point type T (T = Float64 by default). This is defined as the gap between 1 and the next largest value representable by typeof(one(T)), and is equivalent to eps(one(T)). (Since eps(T) is a bound on the relative error of T, it is a “dimensionless” quantity like one.)

Examples

  1. julia> eps()
  2. 2.220446049250313e-16
  3. julia> eps(Float32)
  4. 1.1920929f-7
  5. julia> 1.0 + eps()
  6. 1.0000000000000002
  7. julia> 1.0 + eps()/2
  8. 1.0

source

Base.eps — Method

  1. eps(x::AbstractFloat)

Return the unit in last place (ulp) of x. This is the distance between consecutive representable floating point values at x. In most cases, if the distance on either side of x is different, then the larger of the two is taken, that is

  1. eps(x) == max(x-prevfloat(x), nextfloat(x)-x)

The exceptions to this rule are the smallest and largest finite values (e.g. nextfloat(-Inf) and prevfloat(Inf) for Float64), which round to the smaller of the values.

The rationale for this behavior is that eps bounds the floating point rounding error. Under the default RoundNearest rounding mode, if $y$ is a real number and $x$ is the nearest floating point number to $y$, then

\[|y-x| \leq \operatorname{eps}(x)/2.\]

See also: nextfloat, issubnormal, floatmax.

Examples

  1. julia> eps(1.0)
  2. 2.220446049250313e-16
  3. julia> eps(prevfloat(2.0))
  4. 2.220446049250313e-16
  5. julia> eps(2.0)
  6. 4.440892098500626e-16
  7. julia> x = prevfloat(Inf) # largest finite Float64
  8. 1.7976931348623157e308
  9. julia> x + eps(x)/2 # rounds up
  10. Inf
  11. julia> x + prevfloat(eps(x)/2) # rounds down
  12. 1.7976931348623157e308

source

Base.instances — Function

  1. instances(T::Type)

Return a collection of all instances of the given type, if applicable. Mostly used for enumerated types (see @enum).

Example

  1. julia> @enum Color red blue green
  2. julia> instances(Color)
  3. (red, blue, green)

source

Special Types

Core.Any — Type

  1. Any::DataType

Any is the union of all types. It has the defining property isa(x, Any) == true for any x. Any therefore describes the entire universe of possible values. For example Integer is a subset of Any that includes Int, Int8, and other integer types.

source

Core.Union — Type

  1. Union{Types...}

A type union is an abstract type which includes all instances of any of its argument types. The empty union Union{} is the bottom type of Julia.

Examples

  1. julia> IntOrString = Union{Int,AbstractString}
  2. Union{Int64, AbstractString}
  3. julia> 1 :: IntOrString
  4. 1
  5. julia> "Hello!" :: IntOrString
  6. "Hello!"
  7. julia> 1.0 :: IntOrString
  8. ERROR: TypeError: in typeassert, expected Union{Int64, AbstractString}, got a value of type Float64

source

Union{} — Keyword

  1. Union{}

Union{}, the empty Union of types, is the type that has no values. That is, it has the defining property isa(x, Union{}) == false for any x. Base.Bottom is defined as its alias and the type of Union{} is Core.TypeofBottom.

Examples

  1. julia> isa(nothing, Union{})
  2. false

source

Core.UnionAll — Type

  1. UnionAll

A union of types over all values of a type parameter. UnionAll is used to describe parametric types where the values of some parameters are not known.

Examples

  1. julia> typeof(Vector)
  2. UnionAll
  3. julia> typeof(Vector{Int})
  4. DataType

source

Core.Tuple — Type

  1. Tuple{Types...}

Tuples are an abstraction of the arguments of a function – without the function itself. The salient aspects of a function’s arguments are their order and their types. Therefore a tuple type is similar to a parameterized immutable type where each parameter is the type of one field. Tuple types may have any number of parameters.

Tuple types are covariant in their parameters: Tuple{Int} is a subtype of Tuple{Any}. Therefore Tuple{Any} is considered an abstract type, and tuple types are only concrete if their parameters are. Tuples do not have field names; fields are only accessed by index.

See the manual section on Tuple Types.

See also Vararg, NTuple, tuple, NamedTuple.

source

Core.NTuple — Type

  1. NTuple{N, T}

A compact way of representing the type for a tuple of length N where all elements are of type T.

Examples

  1. julia> isa((1, 2, 3, 4, 5, 6), NTuple{6, Int})
  2. true

source

Core.NamedTuple — Type

  1. NamedTuple

NamedTuples are, as their name suggests, named Tuples. That is, they’re a tuple-like collection of values, where each entry has a unique name, represented as a Symbol. Like Tuples, NamedTuples are immutable; neither the names nor the values can be modified in place after construction.

Accessing the value associated with a name in a named tuple can be done using field access syntax, e.g. x.a, or using getindex, e.g. x[:a] or x[(:a, :b)]. A tuple of the names can be obtained using keys, and a tuple of the values can be obtained using values.

Note

Iteration over NamedTuples produces the values without the names. (See example below.) To iterate over the name-value pairs, use the pairs function.

The @NamedTuple macro can be used for conveniently declaring NamedTuple types.

Examples

  1. julia> x = (a=1, b=2)
  2. (a = 1, b = 2)
  3. julia> x.a
  4. 1
  5. julia> x[:a]
  6. 1
  7. julia> x[(:a,)]
  8. (a = 1,)
  9. julia> keys(x)
  10. (:a, :b)
  11. julia> values(x)
  12. (1, 2)
  13. julia> collect(x)
  14. 2-element Vector{Int64}:
  15. 1
  16. 2
  17. julia> collect(pairs(x))
  18. 2-element Vector{Pair{Symbol, Int64}}:
  19. :a => 1
  20. :b => 2

In a similar fashion as to how one can define keyword arguments programmatically, a named tuple can be created by giving a pair name::Symbol => value or splatting an iterator yielding such pairs after a semicolon inside a tuple literal:

  1. julia> (; :a => 1)
  2. (a = 1,)
  3. julia> keys = (:a, :b, :c); values = (1, 2, 3);
  4. julia> (; zip(keys, values)...)
  5. (a = 1, b = 2, c = 3)

As in keyword arguments, identifiers and dot expressions imply names:

  1. julia> x = 0
  2. 0
  3. julia> t = (; x)
  4. (x = 0,)
  5. julia> (; t.x)
  6. (x = 0,)

Julia 1.5

Implicit names from identifiers and dot expressions are available as of Julia 1.5.

Julia 1.7

Use of getindex methods with multiple Symbols is available as of Julia 1.7.

source

Base.@NamedTuple — Macro

  1. @NamedTuple{key1::Type1, key2::Type2, ...}
  2. @NamedTuple begin key1::Type1; key2::Type2; ...; end

This macro gives a more convenient syntax for declaring NamedTuple types. It returns a NamedTuple type with the given keys and types, equivalent to NamedTuple{(:key1, :key2, ...), Tuple{Type1,Type2,...}}. If the ::Type declaration is omitted, it is taken to be Any. The begin ... end form allows the declarations to be split across multiple lines (similar to a struct declaration), but is otherwise equivalent.

For example, the tuple (a=3.1, b="hello") has a type NamedTuple{(:a, :b),Tuple{Float64,String}}, which can also be declared via @NamedTuple as:

  1. julia> @NamedTuple{a::Float64, b::String}
  2. NamedTuple{(:a, :b), Tuple{Float64, String}}
  3. julia> @NamedTuple begin
  4. a::Float64
  5. b::String
  6. end
  7. NamedTuple{(:a, :b), Tuple{Float64, String}}

Julia 1.5

This macro is available as of Julia 1.5.

source

Base.Val — Type

  1. Val(c)

Return Val{c}(), which contains no run-time data. Types like this can be used to pass the information between functions through the value c, which must be an isbits value or a Symbol. The intent of this construct is to be able to dispatch on constants directly (at compile time) without having to test the value of the constant at run time.

Examples

  1. julia> f(::Val{true}) = "Good"
  2. f (generic function with 1 method)
  3. julia> f(::Val{false}) = "Bad"
  4. f (generic function with 2 methods)
  5. julia> f(Val(true))
  6. "Good"

source

Core.Vararg — Constant

  1. Vararg{T,N}

The last parameter of a tuple type Tuple can be the special value Vararg, which denotes any number of trailing elements. Vararg{T,N} corresponds to exactly N elements of type T. Finally Vararg{T} corresponds to zero or more elements of type T. Vararg tuple types are used to represent the arguments accepted by varargs methods (see the section on Varargs Functions in the manual.)

See also NTuple.

Examples

  1. julia> mytupletype = Tuple{AbstractString, Vararg{Int}}
  2. Tuple{AbstractString, Vararg{Int64}}
  3. julia> isa(("1",), mytupletype)
  4. true
  5. julia> isa(("1",1), mytupletype)
  6. true
  7. julia> isa(("1",1,2), mytupletype)
  8. true
  9. julia> isa(("1",1,2,3.0), mytupletype)
  10. false

source

Core.Nothing — Type

  1. Nothing

A type with no fields that is the type of nothing.

See also: isnothing, Some, Missing.

source

Base.isnothing — Function

  1. isnothing(x)

Return true if x === nothing, and return false if not.

Julia 1.1

This function requires at least Julia 1.1.

See also something, notnothing, ismissing.

source

Base.notnothing — Function

  1. notnothing(x)

Throw an error if x === nothing, and return x if not.

source

Base.Some — Type

  1. Some{T}

A wrapper type used in Union{Some{T}, Nothing} to distinguish between the absence of a value (nothing) and the presence of a nothing value (i.e. Some(nothing)).

Use something to access the value wrapped by a Some object.

source

Base.something — Function

  1. something(x...)

Return the first value in the arguments which is not equal to nothing, if any. Otherwise throw an error. Arguments of type Some are unwrapped.

See also coalesce, skipmissing, @something.

Examples

  1. julia> something(nothing, 1)
  2. 1
  3. julia> something(Some(1), nothing)
  4. 1
  5. julia> something(missing, nothing)
  6. missing
  7. julia> something(nothing, nothing)
  8. ERROR: ArgumentError: No value arguments present

source

Base.@something — Macro

  1. @something(x...)

Short-circuiting version of something.

Examples

  1. julia> f(x) = (println("f($x)"); nothing);
  2. julia> a = 1;
  3. julia> a = @something a f(2) f(3) error("Unable to find default for `a`")
  4. 1
  5. julia> b = nothing;
  6. julia> b = @something b f(2) f(3) error("Unable to find default for `b`")
  7. f(2)
  8. f(3)
  9. ERROR: Unable to find default for `b`
  10. [...]
  11. julia> b = @something b f(2) f(3) Some(nothing)
  12. f(2)
  13. f(3)
  14. julia> b === nothing
  15. true

Julia 1.7

This macro is available as of Julia 1.7.

source

Base.Enums.Enum — Type

  1. Enum{T<:Integer}

The abstract supertype of all enumerated types defined with @enum.

source

Base.Enums.@enum — Macro

  1. @enum EnumName[::BaseType] value1[=x] value2[=y]

Create an Enum{BaseType} subtype with name EnumName and enum member values of value1 and value2 with optional assigned values of x and y, respectively. EnumName can be used just like other types and enum member values as regular values, such as

Examples

  1. julia> @enum Fruit apple=1 orange=2 kiwi=3
  2. julia> f(x::Fruit) = "I'm a Fruit with value: $(Int(x))"
  3. f (generic function with 1 method)
  4. julia> f(apple)
  5. "I'm a Fruit with value: 1"
  6. julia> Fruit(1)
  7. apple::Fruit = 1

Values can also be specified inside a begin block, e.g.

  1. @enum EnumName begin
  2. value1
  3. value2
  4. end

BaseType, which defaults to Int32, must be a primitive subtype of Integer. Member values can be converted between the enum type and BaseType. read and write perform these conversions automatically. In case the enum is created with a non-default BaseType, Integer(value1) will return the integer value1 with the type BaseType.

To list all the instances of an enum use instances, e.g.

  1. julia> instances(Fruit)
  2. (apple, orange, kiwi)

source

Core.Expr — Type

  1. Expr(head::Symbol, args...)

A type representing compound expressions in parsed julia code (ASTs). Each expression consists of a head Symbol identifying which kind of expression it is (e.g. a call, for loop, conditional statement, etc.), and subexpressions (e.g. the arguments of a call). The subexpressions are stored in a Vector{Any} field called args.

See the manual chapter on Metaprogramming and the developer documentation Julia ASTs.

Examples

  1. julia> Expr(:call, :+, 1, 2)
  2. :(1 + 2)
  3. julia> dump(:(a ? b : c))
  4. Expr
  5. head: Symbol if
  6. args: Array{Any}((3,))
  7. 1: Symbol a
  8. 2: Symbol b
  9. 3: Symbol c

source

Core.Symbol — Type

  1. Symbol

The type of object used to represent identifiers in parsed julia code (ASTs). Also often used as a name or label to identify an entity (e.g. as a dictionary key). Symbols can be entered using the : quote operator:

  1. julia> :name
  2. :name
  3. julia> typeof(:name)
  4. Symbol
  5. julia> x = 42
  6. 42
  7. julia> eval(:x)
  8. 42

Symbols can also be constructed from strings or other values by calling the constructor Symbol(x...).

Symbols are immutable and should be compared using ===. The implementation re-uses the same object for all Symbols with the same name, so comparison tends to be efficient (it can just compare pointers).

Unlike strings, Symbols are “atomic” or “scalar” entities that do not support iteration over characters.

source

Core.Symbol — Method

  1. Symbol(x...) -> Symbol

Create a Symbol by concatenating the string representations of the arguments together.

Examples

  1. julia> Symbol("my", "name")
  2. :myname
  3. julia> Symbol("day", 4)
  4. :day4

source

Core.Module — Type

  1. Module

A Module is a separate global variable workspace. See module and the manual section about modules for details.

  1. Module(name::Symbol=:anonymous, std_imports=true, default_names=true)

Return a module with the specified name. A baremodule corresponds to Module(:ModuleName, false)

An empty module containing no names at all can be created with Module(:ModuleName, false, false). This module will not import Base or Core and does not contain a reference to itself.

source

Generic Functions

Core.Function — Type

  1. Function

Abstract type of all functions.

Examples

  1. julia> isa(+, Function)
  2. true
  3. julia> typeof(sin)
  4. typeof(sin) (singleton type of function sin, subtype of Function)
  5. julia> ans <: Function
  6. true

source

Base.hasmethod — Function

  1. hasmethod(f, t::Type{<:Tuple}[, kwnames]; world=get_world_counter()) -> Bool

Determine whether the given generic function has a method matching the given Tuple of argument types with the upper bound of world age given by world.

If a tuple of keyword argument names kwnames is provided, this also checks whether the method of f matching t has the given keyword argument names. If the matching method accepts a variable number of keyword arguments, e.g. with kwargs..., any names given in kwnames are considered valid. Otherwise the provided names must be a subset of the method’s keyword arguments.

See also applicable.

Julia 1.2

Providing keyword argument names requires Julia 1.2 or later.

Examples

  1. julia> hasmethod(length, Tuple{Array})
  2. true
  3. julia> f(; oranges=0) = oranges;
  4. julia> hasmethod(f, Tuple{}, (:oranges,))
  5. true
  6. julia> hasmethod(f, Tuple{}, (:apples, :bananas))
  7. false
  8. julia> g(; xs...) = 4;
  9. julia> hasmethod(g, Tuple{}, (:a, :b, :c, :d)) # g accepts arbitrary kwargs
  10. true

source

Core.applicable — Function

  1. applicable(f, args...) -> Bool

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

See also hasmethod.

Examples

  1. julia> function f(x, y)
  2. x + y
  3. end;
  4. julia> applicable(f, 1)
  5. false
  6. julia> applicable(f, 1, 2)
  7. true

source

Base.isambiguous — Function

  1. Base.isambiguous(m1, m2; ambiguous_bottom=false) -> Bool

Determine whether two methods m1 and m2 may be ambiguous for some call signature. This test is performed in the context of other methods of the same function; in isolation, m1 and m2 might be ambiguous, but if a third method resolving the ambiguity has been defined, this returns false. Alternatively, in isolation m1 and m2 might be ordered, but if a third method cannot be sorted with them, they may cause an ambiguity together.

For parametric types, the ambiguous_bottom keyword argument controls whether Union{} counts as an ambiguous intersection of type parameters – when true, it is considered ambiguous, when false it is not.

Examples

  1. julia> foo(x::Complex{<:Integer}) = 1
  2. foo (generic function with 1 method)
  3. julia> foo(x::Complex{<:Rational}) = 2
  4. foo (generic function with 2 methods)
  5. julia> m1, m2 = collect(methods(foo));
  6. julia> typeintersect(m1.sig, m2.sig)
  7. Tuple{typeof(foo), Complex{Union{}}}
  8. julia> Base.isambiguous(m1, m2, ambiguous_bottom=true)
  9. true
  10. julia> Base.isambiguous(m1, m2, ambiguous_bottom=false)
  11. false

source

Core.invoke — Function

  1. invoke(f, argtypes::Type, args...; kwargs...)

Invoke a method for the given generic function f matching the specified types argtypes on the specified arguments args and passing the keyword arguments kwargs. The arguments args must conform with the specified types in argtypes, i.e. conversion is not automatically performed. This method 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).

Be careful when using invoke for functions that you don’t write. What definition is used for given argtypes is an implementation detail unless the function is explicitly states that calling with certain argtypes is a part of public API. For example, the change between f1 and f2 in the example below is usually considered compatible because the change is invisible by the caller with a normal (non-invoke) call. However, the change is visible if you use invoke.

Examples

  1. julia> f(x::Real) = x^2;
  2. julia> f(x::Integer) = 1 + invoke(f, Tuple{Real}, x);
  3. julia> f(2)
  4. 5
  5. julia> f1(::Integer) = Integer
  6. f1(::Real) = Real;
  7. julia> f2(x::Real) = _f2(x)
  8. _f2(::Integer) = Integer
  9. _f2(_) = Real;
  10. julia> f1(1)
  11. Integer
  12. julia> f2(1)
  13. Integer
  14. julia> invoke(f1, Tuple{Real}, 1)
  15. Real
  16. julia> invoke(f2, Tuple{Real}, 1)
  17. Integer

source

Base.@invoke — Macro

  1. @invoke f(arg::T, ...; kwargs...)

Provides a convenient way to call invoke; @invoke f(arg1::T1, arg2::T2; kwargs...) will be expanded into invoke(f, Tuple{T1,T2}, arg1, arg2; kwargs...). When an argument’s type annotation is omitted, it’s specified as Any argument, e.g. @invoke f(arg1::T, arg2) will be expanded into invoke(f, Tuple{T,Any}, arg1, arg2).

Julia 1.7

This macro requires Julia 1.7 or later.

source

Base.invokelatest — Function

  1. invokelatest(f, args...; kwargs...)

Calls f(args...; kwargs...), but guarantees that the most recent method of f will be executed. This is useful in specialized circumstances, e.g. long-running event loops or callback functions that may call obsolete versions of a function f. (The drawback is that invokelatest is somewhat slower than calling f directly, and the type of the result cannot be inferred by the compiler.)

source

Base.@invokelatest — Macro

  1. @invokelatest f(args...; kwargs...)

Provides a convenient way to call Base.invokelatest. @invokelatest f(args...; kwargs...) will simply be expanded into Base.invokelatest(f, args...; kwargs...).

Julia 1.7

This macro requires Julia 1.7 or later.

source

new — Keyword

  1. new, or new{A,B,...}

Special function available to inner constructors which creates a new object of the type. The form new{A,B,…} explicitly specifies values of parameters for parametric types. See the manual section on Inner Constructor Methods for more information.

source

Base.:|> — Function

  1. |>(x, f)

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

Examples

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

source

Base.:∘ — Function

  1. f g

Compose functions: i.e. (f ∘ g)(args...; kwargs...) means f(g(args...; kwargs...)). The symbol can be entered in the Julia REPL (and most editors, appropriately configured) by typing \circ<tab>.

Function composition also works in prefix form: ∘(f, g) is the same as f ∘ g. The prefix form supports composition of multiple functions: ∘(f, g, h) = f ∘ g ∘ h and splatting ∘(fs...) for composing an iterable collection of functions.

Julia 1.4

Multiple function composition requires at least Julia 1.4.

Julia 1.5

Composition of one function ∘(f) requires at least Julia 1.5.

Julia 1.7

Using keyword arguments requires at least Julia 1.7.

Examples

  1. julia> map(uppercasefirst, ["apple", "banana", "carrot"])
  2. 3-element Vector{Char}:
  3. 'A': ASCII/Unicode U+0041 (category Lu: Letter, uppercase)
  4. 'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase)
  5. 'C': ASCII/Unicode U+0043 (category Lu: Letter, uppercase)
  6. julia> fs = [
  7. x -> 2x
  8. x -> x/2
  9. x -> x-1
  10. x -> x+1
  11. ];
  12. julia> ∘(fs...)(3)
  13. 3.0

See also ComposedFunction, !f::Function.

source

Base.ComposedFunction — Type

  1. ComposedFunction{Outer,Inner} <: Function

Represents the composition of two callable objects outer::Outer and inner::Inner. That is

  1. ComposedFunction(outer, inner)(args...; kw...) === outer(inner(args...; kw...))

The preferred way to construct instance of ComposedFunction is to use the composition operator :

  1. julia> sin cos === ComposedFunction(sin, cos)
  2. true
  3. julia> typeof(sincos)
  4. ComposedFunction{typeof(sin), typeof(cos)}

The composed pieces are stored in the fields of ComposedFunction and can be retrieved as follows:

  1. julia> composition = sin cos
  2. sin cos
  3. julia> composition.outer === sin
  4. true
  5. julia> composition.inner === cos
  6. true

Julia 1.6

ComposedFunction requires at least Julia 1.6. In earlier versions returns an anonymous function instead.

See also .

source

Base.splat — Function

  1. splat(f)

Defined as

  1. splat(f) = args->f(args...)

i.e. given a function returns a new function that takes one argument and splats its argument into the original function. This is useful as an adaptor to pass a multi-argument function in a context that expects a single argument, but passes a tuple as that single argument.

Example usage:

  1. julia> map(Base.splat(+), zip(1:3,4:6))
  2. 3-element Vector{Int64}:
  3. 5
  4. 7
  5. 9

source

Base.Fix1 — Type

  1. Fix1(f, x)

A type representing a partially-applied version of the two-argument function f, with the first argument fixed to the value “x”. In other words, Fix1(f, x) behaves similarly to y->f(x, y).

See also Fix2.

source

Base.Fix2 — Type

  1. Fix2(f, x)

A type representing a partially-applied version of the two-argument function f, with the second argument fixed to the value “x”. In other words, Fix2(f, x) behaves similarly to y->f(y, x).

source

Syntax

Core.eval — Function

  1. Core.eval(m::Module, expr)

Evaluate an expression in the given module and return the result.

source

Base.MainInclude.eval — Function

  1. eval(expr)

Evaluate an expression in the global scope of the containing module. Every Module (except those defined with baremodule) has its own 1-argument definition of eval, which evaluates expressions in that module.

source

Base.@eval — Macro

  1. @eval [mod,] ex

Evaluate an expression with values interpolated into it using eval. If two arguments are provided, the first is the module to evaluate in.

source

Base.evalfile — Function

  1. evalfile(path::AbstractString, args::Vector{String}=String[])

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

source

Base.esc — Function

  1. esc(e)

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 Macros section of the Metaprogramming chapter of the manual for more details and examples.

source

Base.@inbounds — Macro

  1. @inbounds(blk)

Eliminates array bounds checking within expressions.

In the example below the in-range check for referencing element i of array A is skipped to improve performance.

  1. function sum(A::AbstractArray)
  2. r = zero(eltype(A))
  3. for i in eachindex(A)
  4. @inbounds r += A[i]
  5. end
  6. return r
  7. end

Warning

Using @inbounds may return incorrect results/crashes/corruption for out-of-bounds indices. The user is responsible for checking it manually. Only use @inbounds when it is certain from the information locally available that all accesses are in bounds.

source

Base.@boundscheck — Macro

  1. @boundscheck(blk)

Annotates the expression blk as a bounds checking block, allowing it to be elided by @inbounds.

Note

The function in which @boundscheck is written must be inlined into its caller in order for @inbounds to have effect.

Examples

  1. julia> @inline function g(A, i)
  2. @boundscheck checkbounds(A, i)
  3. return "accessing ($A)[$i]"
  4. end;
  5. julia> f1() = return g(1:2, -1);
  6. julia> f2() = @inbounds return g(1:2, -1);
  7. julia> f1()
  8. ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]
  9. Stacktrace:
  10. [1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455
  11. [2] checkbounds at ./abstractarray.jl:420 [inlined]
  12. [3] g at ./none:2 [inlined]
  13. [4] f1() at ./none:1
  14. [5] top-level scope
  15. julia> f2()
  16. "accessing (1:2)[-1]"

Warning

The @boundscheck annotation allows you, as a library writer, to opt-in to allowing other code to remove your bounds checks with @inbounds. As noted there, the caller must verify—using information they can access—that their accesses are valid before using @inbounds. For indexing into your AbstractArray subclasses, for example, this involves checking the indices against its axes. Therefore, @boundscheck annotations should only be added to a getindex or setindex! implementation after you are certain its behavior is correct.

source

Base.@propagate_inbounds — Macro

  1. @propagate_inbounds

Tells the compiler to inline a function while retaining the caller’s inbounds context.

source

Base.@inline — Macro

  1. @inline

Give a hint to the compiler that this function is worth inlining.

Small functions typically do not need the @inline annotation, as the compiler does it automatically. By using @inline on bigger functions, an extra nudge can be given to the compiler to inline it.

@inline can be applied immediately before the definition or in its function body.

  1. # annotate long-form definition
  2. @inline function longdef(x)
  3. ...
  4. end
  5. # annotate short-form definition
  6. @inline shortdef(x) = ...
  7. # annotate anonymous function that a `do` block creates
  8. f() do
  9. @inline
  10. ...
  11. end

Julia 1.8

The usage within a function body requires at least Julia 1.8.


  1. @inline block

Give a hint to the compiler that calls within block are worth inlining.

  1. # The compiler will try to inline `f`
  2. @inline f(...)
  3. # The compiler will try to inline `f`, `g` and `+`
  4. @inline f(...) + g(...)

Note

A callsite annotation always has the precedence over the annotation applied to the definition of the called function:

  1. @noinline function explicit_noinline(args...)
  2. # body
  3. end
  4. let
  5. @inline explicit_noinline(args...) # will be inlined
  6. end

Note

When there are nested callsite annotations, the innermost annotation has the precedence:

  1. @noinline let a0, b0 = ...
  2. a = @inline f(a0) # the compiler will try to inline this call
  3. b = f(b0) # the compiler will NOT try to inline this call
  4. return a, b
  5. end

Warning

Although a callsite annotation will try to force inlining in regardless of the cost model, there are still chances it can’t succeed in it. Especially, recursive calls can not be inlined even if they are annotated as @inlined.

Julia 1.8

The callsite annotation requires at least Julia 1.8.

source

Base.@noinline — Macro

  1. @noinline

Give a hint to the compiler that it should not inline a function.

Small functions are typically inlined automatically. By using @noinline on small functions, auto-inlining can be prevented.

@noinline can be applied immediately before the definition or in its function body.

  1. # annotate long-form definition
  2. @noinline function longdef(x)
  3. ...
  4. end
  5. # annotate short-form definition
  6. @noinline shortdef(x) = ...
  7. # annotate anonymous function that a `do` block creates
  8. f() do
  9. @noinline
  10. ...
  11. end

Julia 1.8

The usage within a function body requires at least Julia 1.8.


  1. @noinline block

Give a hint to the compiler that it should not inline the calls within block.

  1. # The compiler will try to not inline `f`
  2. @noinline f(...)
  3. # The compiler will try to not inline `f`, `g` and `+`
  4. @noinline f(...) + g(...)

Note

A callsite annotation always has the precedence over the annotation applied to the definition of the called function:

  1. @inline function explicit_inline(args...)
  2. # body
  3. end
  4. let
  5. @noinline explicit_inline(args...) # will not be inlined
  6. end

Note

When there are nested callsite annotations, the innermost annotation has the precedence:

  1. @inline let a0, b0 = ...
  2. a = @noinline f(a0) # the compiler will NOT try to inline this call
  3. b = f(b0) # the compiler will try to inline this call
  4. return a, b
  5. end

Julia 1.8

The callsite annotation requires at least Julia 1.8.


Note

If the function is trivial (for example returning a constant) it might get inlined anyway.

source

Base.@nospecialize — Macro

  1. @nospecialize

Applied to a function argument name, hints to the compiler that the method should not be specialized for different types of that argument, but instead to use precisely the declared type for each argument. This is only a hint for avoiding excess code generation. Can be applied to an argument within a formal argument list, or in the function body. When applied to an argument, the macro must wrap the entire argument expression. When used in a function body, the macro must occur in statement position and before any code.

When used without arguments, it applies to all arguments of the parent scope. In local scope, this means all arguments of the containing function. In global (top-level) scope, this means all methods subsequently defined in the current module.

Specialization can reset back to the default by using @specialize.

  1. function example_function(@nospecialize x)
  2. ...
  3. end
  4. function example_function(x, @nospecialize(y = 1))
  5. ...
  6. end
  7. function example_function(x, y, z)
  8. @nospecialize x y
  9. ...
  10. end
  11. @nospecialize
  12. f(y) = [x for x in y]
  13. @specialize

source

Base.@specialize — Macro

  1. @specialize

Reset the specialization hint for an argument back to the default. For details, see @nospecialize.

source

Base.gensym — Function

  1. gensym([tag])

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

source

Base.@gensym — Macro

  1. @gensym

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

source

var”name” — Keyword

  1. var

The syntax var"#example#" refers to a variable named Symbol("#example#"), even though #example# is not a valid Julia identifier name.

This can be useful for interoperability with programming languages which have different rules for the construction of valid identifiers. For example, to refer to the R variable draw.segments, you can use var"draw.segments" in your Julia code.

It is also used to show julia source code which has gone through macro hygiene or otherwise contains variable names which can’t be parsed normally.

Note that this syntax requires parser support so it is expanded directly by the parser rather than being implemented as a normal string macro @var_str.

Julia 1.3

This syntax requires at least Julia 1.3.

source

Base.@goto — Macro

  1. @goto name

@goto name unconditionally jumps to the statement at the location @label name.

@label and @goto cannot create jumps to different top-level statements. Attempts cause an error. To still use @goto, enclose the @label and @goto in a block.

source

Base.@label — Macro

  1. @label name

Labels a statement with the symbolic label name. The label marks the end-point of an unconditional jump with @goto name.

source

Base.SimdLoop.@simd — Macro

  1. @simd

Annotate a for loop to allow the compiler to take extra liberties to allow loop re-ordering

Warning

This feature is experimental and could change or disappear in future versions of Julia. Incorrect use of the @simd macro may cause unexpected results.

The object iterated over in a @simd for loop should be a one-dimensional range. By using @simd, you are asserting several properties of the loop:

  • It is safe to execute iterations in arbitrary or overlapping order, with special consideration for reduction variables.
  • Floating-point operations on reduction variables can be reordered, possibly causing different results than without @simd.

In many cases, Julia is able to automatically vectorize inner for loops without the use of @simd. Using @simd gives the compiler a little extra leeway to make it possible in more situations. In either case, your inner loop should have the following properties to allow vectorization:

  • The loop must be an innermost loop
  • The loop body must be straight-line code. Therefore, @inbounds is currently needed for all array accesses. The compiler can sometimes turn short &&, ||, and ?: expressions into straight-line code if it is safe to evaluate all operands unconditionally. Consider using the ifelse function instead of ?: in the loop if it is safe to do so.
  • Accesses must have a stride pattern and cannot be “gathers” (random-index reads) or “scatters” (random-index writes).
  • The stride should be unit stride.

Note

The @simd does not assert by default that the loop is completely free of loop-carried memory dependencies, which is an assumption that can easily be violated in generic code. If you are writing non-generic code, you can use @simd ivdep for ... end to also assert that:

  • There exists no loop-carried memory dependencies
  • No iteration ever waits on a previous iteration to make forward progress.

source

Base.@polly — Macro

  1. @polly

Tells the compiler to apply the polyhedral optimizer Polly to a function.

source

Base.@generated — Macro

  1. @generated f

@generated is used to annotate a function which will be generated. In the body of the generated function, only types of arguments can be read (not the values). The function returns a quoted expression evaluated when the function is called. The @generated macro should not be used on functions mutating the global scope or depending on mutable elements.

See Metaprogramming for further details.

Example:

  1. julia> @generated function bar(x)
  2. if x <: Integer
  3. return :(x ^ 2)
  4. else
  5. return :(x)
  6. end
  7. end
  8. bar (generic function with 1 method)
  9. julia> bar(4)
  10. 16
  11. julia> bar("baz")
  12. "baz"

source

Base.@pure — Macro

  1. @pure ex

@pure gives the compiler a hint for the definition of a pure function, helping for type inference.

Warning

This macro is intended for internal compiler use and may be subject to changes.

Warning

In Julia 1.8 and higher, it is favorable to use @assume_effects instead of @pure. This is because @assume_effects allows a finer grained control over Julia’s purity modeling and the effect system enables a wider range of optimizations.

source

Base.@assume_effects — Macro

  1. @assume_effects setting... ex

@assume_effects overrides the compiler’s effect modeling for the given method. ex must be a method definition or @ccall expression.

Julia 1.8

Using Base.@assume_effects requires Julia version 1.8.

  1. julia> Base.@assume_effects :terminates_locally function pow(x)
  2. # this :terminates_locally allows `pow` to be constant-folded
  3. res = 1
  4. 1 < x < 20 || error("bad pow")
  5. while x > 1
  6. res *= x
  7. x -= 1
  8. end
  9. return res
  10. end
  11. pow (generic function with 1 method)
  12. julia> code_typed() do
  13. pow(12)
  14. end
  15. 1-element Vector{Any}:
  16. CodeInfo(
  17. 1 return 479001600
  18. ) => Int64
  19. julia> Base.@assume_effects :total !:nothrow @ccall jl_type_intersection(Vector{Int}::Any, Vector{<:Integer}::Any)::Any
  20. Vector{Int64} (alias for Array{Int64, 1})

Warning

Improper use of this macro causes undefined behavior (including crashes, incorrect answers, or other hard to track bugs). Use with care and only if absolutely required.

In general, each setting value makes an assertion about the behavior of the function, without requiring the compiler to prove that this behavior is indeed true. These assertions are made for all world ages. It is thus advisable to limit the use of generic functions that may later be extended to invalidate the assumption (which would cause undefined behavior).

The following settings are supported.

  • :consistent
  • :effect_free
  • :nothrow
  • :terminates_globally
  • :terminates_locally
  • :foldable
  • :total

Extended help


:consistent

The :consistent setting asserts that for egal (===) inputs:

  • The manner of termination (return value, exception, non-termination) will always be the same.
  • If the method returns, the results will always be egal.

Note

This in particular implies that the return value of the method must be immutable. Multiple allocations of mutable objects (even with identical contents) are not egal.

Note

The :consistent-cy assertion is made world-age wise. More formally, write $fᵢ$ for the evaluation of $f$ in world-age $i$, then we require:

\[∀ i, x, y: x ≡ y → fᵢ(x) ≡ fᵢ(y)\]

However, for two world ages $i$, $j$ s.t. $i ≠ j$, we may have $fᵢ(x) ≢ fⱼ(y)$.

A further implication is that :consistent functions may not make their return value dependent on the state of the heap or any other global state that is not constant for a given world age.

Note

The :consistent-cy includes all legal rewrites performed by the optimizer. For example, floating-point fastmath operations are not considered :consistent, because the optimizer may rewrite them causing the output to not be :consistent, even for the same world age (e.g. because one ran in the interpreter, while the other was optimized).

Note

If :consistent functions terminate by throwing an exception, that exception itself is not required to meet the egality requirement specified above.


:effect_free

The :effect_free setting asserts that the method is free of externally semantically visible side effects. The following is an incomplete list of externally semantically visible side effects:

  • Changing the value of a global variable.
  • Mutating the heap (e.g. an array or mutable value), except as noted below
  • Changing the method table (e.g. through calls to eval)
  • File/Network/etc. I/O
  • Task switching

However, the following are explicitly not semantically visible, even if they may be observable:

  • Memory allocations (both mutable and immutable)
  • Elapsed time
  • Garbage collection
  • Heap mutations of objects whose lifetime does not exceed the method (i.e. were allocated in the method and do not escape).
  • The returned value (which is externally visible, but not a side effect)

The rule of thumb here is that an externally visible side effect is anything that would affect the execution of the remainder of the program if the function were not executed.

Note

The :effect_free assertion is made both for the method itself and any code that is executed by the method. Keep in mind that the assertion must be valid for all world ages and limit use of this assertion accordingly.


:nothrow

The :nothrow settings asserts that this method does not terminate abnormally (i.e. will either always return a value or never return).

Note

It is permissible for :nothrow annotated methods to make use of exception handling internally as long as the exception is not rethrown out of the method itself.

Note

MethodErrors and similar exceptions count as abnormal termination.


:terminates_globally

The :terminates_globally settings asserts that this method will eventually terminate (either normally or abnormally), i.e. does not loop indefinitely.

Note

This :terminates_globally assertion covers any other methods called by the annotated method.

Note

The compiler will consider this a strong indication that the method will terminate relatively quickly and may (if otherwise legal), call this method at compile time. I.e. it is a bad idea to annotate this setting on a method that technically, but not practically, terminates.


:terminates_locally

The :terminates_locally setting is like :terminates_globally, except that it only applies to syntactic control flow within the annotated method. It is thus a much weaker (and thus safer) assertion that allows for the possibility of non-termination if the method calls some other method that does not terminate.

Note

:terminates_globally implies :terminates_locally.


:foldable

This setting is a convenient shortcut for the set of effects that the compiler requires to be guaranteed to constant fold a call at compile time. It is currently equivalent to the following settings:

  • :consistent
  • :effect_free
  • :terminates_globally

Note

This list in particular does not include :nothrow. The compiler will still attempt constant propagation and note any thrown error at compile time. Note however, that by the :consistent-cy requirements, any such annotated call must consistently throw given the same argument values.


:total

This setting is the maximum possible set of effects. It currently implies the following other settings:

  • :consistent
  • :effect_free
  • :nothrow
  • :terminates_globally

Warning

:total is a very strong assertion and will likely gain additional semantics in future versions of Julia (e.g. if additional effects are added and included in the definition of :total). As a result, it should be used with care. Whenever possible, prefer to use the minimum possible set of specific effect assertions required for a particular application. In cases where a large number of effect overrides apply to a set of functions, a custom macro is recommended over the use of :total.


Negated effects

Effect names may be prefixed by ! to indicate that the effect should be removed from an earlier meta effect. For example, :total !:nothrow indicates that while the call is generally total, it may however throw.


Comparison to @pure

@assume_effects :foldable is similar to @pure with the primary distinction that the :consistent-cy requirement applies world-age wise rather than globally as described above. However, in particular, a method annotated @pure should always be at least :foldable. Another advantage is that effects introduced by @assume_effects are propagated to callers interprocedurally while a purity defined by @pure is not.

source

Base.@deprecate — Macro

  1. @deprecate old new [export_old=true]

Deprecate method old and specify the replacement call new. Prevent @deprecate from exporting old by setting export_old to false. @deprecate defines a new method with the same signature as old.

Julia 1.5

As of Julia 1.5, functions defined by @deprecate do not print warning when julia is run without the --depwarn=yes flag set, as the default value of --depwarn option is no. The warnings are printed from tests run by Pkg.test().

Examples

  1. julia> @deprecate old(x) new(x)
  2. old (generic function with 1 method)
  3. julia> @deprecate old(x) new(x) false
  4. old (generic function with 1 method)

source

Missing Values

Base.Missing — Type

  1. Missing

A type with no fields whose singleton instance missing is used to represent missing values.

See also: skipmissing, nonmissingtype, Nothing.

source

Base.missing — Constant

  1. missing

The singleton instance of type Missing representing a missing value.

See also: NaN, skipmissing, nonmissingtype.

source

Base.coalesce — Function

  1. coalesce(x...)

Return the first value in the arguments which is not equal to missing, if any. Otherwise return missing.

See also skipmissing, something, @coalesce.

Examples

  1. julia> coalesce(missing, 1)
  2. 1
  3. julia> coalesce(1, missing)
  4. 1
  5. julia> coalesce(nothing, 1) # returns `nothing`
  6. julia> coalesce(missing, missing)
  7. missing

source

Base.@coalesce — Macro

  1. @coalesce(x...)

Short-circuiting version of coalesce.

Examples

  1. julia> f(x) = (println("f($x)"); missing);
  2. julia> a = 1;
  3. julia> a = @coalesce a f(2) f(3) error("`a` is still missing")
  4. 1
  5. julia> b = missing;
  6. julia> b = @coalesce b f(2) f(3) error("`b` is still missing")
  7. f(2)
  8. f(3)
  9. ERROR: `b` is still missing
  10. [...]

Julia 1.7

This macro is available as of Julia 1.7.

source

Base.ismissing — Function

  1. ismissing(x)

Indicate whether x is missing.

See also: skipmissing, isnothing, isnan.

source

Base.skipmissing — Function

  1. skipmissing(itr)

Return an iterator over the elements in itr skipping missing values. The returned object can be indexed using indices of itr if the latter is indexable. Indices corresponding to missing values are not valid: they are skipped by keys and eachindex, and a MissingException is thrown when trying to use them.

Use collect to obtain an Array containing the non-missing values in itr. Note that even if itr is a multidimensional array, the result will always be a Vector since it is not possible to remove missings while preserving dimensions of the input.

See also coalesce, ismissing, something.

Examples

  1. julia> x = skipmissing([1, missing, 2])
  2. skipmissing(Union{Missing, Int64}[1, missing, 2])
  3. julia> sum(x)
  4. 3
  5. julia> x[1]
  6. 1
  7. julia> x[2]
  8. ERROR: MissingException: the value at index (2,) is missing
  9. [...]
  10. julia> argmax(x)
  11. 3
  12. julia> collect(keys(x))
  13. 2-element Vector{Int64}:
  14. 1
  15. 3
  16. julia> collect(skipmissing([1, missing, 2]))
  17. 2-element Vector{Int64}:
  18. 1
  19. 2
  20. julia> collect(skipmissing([1 missing; 2 missing]))
  21. 2-element Vector{Int64}:
  22. 1
  23. 2

source

Base.nonmissingtype — Function

  1. nonmissingtype(T::Type)

If T is a union of types containing Missing, return a new type with Missing removed.

Examples

  1. julia> nonmissingtype(Union{Int64,Missing})
  2. Int64
  3. julia> nonmissingtype(Any)
  4. Any

Julia 1.3

This function is exported as of Julia 1.3.

source

System

Base.run — Function

  1. run(command, args...; wait::Bool = true)

Run a command object, constructed with backticks (see the Running External Programs section in the manual). Throws an error if anything goes wrong, including the process exiting with a non-zero status (when wait is true).

The args... allow you to pass through file descriptors to the command, and are ordered like regular unix file descriptors (eg stdin, stdout, stderr, FD(3), FD(4)...).

If wait is false, the process runs asynchronously. You can later wait for it and check its exit status by calling success on the returned process object.

When wait is false, the process’ I/O streams are directed to devnull. When wait is true, I/O streams are shared with the parent process. Use pipeline to control I/O redirection.

source

Base.devnull — Constant

  1. 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:

  1. run(pipeline(`cat test.txt`, devnull))

source

Base.success — Function

  1. success(command)

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

source

Base.process_running — Function

  1. process_running(p::Process)

Determine whether a process is currently running.

source

Base.process_exited — Function

  1. process_exited(p::Process)

Determine whether a process has exited.

source

Base.kill — Method

  1. kill(p::Process, signum=Base.SIGTERM)

Send a signal to a process. The default is to terminate the process. Returns successfully if the process has already exited, but throws an error if killing the process failed for other reasons (e.g. insufficient permissions).

source

Base.Sys.set_process_title — Function

  1. Sys.set_process_title(title::AbstractString)

Set the process title. No-op on some operating systems.

source

Base.Sys.get_process_title — Function

  1. Sys.get_process_title()

Get the process title. On some systems, will always return an empty string.

source

Base.ignorestatus — Function

  1. ignorestatus(command)

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

source

Base.detach — Function

  1. 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.

source

Base.Cmd — Type

  1. Cmd(cmd::Cmd; ignorestatus, detach, windows_verbatim, windows_hide, env, dir)

Construct a new Cmd object, representing an external program and arguments, from cmd, while changing the settings of the optional keyword arguments:

  • ignorestatus::Bool: If true (defaults to false), then the Cmd will not throw an error if the return code is nonzero.
  • detach::Bool: If true (defaults to false), then the Cmd will be run in a new process group, allowing it to outlive the julia process and not have Ctrl-C passed to it.
  • windows_verbatim::Bool: If true (defaults to false), then on Windows the Cmd will send a command-line string to the process with no quoting or escaping of arguments, even arguments containing spaces. (On Windows, arguments are sent to a program as a single “command-line” string, and programs are responsible for parsing it into arguments. By default, empty arguments and arguments with spaces or tabs are quoted with double quotes " in the command line, and \ or " are preceded by backslashes. windows_verbatim=true is useful for launching programs that parse their command line in nonstandard ways.) Has no effect on non-Windows systems.
  • windows_hide::Bool: If true (defaults to false), then on Windows no new console window is displayed when the Cmd is executed. This has no effect if a console is already open or on non-Windows systems.
  • env: Set environment variables to use when running the Cmd. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", an array or tuple of "var"=>val pairs. In order to modify (rather than replace) the existing environment, initialize env with copy(ENV) and then set env["var"]=val as desired. To add to an environment block within a Cmd object without replacing all elements, use addenv() which will return a Cmd object with the updated environment.
  • dir::AbstractString: Specify a working directory for the command (instead of the current directory).

For any keywords that are not specified, the current settings from cmd are used. Normally, to create a Cmd object in the first place, one uses backticks, e.g.

  1. Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)

source

Base.setenv — Function

  1. setenv(command::Cmd, env; dir)

Set environment variables to use when running the given command. env is either a dictionary mapping strings to strings, an array of strings of the form "var=val", or zero or more "var"=>val pair arguments. In order to modify (rather than replace) the existing environment, create env through copy(ENV) and then setting env["var"]=val as desired, or use addenv.

The dir keyword argument can be used to specify a working directory for the command. dir defaults to the currently set dir for command (which is the current working directory if not specified already).

See also Cmd, addenv, ENV, pwd.

source

Base.addenv — Function

  1. addenv(command::Cmd, env...; inherit::Bool = true)

Merge new environment mappings into the given Cmd object, returning a new Cmd object. Duplicate keys are replaced. If command does not contain any environment values set already, it inherits the current environment at time of addenv() call if inherit is true. Keys with value nothing are deleted from the env.

See also Cmd, setenv, ENV.

Julia 1.6

This function requires Julia 1.6 or later.

source

Base.withenv — Function

  1. withenv(f, kv::Pair...)

Execute f in an environment that is temporarily modified (not replaced as in setenv) by zero or more "var"=>val arguments kv. withenv is generally used via the withenv(kv...) do ... end syntax. A value of nothing can be used to temporarily unset an environment variable (if it is set). When withenv returns, the original environment has been restored.

source

Base.setcpuaffinity — Function

  1. setcpuaffinity(original_command::Cmd, cpus) -> command::Cmd

Set the CPU affinity of the command by a list of CPU IDs (1-based) cpus. Passing cpus = nothing means to unset the CPU affinity if the original_command has any.

This function is supported only in Linux and Windows. It is not supported in macOS because libuv does not support affinity setting.

Julia 1.8

This function requires at least Julia 1.8.

Examples

In Linux, the taskset command line program can be used to see how setcpuaffinity works.

  1. julia> run(setcpuaffinity(`sh -c 'taskset -p $$'`, [1, 2, 5]));
  2. pid 2273's current affinity mask: 13

Note that the mask value 13 reflects that the first, second, and the fifth bits (counting from the least significant position) are turned on:

  1. julia> 0b010011
  2. 0x13

source

Base.pipeline — Method

  1. pipeline(from, to, ...)

Create a pipeline from a data source to a destination. The source and destination can be commands, I/O streams, strings, or results of other pipeline calls. At least one argument must be a command. Strings refer to filenames. When called with more than two arguments, they are chained together from left to right. For example, pipeline(a,b,c) is equivalent to pipeline(pipeline(a,b),c). This provides a more concise way to specify multi-stage pipelines.

Examples:

  1. run(pipeline(`ls`, `grep xyz`))
  2. run(pipeline(`ls`, "out.txt"))
  3. run(pipeline("out.txt", `grep xyz`))

source

Base.pipeline — Method

  1. pipeline(command; stdin, stdout, stderr, append=false)

Redirect I/O to or from the given command. Keyword arguments specify which of the command’s streams should be redirected. append controls whether file output appends to the file. This is a more general version of the 2-argument pipeline function. pipeline(from, to) is equivalent to pipeline(from, stdout=to) when from is a command, and to pipeline(to, stdin=from) when from is another kind of data source.

Examples:

  1. run(pipeline(`dothings`, stdout="out.txt", stderr="errs.txt"))
  2. run(pipeline(`update`, stdout="log.txt", append=true))

source

Base.Libc.gethostname — Function

  1. gethostname() -> AbstractString

Get the local machine’s host name.

source

Base.Libc.getpid — Function

  1. getpid() -> Int32

Get Julia’s process ID.

source

  1. getpid(process) -> Int32

Get the child process ID, if it still exists.

Julia 1.1

This function requires at least Julia 1.1.

source

Base.Libc.time — Method

  1. time()

Get the system time in seconds since the epoch, with fairly high (typically, microsecond) resolution.

source

Base.time_ns — Function

  1. time_ns()

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

source

Base.@time — Macro

  1. @time expr
  2. @time "description" expr

A macro to execute an expression, printing the time it took to execute, the number of allocations, and the total number of bytes its execution caused to be allocated, before returning the value of the expression. Any time spent garbage collecting (gc), compiling new code, or recompiling invalidated code is shown as a percentage.

Optionally provide a description string to print before the time report.

In some cases the system will look inside the @time expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run @time @eval ....

See also @showtime, @timev, @timed, @elapsed, and @allocated.

Note

For more serious benchmarking, consider the @btime macro from the BenchmarkTools.jl package which among other things evaluates the function multiple times in order to reduce noise.

Julia 1.8

The option to add a description was introduced in Julia 1.8.

Recompilation time being shown separately from compilation time was introduced in Julia 1.8

  1. julia> x = rand(10,10);
  2. julia> @time x * x;
  3. 0.606588 seconds (2.19 M allocations: 116.555 MiB, 3.75% gc time, 99.94% compilation time)
  4. julia> @time x * x;
  5. 0.000009 seconds (1 allocation: 896 bytes)
  6. julia> @time begin
  7. sleep(0.3)
  8. 1+1
  9. end
  10. 0.301395 seconds (8 allocations: 336 bytes)
  11. 2
  12. julia> @time "A one second sleep" sleep(1)
  13. A one second sleep: 1.005750 seconds (5 allocations: 144 bytes)
  14. julia> for loop in 1:3
  15. @time loop sleep(1)
  16. end
  17. 1: 1.006760 seconds (5 allocations: 144 bytes)
  18. 2: 1.001263 seconds (5 allocations: 144 bytes)
  19. 3: 1.003676 seconds (5 allocations: 144 bytes)

source

Base.@showtime — Macro

  1. @showtime expr

Like @time but also prints the expression being evaluated for reference.

Julia 1.8

This macro was added in Julia 1.8.

See also @time.

  1. julia> @showtime sleep(1)
  2. sleep(1): 1.002164 seconds (4 allocations: 128 bytes)

source

Base.@timev — Macro

  1. @timev expr
  2. @timev "description" expr

This is a verbose version of the @time macro. It first prints the same information as @time, then any non-zero memory allocation counters, and then returns the value of the expression.

Optionally provide a description string to print before the time report.

Julia 1.8

The option to add a description was introduced in Julia 1.8.

See also @time, @timed, @elapsed, and @allocated.

  1. julia> x = rand(10,10);
  2. julia> @timev x * x;
  3. 0.546770 seconds (2.20 M allocations: 116.632 MiB, 4.23% gc time, 99.94% compilation time)
  4. elapsed time (ns): 546769547
  5. gc time (ns): 23115606
  6. bytes allocated: 122297811
  7. pool allocs: 2197930
  8. non-pool GC allocs:1327
  9. malloc() calls: 36
  10. realloc() calls: 5
  11. GC pauses: 3
  12. julia> @timev x * x;
  13. 0.000010 seconds (1 allocation: 896 bytes)
  14. elapsed time (ns): 9848
  15. bytes allocated: 896
  16. pool allocs: 1

source

Base.@timed — Macro

  1. @timed

A macro to execute an expression, and return the value of the expression, elapsed time, total bytes allocated, garbage collection time, and an object with various memory allocation counters.

In some cases the system will look inside the @timed expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run @timed @eval ....

See also @time, @timev, @elapsed, and @allocated.

  1. julia> stats = @timed rand(10^6);
  2. julia> stats.time
  3. 0.006634834
  4. julia> stats.bytes
  5. 8000256
  6. julia> stats.gctime
  7. 0.0055765
  8. julia> propertynames(stats.gcstats)
  9. (:allocd, :malloc, :realloc, :poolalloc, :bigalloc, :freecall, :total_time, :pause, :full_sweep)
  10. julia> stats.gcstats.total_time
  11. 5576500

Julia 1.5

The return type of this macro was changed from Tuple to NamedTuple in Julia 1.5.

source

Base.@elapsed — Macro

  1. @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.

In some cases the system will look inside the @elapsed expression and compile some of the called code before execution of the top-level expression begins. When that happens, some compilation time will not be counted. To include this time you can run @elapsed @eval ....

See also @time, @timev, @timed, and @allocated.

  1. julia> @elapsed sleep(0.3)
  2. 0.301391426

source

Base.@allocated — Macro

  1. @allocated

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

See also @time, @timev, @timed, and @elapsed.

  1. julia> @allocated rand(10^6)
  2. 8000080

source

Base.EnvDict — Type

  1. EnvDict() -> EnvDict

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

source

Base.ENV — Constant

  1. ENV

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

(On Windows, system environment variables are case-insensitive, and ENV correspondingly converts all keys to uppercase for display, iteration, and copying. Portable code should not rely on the ability to distinguish variables by case, and should beware that setting an ostensibly lowercase variable may result in an uppercase ENV key.)

source

Base.Sys.isunix — Function

  1. Sys.isunix([os])

Predicate for testing if the OS provides a Unix-like interface. See documentation in Handling Operating System Variation.

source

Base.Sys.isapple — Function

  1. Sys.isapple([os])

Predicate for testing if the OS is a derivative of Apple Macintosh OS X or Darwin. See documentation in Handling Operating System Variation.

source

Base.Sys.islinux — Function

  1. Sys.islinux([os])

Predicate for testing if the OS is a derivative of Linux. See documentation in Handling Operating System Variation.

source

Base.Sys.isbsd — Function

  1. Sys.isbsd([os])

Predicate for testing if the OS is a derivative of BSD. See documentation in Handling Operating System Variation.

Note

The Darwin kernel descends from BSD, which means that Sys.isbsd() is true on macOS systems. To exclude macOS from a predicate, use Sys.isbsd() && !Sys.isapple().

source

Base.Sys.isfreebsd — Function

  1. Sys.isfreebsd([os])

Predicate for testing if the OS is a derivative of FreeBSD. See documentation in Handling Operating System Variation.

Note

Not to be confused with Sys.isbsd(), which is true on FreeBSD but also on other BSD-based systems. Sys.isfreebsd() refers only to FreeBSD.

Julia 1.1

This function requires at least Julia 1.1.

source

Base.Sys.isopenbsd — Function

  1. Sys.isopenbsd([os])

Predicate for testing if the OS is a derivative of OpenBSD. See documentation in Handling Operating System Variation.

Note

Not to be confused with Sys.isbsd(), which is true on OpenBSD but also on other BSD-based systems. Sys.isopenbsd() refers only to OpenBSD.

Julia 1.1

This function requires at least Julia 1.1.

source

Base.Sys.isnetbsd — Function

  1. Sys.isnetbsd([os])

Predicate for testing if the OS is a derivative of NetBSD. See documentation in Handling Operating System Variation.

Note

Not to be confused with Sys.isbsd(), which is true on NetBSD but also on other BSD-based systems. Sys.isnetbsd() refers only to NetBSD.

Julia 1.1

This function requires at least Julia 1.1.

source

Base.Sys.isdragonfly — Function

  1. Sys.isdragonfly([os])

Predicate for testing if the OS is a derivative of DragonFly BSD. See documentation in Handling Operating System Variation.

Note

Not to be confused with Sys.isbsd(), which is true on DragonFly but also on other BSD-based systems. Sys.isdragonfly() refers only to DragonFly.

Julia 1.1

This function requires at least Julia 1.1.

source

Base.Sys.iswindows — Function

  1. Sys.iswindows([os])

Predicate for testing if the OS is a derivative of Microsoft Windows NT. See documentation in Handling Operating System Variation.

source

Base.Sys.windows_version — Function

  1. Sys.windows_version()

Return the version number for the Windows NT Kernel as a VersionNumber, i.e. v"major.minor.build", or v"0.0.0" if this is not running on Windows.

source

Base.Sys.free_memory — Function

  1. Sys.free_memory()

Get the total free memory in RAM in bytes.

source

Base.Sys.total_memory — Function

  1. Sys.total_memory()

Get the total memory in RAM (including that which is currently used) in bytes. This amount may be constrained, e.g., by Linux control groups. For the unconstrained amount, see Sys.physical_memory().

source

Base.Sys.free_physical_memory — Function

  1. Sys.free_physical_memory()

Get the free memory of the system in bytes. The entire amount may not be available to the current process; use Sys.free_memory() for the actually available amount.

source

Base.Sys.total_physical_memory — Function

  1. Sys.total_physical_memory()

Get the total memory in RAM (including that which is currently used) in bytes. The entire amount may not be available to the current process; see Sys.total_memory().

source

Base.@static — Macro

  1. @static

Partially evaluate an expression at parse time.

For example, @static Sys.iswindows() ? foo : bar will evaluate Sys.iswindows() and insert either foo or bar into the expression. This is useful in cases where a construct would be invalid on other platforms, such as a ccall to a non-existent function. @static if Sys.isapple() foo end and @static foo <&&,||> bar are also valid syntax.

source

Versioning

Base.VersionNumber — Type

  1. VersionNumber

Version number type which follows the specifications of semantic versioning (semver), composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations.

VersionNumber objects can be compared with all of the standard comparison operators (==, <, <=, etc.), with the result following semver rules.

See also @v_str to efficiently construct VersionNumber objects from semver-format literal strings, VERSION for the VersionNumber of Julia itself, and Version Number Literals in the manual.

Examples

  1. julia> a = VersionNumber(1, 2, 3)
  2. v"1.2.3"
  3. julia> a >= v"1.2"
  4. true
  5. julia> b = VersionNumber("2.0.1-rc1")
  6. v"2.0.1-rc1"
  7. julia> b >= v"2.0.1"
  8. false

source

Base.@v_str — Macro

  1. @v_str

String macro used to parse a string to a VersionNumber.

Examples

  1. julia> v"1.2.3"
  2. v"1.2.3"
  3. julia> v"2.0.1-rc1"
  4. v"2.0.1-rc1"

source

Errors

Base.error — Function

  1. error(message::AbstractString)

Raise an ErrorException with the given message.

source

  1. error(msg...)

Raise an ErrorException with the given message.

source

Core.throw — Function

  1. throw(e)

Throw an object as an exception.

See also: rethrow, error.

source

Base.rethrow — Function

  1. rethrow()

Rethrow the current exception from within a catch block. The rethrown exception will continue propagation as if it had not been caught.

Note

The alternative form rethrow(e) allows you to associate an alternative exception object e with the current backtrace. However this misrepresents the program state at the time of the error so you’re encouraged to instead throw a new exception using throw(e). In Julia 1.1 and above, using throw(e) will preserve the root cause exception on the stack, as described in current_exceptions.

source

Base.backtrace — Function

  1. backtrace()

Get a backtrace object for the current program point.

source

Base.catch_backtrace — Function

  1. catch_backtrace()

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

source

Base.current_exceptions — Function

  1. current_exceptions(task::Task=current_task(); [backtrace::Bool=true])

Get the stack of exceptions currently being handled. For nested catch blocks there may be more than one current exception in which case the most recently thrown exception is last in the stack. The stack is returned as an ExceptionStack which is an AbstractVector of named tuples (exception,backtrace). If backtrace is false, the backtrace in each pair will be set to nothing.

Explicitly passing task will return the current exception stack on an arbitrary task. This is useful for inspecting tasks which have failed due to uncaught exceptions.

Julia 1.7

This function went by the experimental name catch_stack() in Julia 1.1–1.6, and had a plain Vector-of-tuples as a return type.

source

Base.@assert — Macro

  1. @assert cond [text]

Throw an AssertionError if cond is false. Preferred syntax for writing assertions. Message text is optionally displayed upon assertion failure.

Warning

An assert might be disabled at various optimization levels. Assert should therefore only be used as a debugging tool and not used for authentication verification (e.g., verifying passwords), nor should side effects needed for the function to work correctly be used inside of asserts.

Examples

  1. julia> @assert iseven(3) "3 is an odd number!"
  2. ERROR: AssertionError: 3 is an odd number!
  3. julia> @assert isodd(3) "What even are numbers?"

source

Base.Experimental.register_error_hint — Function

  1. Experimental.register_error_hint(handler, exceptiontype)

Register a “hinting” function handler(io, exception) that can suggest potential ways for users to circumvent errors. handler should examine exception to see whether the conditions appropriate for a hint are met, and if so generate output to io. Packages should call register_error_hint from within their __init__ function.

For specific exception types, handler is required to accept additional arguments:

  • MethodError: provide handler(io, exc::MethodError, argtypes, kwargs), which splits the combined arguments into positional and keyword arguments.

When issuing a hint, the output should typically start with \n.

If you define custom exception types, your showerror method can support hints by calling Experimental.show_error_hints.

Example

  1. julia> module Hinter
  2. only_int(x::Int) = 1
  3. any_number(x::Number) = 2
  4. function __init__()
  5. Base.Experimental.register_error_hint(MethodError) do io, exc, argtypes, kwargs
  6. if exc.f == only_int
  7. # Color is not necessary, this is just to show it's possible.
  8. print(io, "\nDid you mean to call ")
  9. printstyled(io, "`any_number`?", color=:cyan)
  10. end
  11. end
  12. end
  13. end

Then if you call Hinter.only_int on something that isn’t an Int (thereby triggering a MethodError), it issues the hint:

  1. julia> Hinter.only_int(1.0)
  2. ERROR: MethodError: no method matching only_int(::Float64)
  3. Did you mean to call `any_number`?
  4. Closest candidates are:
  5. ...

Julia 1.5

Custom error hints are available as of Julia 1.5.

Warning

This interface is experimental and subject to change or removal without notice. To insulate yourself against changes, consider putting any registrations inside an if isdefined(Base.Experimental, :register_error_hint) ... end block.

source

Base.Experimental.show_error_hints — Function

  1. Experimental.show_error_hints(io, ex, args...)

Invoke all handlers from Experimental.register_error_hint for the particular exception type typeof(ex). args must contain any other arguments expected by the handler for that type.

Julia 1.5

Custom error hints are available as of Julia 1.5.

Warning

This interface is experimental and subject to change or removal without notice.

source

Core.ArgumentError — Type

  1. ArgumentError(msg)

The arguments passed to a function are invalid. msg is a descriptive error message.

source

Core.AssertionError — Type

  1. AssertionError([msg])

The asserted condition did not evaluate to true. Optional argument msg is a descriptive error string.

Examples

  1. julia> @assert false "this is not true"
  2. ERROR: AssertionError: this is not true

AssertionError is usually thrown from @assert.

source

Core.BoundsError — Type

  1. BoundsError([a],[i])

An indexing operation into an array, a, tried to access an out-of-bounds element at index i.

Examples

  1. julia> A = fill(1.0, 7);
  2. julia> A[8]
  3. ERROR: BoundsError: attempt to access 7-element Vector{Float64} at index [8]
  4. julia> B = fill(1.0, (2,3));
  5. julia> B[2, 4]
  6. ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [2, 4]
  7. julia> B[9]
  8. ERROR: BoundsError: attempt to access 2×3 Matrix{Float64} at index [9]

source

Base.CompositeException — Type

  1. CompositeException

Wrap a Vector of exceptions thrown by a Task (e.g. generated from a remote worker over a channel or an asynchronously executing local I/O write or a remote worker under pmap) with information about the series of exceptions. For example, if a group of workers are executing several tasks, and multiple workers fail, the resulting CompositeException will contain a “bundle” of information from each worker indicating where and why the exception(s) occurred.

source

Base.DimensionMismatch — Type

  1. DimensionMismatch([msg])

The objects called do not have matching dimensionality. Optional argument msg is a descriptive error string.

source

Core.DivideError — Type

  1. DivideError()

Integer division was attempted with a denominator value of 0.

Examples

  1. julia> 2/0
  2. Inf
  3. julia> div(2, 0)
  4. ERROR: DivideError: integer division error
  5. Stacktrace:
  6. [...]

source

Core.DomainError — Type

  1. DomainError(val)
  2. DomainError(val, msg)

The argument val to a function or constructor is outside the valid domain.

Examples

  1. julia> sqrt(-1)
  2. ERROR: DomainError with -1.0:
  3. sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
  4. Stacktrace:
  5. [...]

source

Base.EOFError — Type

  1. EOFError()

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

source

Core.ErrorException — Type

  1. ErrorException(msg)

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

Examples

  1. julia> ex = ErrorException("I've done a bad thing");
  2. julia> ex.msg
  3. "I've done a bad thing"

source

Core.InexactError — Type

  1. InexactError(name::Symbol, T, val)

Cannot exactly convert val to type T in a method of function name.

Examples

  1. julia> convert(Float64, 1+2im)
  2. ERROR: InexactError: Float64(1 + 2im)
  3. Stacktrace:
  4. [...]

source

Core.InterruptException — Type

  1. InterruptException()

The process was stopped by a terminal interrupt (CTRL+C).

Note that, in Julia script started without -i (interactive) option, InterruptException is not thrown by default. Calling Base.exit_on_sigint(false) in the script can recover the behavior of the REPL. Alternatively, a Julia script can be started with

  1. julia -e "include(popfirst!(ARGS))" script.jl

to let InterruptException be thrown by CTRL+C during the execution.

source

Base.KeyError — Type

  1. KeyError(key)

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

source

Core.LoadError — Type

  1. LoadError(file::AbstractString, line::Int, error)

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

Julia 1.7

LoadErrors are no longer emitted by @macroexpand, @macroexpand1, and macroexpand as of Julia 1.7.

source

Core.MethodError — Type

  1. MethodError(f, args)

A method with the required type signature does not exist in the given generic function. Alternatively, there is no unique most-specific method.

source

Base.MissingException — Type

  1. MissingException(msg)

Exception thrown when a missing value is encountered in a situation where it is not supported. The error message, in the msg field may provide more specific details.

source

Core.OutOfMemoryError — Type

  1. OutOfMemoryError()

An operation allocated too much memory for either the system or the garbage collector to handle properly.

source

Core.ReadOnlyMemoryError — Type

  1. ReadOnlyMemoryError()

An operation tried to write to memory that is read-only.

source

Core.OverflowError — Type

  1. OverflowError(msg)

The result of an expression is too large for the specified type and will cause a wraparound.

source

Base.ProcessFailedException — Type

  1. ProcessFailedException

Indicates problematic exit status of a process. When running commands or pipelines, this is thrown to indicate a nonzero exit code was returned (i.e. that the invoked process failed).

source

Core.StackOverflowError — Type

  1. StackOverflowError()

The function call grew beyond the size of the call stack. This usually happens when a call recurses infinitely.

source

Base.SystemError — Type

  1. SystemError(prefix::AbstractString, [errno::Int32])

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

source

Core.TypeError — Type

  1. TypeError(func::Symbol, context::AbstractString, expected::Type, got)

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

source

Core.UndefKeywordError — Type

  1. UndefKeywordError(var::Symbol)

The required keyword argument var was not assigned in a function call.

Examples

  1. julia> function my_func(;my_arg)
  2. return my_arg + 1
  3. end
  4. my_func (generic function with 1 method)
  5. julia> my_func()
  6. ERROR: UndefKeywordError: keyword argument my_arg not assigned
  7. Stacktrace:
  8. [1] my_func() at ./REPL[1]:2
  9. [2] top-level scope at REPL[2]:1

source

Core.UndefRefError — Type

  1. UndefRefError()

The item or field is not defined for the given object.

Examples

  1. julia> struct MyType
  2. a::Vector{Int}
  3. MyType() = new()
  4. end
  5. julia> A = MyType()
  6. MyType(#undef)
  7. julia> A.a
  8. ERROR: UndefRefError: access to undefined reference
  9. Stacktrace:
  10. [...]

source

Core.UndefVarError — Type

  1. UndefVarError(var::Symbol)

A symbol in the current scope is not defined.

Examples

  1. julia> a
  2. ERROR: UndefVarError: a not defined
  3. julia> a = 1;
  4. julia> a
  5. 1

source

Base.StringIndexError — Type

  1. StringIndexError(str, i)

An error occurred when trying to access str at index i that is not valid.

source

Core.InitError — Type

  1. InitError(mod::Symbol, error)

An error occurred when running a module’s __init__ function. The actual error thrown is available in the .error field.

source

Base.retry — Function

  1. retry(f; delays=ExponentialBackOff(), check=nothing) -> Function

Return an anonymous function that calls function f. If an exception arises, f is repeatedly called again, each time check returns true, after waiting the number of seconds specified in delays. check should input delays‘s current state and the Exception.

Julia 1.2

Before Julia 1.2 this signature was restricted to f::Function.

Examples

  1. retry(f, delays=fill(5.0, 3))
  2. retry(f, delays=rand(5:10, 2))
  3. retry(f, delays=Base.ExponentialBackOff(n=3, first_delay=5, max_delay=1000))
  4. retry(http_get, check=(s,e)->e.status == "503")(url)
  5. retry(read, check=(s,e)->isa(e, IOError))(io, 128; all=false)

source

Base.ExponentialBackOff — Type

  1. ExponentialBackOff(; n=1, first_delay=0.05, max_delay=10.0, factor=5.0, jitter=0.1)

A Float64 iterator of length n whose elements exponentially increase at a rate in the interval factor * (1 ± jitter). The first element is first_delay and all elements are clamped to max_delay.

source

Events

Base.Timer — Method

  1. Timer(callback::Function, delay; interval = 0)

Create a timer that runs the function callback at each timer expiration.

Waiting tasks are woken and the function callback is called after an initial delay of delay seconds, and then repeating with the given interval in seconds. If interval is equal to 0, the callback is only run once. The function callback is called with a single argument, the timer itself. Stop a timer by calling close. The cb may still be run one final time, if the timer has already expired.

Examples

Here the first number is printed after a delay of two seconds, then the following numbers are printed quickly.

  1. julia> begin
  2. i = 0
  3. cb(timer) = (global i += 1; println(i))
  4. t = Timer(cb, 2, interval=0.2)
  5. wait(t)
  6. sleep(0.5)
  7. close(t)
  8. end
  9. 1
  10. 2
  11. 3

source

Base.Timer — Type

  1. Timer(delay; interval = 0)

Create a timer that wakes up tasks waiting for it (by calling wait on the timer object).

Waiting tasks are woken after an initial delay of at least delay seconds, and then repeating after at least interval seconds again elapse. If interval is equal to 0, the timer is only triggered once. When the timer is closed (by close) waiting tasks are woken with an error. Use isopen to check whether a timer is still active.

Note

interval is subject to accumulating time skew. If you need precise events at a particular absolute time, create a new timer at each expiration with the difference to the next time computed.

Note

A Timer requires yield points to update its state. For instance, isopen(t::Timer) cannot be used to timeout a non-yielding while loop.

source

Base.AsyncCondition — Type

  1. AsyncCondition()

Create a async condition that wakes up tasks waiting for it (by calling wait on the object) when notified from C by a call to uv_async_send. Waiting tasks are woken with an error when the object is closed (by close). Use isopen to check whether it is still active.

This provides an implicit acquire & release memory ordering between the sending and waiting threads.

source

Base.AsyncCondition — Method

  1. AsyncCondition(callback::Function)

Create a async condition that calls the given callback function. The callback is passed one argument, the async condition object itself.

source

Reflection

Base.nameof — Method

  1. nameof(m::Module) -> Symbol

Get the name of a Module as a Symbol.

Examples

  1. julia> nameof(Base.Broadcast)
  2. :Broadcast

source

Base.parentmodule — Function

  1. parentmodule(m::Module) -> Module

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

See also: names, nameof, fullname, @__MODULE__.

Examples

  1. julia> parentmodule(Main)
  2. Main
  3. julia> parentmodule(Base.Broadcast)
  4. Base

source

  1. parentmodule(t::DataType) -> Module

Determine the module containing the definition of a (potentially UnionAll-wrapped) DataType.

Examples

  1. julia> module Foo
  2. struct Int end
  3. end
  4. Foo
  5. julia> parentmodule(Int)
  6. Core
  7. julia> parentmodule(Foo.Int)
  8. Foo

source

  1. parentmodule(f::Function) -> Module

Determine the module containing the (first) definition of a generic function.

source

  1. parentmodule(f::Function, types) -> Module

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

source

Base.pathof — Method

  1. pathof(m::Module)

Return the path of the m.jl file that was used to import module m, or nothing if m was not imported from a package.

Use dirname to get the directory part and basename to get the file name part of the path.

source

Base.pkgdir — Method

  1. pkgdir(m::Module[, paths::String...])

Return the root directory of the package that imported module m, or nothing if m was not imported from a package. Optionally further path component strings can be provided to construct a path within the package root.

  1. julia> pkgdir(Foo)
  2. "/path/to/Foo.jl"
  3. julia> pkgdir(Foo, "src", "file.jl")
  4. "/path/to/Foo.jl/src/file.jl"

Julia 1.7

The optional argument paths requires at least Julia 1.7.

source

Base.moduleroot — Function

  1. moduleroot(m::Module) -> Module

Find the root module of a given module. This is the first module in the chain of parent modules of m which is either a registered root module or which is its own parent module.

source

__module__ — Keyword

  1. __module__

The argument __module__ is only visible inside the macro, and it provides information (in the form of a Module object) about the expansion context of the macro invocation. See the manual section on Macro invocation for more information.

source

__source__ — Keyword

  1. __source__

The argument __source__ is only visible inside the macro, and it provides information (in the form of a LineNumberNode object) about the parser location of the @ sign from the macro invocation. See the manual section on Macro invocation for more information.

source

Base.@__MODULE__ — Macro

  1. @__MODULE__ -> Module

Get the Module of the toplevel eval, which is the Module code is currently being read from.

source

Base.@__FILE__ — Macro

  1. @__FILE__ -> AbstractString

Expand to a string with the path to the file containing the macrocall, or an empty string if evaluated by julia -e <expr>. Return nothing if the macro was missing parser source information. Alternatively see PROGRAM_FILE.

source

Base.@__DIR__ — Macro

  1. @__DIR__ -> AbstractString

Expand to a string with the absolute path to the directory of the file containing the macrocall. Return the current working directory if run from a REPL or if evaluated by julia -e <expr>.

source

Base.@__LINE__ — Macro

  1. @__LINE__ -> Int

Expand to the line number of the location of the macrocall. Return 0 if the line number could not be determined.

source

Base.fullname — Function

  1. fullname(m::Module)

Get the fully-qualified name of a module as a tuple of symbols. For example,

Examples

  1. julia> fullname(Base.Iterators)
  2. (:Base, :Iterators)
  3. julia> fullname(Main)
  4. (:Main,)

source

Base.names — Function

  1. names(x::Module; all::Bool = false, imported::Bool = false)

Get an array of the names exported by a Module, excluding deprecated names. If all is true, then the list also includes non-exported names defined in the module, deprecated names, and compiler-generated names. If imported is true, then names explicitly imported from other modules are also included.

As a special case, all names defined in Main are considered “exported”, since it is not idiomatic to explicitly export names from Main.

See also: @locals, @__MODULE__.

source

Base.nameof — Method

  1. nameof(f::Function) -> Symbol

Get the name of a generic Function as a symbol. For anonymous functions, this is a compiler-generated name. For explicitly-declared subtypes of Function, it is the name of the function’s type.

source

Base.functionloc — Method

  1. functionloc(f::Function, types)

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

source

Base.functionloc — Method

  1. functionloc(m::Method)

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

source

Base.@locals — Macro

  1. @locals()

Construct a dictionary of the names (as symbols) and values of all local variables defined as of the call site.

Julia 1.1

This macro requires at least Julia 1.1.

Examples

  1. julia> let x = 1, y = 2
  2. Base.@locals
  3. end
  4. Dict{Symbol, Any} with 2 entries:
  5. :y => 2
  6. :x => 1
  7. julia> function f(x)
  8. local y
  9. show(Base.@locals); println()
  10. for i = 1:1
  11. show(Base.@locals); println()
  12. end
  13. y = 2
  14. show(Base.@locals); println()
  15. nothing
  16. end;
  17. julia> f(42)
  18. Dict{Symbol, Any}(:x => 42)
  19. Dict{Symbol, Any}(:i => 1, :x => 42)
  20. Dict{Symbol, Any}(:y => 2, :x => 42)

source

Internals

Base.GC.gc — Function

  1. GC.gc([full=true])

Perform garbage collection. The argument full determines the kind of collection: A full collection (default) sweeps all objects, which makes the next GC scan much slower, while an incremental collection may only sweep so-called young objects.

Warning

Excessive use will likely lead to poor performance.

source

Base.GC.enable — Function

  1. GC.enable(on::Bool)

Control whether garbage collection is enabled using a boolean argument (true for enabled, false for disabled). Return previous GC state.

Warning

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

source

Base.GC.@preserve — Macro

  1. GC.@preserve x1 x2 ... xn expr

Mark the objects x1, x2, ... as being in use during the evaluation of the expression expr. This is only required in unsafe code where expr implicitly uses memory or other resources owned by one of the xs.

Implicit use of x covers any indirect use of resources logically owned by x which the compiler cannot see. Some examples:

  • Accessing memory of an object directly via a Ptr
  • Passing a pointer to x to ccall
  • Using resources of x which would be cleaned up in the finalizer.

@preserve should generally not have any performance impact in typical use cases where it briefly extends object lifetime. In implementation, @preserve has effects such as protecting dynamically allocated objects from garbage collection.

Examples

When loading from a pointer with unsafe_load, the underlying object is implicitly used, for example x is implicitly used by unsafe_load(p) in the following:

  1. julia> let
  2. x = Ref{Int}(101)
  3. p = Base.unsafe_convert(Ptr{Int}, x)
  4. GC.@preserve x unsafe_load(p)
  5. end
  6. 101

When passing pointers to ccall, the pointed-to object is implicitly used and should be preserved. (Note however that you should normally just pass x directly to ccall which counts as an explicit use.)

  1. julia> let
  2. x = "Hello"
  3. p = pointer(x)
  4. Int(GC.@preserve x @ccall strlen(p::Cstring)::Csize_t)
  5. # Preferred alternative
  6. Int(@ccall strlen(x::Cstring)::Csize_t)
  7. end
  8. 5

source

Base.GC.safepoint — Function

  1. GC.safepoint()

Inserts a point in the program where garbage collection may run. This can be useful in rare cases in multi-threaded programs where some threads are allocating memory (and hence may need to run GC) but other threads are doing only simple operations (no allocation, task switches, or I/O). Calling this function periodically in non-allocating threads allows garbage collection to run.

Julia 1.4

This function is available as of Julia 1.4.

source

Base.GC.enable_logging — Function

  1. GC.enable_logging(on::Bool)

When turned on, print statistics about each GC to stderr.

source

Base.Meta.lower — Function

  1. lower(m, x)

Takes the expression x and returns an equivalent expression in lowered form for executing in module m. See also code_lowered.

source

Base.Meta.@lower — Macro

  1. @lower [m] x

Return lowered form of the expression x in module m. By default m is the module in which the macro is called. See also lower.

source

Base.Meta.parse — Method

  1. parse(str, start; greedy=true, raise=true, depwarn=true)

Parse the expression string and return an expression (which could later be passed to eval for execution). start is the code unit index into str of the first character to start parsing at (as with all string indexing, these are not character indices). 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. If depwarn is false, deprecation warnings will be suppressed.

  1. julia> Meta.parse("(α, β) = 3, 5", 1) # start of string
  2. (:((α, β) = (3, 5)), 16)
  3. julia> Meta.parse("(α, β) = 3, 5", 1, greedy=false)
  4. (:((α, β)), 9)
  5. julia> Meta.parse("(α, β) = 3, 5", 16) # end of string
  6. (nothing, 16)
  7. julia> Meta.parse("(α, β) = 3, 5", 11) # index of 3
  8. (:((3, 5)), 16)
  9. julia> Meta.parse("(α, β) = 3, 5", 11, greedy=false)
  10. (3, 13)

source

Base.Meta.parse — Method

  1. parse(str; raise=true, depwarn=true)

Parse the expression 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. If depwarn is false, deprecation warnings will be suppressed.

  1. julia> Meta.parse("x = 3")
  2. :(x = 3)
  3. julia> Meta.parse("x = ")
  4. :($(Expr(:incomplete, "incomplete: premature end of input")))
  5. julia> Meta.parse("1.0.2")
  6. ERROR: Base.Meta.ParseError("invalid numeric constant \"1.0.\"")
  7. Stacktrace:
  8. [...]
  9. julia> Meta.parse("1.0.2"; raise = false)
  10. :($(Expr(:error, "invalid numeric constant \"1.0.\"")))

source

Base.Meta.ParseError — Type

  1. ParseError(msg)

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

source

Core.QuoteNode — Type

  1. QuoteNode

A quoted piece of code, that does not support interpolation. See the manual section about QuoteNodes for details.

source

Base.macroexpand — Function

  1. macroexpand(m::Module, x; recursive=true)

Take the expression x and return an equivalent expression with all macros removed (expanded) for executing in module m. The recursive keyword controls whether deeper levels of nested macros are also expanded. This is demonstrated in the example below:

  1. julia> module M
  2. macro m1()
  3. 42
  4. end
  5. macro m2()
  6. :(@m1())
  7. end
  8. end
  9. M
  10. julia> macroexpand(M, :(@m2()), recursive=true)
  11. 42
  12. julia> macroexpand(M, :(@m2()), recursive=false)
  13. :(#= REPL[16]:6 =# M.@m1)

source

Base.@macroexpand — Macro

  1. @macroexpand

Return equivalent expression with all macros removed (expanded).

There are differences between @macroexpand and macroexpand.

  • While macroexpand takes a keyword argument recursive, @macroexpand is always recursive. For a non recursive macro version, see @macroexpand1.

  • While macroexpand has an explicit module argument, @macroexpand always expands with respect to the module in which it is called.

This is best seen in the following example:

  1. julia> module M
  2. macro m()
  3. 1
  4. end
  5. function f()
  6. (@macroexpand(@m),
  7. macroexpand(M, :(@m)),
  8. macroexpand(Main, :(@m))
  9. )
  10. end
  11. end
  12. M
  13. julia> macro m()
  14. 2
  15. end
  16. @m (macro with 1 method)
  17. julia> M.f()
  18. (1, 1, 2)

With @macroexpand the expression expands where @macroexpand appears in the code (module M in the example). With macroexpand the expression expands in the module given as the first argument.

source

Base.@macroexpand1 — Macro

  1. @macroexpand1

Non recursive version of @macroexpand.

source

Base.code_lowered — Function

  1. code_lowered(f, types; generated=true, debuginfo=:default)

Return an array of the lowered forms (IR) for the methods matching the given generic function and type signature.

If generated is false, the returned CodeInfo instances will correspond to fallback implementations. An error is thrown if no fallback implementation exists. If generated is true, these CodeInfo instances will correspond to the method bodies yielded by expanding the generators.

The keyword debuginfo controls the amount of code metadata present in the output.

Note that an error will be thrown if types are not leaf types when generated is true and any of the corresponding methods are an @generated method.

source

Base.code_typed — Function

  1. code_typed(f, types; kw...)

Returns an array of type-inferred lowered form (IR) for the methods matching the given generic function and type signature.

Keyword Arguments

  • optimize=true: controls whether additional optimizations, such as inlining, are also applied.
  • debuginfo=:default: controls the amount of code metadata present in the output,

possible options are :source or :none.

Internal Keyword Arguments

This section should be considered internal, and is only for who understands Julia compiler internals.

  • world=Base.get_world_counter(): optional, controls the world age to use when looking up methods,

use current world age if not specified.

  • interp=Core.Compiler.NativeInterpreter(world): optional, controls the interpreter to use,

use the native interpreter Julia uses if not specified.

Example

One can put the argument types in a tuple to get the corresponding code_typed.

  1. julia> code_typed(+, (Float64, Float64))
  2. 1-element Vector{Any}:
  3. CodeInfo(
  4. 1 %1 = Base.add_float(x, y)::Float64
  5. └── return %1
  6. ) => Float64

source

Base.precompile — Function

  1. precompile(f, args::Tuple{Vararg{Any}})

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

source

Base.jit_total_bytes — Function

  1. Base.jit_total_bytes()

Return the total amount (in bytes) allocated by the just-in-time compiler for e.g. native code and data.

source

Meta

Base.Meta.quot — Function

  1. Meta.quot(ex)::Expr

Quote expression ex to produce an expression with head quote. This can for instance be used to represent objects of type Expr in the AST. See also the manual section about QuoteNode.

Examples

  1. julia> eval(Meta.quot(:x))
  2. :x
  3. julia> dump(Meta.quot(:x))
  4. Expr
  5. head: Symbol quote
  6. args: Array{Any}((1,))
  7. 1: Symbol x
  8. julia> eval(Meta.quot(:(1+2)))
  9. :(1 + 2)

source

Base.isexpr — Function

  1. Meta.isexpr(ex, head[, n])::Bool

Return true if ex is an Expr with the given type head and optionally that the argument list is of length n. head may be a Symbol or collection of Symbols. For example, to check that a macro was passed a function call expression, you might use isexpr(ex, :call).

Examples

  1. julia> ex = :(f(x))
  2. :(f(x))
  3. julia> Meta.isexpr(ex, :block)
  4. false
  5. julia> Meta.isexpr(ex, :call)
  6. true
  7. julia> Meta.isexpr(ex, [:block, :call]) # multiple possible heads
  8. true
  9. julia> Meta.isexpr(ex, :call, 1)
  10. false
  11. julia> Meta.isexpr(ex, :call, 2)
  12. true

source

Base.isidentifier — Function

  1. isidentifier(s) -> Bool

Return whether the symbol or string s contains characters that are parsed as a valid ordinary identifier (not a binary/unary operator) in Julia code; see also Base.isoperator.

Internally Julia allows any sequence of characters in a Symbol (except \0s), and macros automatically use variable names containing # in order to avoid naming collision with the surrounding code. In order for the parser to recognize a variable, it uses a limited set of characters (greatly extended by Unicode). isidentifier() makes it possible to query the parser directly whether a symbol contains valid characters.

Examples

  1. julia> Meta.isidentifier(:x), Meta.isidentifier("1x")
  2. (true, false)

source

Base.isoperator — Function

  1. isoperator(s::Symbol)

Return true if the symbol can be used as an operator, false otherwise.

Examples

  1. julia> Meta.isoperator(:+), Meta.isoperator(:f)
  2. (true, false)

source

Base.isunaryoperator — Function

  1. isunaryoperator(s::Symbol)

Return true if the symbol can be used as a unary (prefix) operator, false otherwise.

Examples

  1. julia> Meta.isunaryoperator(:-), Meta.isunaryoperator(:√), Meta.isunaryoperator(:f)
  2. (true, true, false)

source

Base.isbinaryoperator — Function

  1. isbinaryoperator(s::Symbol)

Return true if the symbol can be used as a binary (infix) operator, false otherwise.

Examples

  1. julia> Meta.isbinaryoperator(:-), Meta.isbinaryoperator(:√), Meta.isbinaryoperator(:f)
  2. (true, false, false)

source

Base.Meta.show_sexpr — Function

  1. Meta.show_sexpr([io::IO,], ex)

Show expression ex as a lisp style S-expression.

Examples

  1. julia> Meta.show_sexpr(:(f(x, g(y,z))))
  2. (:call, :f, :x, (:call, :g, :y, :z))

source