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.
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-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”.)
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.
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.
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.
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.
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 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.
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.
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.
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.
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.
Base.@show — Macro
1. @show
Show an expression and result, returning the result. See also show.
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.
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. Also in and isa are parsed as infix operators. Creation of a variable named where, in or isa 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.
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 ;.
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 into an array to represent the last index of a dimension.
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 statements allocate new variable bindings each time they run. Whereas an assignment modifies an existing value location, let creates new locations. 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.
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.
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
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.
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 after new lines, but can be used to separate statements on a single line or to join statements into a single expression. ; is also used to suppress output printing in the REPL and similar interfaces.
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!"
= — 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] = vcallssetindex!(a,v,i).a.b = ccallssetproperty!(a,:b,c).- Inside a function call,
f(a=b)passesbas the value of keyword argumenta. - Inside parentheses with commas,
(a=1,)constructs aNamedTuple.
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> println(x > y ? "x is larger" : "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 for more information.
Base.Iterators — Module
Methods for working with Iterators.
Base.Libc — Module
Interface to libc, the C standard library.
Base.Meta — Module
Convenience functions for metaprogramming.
Base.StackTraces — Module
Tools for collecting and manipulating stack traces. Mainly used for building errors.
Base.Sys — Module
Provide methods for retrieving information about hardware and the operating system.
Base.Threads — Module
Multithreading support.
Base.GC — Module
1. Base.GC
Module with garbage collection utilities.
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];
3. julia> a == b
4. true
6. julia> a === b
7. false
9. julia> a === a
10. true
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
4. julia> isa(1, Matrix)
5. false
7. julia> isa(1, Char)
8. false
10. julia> isa(1, Number)
11. true
13. julia> 1 isa Number
14. true
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.
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.
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
4. julia> [1., NaN] == [1., NaN]
5. false
7. julia> 0.0 == -0.0
8. true
10. julia> isequal(0.0, -0.0)
11. false
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.
Base.isless — Function
1. isless(x, y)
Test whether x is less than y, according to a fixed total order. 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 isisless(y, x)andisequal(x, y), and exactly one of those three yieldstrue. - The relation defined by
islessis transitive, i.e.,isless(x, y) && isless(y, z)impliesisless(x, z).
Values that are normally unordered, such as NaN, are ordered in an arbitrary but consistent fashion. 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
4. julia> isless("Red", "Blue")
5. false
Core.ifelse — Function
1. ifelse(condition::Bool, x, y)
Return x if condition is `true
(本文超出站点单文档体积上限,已截断)
