基本功能

介绍

Julia Base 中包含一系列适用于科学及数值计算的函数和宏,但也可以用于通用编程,其它功能则由 Julia 生态圈中的各种库来提供。函数按主题划分如下:

一些通用的提示:

  • 可以通过 Import Module 导入想要使用的模块,并利用 Module.fn(x) 语句来实现对模块内函数的调用。
  • 此外,using Module 语句会将名为 Module 的模块中的所有可调函数引入当前的命名空间。
  • 按照约定,名字以感叹号(!)结尾的函数会改变其输入参数的内容。 一些函数同时拥有改变参数(例如 sort!)和不改变参数(sort)的版本

概览

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.

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

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.

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([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 1-argument 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.

source

Base.MainInclude.include — Function.

  1. include(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 1-argument 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.

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

source

Base.include_string — Function.

  1. include_string(m::Module, code::AbstractString, filename::AbstractString="string")

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

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.

source

Base.methods — Function.

  1. methods(f, [types])

Returns the method table for f.

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

source

Base.@show — Macro.

  1. @show

Show an expression and result, returning the result.

source

ans — Keyword.

  1. ans

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

source

关键字

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 a definition of eval. It does still import Core.

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 to include generated code in the final body of a program. A macro maps a tuple of arguments to a returned expression, and the resulting expression is compiled directly rather than requiring a runtime eval call. Macro arguments may include expressions, literal values, and symbols. For example:

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!

source

return — Keyword.

  1. return

return can be used in function bodies to exit early and return a given value, e.g.

  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 its enclosing function 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].

source

do — Keyword.

  1. do

Create an anonymous function. 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 ;.

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 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
  5. julia> A[end, :]
  6. 2-element Array{Int64,1}:
  7. 3
  8. 4

source

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.

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.

source

for — Keyword.

  1. for

for loops repeatedly evaluate the body of the loop by 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 continues evaluating the body of the while loop so 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 for Exceptions to be tested for. For example, a customized square root function can be written to automatically call either the real or complex square root method on demand using Exceptions:

  1. f(x) = try
  2. sqrt(x)
  3. catch
  4. sqrt(complex(x, 0))
  5. end

try/catch statements also allow the Exception to be saved in a variable, e.g. catch y.

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

— 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 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)
  6. julia> bar() = (x = "Hello, Mars!"; return x)
  7. bar (generic function with 1 method)
  8. julia> foo();
  9. julia> bar()
  10. "Hello, Mars!"

source

Base 模块

Base — Keyword.

The base library of Julia.

source

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.

Experimental multithreading support.

source

Base.GC — Module.

  1. Base.GC

Module with garbage collection utilities.

source

所有对象

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.

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

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 canonical total order. 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 canonical total order should implement this function. Numeric types only need to implement it if they have special values such as NaN. Types with a canonical partial order should implement <.

source

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

source

Core.typeof — Function.

  1. typeof(x)

Get the concrete type of x.

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. Array{Float64,2}

source

Core.tuple — Function.

  1. tuple(xs...)

Construct a tuple of the given objects.

Examples

  1. julia> tuple(1, 'a', pi)
  2. (1, 'a', π = 3.1415926535897...)

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

Base.objectid — Function.

  1. objectid(x)

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

source

Base.hash — Function.

  1. hash(x[, h::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.

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.

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.

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.

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

While it isn't normally necessary, user-defined types can override the default deepcopy behavior by defining a specialized version of the function deepcopy_internal(x::T, dict::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)

The syntax a.b calls getproperty(a, :b).

See also propertynames and setproperty!.

source

Base.setproperty! — Function.

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

The syntax a.b = c calls setproperty!(a, :b, c).

See also 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.

source

Core.getfield — Function.

  1. getfield(value, name::Symbol)

Extract a named field from a value of composite type. See also getproperty.

Examples

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

source

Core.setfield! — Function.

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

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). 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: type Rational is immutable

source

Core.isdefined — Function.

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

Tests whether an assignable location is defined. The arguments can be a module and a symbol or a composite object and field name (as a symbol) or index.

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.

Examples

  1. julia> function f()
  2. println(@isdefined x)
  3. x = 3
  4. println(@isdefined x)
  5. end
  6. f (generic function with 1 method)
  7. julia> f()
  8. false
  9. 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(Int64, 3.5)
  5. Stacktrace:
  6. [...]

If T is a AbstractFloat or Rational 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(Rational{Int32}, x)
  6. 1//3
  7. julia> convert(Rational{Int64}, x)
  8. 6004799503160661//18014398509481984

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

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.

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.

Examples

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

source

类型的属性

类型关系

Base.supertype — Function.

  1. supertype(T::DataType)

Return the supertype of DataType T.

Examples

  1. julia> supertype(Int32)
  2. Signed

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, S)

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

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.

  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

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

已声明结构

Base.isimmutable — Function.

  1. isimmutable(v) -> Bool

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. Base.isabstracttype(T)

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

Examples

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

source

Base.isprimitivetype — Function.

  1. Base.isprimitivetype(T) -> Bool

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

source

Base.isstructtype — Function.

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

Examples

  1. julia> fieldnames(Rational)
  2. (:num, :den)

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

内存布局

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. Size, in bytes, of object obj if it is not DataType.

Examples

  1. julia> sizeof(Float32)
  2. 4
  3. julia> sizeof(ComplexF64)
  4. 16
  5. julia> sizeof(1.0)
  6. 8
  7. julia> sizeof([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: argument is an abstract type; size is indeterminate
  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).

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.

Examples

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

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.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.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. 12-element Array{Tuple{UInt64,Symbol,DataType},1}:
  4. (0x0000000000000000, :device, UInt64)
  5. (0x0000000000000008, :inode, UInt64)
  6. (0x0000000000000010, :mode, UInt64)
  7. (0x0000000000000018, :nlink, Int64)
  8. (0x0000000000000020, :uid, UInt64)
  9. (0x0000000000000028, :gid, UInt64)
  10. (0x0000000000000030, :rdev, UInt64)
  11. (0x0000000000000038, :size, Int64)
  12. (0x0000000000000040, :blksize, Int64)
  13. (0x0000000000000048, :blocks, Int64)
  14. (0x0000000000000050, :mtime, Float64)
  15. (0x0000000000000058, :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

特殊值

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.

Examples

  1. julia> typemax(Int8)
  2. 127
  3. julia> typemax(UInt32)
  4. 0xffffffff

source

Base.floatmin — Function.

  1. floatmin(T)

The smallest in absolute value non-subnormal value representable by the given floating-point DataType T.

source

Base.floatmax — Function.

  1. floatmax(T)

The highest finite value representable by the given floating-point DataType T.

Examples

  1. julia> floatmax(Float16)
  2. Float16(6.55e4)
  3. julia> floatmax(Float32)
  4. 3.4028235f38

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

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::Color = 0, blue::Color = 1, green::Color = 2)

source

特殊类型

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

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

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> keys(x)
  8. (:a, :b)
  9. julia> values(x)
  10. (1, 2)
  11. julia> collect(x)
  12. 2-element Array{Int64,1}:
  13. 1
  14. 2
  15. julia> collect(pairs(x))
  16. 2-element Array{Pair{Symbol,Int64},1}:
  17. :a => 1
  18. :b => 2

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. 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 — Type.

  1. Vararg{T,N}

The last parameter of a tuple type Tuple can be the special type Vararg, which denotes any number of trailing elements. The type Vararg{T,N} corresponds to exactly N elements of type T. 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.)

Examples

  1. julia> mytupletype = Tuple{AbstractString,Vararg{Int}}
  2. Tuple{AbstractString,Vararg{Int64,N} where N}
  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.

Nothing

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

source

Base.Some — Type.

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.

something(x, y...)

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.

Examples

julia> something(nothing, 1)
1

julia> something(Some(1), nothing)
1

julia> something(missing, nothing)
missing

julia> something(nothing, nothing)
ERROR: ArgumentError: No value arguments present

source

Base.Enums.@enum — Macro.

@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

julia> @enum Fruit apple=1 orange=2 kiwi=3

julia> f(x::Fruit) = "I'm a Fruit with value: $(Int(x))"
f (generic function with 1 method)

julia> f(apple)
"I'm a Fruit with value: 1"

julia> Fruit(1)
apple::Fruit = 1

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

@enum EnumName begin
    value1
    value2
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.

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

julia> instances(Fruit)
(apple::Fruit = 1, orange::Fruit = 2, kiwi::Fruit = 3)

source

泛型

Core.Function — Type.

Function

Abstract type of all functions.

julia> isa(+, Function)
true

julia> typeof(sin)
typeof(sin)

julia> ans <: Function
true

source

Base.hasmethod — Function.

hasmethod(f, Tuple type; world = typemax(UInt)) -> 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.

See also applicable.

Examples

julia> hasmethod(length, Tuple{Array})
true

source

Core.applicable — Function.

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

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

See also hasmethod.

Examples

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

julia> applicable(f, 1)
false

julia> applicable(f, 1, 2)
true

source

Core.invoke — Function.

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

Examples

julia> f(x::Real) = x^2;

julia> f(x::Integer) = 1 + invoke(f, Tuple{Real}, x);

julia> f(2)
5

source

Base.invokelatest — Function.

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

new — Keyword.

new

Special function available to inner constructors which created a new object of the type. See the manual section on Inner Constructor Methods for more information.

source

Base.:|> — Function.

|>(x, f)

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

Examples

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

source

Base.:∘ — Function.

f ∘ g

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

Examples

julia> map(uppercase∘first, ["apple", "banana", "carrot"])
3-element Array{Char,1}:
 'A'
 'B'
 'C'

source

语法

Core.eval — Function.

Core.eval(m::Module, expr)

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

source

Base.MainInclude.eval — Function.

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.

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

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

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

source

Base.esc — Function.

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.

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

function sum(A::AbstractArray)
    r = zero(eltype(A))
    for i = 1:length(A)
        @inbounds r += A[i]
    end
    return r
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.

@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

julia> @inline function g(A, i)
           @boundscheck checkbounds(A, i)
           return "accessing ($A)[$i]"
       end;

julia> f1() = return g(1:2, -1);

julia> f2() = @inbounds return g(1:2, -1);

julia> f1()
ERROR: BoundsError: attempt to access 2-element UnitRange{Int64} at index [-1]
Stacktrace:
 [1] throw_boundserror(::UnitRange{Int64}, ::Tuple{Int64}) at ./abstractarray.jl:455
 [2] checkbounds at ./abstractarray.jl:420 [inlined]
 [3] g at ./none:2 [inlined]
 [4] f1() at ./none:1
 [5] top-level scope

julia> f2()
"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 size. Therefore, @boundscheck annotations should only be added to a getindex or setindex! implementation after you are certain its behavior is correct.

source

Base.@inline — Macro.

@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. This is shown in the following example:

@inline function bigfunction(x)
    #=
        Function Definition
    =#
end

source

Base.@noinline — Macro.

@noinline

Prevents the compiler from inlining a function.

Small functions are typically inlined automatically. By using @noinline on small functions, auto-inlining can be prevented. This is shown in the following example:

@noinline function smallfunction(x)
    #=
        Function Definition
    =#
end

source

Base.@nospecialize — Macro.

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

function example_function(@nospecialize x)
    ...
end

function example_function(@nospecialize(x = 1), y)
    ...
end

function example_function(x, y, z)
    @nospecialize x y
    ...
end

@nospecialize
f(y) = [x for x in y]
@specialize

source

Base.@specialize — Macro.

@specialize

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

source

Base.gensym — Function.

gensym([tag])

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

source

Base.@gensym — Macro.

@gensym

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

source

Base.@goto — Macro.

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

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

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

@polly

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

source

Base.@generated — Macro.

@generated f
@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:

julia> @generated function bar(x)
           if x <: Integer
               return :(x ^ 2)
           else
               return :(x)
           end
       end
bar (generic function with 1 method)

julia> bar(4)
16

julia> bar("baz")
"baz"

source

Base.@pure — Macro.

@pure ex
@pure(ex)

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

A pure function can only depend on immutable information. This also means a @pure function cannot use any global mutable state, including generic functions. Calls to generic functions depend on method tables which are mutable global state. Use with caution, incorrect @pure annotation of a function may introduce hard to identify bugs. Double check for calls to generic functions.

source

缺失值

Base.Missing — Type.

Missing

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

source

Base.missing — Constant.

missing

The singleton instance of type Missing representing a missing value.

source

Base.coalesce — Function.

coalesce(x, y...)

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

Examples

julia> coalesce(missing, 1)
1

julia> coalesce(1, missing)
1

julia> coalesce(nothing, 1)  # returns `nothing`

julia> coalesce(missing, missing)
missing

source

Base.ismissing — Function.

ismissing(x)

Indicate whether x is missing.

source

Base.skipmissing — Function.

skipmissing(itr)

Return an iterator over the elements in itr skipping missing values.

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.

Examples

julia> sum(skipmissing([1, missing, 2]))
3

julia> collect(skipmissing([1, missing, 2]))
2-element Array{Int64,1}:
 1
 2

julia> collect(skipmissing([1 missing; 2 missing]))
2-element Array{Int64,1}:
 1
 2

source

系统

Base.run — Function.

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

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

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.

devnull

Used in a stream redirect to discard all data written to it. Essentially equivalent to /dev/null on Unix or NUL on Windows. Usage:

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

source

Base.success — Function.

success(command)

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

source

Base.process_running — Function.

process_running(p::Process)

Determine whether a process is currently running.

source

Base.process_exited — Function.

process_exited(p::Process)

Determine whether a process has exited.

source

Base.kill — Method.

kill(p::Process, signum=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.

Sys.set_process_title(title::AbstractString)

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

source

Base.Sys.get_process_title — Function.

Sys.get_process_title()

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

source

Base.ignorestatus — Function.

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.

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.

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, or nothing. In order to modify (rather than replace) the existing environment, create env by copy(ENV) and then set env["var"]=val as desired.
  • 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.
Cmd(`echo "Hello world"`, ignorestatus=true, detach=false)

source

Base.setenv — Function.

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 by copy(ENV) and then setting env["var"]=val as desired, or use withenv.

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

source

Base.withenv — Function.

withenv(f::Function, 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.pipeline — Method.

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:

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

source

Base.pipeline — Method.

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:

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

source

Base.Libc.gethostname — Function.

gethostname() -> AbstractString

Get the local machine's host name.

source

Base.Libc.getpid — Function.

getpid() -> Int32

Get Julia's process ID.

source

Base.Libc.time — Method.

time()

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

source

Base.time_ns — Function.

time_ns()

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

source

Base.@time — Macro.

@time

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.

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

julia> @time rand(10^6);
  0.001525 seconds (7 allocations: 7.630 MiB)

julia> @time begin
           sleep(0.3)
           1+1
       end
  0.301395 seconds (8 allocations: 336 bytes)
2

source

Base.@timev — Macro.

@timev

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.

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

julia> @timev rand(10^6);
  0.001006 seconds (7 allocations: 7.630 MiB)
elapsed time (ns): 1005567
bytes allocated:   8000256
pool allocs:       6
malloc() calls:    1

source

Base.@timed — Macro.

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

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

julia> val, t, bytes, gctime, memallocs = @timed rand(10^6);

julia> t
0.006634834

julia> bytes
8000256

julia> gctime
0.0055765

julia> fieldnames(typeof(memallocs))
(:allocd, :malloc, :realloc, :poolalloc, :bigalloc, :freecall, :total_time, :pause, :full_sweep)

julia> memallocs.total_time
5576500

source

Base.@elapsed — Macro.

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

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

julia> @elapsed sleep(0.3)
0.301391426

source

Base.@allocated — Macro.

@allocated

A macro to evaluate an expression, discarding the resulting value, instead returning the total number of bytes allocated during evaluation of the expression. Note: the expression is evaluated inside a local function, instead of the current context, in order to eliminate the effects of compilation, however, there still may be some allocations due to JIT compilation. This also makes the results inconsistent with the @time macros, which do not try to adjust for the effects of compilation.

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

julia> @allocated rand(10^6)
8000080

source

Base.EnvDict — Type.

EnvDict() -> EnvDict

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

source

Base.ENV — Constant.

ENV

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

source

Base.Sys.isunix — Function.

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.

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.

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.

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.iswindows — Function.

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.

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.@static — Macro.

@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

版本控制

Base.VersionNumber — Type.

VersionNumber

Version number type which follow the specifications of semantic versioning, composed of major, minor and patch numeric values, followed by pre-release and build alpha-numeric annotations. See also @v_str.

Examples

julia> VersionNumber("1.2.3")
v"1.2.3"

julia> VersionNumber("2.0.1-rc1")
v"2.0.1-rc1"

source

Base.@v_str — Macro.

@v_str

String macro used to parse a string to a VersionNumber.

Examples

julia> v"1.2.3"
v"1.2.3"

julia> v"2.0.1-rc1"
v"2.0.1-rc1"

source

错误

Base.error — Function.

error(message::AbstractString)

Raise an ErrorException with the given message.

source

error(msg...)

Raise an ErrorException with the given message.

source

Core.throw — Function.

throw(e)

Throw an object as an exception.

source

Base.rethrow — Function.

rethrow([e])

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

source

Base.backtrace — Function.

backtrace()

Get a backtrace object for the current program point.

source

Base.catch_backtrace — Function.

catch_backtrace()

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

source

Base.@assert — Macro.

@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

julia> @assert iseven(3) "3 is an odd number!"
ERROR: AssertionError: 3 is an odd number!

julia> @assert isodd(3) "What even are numbers?"

source

Core.ArgumentError — Type.

ArgumentError(msg)

The parameters to a function call do not match a valid signature. Argument msg is a descriptive error string.

source

Core.AssertionError — Type.

AssertionError([msg])

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

Examples

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

AssertionError is usually thrown from @assert.

source

Core.BoundsError — Type.

BoundsError([a],[i])

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

Examples

julia> A = fill(1.0, 7);

julia> A[8]
ERROR: BoundsError: attempt to access 7-element Array{Float64,1} at index [8]
Stacktrace:
 [1] getindex(::Array{Float64,1}, ::Int64) at ./array.jl:660
 [2] top-level scope

julia> B = fill(1.0, (2,3));

julia> B[2, 4]
ERROR: BoundsError: attempt to access 2×3 Array{Float64,2} at index [2, 4]
Stacktrace:
 [1] getindex(::Array{Float64,2}, ::Int64, ::Int64) at ./array.jl:661
 [2] top-level scope

julia> B[9]
ERROR: BoundsError: attempt to access 2×3 Array{Float64,2} at index [9]
Stacktrace:
 [1] getindex(::Array{Float64,2}, ::Int64) at ./array.jl:660
 [2] top-level scope

source

Base.CompositeException — Type.

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.

DimensionMismatch([msg])

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

source

Core.DivideError — Type.

DivideError()

Integer division was attempted with a denominator value of 0.

Examples

julia> 2/0
Inf

julia> div(2, 0)
ERROR: DivideError: integer division error
Stacktrace:
[...]

source

Core.DomainError — Type.

DomainError(val)
DomainError(val, msg)

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

Examples

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

source

Base.EOFError — Type.

EOFError()

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

source

Core.ErrorException — Type.

ErrorException(msg)

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

Example

julia> ex = ErrorException("I've done a bad thing");

julia> ex.msg
"I've done a bad thing"

source

Core.InexactError — Type.

InexactError(name::Symbol, T, val)

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

Examples

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

source

Core.InterruptException — Type.

InterruptException()

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

source

Base.KeyError — Type.

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.

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.

source

Core.MethodError — Type.

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.

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.

OutOfMemoryError()

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

source

Core.ReadOnlyMemoryError — Type.

ReadOnlyMemoryError()

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

source

Core.OverflowError — Type.

OverflowError(msg)

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

source

Core.StackOverflowError — Type.

StackOverflowError()

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

source

Base.SystemError — Type.

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

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

source

Core.TypeError — Type.

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.

UndefKeywordError(var::Symbol)

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

source

Core.UndefRefError — Type.

UndefRefError()

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

source

Core.UndefVarError — Type.

UndefVarError(var::Symbol)

A symbol in the current scope is not defined.

Examples

julia> a
ERROR: UndefVarError: a not defined

julia> a = 1;

julia> a
1

source

Base.StringIndexError — Type.

StringIndexError(str, i)

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

source

Core.InitError — Type.

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.

retry(f::Function;  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.

Examples

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

source

Base.ExponentialBackOff — Type.

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

事件

Base.Timer — Method.

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

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

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 timer is only triggered once. The function callback is called with a single argument, the timer itself. When the timer is closed (by close waiting tasks are woken with an error. Use isopen to check whether a timer is still active.

Examples

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

julia> begin
           i = 0
           cb(timer) = (global i += 1; println(i))
           t = Timer(cb, 2, interval = 0.2)
           wait(t)
           sleep(0.5)
           close(t)
       end
1
2
3

source

Base.Timer — Type.

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 delay seconds, and then repeating with the given interval in seconds. 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.

source

Base.AsyncCondition — Type.

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.

source

Base.AsyncCondition — Method.

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

反射

Base.nameof — Method.

nameof(m::Module) -> Symbol

Get the name of a Module as a Symbol.

Examples

julia> nameof(Base.Broadcast)
:Broadcast

source

Base.parentmodule — Function.

parentmodule(m::Module) -> Module

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

Examples

julia> parentmodule(Main)
Main

julia> parentmodule(Base.Broadcast)
Base

source

parentmodule(t::DataType) -> Module

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

Examples

julia> module Foo
           struct Int end
       end
Foo

julia> parentmodule(Int)
Core

julia> parentmodule(Foo.Int)
Foo

source

parentmodule(f::Function) -> Module

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

source

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

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

source

Base.pathof — Method.

pathof(m::Module)

Return the path of 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.moduleroot — Function.

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

Base.@MODULE — Macro.

@__MODULE__ -> Module

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

source

Base.fullname — Function.

fullname(m::Module)

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

Examples

julia> fullname(Base.Iterators)
(:Base, :Iterators)

julia> fullname(Main)
(:Main,)

source

Base.names — Function.

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.

source

Core.nfields — Function.

nfields(x) -> Int

Get the number of fields in the given object.

Examples

julia> a = 1//2;

julia> nfields(a)
2

julia> b = 1
1

julia> nfields(b)
0

julia> ex = ErrorException("I've done a bad thing");

julia> nfields(ex)
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.

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

Determine whether a global is declared const in a given Module.

source

Base.nameof — Method.

nameof(f::Function) -> Symbol

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

source

Base.functionloc — Method.

functionloc(f::Function, types)

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

source

Base.functionloc — Method.

functionloc(m::Method)

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

source

内核

Base.GC.gc — Function.

GC.gc()

Perform garbage collection.

Warning

Excessive use will likely lead to poor performance.

source

Base.GC.enable — Function.

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.

GC.@preserve x1 x2 ... xn expr

Temporarily protect the given objects from being garbage collected, even if they would otherwise be unreferenced.

The last argument is the expression during which the object(s) will be preserved. The previous arguments are the objects to preserve.

source

Base.Meta.lower — Function.

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.

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

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 index of the first character to start parsing. If greedy is true (default), parse will try to consume as much input as it can; otherwise, it will stop as soon as it has parsed a valid expression. Incomplete but otherwise syntactically valid expressions will return Expr(:incomplete, "(error message)"). If raise is true (default), syntax errors other than incomplete expressions will raise an error. If raise is false, parse will return an expression that will raise an error upon evaluation. If depwarn is false, deprecation warnings will be suppressed.

julia> Meta.parse("x = 3, y = 5", 7)
(:(y = 5), 13)

julia> Meta.parse("x = 3, y = 5", 5)
(:((3, y) = 5), 13)

source

Base.Meta.parse — Method.

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.

julia> Meta.parse("x = 3")
:(x = 3)

julia> Meta.parse("x = ")
:($(Expr(:incomplete, "incomplete: premature end of input")))

julia> Meta.parse("1.0.2")
ERROR: Base.Meta.ParseError("invalid numeric constant \"1.0.\"")
Stacktrace:
[...]

julia> Meta.parse("1.0.2"; raise = false)
:($(Expr(:error, "invalid numeric constant \"1.0.\"")))

source

Base.Meta.ParseError — Type.

ParseError(msg)

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

source

Base.macroexpand — Function.

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:

julia> module M
           macro m1()
               42
           end
           macro m2()
               :(@m1())
           end
       end
M

julia> macroexpand(M, :(@m2()), recursive=true)
42

julia> macroexpand(M, :(@m2()), recursive=false)
:(#= REPL[16]:6 =# M.@m1)

source

Base.@macroexpand — Macro.

@macroexpand

Return equivalent expression with all macros removed (expanded).

There are differences between @macroexpand and macroexpand.

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

  • While macroexpand has an explicit module argument, @macroexpand alwaysexpands with respect to the module in which it is called. This is best seen in the following example:

julia> module M
           macro m()
               1
           end
           function f()
               (@macroexpand(@m),
                macroexpand(M, :(@m)),
                macroexpand(Main, :(@m))
               )
           end
       end
M

julia> macro m()
           2
       end
@m (macro with 1 method)

julia> M.f()
(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.

@macroexpand1

Non recursive version of @macroexpand.

source

Base.code_lowered — Function.

code_lowered(f, types; generated = true)

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.

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

source

Base.code_typed — Function.

code_typed(f, types; optimize=true)

Returns an array of type-inferred lowered form (IR) for the methods matching the given generic function and type signature. The keyword argument optimize controls whether additional optimizations, such as inlining, are also applied.

source

Base.precompile — Function.

precompile(f, args::Tuple{Vararg{Any}})

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

source