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 Moduleto import the module, andModule.fn(x)to use the functions. - Alternatively,
using Modulewill import all exportedModulefunctions 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.
Base.atexit — Function
1. atexit(f)
Register a zero- or one-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.
If f has a method defined for one integer argument, it will be called as f(n::Int32), where n is the current exit code, otherwise it will be called as f().
Julia 1.9
The one-argument form requires Julia 1.9
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”.)
Base.isinteractive — Function
1. isinteractive() -> Bool
Determine whether Julia is running an interactive session.
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
4. julia> Base.summarysize(Ref(rand(100)))
5. 848
7. julia> sizeof(Ref(rand(100)))
8. 8
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.
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.
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.
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.
Base.include_dependency — Function
1. include_dependency(path::AbstractString)
In a module, declare that the file, directory, or symbolic link specified by path (relative or absolute) is a dependency for precompilation; that is, the module will need to be recompiled if the modification time of path changes.
This is only needed if your module depends on a path that is not used via include. It has no effect outside of compilation.
__init__ — Keyword
1. __init__
The __init__() function in a module executes immediately after the module is loaded at runtime for the first time. It is called once, after all other statements in the module have been executed. Because it is called after fully importing the module, __init__ functions of submodules will be executed first. Two typical uses of __init__ are calling runtime initialization functions of external C libraries and initializing global constants that involve pointers returned by external libraries. See the manual section about modules for more details.
Examples
1. const foo_data_ptr = Ref{Ptr{Cvoid}}(0)
2. function __init__()
3. ccall((:foo_init, :libfoo), Cvoid, ())
4. foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ())
5. nothing
6. end
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.
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.
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
5. julia> @show x^2 x/2;
6. x ^ 2 = 9
7. x / 2 = 1.5
ans — Keyword
1. ans
A variable referring to the last computed value, automatically set at the interactive prompt.
Base.active_project — Function
1. active_project()
Return the path of the active Project.toml file. See also Base.set_active_project.
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.
Julia 1.8
This function requires at least Julia 1.8.
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. 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
5. struct MyType
6. x
7. end
9. bar(x) = 2x
10. foo(a::MyType) = bar(a.x) + 1
11. show(io::IO, a::MyType) = print(io, "MyType $(a.x)")
12. end
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.
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.
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.
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
3. ...
5. end
is equivalent to
1. baremodule Mod
3. using Base
5. eval(x) = Core.eval(Mod, x)
6. include(p) = Base.include(Mod, p)
8. ...
10. end
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.
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.
See the manual section on Metaprogramming for more information about how to write a macro.
Examples
1. julia> macro sayhello(name)
2. return :( println("Hello, ", $name, "!") )
3. end
4. @sayhello (macro with 1 method)
6. julia> @sayhello "Charlie"
7. Hello, Charlie!
9. julia> macro saylots(x...)
10. return :( println("Say: ", $(x...)) )
11. end
12. @saylots (macro with 1 method)
14. julia> @saylots "hey " "there " "friend"
15. Say: hey there friend
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
7. function test2(xs)
8. map(xs) do x
9. iseven(x) && return 2x
10. x
11. end
12. 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.
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
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
6. julia> A[begin, :]
7. 2-element Array{Int64,1}:
8. 1
9. 2
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
6. julia> A[end, :]
7. 2-element Array{Int64, 1}:
8. 3
9. 4
let — Keyword
1. let
let blocks create a new hard scope and optionally introduce new local bindings.
Just like the other scope constructs, let blocks define the block of code where newly introduced local variables are accessible. Additionally, the syntax has a special meaning for comma-separated assignments and variable names that may optionally appear on the same line as the let:
1. let var1 = value1, var2, var3 = value3
2. code
3. end
The variables introduced on this line are local to the let block and the assignments are evaluated in order, with each right-hand side evaluated in the scope without considering the name on the left-hand side. Therefore it makes sense to write something like let x = x, since the two x variables are distinct with the left-hand side locally shadowing the x from the outer scope. This can even be a useful idiom as new local variables are freshly created each time local scopes are entered, but this is only observable in the case of variables that outlive their scope via closures.
By contrast, begin blocks also group multiple expressions together but do not introduce scope or have the special assignment syntax.
Examples
In the function below, there is a single x that is iteratively updated three times by the map. The closures returned all reference that one x at its final value:
1. julia> function test_outer_x()
2. x = 0
3. map(1:3) do _
4. x += 1
5. return ()->x
6. end
7. end
8. test_outer_x (generic function with 1 method)
10. julia> [f() for f in test_outer_x()]
11. 3-element Vector{Int64}:
12. 3
13. 3
14. 3
If, however, we add a let block that introduces a new local variable we will end up with three distinct variables being captured (one at each iteration) even though we chose to use (shadow) the same name.
1. julia> function test_let_x()
2. x = 0
3. map(1:3) do _
4. x += 1
5. let x = x
6. return ()->x
7. end
8. end
9. end
10. test_let_x (generic function with 1 method)
12. julia> [f() for f in test_let_x()]
13. 3-element Vector{Int64}:
14. 1
15. 2
16. 3
All scope constructs that introduce new local variables behave this way when repeatedly run; the distinctive feature of let is its ability to succinctly declare new locals that may shadow outer variables of the same name. For example, directly using the argument of the do function similarly captures three distinct variables:
1. julia> function test_do_x()
2. map(1:3) do x
3. return ()->x
4. end
5. end
6. test_do_x (generic function with 1 method)
8. julia> [f() for f in test_do_x()]
9. 3-element Vector{Int64}:
10. 1
11. 2
12. 3
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
for — Keyword
1. for
for loops repeatedly evaluate a block of statements while iterating over a sequence of values.
The iteration variable is always a new variable, even if a variable of the same name exists in the enclosing scope. Use outer to reuse an existing local variable for iteration.
Examples
1. julia> for i in [1, 4, 0]
2. println(i)
3. end
4. 1
5. 4
6. 0
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
4. julia> while i < 5
5. println(i)
6. global i += 1
7. end
8. 1
9. 2
10. 3
11. 4
break — Keyword
1. break
Break out of a loop immediately.
Examples
1. julia> i = 0
2. 0
4. julia> while true
5. global i += 1
6. i > 5 && break
7. println(i)
8. end
9. 1
10. 2
11. 3
12. 4
13. 5
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
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.
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.
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.
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)
11. julia> foo(10)
12. 0
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
4. julia> function foo()
5. global z = 6 # use the z variable defined outside foo
6. end
7. foo (generic function with 1 method)
9. julia> foo()
10. 6
12. julia> z
13. 6
outer — Keyword
1. for outer
Reuse an existing local variable for iteration in a for loop.
See the manual section on variable scoping for more information.
See also for.
Examples
1. julia> function f()
2. i = 0
3. for i = 1:3
4. # empty
5. end
6. return i
7. end;
9. julia> f()
10. 0
1. julia> function f()
2. i = 0
3. for outer i = 1:3
4. # empty
5. end
6. return i
7. end;
9. julia> f()
10. 3
1. julia> i = 0 # global variable
2. for outer i = 1:3
3. end
4. ERROR: syntax: no outer local variable declaration exists for "for outer"
5. [...]
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.
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.
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.
Base.@kwdef — Macro
1. @kwdef typedef
This is a helper macro that automatically defines a keyword-based constructor for the type declared in the expression typedef, which must be a struct or mutable struct expression. The default argument is supplied by declaring fields of the form field::T = default or field = default. If no default is provided then the keyword argument becomes a required keyword argument in the resulting type constructor.
Inner constructors can still be defined, but at least one should accept arguments in the same form as the default inner constructor (i.e. one positional argument per field) in order to function correctly with the keyword outer constructor.
Julia 1.1
Base.@kwdef for parametric structs, and structs with supertypes requires at least Julia 1.1.
Julia 1.9
This macro is exported as of Julia 1.9.
Examples
1. julia> @kwdef struct Foo
2. a::Int = 1 # specified default
3. b::String # required keyword
4. end
5. Foo
7. julia> Foo(b="hi")
8. Foo(1, "hi")
10. julia> Foo()
11. ERROR: UndefKeywordError: keyword argument `b` not assigned
12. Stacktrace:
13. [...]
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.
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.
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, ...}.
… — 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)
4. julia> add(1, 2, 3, 4, 5)
5. 15
7. julia> add([1, 2, 3]...)
8. 6
10. julia> add(7, 1:100..., 1000:1100...)
11. 111107
; — 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)
7. julia> bar() = (x = "Hello, Mars!"; return x)
8. bar (generic function with 1 method)
10. julia> foo();
12. julia> bar()
13. "Hello, Mars!"
15. julia> function plot(x, y; style="solid", width=1, color="black")
16. ###
17. end
19. julia> [1 2; 3 4]
20. 2×2 Matrix{Int64}:
21. 1 2
22. 3 4
24. julia> ; # upon typing ;, the prompt changes (in place) to: shell>
25. shell> echo hello
26. hello
\= — Keyword
1. =
= is the assignment operator.
- For variable
aand expressionb,a = bmakesarefer to the value ofb. - For functions
f(x),f(x) = xdefines a new function constantf, or adds a new method tofiffis already defined; this usage is equivalent tofunction f(x); x; end. a[i] = vcalls setindex!(a,v,i).a.b = ccalls setproperty!(a,:b,c).- Inside a function call,
f(a=b)passesbas the value of keyword argumenta. - 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
5. julia> b = [1]; a = copy(b); b[1] = 2; a
6. 1-element Array{Int64, 1}:
7. 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)
4. julia> a = [1]; f!(a); a
5. 1-element Array{Int64, 1}:
6. 2
Assignment can operate on multiple variables in parallel, taking values from an iterable:
1. julia> a, b = 4, 5
2. (4, 5)
4. julia> a, b = 1:3
5. 1:3
7. julia> a, b
8. (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
5. julia> b[1] = 2; a, b, c
6. ([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. [...]
5. julia> push!(a, 2, 3)
6. 4-element Array{Int64, 1}:
7. 1
8. 1
9. 2
10. 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. [...]
5. julia> filter!(x -> x > 1, a) # in-place & thus more efficient than a = a[a .> 1]
6. 2-element Array{Int64, 1}:
7. 2
8. 3
?: — 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;
3. julia> x > y ? println("x is larger") : println("y is larger")
4. y is larger
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
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.
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.
Base Submodules
Base.Broadcast — Module
1. Base.Broadcast
Module containing the broadcasting implementation.
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](/read/julia-1.9-
(本文超出站点单文档体积上限,已截断)
