licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2034
# JuliaZH.jl | |国内镜像 | Stable | Latest | Preview | |:---:|:---:|:---:|:---:|:---:| | 文档 | [![][docs-mirror-img]][docs-mirror-url] | [![][docs-stable-img]][docs-stable-url] | [![][docs-latest-img]][docs-latest-url] | [![][docs-preview-img]][docs-preview-url] | ## 安装 ```julia pkg> add JuliaZH ``` ## 使用 在代码中使用这个包,就能够获得中文版本的文档: ```julia julia> using JuliaZH help?> julia search: JuliaZH 欢迎来到 Julia 1.6.2. 完整的中文手册可以在这里找到 https://docs.juliacn.com/ 更多中文资料和教程,也请关注 Julia 中文社区 https://cn.julialang.org 新手请参考中文 discourse 上的新手指引 https://discourse.juliacn.com/t/topic/159 输入 ?, 然后输入你想要查看帮助文档的函数或者宏名称就可以查看它们的文档。例如 ?cos, 或者 ?@time 然后按回车键即可。 在 REPL 中输入 ENV["REPL_LOCALE"]="" 将恢复英文模式。再次回到中文模式请输入 ENV["REPL_LOCALE"]="zh_CN"。 ``` ## 贡献 我们目前使用 [Transifex](https://www.transifex.com) 作为翻译平台。 翻译工作依靠社区的贡献者来推进,有任何疑问或建议请到[社区论坛文档区](http://discourse.juliacn.com/c/community/document)反馈。若有意参与翻译工作,请参考[翻译指南](http://discourse.juliacn.com/t/topic/277)。 ## 致谢 所有贡献者都可以在[Transifex上的JuliaCN组织](https://www.transifex.com/juliacn/public/)以及[贡献者列表](https://github.com/JuliaCN/JuliaZH.jl/graphs/contributors)中找到,此外也感谢曾经参与 0.3 版本文档的[贡献者们](https://github.com/JuliaCN/julia_zh_cn/graphs/contributors)。 感谢[集智俱乐部](http://swarma.org/)提供的慷慨支持。 ## License 本项目文档部分采用<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a>进行许可,代码部分采用[MIT license](https://github.com/JuliaCN/JuliaZH.jl/blob/master/LICENSE)进行许可。 [docs-mirror-img]: https://img.shields.io/website-up-down-green-red/https/shields.io.svg?label=docs.juliacn.com [docs-mirror-url]: https://docs.juliacn.com [docs-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [docs-stable-url]: https://juliacn.github.io/JuliaZH.jl/stable [docs-latest-img]: https://img.shields.io/badge/docs-latest-blue.svg [docs-latest-url]: https://juliacn.github.io/JuliaZH.jl/latest [docs-preview-img]: https://img.shields.io/badge/Gitlab%20Pages-Preview-brightgreen.svg [docs-preview-url]: https://juliacn.gitlab.io/JuliaZH.jl
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
679
# 中文文档 这里是手册等文字部分的文档源文件,所有文档内容都在 `src` 目录下。目前主要结构是: - `assets`:素材,logo等 - `base`:Base中的文档自动生成脚本 (需要通过doc string替换来实现翻译) - `juliacn`: JuliaZH的开发文档 - `manual`:手册 如果复制新的文件夹进来请保持master分支的目录结构与julia源代码的master分支中的doc目录一致。 ## 本地编译 PDF 首先你需要安装 [latexmk](https://mg.readthedocs.io/latexmk.html) 和相应平台的 LaTeX 编译器XeLaTeX。之后确认已安装 CTex 套装。然后在这个package的根目录下,在命令行中运行 ```sh julia --project=doc doc/make.jl pdf ``` 或者,如果你已经安装了docker,可以执行 ```sh julia --project=doc/ doc/make.jl pdf texplatform=docker ``` 就会在 `doc/build` 中获得 `Julia中文文档.pdf` 文件。 ## 镜像 CI 在 `gh-pages` 与 `pdf` 分支上均存在 `.github/workflows/deploy.yml` 来将改动推送到 国内的镜像服务器上. 它们由 `master` 或者 `release-*` 分支的 Documenter CI 来更新并触发。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3446
# Julia 1.7 中文文档 欢迎来到 Julia 1.7 中文文档([PDF版本](https://docs.juliacn.com/pdf/dev/Julia中文文档.pdf))! 请先阅读 [Julia 1.0 正式发布博文](https://julialang.org/blog/2018/08/one-point-zero-zh_cn) 以获得对这门语言的总体概观。我们推荐刚刚开始学习 Julia 语言的朋友阅读中文社区提供的 [Julia入门指引](https://discourse.juliacn.com/t/topic/159),也推荐你在[中文论坛](https://discourse.juliacn.com)对遇到的问题进行提问。 !!! tip "镜像加速" 使用镜像站来加速下载几乎是每个国内用户都需要了解的事情,关于镜像站的使用说明及汇总可以在 [Julia PkgServer 镜像服务及镜像站索引](https://discourse.juliacn.com/t/topic/2969) 中可以看到。 !!! note "关于中文文档" Julia 语言相关的本地化工作是一个由社区驱动的开源项目 [JuliaZH.jl](https://github.com/JuliaCN/JuliaZH.jl),旨在方便 Julia 的中文用户。我们目前使用 [Transifex](https://www.transifex.com) 作为翻译平台。翻译工作正在进行,有任何疑问或建议请到[社区论坛文档区](https://discourse.juliacn.com/c/community/document)反馈。若有意参与翻译工作,请参考[翻译指南](https://discourse.juliacn.com/t/topic/277)。 ## 鸣谢 ```@raw html <a href="https://swarma.org"> <img src="https://swarma.org/wp-content/uploads/2018/08/logochange_副本2.png" alt="集智俱乐部" width="210"></img> </a> ``` ## [简介](@id man-introduction) 科学计算对性能一直有着最高的需求,但目前各领域的专家却大量使用较慢的动态语言来开展他们的日常工作。 偏爱动态语言有很多很好的理由,因此我们不会舍弃动态的特性。 幸运的是,现代编程语言设计与编译器技术可以大大消除性能折衷(trade-off),并提供有足够生产力的单一环境进行原型设计,而且能高效地部署性能密集型应用程序。 Julia 语言在这其中扮演了这样一个角色:它是一门灵活的动态语言,适合用于科学计算和数值计算,并且性能可与传统的静态类型语言媲美。 由于 Julia 的编译器和其它语言比如 Python 或 R 的解释器有所不同,一开始你可能发现 Julia 的性能并不是很突出。 如果你觉得速度有点慢,我们强烈建议在尝试其他功能前,先读一读文档中的[提高性能的窍门](@ref man-performance-tips)。 在理解了 Julia 的运作方式后,写出和 C 一样快的代码对你而言就是小菜一碟。 Julia 拥有可选类型标注和多重派发这两个特性,同时还拥有很棒的性能。 这些都得归功于使用 [LLVM](https://discourse.juliacn.com/t/topic/4203#llvm) 实现的类型推导和[即时编译(JIT)](https://discourse.juliacn.com/t/topic/4203#just-in-time-compilation)技术。Julia 是一门支持过程式、函数式和面向对象的多范式语言。 它像 R、MATLAB 和 Python 一样简单,在高级数值计算方面有丰富的表现力,并且支持通用编程。 为了实现这个目标,Julia 以数学编程语言(mathematical programming languages)为基础,同时也参考了不少流行的动态语言,例如 [Lisp](https://discourse.juliacn.com/t/topic/4203#lisp)、[Perl](https://discourse.juliacn.com/t/topic/4203#perl)、[Python](https://discourse.juliacn.com/t/topic/4203#python)、[Lua](https://discourse.juliacn.com/t/topic/4203#lua)、和 [Ruby](https://discourse.juliacn.com/t/topic/4203#ruby)。 Julia 与传统动态语言最重要的区别是: * 核心语言很小:标准库是用 Julia 自身写的,包括整数运算这样的基础运算 * 丰富的基础类型:既可用于定义和描述对象,也可用于做可选的类型标注 * 通过[多重派发](https://discourse.juliacn.com/t/topic/4203#multiple-dispatch),可以根据类型的不同,来调用同名函数的不同实现 * 为不同的参数类型,自动生成高效、专用的代码 * 接近 C 语言的性能 尽管人们有时会说动态语言是“无类型的”,但实际上绝对不是这样的:每一个对象都有一个类型,无论它是基础的类型(primitive)还是用户自定义的类型。 大多数的动态语言都缺乏类型声明,这意味着程序员无法告诉编译器值的类型,也就无法显式地讨论类型。 另一方面,在静态语言中,往往必须标注对象的类型。但类型只在编译期才存在,而无法在运行时进行操作和表达。 而在 Julia 中,类型本身是运行时的对象,并可用于向编译器传达信息。 类型系统和多重派发是 Julia 语言最主要的特征,但一般不需要显式地手动标注或使用:函数通过函数名称和不同类型参数的组合进行定义,在调用时会派发到最接近(most specific)的定义上去。这样的编程模型非常适合数学化的编程,尤其是在传统的面向对象派发中,一些函数的第一个变量理论上并不“拥有”这样一个操作时。 在 Julia 中运算符只是函数的一个特殊标记——例如,为用户定义的新类型添加加法运算,你只要为 `+` 函数定义一个新的方法就可以了。 已有的代码就可以无缝接入这个新的类型。 Julia 在设计之初就非常看重性能,再加上它的动态类型推导(可以被可选的类型标注增强),使得 Julia 的计算性能超过了其它的动态语言,甚至能够与静态编译语言竞争。对于大型数值问题,速度一直都是,也一直会是一个重要的关注点:在过去的几十年里,需要处理的数据量很容易与摩尔定律保持同步。 Julia 的目标是创建一个前所未有的集易用、强大、高效于一体的语言。除此之外,Julia 还拥有以下优势: * 采用 [MIT 许可证](https://github.com/JuliaLang/julia/blob/master/LICENSE.md):免费又开源 * 用户自定义类型的速度与兼容性和内建类型一样好 * 无需特意编写向量化的代码:非向量化的代码就很快 * 为并行计算和分布式计算设计 * 轻量级的“绿色”线程:[协程](https://discourse.juliacn.com/t/topic/4203#coroutine) * 低调又牛逼的类型系统 * 优雅、可扩展的类型转换和类型提升 * 对 [Unicode](https://discourse.juliacn.com/t/topic/4203#unicode) 的有效支持,包括但不限于 [UTF-8](https://discourse.juliacn.com/t/topic/4203#utf-8) * 直接调用 C 函数,无需封装或调用特别的 API * 像 Shell 一样强大的管理其他进程的能力 * 像 Lisp 一样的宏和其他元编程工具
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3568
# [数组](@id lib-arrays) ## 构造函数与类型 ```@docs Core.AbstractArray Base.AbstractVector Base.AbstractMatrix Base.AbstractVecOrMat Core.Array Core.Array(::UndefInitializer, ::Any) Core.Array(::Nothing, ::Any) Core.Array(::Missing, ::Any) Core.UndefInitializer Core.undef Base.Vector Base.Vector(::UndefInitializer, ::Any) Base.Vector(::Nothing, ::Any) Base.Vector(::Missing, ::Any) Base.Matrix Base.Matrix(::UndefInitializer, ::Any, ::Any) Base.Matrix(::Nothing, ::Any, ::Any) Base.Matrix(::Missing, ::Any, ::Any) Base.VecOrMat Core.DenseArray Base.DenseVector Base.DenseMatrix Base.DenseVecOrMat Base.StridedArray Base.StridedVector Base.StridedMatrix Base.StridedVecOrMat Base.getindex(::Type, ::Any...) Base.zeros Base.ones Base.BitArray Base.BitArray(::UndefInitializer, ::Integer...) Base.BitArray(::Any) Base.trues Base.falses Base.fill Base.fill! Base.empty Base.similar ``` ## 基础函数 ```@docs Base.ndims Base.size Base.axes(::Any) Base.axes(::AbstractArray, ::Any) Base.length(::AbstractArray) Base.keys(::AbstractArray) Base.eachindex Base.IndexStyle Base.IndexLinear Base.IndexCartesian Base.conj! Base.stride Base.strides ``` ## 广播与矢量化 也可参照 [dot syntax for vectorizing functions](@ref man-vectorized); 例如,`f.(args...)` 隐式调用 `broadcast(f, args...)`。 与其依赖如 `sin` 函数的“已矢量化”方法,你应该使用 `sin.(a)` 来使用`broadcast`来矢量化。 ```@docs Base.broadcast Base.Broadcast.broadcast! Base.@__dot__ ``` 自定义类型的广播,请参照 ```@docs Base.BroadcastStyle Base.Broadcast.AbstractArrayStyle Base.Broadcast.ArrayStyle Base.Broadcast.DefaultArrayStyle Base.Broadcast.broadcastable Base.Broadcast.combine_axes Base.Broadcast.combine_styles Base.Broadcast.result_style ``` ## 索引与赋值 ```@docs Base.getindex(::AbstractArray, ::Any...) Base.setindex!(::AbstractArray, ::Any, ::Any...) Base.copyto!(::AbstractArray, ::CartesianIndices, ::AbstractArray, ::CartesianIndices) Base.copy! Base.isassigned Base.Colon Base.CartesianIndex Base.CartesianIndices Base.Dims Base.LinearIndices Base.to_indices Base.checkbounds Base.checkindex Base.elsize ``` ## Views (SubArrays 以及其它 view 类型) “视图”是一种表现和数组相似的数据结构(它是 `AbstractArray` 的子类型),但是它的底层数据实际上是另一个数组的一部分。 例如,`x` 是一个数组,`v = @view x[1:10]`,则 `v` 表现得就像一个含有 10 个元素的数组,但是它的数据实际上是访问 `x` 的前 10 个元素。对视图的写入,如 `v[3] = 2`,直接写入了底层的数组 `x` (这里是修改 `x[3]`)。 在 Julia 中,像 `x[1:10]` 这样的切片操作会创建一个副本。`@view x[1:10]` 将它变成创建一个视图。 `@views` 宏可以用于整个代码块(如 `@views function foo() .... end` 或 `@views begin ... end`)来将整个代码块中的切片操作变为使用视图。 如[性能建议](@ref man-performance-views)所描述的,有时候使用数据的副本更快,而有时候使用视图会更快。 ```@docs Base.view Base.@view Base.@views Base.parent Base.parentindices Base.selectdim Base.reinterpret Base.reshape Base.dropdims Base.vec Base.SubArray ``` ## 拼接与排列 ```@docs Base.cat Base.vcat Base.hcat Base.hvcat Base.hvncat Base.vect Base.circshift Base.circshift! Base.circcopy! Base.findall(::Any) Base.findall(::Function, ::Any) Base.findfirst(::Any) Base.findfirst(::Function, ::Any) Base.findlast(::Any) Base.findlast(::Function, ::Any) Base.findnext(::Any, ::Integer) Base.findnext(::Function, ::Any, ::Integer) Base.findprev(::Any, ::Integer) Base.findprev(::Function, ::Any, ::Integer) Base.permutedims Base.permutedims! Base.PermutedDimsArray Base.promote_shape ``` ## 数组函数 ```@docs Base.accumulate Base.accumulate! Base.cumprod Base.cumprod! Base.cumsum Base.cumsum! Base.diff Base.repeat Base.rot180 Base.rotl90 Base.rotr90 Base.mapslices Base.eachrow Base.eachcol Base.eachslice ``` ## 组合学 ```@docs Base.invperm Base.isperm Base.permute!(::Any, ::AbstractVector) Base.invpermute! Base.reverse(::AbstractVector; kwargs...) Base.reverseind Base.reverse! ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
7096
# 基本功能 ## 介绍 Julia Base 中包含一系列适用于科学及数值计算的函数和宏,但也可以用于通用编程,其它功能则由 Julia 生态圈中的各种库来提供。函数按主题划分如下: 一些通用的提示: * 可以通过 `Import Module` 导入想要使用的模块,并利用 `Module.fn(x)` 语句来实现对模块内函数的调用。 * 此外,`using Module` 语句会将名为 `Module` 的模块中的所有可调函数引入当前的命名空间。 * 按照约定,名字以感叹号(`!`)结尾的函数会改变其输入参数的内容。 一些函数同时拥有改变参数(例如 `sort!`)和不改变参数(`sort`)的版本 The behaviors of `Base` and standard libraries are stable as defined in [SemVer](https://semver.org/) only if they are documented; i.e., included in the [Julia documentation](https://docs.julialang.org/) and not marked as unstable. See [API FAQ](@ref man-api) for more information. ## Getting Around ```@docs Base.exit Base.atexit Base.isinteractive Base.summarysize Base.require Base.compilecache Base.__precompile__ Base.include Base.MainInclude.include Base.include_string Base.include_dependency Base.which(::Any, ::Any) Base.methods Base.@show ans Base.active_project ``` ## Keywords This is the list of reserved keywords in Julia: `baremodule`, `begin`, `break`, `catch`, `const`, `continue`, `do`, `else`, `elseif`, `end`, `export`, `false`, `finally`, `for`, `function`, `global`, `if`, `import`, `let`, `local`, `macro`, `module`, `quote`, `return`, `struct`, `true`, `try`, `using`, `while`. Those keywords are not allowed to be used as variable names. The following two-word sequences are reserved: `abstract type`, `mutable struct`, `primitive type`. However, you can create variables with names: `abstract`, `mutable`, `primitive` and `type`. Finally: `where` is parsed as an infix operator for writing parametric method and type definitions; `in` and `isa` are parsed as infix operators; and `outer` is parsed as a keyword when used to modify the scope of a variable in an iteration specification of a `for` loop or `generator` expression. Creation of variables named `where`, `in`, `isa` or `outer` is allowed though. ```@docs module export import using baremodule function macro return do begin end let if for while break continue try finally quote local global const struct mutable struct abstract type primitive type where ... ; = ?: ``` ## Standard Modules ```@docs Main Core Base ``` ## Base Submodules ```@docs Base.Broadcast Base.Docs Base.Iterators Base.Libc Base.Meta Base.StackTraces Base.Sys Base.Threads Base.GC ``` ## All Objects ```@docs Core.:(===) Core.isa Base.isequal Base.isless Base.ifelse Core.typeassert Core.typeof Core.tuple Base.ntuple Base.objectid Base.hash Base.finalizer Base.finalize Base.copy Base.deepcopy Base.getproperty Base.setproperty! Base.propertynames Base.hasproperty Core.getfield Core.setfield! Core.isdefined Base.@isdefined Base.convert Base.promote Base.oftype Base.widen Base.identity ``` ## Properties of Types ### Type relations ```@docs Base.supertype Core.Type Core.DataType Core.:(<:) Base.:(>:) Base.typejoin Base.typeintersect Base.promote_type Base.promote_rule Base.promote_typejoin Base.isdispatchtuple ``` ### Declared structure ```@docs Base.ismutable Base.isimmutable Base.isabstracttype Base.isprimitivetype Base.issingletontype Base.isstructtype Base.nameof(::DataType) Base.fieldnames Base.fieldname Base.hasfield ``` ### Memory layout ```@docs Base.sizeof(::Type) Base.isconcretetype Base.isbits Base.isbitstype Core.fieldtype Base.fieldtypes Base.fieldcount Base.fieldoffset Base.datatype_alignment Base.datatype_haspadding Base.datatype_pointerfree ``` ### Special values ```@docs Base.typemin Base.typemax Base.floatmin Base.floatmax Base.maxintfloat Base.eps(::Type{<:AbstractFloat}) Base.eps(::AbstractFloat) Base.instances ``` ## Special Types ```@docs Core.Any Core.Union Union{} Core.UnionAll Core.Tuple Core.NTuple Core.NamedTuple Base.@NamedTuple Base.Val Core.Vararg Core.Nothing Base.isnothing Base.notnothing Base.Some Base.something Base.@something Base.Enums.Enum Base.Enums.@enum Core.Expr Core.Symbol Core.Symbol(x...) Core.Module ``` ## Generic Functions ```@docs Core.Function Base.hasmethod Core.applicable Base.isambiguous Core.invoke Base.@invoke Base.invokelatest Base.@invokelatest new Base.:(|>) Base.:(∘) Base.ComposedFunction Base.splat Base.Fix1 Base.Fix2 ``` ## Syntax ```@docs Core.eval Base.MainInclude.eval Base.@eval Base.evalfile Base.esc Base.@inbounds Base.@boundscheck Base.@propagate_inbounds Base.@inline Base.@noinline Base.@nospecialize Base.@specialize Base.gensym Base.@gensym var"name" Base.@goto Base.@label Base.@simd Base.@polly Base.@generated Base.@pure Base.@deprecate ``` ## Missing Values ```@docs Base.Missing Base.missing Base.coalesce Base.@coalesce Base.ismissing Base.skipmissing Base.nonmissingtype ``` ## System ```@docs Base.run Base.devnull Base.success Base.process_running Base.process_exited Base.kill(::Base.Process, ::Integer) Base.Sys.set_process_title Base.Sys.get_process_title Base.ignorestatus Base.detach Base.Cmd Base.setenv Base.addenv Base.withenv Base.pipeline(::Any, ::Any, ::Any, ::Any...) Base.pipeline(::Base.AbstractCmd) Base.Libc.gethostname Base.Libc.getpid Base.Libc.time() Base.time_ns Base.@time Base.@timev Base.@timed Base.@elapsed Base.@allocated Base.EnvDict Base.ENV Base.Sys.isunix Base.Sys.isapple Base.Sys.islinux Base.Sys.isbsd Base.Sys.isfreebsd Base.Sys.isopenbsd Base.Sys.isnetbsd Base.Sys.isdragonfly Base.Sys.iswindows Base.Sys.windows_version Base.Sys.free_memory Base.Sys.total_memory Base.@static ``` ## Versioning ```@docs Base.VersionNumber Base.@v_str ``` ## Errors ```@docs Base.error Core.throw Base.rethrow Base.backtrace Base.catch_backtrace Base.current_exceptions Base.@assert Base.Experimental.register_error_hint Base.Experimental.show_error_hints Base.ArgumentError Base.AssertionError Core.BoundsError Base.CompositeException Base.DimensionMismatch Core.DivideError Core.DomainError Base.EOFError Core.ErrorException Core.InexactError Core.InterruptException Base.KeyError Base.LoadError Base.MethodError Base.MissingException Core.OutOfMemoryError Core.ReadOnlyMemoryError Core.OverflowError Base.ProcessFailedException Core.StackOverflowError Base.SystemError Core.TypeError Core.UndefKeywordError Core.UndefRefError Core.UndefVarError Base.StringIndexError Base.InitError Base.retry Base.ExponentialBackOff ``` ## Events ```@docs Base.Timer(::Function, ::Real) Base.Timer Base.AsyncCondition Base.AsyncCondition(::Function) ``` ## Reflection ```@docs Base.nameof(::Module) Base.parentmodule Base.pathof(::Module) Base.pkgdir(::Module) Base.moduleroot __module__ __source__ Base.@__MODULE__ Base.@__FILE__ Base.@__DIR__ Base.@__LINE__ Base.fullname Base.names Core.nfields Base.isconst Base.nameof(::Function) Base.functionloc(::Any, ::Any) Base.functionloc(::Method) Base.@locals ``` ## Internals ```@docs Base.GC.gc Base.GC.enable Base.GC.@preserve Base.GC.safepoint Meta.lower Meta.@lower Meta.parse(::AbstractString, ::Int) Meta.parse(::AbstractString) Meta.ParseError Core.QuoteNode Base.macroexpand Base.@macroexpand Base.@macroexpand1 Base.code_lowered Base.code_typed Base.precompile ``` ## Meta ```@docs Meta.quot Meta.isexpr Meta.isidentifier Meta.isoperator Meta.isunaryoperator Meta.isbinaryoperator Meta.show_sexpr ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
921
# C 接口 ```@docs @ccall ccall Core.Intrinsics.cglobal Base.@cfunction Base.CFunction Base.unsafe_convert Base.cconvert Base.unsafe_load Base.unsafe_store! Base.unsafe_copyto!{T}(::Ptr{T}, ::Ptr{T}, ::Any) Base.unsafe_copyto!{T}(::Array{T}, ::Any, ::Array{T}, ::Any, ::Any) Base.copyto! Base.pointer Base.unsafe_wrap{T,N}(::Union{Type{Array},Type{Array{T}},Type{Array{T,N}}}, ::Ptr{T}, ::NTuple{N,Int}) Base.pointer_from_objref Base.unsafe_pointer_to_objref Base.disable_sigint Base.reenable_sigint Base.exit_on_sigint Base.systemerror Base.windowserror Core.Ptr Core.Ref Base.isassigned(::Base.RefValue) Base.Cchar Base.Cuchar Base.Cshort Base.Cstring Base.Cushort Base.Cint Base.Cuint Base.Clong Base.Culong Base.Clonglong Base.Culonglong Base.Cintmax_t Base.Cuintmax_t Base.Csize_t Base.Cssize_t Base.Cptrdiff_t Base.Cwchar_t Base.Cwstring Base.Cfloat Base.Cdouble ``` # LLVM 接口 ```@docs Core.Intrinsics.llvmcall ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4604
# 集合和数据结构 ## [迭代](@id lib-collections-iteration) 序列迭代由 [`iterate`](@ref) 实现 广义的 `for` 循环 ```julia for i in iter # or "for i = iter" # body end ``` 被转换成 ```julia next = iterate(iter) while next !== nothing (i, state) = next # body next = iterate(iter, state) end ``` `state` 对象可以是任何对象,并且对于每个可迭代类型应该选择合适的 `state` 对象。 请参照 [帮助文档接口的迭代小节](@ref man-interface-iteration) 来获取关于定义一个常见迭代类型的更多细节。 ```@docs Base.iterate Base.IteratorSize Base.IteratorEltype ``` 以下类型均完全实现了上述函数: * [`AbstractRange`](@ref) * [`UnitRange`](@ref) * `Tuple` * `Number` * [`AbstractArray`](@ref) * [`BitSet`](@ref) * [`IdDict`](@ref) * [`Dict`](@ref) * [`WeakKeyDict`](@ref) * `EachLine` * `AbstractString` * [`Set`](@ref) * [`Pair`](@ref) * [`NamedTuple`](@ref) ## 构造函数和类型 ```@docs Base.AbstractRange Base.OrdinalRange Base.AbstractUnitRange Base.StepRange Base.UnitRange Base.LinRange ``` ## 通用集合 ```@docs Base.isempty Base.empty! Base.length Base.checked_length ``` 以下类型均完全实现了上述函数: * [`AbstractRange`](@ref) * [`UnitRange`](@ref) * `Tuple` * `Number` * [`AbstractArray`](@ref) * [`BitSet`](@ref) * [`IdDict`](@ref) * [`Dict`](@ref) * [`WeakKeyDict`](@ref) * `AbstractString` * [`Set`](@ref) * [`NamedTuple`](@ref) ## 可迭代集合 ```@docs Base.in Base.:∉ Base.eltype Base.indexin Base.unique Base.unique! Base.allunique Base.reduce(::Any, ::Any) Base.foldl(::Any, ::Any) Base.foldr(::Any, ::Any) Base.maximum Base.maximum! Base.minimum Base.minimum! Base.extrema Base.argmax Base.argmin Base.findmax Base.findmin Base.findmax! Base.findmin! Base.sum Base.sum! Base.prod Base.prod! Base.any(::Any) Base.any(::AbstractArray, ::Any) Base.any! Base.all(::Any) Base.all(::AbstractArray, ::Any) Base.all! Base.count Base.any(::Any, ::Any) Base.all(::Any, ::Any) Base.foreach Base.map Base.map! Base.mapreduce(::Any, ::Any, ::Any) Base.mapfoldl(::Any, ::Any, ::Any) Base.mapfoldr(::Any, ::Any, ::Any) Base.first Base.last Base.front Base.tail Base.step Base.collect(::Any) Base.collect(::Type, ::Any) Base.filter Base.filter! Base.replace(::Any, ::Pair...) Base.replace(::Base.Callable, ::Any) Base.replace! Base.rest ``` ## 可索引集合 ```@docs Base.getindex Base.setindex! Base.firstindex Base.lastindex ``` 以下类型均完全实现了上述函数: * [`Array`](@ref) * [`BitArray`](@ref) * [`AbstractArray`](@ref) * `SubArray` 以下类型仅实现了部分上述函数: * [`AbstractRange`](@ref) * [`UnitRange`](@ref) * `Tuple` * `AbstractString` * [`Dict`](@ref) * [`IdDict`](@ref) * [`WeakKeyDict`](@ref) * [`NamedTuple`](@ref) ## 字典 [`Dict`](@ref) 是一个标准字典。其实现利用了 [`hash`](@ref) 作为键的哈希函数和 [`isequal`](@ref) 来决定是否相等。对于自定义类型,可以定义这两个函数来重载它们在哈希表内的存储方式。 [`IdDict`](@ref) 是一种特殊的哈希表,在里面键始终是对象标识符。 [`WeakKeyDict`](@ref) 是一个哈希表的实现,里面键是对象的弱引用, 所以即使键在哈希表中被引用也有可能被垃圾回收。 它像 `Dict` 一样使用 `hash` 来做哈希和 `isequal` 来做相等判断, 但是它不会在插入时转换键,这点不像 `Dict`。 [`Dict`](@ref)s 可以由传递含有 `=>` 的成对对象给 [`Dict`](@ref) 的构造函数来被创建:`Dict("A"=>1, "B"=>2)`。 这个调用会尝试从键值对中推到类型信息(比如这个例子创造了一个 `Dict{String, Int64}`)。 为了显式指定类型,请使用语法 `Dict{KeyType,ValueType}(...)`。例如:`Dict{String,Int32}("A"=>1, "B"=>2)`。 字典也可以用生成器创建。例如:`Dict(i => f(i) for i = 1:10)`。 对于字典 `D`,若键 `x` 的值存在,则语法 `D[x]` 返回 `x` 的值;否则抛出一个错误。 `D[x] = y` 存储键值对 `x => y` 到 `D` 中,会覆盖键 `x` 的已有的值。 多个参数传入`D[...]` 会被转化成元组; 例如:语法 `D[x,y]` 等于 `D[(x,y)]`,也就是说,它指向键为元组 `(x,y)` 的值。 ```@docs Base.AbstractDict Base.Dict Base.IdDict Base.WeakKeyDict Base.ImmutableDict Base.haskey Base.get Base.get! Base.getkey Base.delete! Base.pop!(::Any, ::Any, ::Any) Base.keys Base.values Base.pairs Base.merge Base.mergewith Base.merge! Base.mergewith! Base.sizehint! Base.keytype Base.valtype ``` 以下类型均完全实现了上述函数: * [`IdDict`](@ref) * [`Dict`](@ref) * [`WeakKeyDict`](@ref) 以下类型仅实现了部分上述函数: * [`BitSet`](@ref) * [`Set`](@ref) * [`EnvDict`](@ref Base.EnvDict) * [`Array`](@ref) * [`BitArray`](@ref) * [`ImmutableDict`](@ref Base.ImmutableDict) * [`Iterators.Pairs`](@ref) ## 类似 Set 的集合 ```@docs Base.AbstractSet Base.Set Base.BitSet Base.union Base.union! Base.intersect Base.setdiff Base.setdiff! Base.symdiff Base.symdiff! Base.intersect! Base.issubset Base.:⊈ Base.:⊊ Base.issetequal Base.isdisjoint ``` 以下类型均完全实现了上述函数: * [`BitSet`](@ref) * [`Set`](@ref) 以下类型仅实现了部分上述函数: * [`Array`](@ref) ## 双端队列 ```@docs Base.push! Base.pop! Base.popat! Base.pushfirst! Base.popfirst! Base.insert! Base.deleteat! Base.keepat! Base.splice! Base.resize! Base.append! Base.prepend! ``` 以下类型均完全实现了上述函数: * `Vector` (a.k.a. 1-dimensional [`Array`](@ref)) * `BitVector` (a.k.a. 1-dimensional [`BitArray`](@ref)) ## 集合相关的实用工具 ```@docs Base.Pair Iterators.Pairs ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
415
# [常量](@id lib-constants) ```@docs Core.nothing Base.PROGRAM_FILE Base.ARGS Base.C_NULL Base.VERSION Base.DEPOT_PATH Base.LOAD_PATH Base.Sys.BINDIR Base.Sys.CPU_THREADS Base.Sys.WORD_SIZE Base.Sys.KERNEL Base.Sys.ARCH Base.Sys.MACHINE ``` 参见: * [`stdin`](@ref) * [`stdout`](@ref) * [`stderr`](@ref) * [`ENV`](@ref) * [`ENDIAN_BOM`](@ref) * `Libc.MS_ASYNC` * `Libc.MS_INVALIDATE` * `Libc.MS_SYNC`
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1503
# 文件系统 ```@docs Base.Filesystem.pwd Base.Filesystem.cd(::AbstractString) Base.Filesystem.cd(::Function) Base.Filesystem.readdir Base.Filesystem.walkdir Base.Filesystem.mkdir Base.Filesystem.mkpath Base.Filesystem.symlink Base.Filesystem.readlink Base.Filesystem.chmod Base.Filesystem.chown Base.RawFD Base.stat Base.Filesystem.lstat Base.Filesystem.ctime Base.Filesystem.mtime Base.Filesystem.filemode Base.Filesystem.filesize Base.Filesystem.uperm Base.Filesystem.gperm Base.Filesystem.operm Base.Filesystem.cp Base.download Base.Filesystem.mv Base.Filesystem.rm Base.Filesystem.touch Base.Filesystem.tempname Base.Filesystem.tempdir Base.Filesystem.mktemp(::AbstractString) Base.Filesystem.mktemp(::Function, ::AbstractString) Base.Filesystem.mktempdir(::AbstractString) Base.Filesystem.mktempdir(::Function, ::AbstractString) Base.Filesystem.isblockdev Base.Filesystem.ischardev Base.Filesystem.isdir Base.Filesystem.isfifo Base.Filesystem.isfile Base.Filesystem.islink Base.Filesystem.ismount Base.Filesystem.ispath Base.Filesystem.issetgid Base.Filesystem.issetuid Base.Filesystem.issocket Base.Filesystem.issticky Base.Filesystem.homedir Base.Filesystem.dirname Base.Filesystem.basename Base.Filesystem.isabspath Base.Filesystem.isdirpath Base.Filesystem.joinpath Base.Filesystem.abspath Base.Filesystem.normpath Base.Filesystem.realpath Base.Filesystem.relpath Base.Filesystem.expanduser Base.Filesystem.splitdir Base.Filesystem.splitdrive Base.Filesystem.splitext Base.Filesystem.splitpath ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3450
# I/O 与网络 ## 通用 I/O ```@docs Base.stdout Base.stderr Base.stdin Base.open Base.IOStream Base.IOBuffer Base.take!(::Base.GenericIOBuffer) Base.fdio Base.flush Base.close Base.write Base.read Base.read! Base.readbytes! Base.unsafe_read Base.unsafe_write Base.readeach Base.peek Base.position Base.seek Base.seekstart Base.seekend Base.skip Base.mark Base.unmark Base.reset Base.ismarked Base.eof Base.isreadonly Base.iswritable Base.isreadable Base.isopen Base.fd Base.redirect_stdio Base.redirect_stdout Base.redirect_stdout(::Function, ::Any) Base.redirect_stderr Base.redirect_stderr(::Function, ::Any) Base.redirect_stdin Base.redirect_stdin(::Function, ::Any) Base.readchomp Base.truncate Base.skipchars Base.countlines Base.PipeBuffer Base.readavailable Base.IOContext Base.IOContext(::IO, ::Pair) Base.IOContext(::IO, ::IOContext) ``` ## 文本 I/O ```@docs Base.show(::IO, ::Any) Base.summary Base.print Base.println Base.printstyled Base.sprint Base.showerror Base.dump Meta.@dump Base.readline Base.readuntil Base.readlines Base.eachline Base.displaysize ``` ## 多媒体 I/O 就像文本输出用 [`print`](@ref) 实现,用户自定义类型可以通过重载 [`show`](@ref) 来指定其文本化表示, Julia 提供了一个应用于富多媒体输出的标准化机制 (例如图片、格式化文本、甚至音频和视频),由以下三部分组成: * 函数 [`display(x)`](@ref) 来请求一个 Julia 对象 `x` 最丰富的多媒体展示,并以纯文本作为后备模式。 * 重载 [`show`](@ref) 允许指定用户自定义类型的任意多媒体表现形式(以标准MIME类型为键值)。 * Multimedia-capable display backends may be registered by subclassing a generic [`AbstractDisplay`](@ref) type 并通过 [`pushdisplay`](@ref) 将其压进显示后端的栈中。 基础 Julia 运行环境只提供纯文本显示, 但是更富的显示可以通过加载外部模块或者使用图形化 Julia 环境 (比如基于 IPython 的 IJulia notebook)来实现。 ```@docs Base.AbstractDisplay Base.Multimedia.display Base.Multimedia.redisplay Base.Multimedia.displayable Base.show(::IO, ::Any, ::Any) Base.Multimedia.showable Base.repr(::MIME, ::Any) Base.MIME Base.@MIME_str ``` 如上面提到的,用户可以定义新的显示后端。 例如,可以在窗口显示 PNG 图片的模块可以在 Julia 中注册这个能力, 以便为有 PNG 表示的类型调用 [`display(x)`](@ref) 时可以在模块窗口中自动显示图片。 In order to define a new display backend, one should first create a subtype `D` of the abstract class [`AbstractDisplay`](@ref). Then, for each MIME type (`mime` string) that can be displayed on `D`, one should define a function `display(d::D, ::MIME"mime", x) = ...` that displays `x` as that MIME type, usually by calling [`show(io, mime, x)`](@ref) or [`repr(io, mime, x)`](@ref). A [`MethodError`](@ref) should be thrown if `x` cannot be displayed as that MIME type; this is automatic if one calls `show` or `repr`. Finally, one should define a function `display(d::D, x)` that queries [`showable(mime, x)`](@ref) for the `mime` types supported by `D` and displays the "best" one; a `MethodError` should be thrown if no supported MIME types are found for `x`. Similarly, some subtypes may wish to override [`redisplay(d::D, ...)`](@ref Base.Multimedia.redisplay). (Again, one should `import Base.display` to add new methods to `display`.) The return values of these functions are up to the implementation (since in some cases it may be useful to return a display "handle" of some type). The display functions for `D` can then be called directly, but they can also be invoked automatically from [`display(x)`](@ref) simply by pushing a new display onto the display-backend stack with: ```@docs Base.Multimedia.pushdisplay Base.Multimedia.popdisplay Base.Multimedia.TextDisplay Base.Multimedia.istextmime ``` ## 网络 I/O ```@docs Base.bytesavailable Base.ntoh Base.hton Base.ltoh Base.htol Base.ENDIAN_BOM ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
470
# 迭代相关 ```@docs Base.Iterators.Stateful Base.Iterators.zip Base.Iterators.enumerate Base.Iterators.rest Base.Iterators.countfrom Base.Iterators.take Base.Iterators.takewhile Base.Iterators.drop Base.Iterators.dropwhile Base.Iterators.cycle Base.Iterators.repeated Base.Iterators.product Base.Iterators.flatten Base.Iterators.partition Base.Iterators.map Base.Iterators.filter Base.Iterators.accumulate Base.Iterators.reverse Base.Iterators.only Base.Iterators.peel ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
310
# C 标准库 ```@docs Base.Libc.malloc Base.Libc.calloc Base.Libc.realloc Base.Libc.free Base.Libc.errno Base.Libc.strerror Base.Libc.GetLastError Base.Libc.FormatMessage Base.Libc.time(::Base.Libc.TmStruct) Base.Libc.strftime Base.Libc.strptime Base.Libc.TmStruct Base.Libc.flush_cstdio Base.Libc.systemsleep ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3658
# 数学相关 ## [数学运算符](@id math-ops) ```@docs Base.:-(::Any) Base.:(+) Base.:-(::Any, ::Any) Base.:*(::Any, ::Any...) Base.:(/) Base.:\(::Any, ::Any) Base.:^(::Number, ::Number) Base.fma Base.muladd Base.inv(::Number) Base.div Base.fld Base.cld Base.mod Base.rem Base.rem2pi Base.Math.mod2pi Base.divrem Base.fldmod Base.fld1 Base.mod1 Base.fldmod1 Base.:(//) Base.rationalize Base.numerator Base.denominator Base.:(<<) Base.:(>>) Base.:(>>>) Base.bitrotate Base.:(:) Base.range Base.OneTo Base.StepRangeLen Base.:(==) Base.:(!=) Base.:(!==) Base.:(<) Base.:(<=) Base.:(>) Base.:(>=) Base.cmp Base.:(~) Base.:(&) Base.:(|) Base.xor Base.nand Base.nor Base.:(!) && || ``` ## 数学函数 ```@docs Base.isapprox Base.sin(::Number) Base.cos(::Number) Base.sincos(::Float64) Base.tan(::Number) Base.Math.sind Base.Math.cosd Base.Math.tand Base.Math.sincosd Base.Math.sinpi Base.Math.cospi Base.Math.sincospi Base.sinh(::Number) Base.cosh(::Number) Base.tanh(::Number) Base.asin(::Number) Base.acos(::Number) Base.atan(::Number) Base.Math.asind Base.Math.acosd Base.Math.atand Base.Math.sec(::Number) Base.Math.csc(::Number) Base.Math.cot(::Number) Base.Math.secd Base.Math.cscd Base.Math.cotd Base.Math.asec(::Number) Base.Math.acsc(::Number) Base.Math.acot(::Number) Base.Math.asecd Base.Math.acscd Base.Math.acotd Base.Math.sech(::Number) Base.Math.csch(::Number) Base.Math.coth(::Number) Base.asinh(::Number) Base.acosh(::Number) Base.atanh(::Number) Base.Math.asech(::Number) Base.Math.acsch(::Number) Base.Math.acoth(::Number) Base.Math.sinc Base.Math.cosc Base.Math.deg2rad Base.Math.rad2deg Base.Math.hypot Base.log(::Number) Base.log(::Number, ::Number) Base.log2 Base.log10 Base.log1p Base.Math.frexp Base.exp(::Float64) Base.exp2 Base.exp10 Base.Math.ldexp Base.Math.modf Base.expm1 Base.round(::Type, ::Any) Base.Rounding.RoundingMode Base.Rounding.RoundNearest Base.Rounding.RoundNearestTiesAway Base.Rounding.RoundNearestTiesUp Base.Rounding.RoundToZero Base.Rounding.RoundFromZero Base.Rounding.RoundUp Base.Rounding.RoundDown Base.round(::Complex{<: AbstractFloat}, ::RoundingMode, ::RoundingMode) Base.ceil Base.floor Base.trunc Base.unsafe_trunc Base.min Base.max Base.minmax Base.Math.clamp Base.Math.clamp! Base.abs Base.Checked.checked_abs Base.Checked.checked_neg Base.Checked.checked_add Base.Checked.checked_sub Base.Checked.checked_mul Base.Checked.checked_div Base.Checked.checked_rem Base.Checked.checked_fld Base.Checked.checked_mod Base.Checked.checked_cld Base.Checked.add_with_overflow Base.Checked.sub_with_overflow Base.Checked.mul_with_overflow Base.abs2 Base.copysign Base.sign Base.signbit Base.flipsign Base.sqrt(::Real) Base.isqrt Base.Math.cbrt Base.real(::Complex) Base.imag Base.reim Base.conj Base.angle Base.cis Base.cispi Base.binomial Base.factorial Base.gcd Base.lcm Base.gcdx Base.ispow2 Base.nextpow Base.prevpow Base.nextprod Base.invmod Base.powermod Base.ndigits Base.add_sum Base.widemul Base.Math.evalpoly Base.Math.@evalpoly Base.FastMath.@fastmath ``` ## 自定义二元运算符 某些 unicode 字符可用于定义新的支持中缀表示法的二元运算符。 例如, ```⊗(x,y) = kron(x,y)``` 定义 `⊗` (otimes) 为 Kronecker 积, 并且可以通过中缀语法将它作为一个二元运算符调用: ```C = A ⊗ B``` 也可以使用常用的前缀语法 ```C = ⊗(A,B)```。 其他支持这种扩展的字符包括 \odot `⊙` 和 \oplus `⊕` The complete list is in the parser code: <https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm> 像 `*` 一样解析的包括(按优先级排列) `* / ÷ % & ⋅ ∘ × |\\| ∩ ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ ⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ ⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛ ⊍ ▷ ⨝ ⟕ ⟖ ⟗` 像 `+` 一样解析的包括 `+ - |\|| ⊕ ⊖ ⊞ ⊟ |++| ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ ⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ ⩛ ⩝ ⩡ ⩢ ⩣` 还有许多其他的与箭头、比较和幂相关的符号。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1616
# [Multi-Threading](@id lib-multithreading) ```@docs Base.Threads.@threads Base.Threads.foreach Base.Threads.@spawn Base.Threads.threadid Base.Threads.nthreads ``` ## 同步 ```@docs Base.Threads.Condition Base.Threads.Event ``` 另见 [同步](@ref lib-task-sync) 。 ## 原子操作 ```@docs Base.@atomic Base.@atomicswap Base.@atomicreplace ``` !!! note The following APIs are fairly primitive, and will likely be exposed through an `unsafe_*`-like wrapper. ``` Core.Intrinsics.atomic_pointerref(pointer::Ptr{T}, order::Symbol) --> T Core.Intrinsics.atomic_pointerset(pointer::Ptr{T}, new::T, order::Symbol) --> pointer Core.Intrinsics.atomic_pointerswap(pointer::Ptr{T}, new::T, order::Symbol) --> old Core.Intrinsics.atomic_pointermodify(pointer::Ptr{T}, function::(old::T,arg::S)->T, arg::S, order::Symbol) --> old Core.Intrinsics.atomic_pointerreplace(pointer::Ptr{T}, expected::Any, new::T, success_order::Symbol, failure_order::Symbol) --> (old, cmp) ``` !!! warning The following APIs are deprecated, though support for them is likely to remain for several releases. ```@docs Base.Threads.Atomic Base.Threads.atomic_cas! Base.Threads.atomic_xchg! Base.Threads.atomic_add! Base.Threads.atomic_sub! Base.Threads.atomic_and! Base.Threads.atomic_nand! Base.Threads.atomic_or! Base.Threads.atomic_xor! Base.Threads.atomic_max! Base.Threads.atomic_min! Base.Threads.atomic_fence ``` ## ccall using a threadpool (Experimental) ```@docs Base.@threadcall ``` ## Low-level synchronization primitives These building blocks are used to create the regular synchronization objects. ```@docs Base.Threads.SpinLock ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2029
# [Numbers](@id lib-numbers) ## 标准数值类型 ### 抽象数值类型 ```@docs Core.Number Core.Real Core.AbstractFloat Core.Integer Core.Signed Core.Unsigned Base.AbstractIrrational ``` ### 具象数值类型 ```@docs Core.Float16 Core.Float32 Core.Float64 Base.BigFloat Core.Bool Core.Int8 Core.UInt8 Core.Int16 Core.UInt16 Core.Int32 Core.UInt32 Core.Int64 Core.UInt64 Core.Int128 Core.UInt128 Base.BigInt Base.Complex Base.Rational Base.Irrational ``` ## 数据格式 ```@docs Base.digits Base.digits! Base.bitstring Base.parse Base.tryparse Base.big Base.signed Base.unsigned Base.float(::Any) Base.Math.significand Base.Math.exponent Base.complex(::Complex) Base.bswap Base.hex2bytes Base.hex2bytes! Base.bytes2hex ``` ## 常用数值函数和常量 ```@docs Base.one Base.oneunit Base.zero Base.im Base.MathConstants.pi Base.MathConstants.ℯ Base.MathConstants.catalan Base.MathConstants.eulergamma Base.MathConstants.golden Base.Inf Base.Inf32 Base.Inf16 Base.NaN Base.NaN32 Base.NaN16 Base.issubnormal Base.isfinite Base.isinf Base.isnan Base.iszero Base.isone Base.nextfloat Base.prevfloat Base.isinteger Base.isreal Core.Float32(::Any) Core.Float64(::Any) Base.Rounding.rounding Base.Rounding.setrounding(::Type, ::Any) Base.Rounding.setrounding(::Function, ::Type, ::RoundingMode) Base.Rounding.get_zero_subnormals Base.Rounding.set_zero_subnormals ``` ### 整型 ```@docs Base.count_ones Base.count_zeros Base.leading_zeros Base.leading_ones Base.trailing_zeros Base.trailing_ones Base.isodd Base.iseven Base.@int128_str Base.@uint128_str ``` ## BigFloats and BigInts The [`BigFloat`](@ref) and [`BigInt`](@ref) types implements arbitrary-precision floating point and integer arithmetic, respectively. For [`BigFloat`](@ref) the [GNU MPFR library](https://www.mpfr.org/) is used, and for [`BigInt`](@ref) the [GNU Multiple Precision Arithmetic Library (GMP)] (https://gmplib.org) is used. ```@docs Base.MPFR.BigFloat(::Any, rounding::RoundingMode) Base.precision Base.MPFR.precision(::Type{BigFloat}) Base.MPFR.setprecision Base.GMP.BigInt(::Any) Base.@big_str ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
855
# Tasks ```@docs Core.Task Base.@task Base.@async Base.asyncmap Base.asyncmap! Base.current_task Base.istaskdone Base.istaskstarted Base.istaskfailed Base.task_local_storage(::Any) Base.task_local_storage(::Any, ::Any) Base.task_local_storage(::Function, ::Any, ::Any) ``` ## Scheduling ```@docs Base.yield Base.yieldto Base.sleep Base.schedule ``` ## [Synchronization](@id lib-task-sync) ```@docs Base.errormonitor Base.@sync Base.wait Base.fetch(t::Task) Base.timedwait Base.Condition Base.notify Base.Semaphore Base.acquire Base.release Base.AbstractLock Base.lock Base.unlock Base.trylock Base.islocked Base.ReentrantLock ``` ## Channels ```@docs Base.Channel Base.Channel(::Function) Base.put!(::Channel, ::Any) Base.take!(::Channel) Base.isready(::Channel) Base.fetch(::Channel) Base.close(::Channel) Base.bind(c::Channel, task::Task) ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
6896
# 运算符与记号 数学符号与函数的扩展文档在 [这里](@ref math-ops). | 符号 | 含义 | |:----------- |:--------------------------------------------------------------------------------------------| | `@` | the at-sign marks a [macro](@ref man-macros) invocation; optionally followed by an argument list | | [`!`](@ref) | 感叹号是一个表示逻辑否定的前缀算符 | | `a!` | 在函数名的末尾,`!` 用作表示函数会修改参数(或多个参数) | | `#` | the number sign (or hash or pound) character begins single line comments | | `#=` | when followed by an equals sign, it begins a multi-line comment (these are nestable) | | `=#` | end a multi-line comment by immediately preceding the number sign with an equals sign | | `$` | the dollar sign is used for [string](@ref string-interpolation) and [expression](@ref man-expression-interpolation) interpolation | | [`%`](@ref rem) | the percent symbol is the remainder operator | | [`^`](@ref) | the caret is the exponentiation operator | | [`&`](@ref) | single ampersand is bitwise and | | [`&&`](@ref)| double ampersands is short-circuiting boolean and | | [`\|`](@ref)| single pipe character is bitwise or | | [`\|\|`](@ref) | double pipe characters is short-circuiting boolean or | | [`⊻`](@ref xor) | the unicode xor character is bitwise exclusive or | | [`~`](@ref) | the tilde is an operator for bitwise not | | `'` | a trailing apostrophe is the [`adjoint`](@ref) (that is, the complex transpose) operator Aᴴ | | [`*`](@ref) | the asterisk is used for multiplication, including matrix multiplication and [string concatenation](@ref man-concatenation) | | [`/`](@ref) | forward slash divides the argument on its left by the one on its right | | [`\`](@ref) | backslash operator divides the argument on its right by the one on its left, commonly used to solve matrix equations | | `()` | parentheses with no arguments constructs an empty [`Tuple`](@ref) | | `(a,...)` | parentheses with comma-separated arguments constructs a tuple containing its arguments | | `(a=1,...)` | parentheses with comma-separated assignments constructs a [`NamedTuple`](@ref) | | `(x;y)` | parentheses can also be used to group one or more semicolon separated expressions | | `a[]` | [array indexing](@ref man-array-indexing) (calling [`getindex`](@ref) or [`setindex!`](@ref)) | | `[,]` | [vector literal constructor](@ref man-array-literals) (calling [`vect`](@ref Base.vect)) | | `[;]` | [vertical concatenation](@ref man-array-concatenation) (calling [`vcat`](@ref) or [`hvcat`](@ref)) | | `[   ]` | with space-separated expressions, [horizontal concatenation](@ref man-concatenation) (calling [`hcat`](@ref) or [`hvcat`](@ref)) | | `T{ }` | curly braces following a type list that type's [parameters](@ref Parametric-Types) | | `{}` | curly braces can also be used to group multiple [`where`](@ref) expressions in function declarations | | `;` | semicolons separate statements, begin a list of keyword arguments in function declarations or calls, or are used to separate array literals for vertical concatenation | | `,` | commas separate function arguments or tuple or array components | | `?` | the question mark delimits the ternary conditional operator (used like: `conditional ? if_true : if_false`) | | `" "` | the single double-quote character delimits [`String`](@ref) literals | | `""" """` | three double-quote characters delimits string literals that may contain `"` and ignore leading indentation | | `' '` | the single-quote character delimits [`Char`](@ref) (that is, character) literals | | ``` ` ` ``` | the backtick character delimits [external process](@ref Running-External-Programs) ([`Cmd`](@ref)) literals | | `A...` | triple periods are a postfix operator that "splat" their arguments' contents into many arguments of a function call or declare a varargs function that "slurps" up many arguments into a single tuple | | `a.b` | single periods access named fields in objects/modules (calling [`getproperty`](@ref Base.getproperty) or [`setproperty!`](@ref Base.setproperty!)) | | `f.()` | periods may also prefix parentheses (like `f.(...)`) or infix operators (like `.+`) to perform the function element-wise (calling [`broadcast`](@ref)) | | `a:b` | colons ([`:`](@ref)) used as a binary infix operator construct a range from `a` to `b` (inclusive) with fixed step size `1` | | `a:s:b` | colons ([`:`](@ref)) used as a ternary infix operator construct a range from `a` to `b` (inclusive) with step size `s` | | `:` | when used by themselves, [`Colon`](@ref)s represent all indices within a dimension, frequently combined with [indexing](@ref man-array-indexing) | | `::` | double-colons represent a type annotation or [`typeassert`](@ref), depending on context, frequently used when declaring function arguments | | `:( )` | quoted expression | | `:a` | [`Symbol`](@ref) a | | [`<:`](@ref)| 子类型运算符 | | [`>:`](@ref)| supertype operator (reverse of subtype operator) | | `=` | single equals sign is [assignment](@ref man-variables) | | [`==`](@ref)| double equals sign is value equality comparison | | [`===`](@ref) | triple equals sign is programmatically identical equality comparison | | [`=>`](@ref Pair) | right arrow using an equals sign defines a [`Pair`](@ref) typically used to populate [dictionaries](@ref Dictionaries) | | `->` | right arrow using a hyphen defines an [anonymous function](@ref man-anonymous-functions) on a single line | | `|>` | pipe operator passes output from the left argument to input of the right argument, usually a [function](@ref Function-composition-and-piping) | | `∘` | function composition operator (typed with \circ{tab}) combines two functions as though they are a single larger [function](@ref Function-composition-and-piping) |
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
738
# SIMD 支持 `VecElement{T}` 类型是为了构建 SIMD 运算符的库。实际使用中要求使用 `llvmcall`。类型按下文定义: ```julia struct VecElement{T} value::T end ``` It has a special compilation rule: a homogeneous tuple of `VecElement{T}` maps to an LLVM `vector` type when `T` is a primitive bits type. 使用 `-O3` 参数时,编译器 *可能* 自动为这样的元组向量化运算符。 例如接下来的程序,使用 `julia -O3` 编译,在x86系统中会生成两个 SIMD 附加指令(`addps`): ```julia const m128 = NTuple{4,VecElement{Float32}} function add(a::m128, b::m128) (VecElement(a[1].value+b[1].value), VecElement(a[2].value+b[2].value), VecElement(a[3].value+b[3].value), VecElement(a[4].value+b[4].value)) end triple(c::m128) = add(add(c,c),c) code_native(triple,(m128,)) ``` 然而,因为无法依靠自动向量化,以后将主要通过使用基于 `llvmcall` 的库来提供 SIMD 支持。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4145
# 排序及相关函数 Julia 拥有为数众多的灵活的 API,用于对已经排序的值数组进行排序和交互。默认情况下,Julia 会选择合理的算法并按标准升序进行排序: ```jldoctest julia> sort([2,3,1]) 3-element Vector{Int64}: 1 2 3 ``` 你同样可以轻松实现逆序排序: ```jldoctest julia> sort([2,3,1], rev=true) 3-element Vector{Int64}: 3 2 1 ``` 对数组进行 in-place 排序时,要使用 `!` 版的排序函数: ```jldoctest julia> a = [2,3,1]; julia> sort!(a); julia> a 3-element Vector{Int64}: 1 2 3 ``` 你可以计算用于排列的索引,而不是直接对数组进行排序: ```julia-repl julia> v = randn(5) 5-element Array{Float64,1}: 0.297288 0.382396 -0.597634 -0.0104452 -0.839027 julia> p = sortperm(v) 5-element Array{Int64,1}: 5 3 4 1 2 julia> v[p] 5-element Array{Float64,1}: -0.839027 -0.597634 -0.0104452 0.297288 0.382396 ``` 数组可以根据对其值任意的转换结果来进行排序; ```julia-repl julia> sort(v, by=abs) 5-element Array{Float64,1}: -0.0104452 0.297288 0.382396 -0.597634 -0.839027 ``` 或者通过转换来进行逆序排序 ```julia-repl julia> sort(v, by=abs, rev=true) 5-element Array{Float64,1}: -0.839027 -0.597634 0.382396 0.297288 -0.0104452 ``` 如有必要,可以选择排序算法: ```julia-repl julia> sort(v, alg=InsertionSort) 5-element Array{Float64,1}: -0.839027 -0.597634 -0.0104452 0.297288 0.382396 ``` 所有与排序和顺序相关的函数依赖于“小于”关系,该关系定义了要操纵的值的总顺序。默认情况下会调用 `isless` 函数,但可以通过 `lt` 关键字指定关系。 ## 排序函数 ```@docs Base.sort! Base.sort Base.sortperm Base.InsertionSort Base.MergeSort Base.QuickSort Base.PartialQuickSort Base.Sort.sortperm! Base.Sort.sortslices ``` ## 排列顺序相关的函数 ```@docs Base.issorted Base.Sort.searchsorted Base.Sort.searchsortedfirst Base.Sort.searchsortedlast Base.Sort.insorted Base.Sort.partialsort! Base.Sort.partialsort Base.Sort.partialsortperm Base.Sort.partialsortperm! ``` ## 排序算法 目前,Julia Base 中有四种可用的排序算法: * [`InsertionSort`](@ref) * [`QuickSort`](@ref) * [`PartialQuickSort(k)`](@ref) * [`MergeSort`](@ref) `InsertionSort` 是一个在 `QuickSort` 中使用的时间复杂度为 O(n^2) 的稳定的排序算法,它通常在 `n` 比较小的时候才具有较高的效率。 `QuickSort` 是一个内置并且非常快,但是不稳定的时间复杂度为 O(n log n)的排序算法,例如即使数组两个元素相等的,它们排序之后的顺序也可能和在原数组中顺序不一致。`QuickSort` 是内置的包括整数和浮点数在内的数字值的默认排序算法。 `PartialQuickSort(k)` 类似于 `QuickSort`,但是如果 `k` 是一个整数,输出数组只排序到索引 `k`,如果 `k` 是 `OrdinalRange`,则输出数组排在 `k` 范围内。 例如: ```julia x = rand(1:500, 100) k = 50 k2 = 50:100 s = sort(x; alg=QuickSort) ps = sort(x; alg=PartialQuickSort(k)) qs = sort(x; alg=PartialQuickSort(k2)) map(issorted, (s, ps, qs)) # => (true, false, false) map(x->issorted(x[1:k]), (s, ps, qs)) # => (true, true, false) map(x->issorted(x[k2]), (s, ps, qs)) # => (true, false, true) s[1:k] == ps[1:k] # => true s[k2] == qs[k2] # => true ``` `MergeSort` 是一个时间复杂度为 O(n log n) 的稳定但是非 in-place 的算法,它需要一个大小为输入数组一般的临时数组——同时也不像 `QuickSort` 一样快。`MergeSort` 是非数值型数据的默认排序算法。 默认排序算法的选择是基于它们的快速稳定,或者 *appear* 之类的。对于数值类型,实际上选择了 `QuickSort`,因为在这种情况下,它更快,与稳定排序没有区别(除非数组以某种方式记录了突变) Julia选择默认排序算法的机制是通过 `Base.Sort.defalg` 来实现的,其允许将特定算法注册为特定数组的所有排序函数中的默认值。例如,这有两个默认算法 [`sort.jl`](https://github.com/JuliaLang/julia/blob/master/base/sort.jl): ```julia defalg(v::AbstractArray) = MergeSort defalg(v::AbstractArray{<:Number}) = QuickSort ``` 对于数值型数组,选择非稳定的默认排序算法的原则是稳定的排序算法没有必要的(例如:但两个值相比较时相等且不可区分时)。 ## Alternate orderings By default, `sort` and related functions use [`isless`](@ref) to compare two elements in order to determine which should come first. The [`Base.Order.Ordering`](@ref) abstract type provides a mechanism for defining alternate orderings on the same set of elements. Instances of `Ordering` define a [total order](https://en.wikipedia.org/wiki/Total_order) on a set of elements, so that for any elements `a`, `b`, `c` the following hold: * Exactly one of the following is true: `a` is less than `b`, `b` is less than `a`, or `a` and `b` are equal (according to [`isequal`](@ref)). * The relation is transitive - if `a` is less than `b` and `b` is less than `c` then `a` is less than `c`. The [`Base.Order.lt`](@ref) function works as a generalization of `isless` to test whether `a` is less than `b` according to a given order. ```@docs Base.Order.Ordering Base.Order.lt Base.Order.ord Base.Order.Forward Base.Order.ReverseOrdering Base.Order.Reverse Base.Order.By Base.Order.Lt Base.Order.Perm ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
246
# 堆栈跟踪 ```@docs Base.StackTraces.StackFrame Base.StackTraces.StackTrace Base.StackTraces.stacktrace ``` `Base.StackTraces` 中以下方法和类型不会被导出,需要显式调用,例如 `StackTraces.lookup(ptr)`。 ```@docs Base.StackTraces.lookup Base.StackTraces.remove_frames! ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1969
# [字符串](@id lib-strings) ```@docs Core.AbstractChar Core.Char Base.codepoint Base.length(::AbstractString) Base.sizeof(::AbstractString) Base.:*(::Union{AbstractChar, AbstractString}, ::Union{AbstractChar, AbstractString}...) Base.:^(::Union{AbstractString, AbstractChar}, ::Integer) Base.string Base.repeat(::AbstractString, ::Integer) Base.repeat(::AbstractChar, ::Integer) Base.repr(::Any) Core.String(::AbstractString) Base.SubString Base.transcode Base.unsafe_string Base.ncodeunits(::AbstractString) Base.codeunit Base.codeunits Base.ascii Base.Regex Base.@r_str Base.SubstitutionString Base.@s_str Base.@raw_str Base.@b_str Base.Docs.@html_str Base.Docs.@text_str Base.isvalid(::Any) Base.isvalid(::Any, ::Any) Base.isvalid(::AbstractString, ::Integer) Base.match Base.eachmatch Base.RegexMatch Base.keys(::RegexMatch) Base.isless(::AbstractString, ::AbstractString) Base.:(==)(::AbstractString, ::AbstractString) Base.cmp(::AbstractString, ::AbstractString) Base.lpad Base.rpad Base.findfirst(::AbstractString, ::AbstractString) Base.findnext(::AbstractString, ::AbstractString, ::Integer) Base.findnext(::AbstractChar, ::AbstractString, ::Integer) Base.findlast(::AbstractString, ::AbstractString) Base.findlast(::AbstractChar, ::AbstractString) Base.findprev(::AbstractString, ::AbstractString, ::Integer) Base.occursin Base.reverse(::Union{String,SubString{String}}) Base.replace(s::AbstractString, ::Pair) Base.split Base.rsplit Base.strip Base.lstrip Base.rstrip Base.startswith Base.endswith Base.contains Base.first(::AbstractString, ::Integer) Base.last(::AbstractString, ::Integer) Base.uppercase Base.lowercase Base.titlecase Base.uppercasefirst Base.lowercasefirst Base.join Base.chop Base.chomp Base.thisind Base.nextind Base.prevind Base.textwidth Base.isascii Base.iscntrl Base.isdigit Base.isletter Base.islowercase Base.isnumeric Base.isprint Base.ispunct Base.isspace Base.isuppercase Base.isxdigit Base.escape_string Base.unescape_string ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
25081
# Julia 的 AST Julia 有两种代码的表现形式。 第一种是解析器返回的表面语法 AST (例如 [`Meta.parse`](@ref) 函数),由宏来操控。是代码编写时的结构化表示,由 `julia-parser.scm` 用字符流构造而成。 另一种则是底层形式,或者 IR(中间表示),这种形式在进行类型推导和代码生成的时候被使用。在这种底层形式中结点的类型相对更少,所有的宏都会被展开,所有的控制流会被转化成显式的分支和语句的序列。底层的形式由 `julia-syntax.scm` 构建。 首先,我们将关注AST,因为需要它来编写宏。 ## 表面语法AST 前端AST几乎由 [`Expr`](@ref) 和原子(例如 符号、数字)。 对于视觉上不同的语法形式,通常有不同的表达式头。 示例将在s-expression 语法中给出。 每个圆括号括着的列表都对应着一个 Expr,其中第一个元素是它的头部。 例如` (call f x) `对应于Julia中的 ` Expr(:call,:f,:x) ` 。 ### 调用 | 输入 | AST | |:---------------- |:---------------------------------- | | `f(x)` | `(call f x)` | | `f(x, y=1, z=2)` | `(call f x (kw y 1) (kw z 2))` | | `f(x; y=1)` | `(call f (parameters (kw y 1)) x)` | | `f(x...)` | `(call f (... x))` | `do` syntax: ```julia f(x) do a,b body end ``` parses as `(do (call f x) (-> (tuple a b) (block body)))`. ### 运算符 Most uses of operators are just function calls, so they are parsed with the head `call`. However some operators are special forms (not necessarily function calls), and in those cases the operator itself is the expression head. In julia-parser.scm these are referred to as "syntactic operators". Some operators (`+` and `*`) use N-ary parsing; chained calls are parsed as a single N-argument call. Finally, chains of comparisons have their own special expression structure. | Input | AST | |:----------- |:------------------------- | | `x+y` | `(call + x y)` | | `a+b+c+d` | `(call + a b c d)` | | `2x` | `(call * 2 x)` | | `a&&b` | `(&& a b)` | | `x += 1` | `(+= x 1)` | | `a ? 1 : 2` | `(if a 1 2)` | | `a:b` | `(: a b)` | | `a:b:c` | `(: a b c)` | | `a,b` | `(tuple a b)` | | `a==b` | `(call == a b)` | | `1<i<=n` | `(comparison 1 < i <= n)` | | `a.b` | `(. a (quote b))` | | `a.(b)` | `(. a (tuple b))` | ### Bracketed forms | Input | AST | |:------------------------ |:------------------------------------------------- | | `a[i]` | `(ref a i)` | | `t[i;j]` | `(typed_vcat t i j)` | | `t[i j]` | `(typed_hcat t i j)` | | `t[a b; c d]` | `(typed_vcat t (row a b) (row c d))` | | `t[a b;;; c d]` | `(typed_ncat t 3 (row a b) (row c d))` | | `a{b}` | `(curly a b)` | | `a{b;c}` | `(curly a (parameters c) b)` | | `[x]` | `(vect x)` | | `[x,y]` | `(vect x y)` | | `[x;y]` | `(vcat x y)` | | `[x y]` | `(hcat x y)` | | `[x y; z t]` | `(vcat (row x y) (row z t))` | | `[x;y;; z;t;;;]` | `(ncat 3 (nrow 2 (nrow 1 x y) (nrow 1 z t)))` | | `[x for y in z, a in b]` | `(comprehension x (= y z) (= a b))` | | `T[x for y in z]` | `(typed_comprehension T x (= y z))` | | `(a, b, c)` | `(tuple a b c)` | | `(a; b; c)` | `(block a (block b c))` | ### Macros | Input | AST | |:------------- |:-------------------------------------------- | | `@m x y` | `(macrocall @m (line) x y)` | | `Base.@m x y` | `(macrocall (. Base (quote @m)) (line) x y)` | | `@Base.m x y` | `(macrocall (. Base (quote @m)) (line) x y)` | ### Strings | Input | AST | |:--------------- |:----------------------------------- | | `"a"` | `"a"` | | `x"y"` | `(macrocall @x_str (line) "y")` | | `x"y"z` | `(macrocall @x_str (line) "y" "z")` | | `"x = $x"` | `(string "x = " x)` | | ``` `a b c` ``` | `(macrocall @cmd (line) "a b c")` | Doc string syntax: ```julia "some docs" f(x) = x ``` parses as `(macrocall (|.| Core '@doc) (line) "some docs" (= (call f x) (block x)))`. ### Imports and such | Input | AST | |:------------------- |:-------------------------------------------- | | `import a` | `(import (. a))` | | `import a.b.c` | `(import (. a b c))` | | `import ...a` | `(import (. . . . a))` | | `import a.b, c.d` | `(import (. a b) (. c d))` | | `import Base: x` | `(import (: (. Base) (. x)))` | | `import Base: x, y` | `(import (: (. Base) (. x) (. y)))` | | `export a, b` | `(export a b)` | `using` has the same representation as `import`, but with expression head `:using` instead of `:import`. ### Numbers Julia supports more number types than many scheme implementations, so not all numbers are represented directly as scheme numbers in the AST. | Input | AST | |:----------------------- |:------------------------------------------------------- | | `11111111111111111111` | `(macrocall @int128_str (null) "11111111111111111111")` | | `0xfffffffffffffffff` | `(macrocall @uint128_str (null) "0xfffffffffffffffff")` | | `1111...many digits...` | `(macrocall @big_str (null) "1111....")` | ### Block forms A block of statements is parsed as `(block stmt1 stmt2 ...)`. If statement: ```julia if a b elseif c d else e end ``` parses as: ``` (if a (block (line 2) b) (elseif (block (line 3) c) (block (line 4) d) (block (line 5 e)))) ``` A `while` loop parses as `(while condition body)`. A `for` loop parses as `(for (= var iter) body)`. If there is more than one iteration specification, they are parsed as a block: `(for (block (= v1 iter1) (= v2 iter2)) body)`. `break` and `continue` are parsed as 0-argument expressions `(break)` and `(continue)`. `let` is parsed as `(let (= var val) body)` or `(let (block (= var1 val1) (= var2 val2) ...) body)`, like `for` loops. A basic function definition is parsed as `(function (call f x) body)`. A more complex example: ```julia function f(x::T; k = 1) where T return x+1 end ``` parses as: ``` (function (where (call f (parameters (kw k 1)) (:: x T)) T) (block (line 2) (return (call + x 1)))) ``` Type definition: ```julia mutable struct Foo{T<:S} x::T end ``` parses as: ``` (struct true (curly Foo (<: T S)) (block (line 2) (:: x T))) ``` The first argument is a boolean telling whether the type is mutable. `try` blocks parse as `(try try_block var catch_block finally_block)`. If no variable is present after `catch`, `var` is `#f`. If there is no `finally` clause, then the last argument is not present. ### Quote expressions Julia source syntax forms for code quoting (`quote` and `:( )`) support interpolation with `$`. In Lisp terminology, this means they are actually "backquote" or "quasiquote" forms. Internally, there is also a need for code quoting without interpolation. In Julia's scheme code, non-interpolating quote is represented with the expression head `inert`. `inert` expressions are converted to Julia `QuoteNode` objects. These objects wrap a single value of any type, and when evaluated simply return that value. A `quote` expression whose argument is an atom also gets converted to a `QuoteNode`. ### Line numbers Source location information is represented as `(line line_num file_name)` where the third component is optional (and omitted when the current line number, but not file name, changes). These expressions are represented as `LineNumberNode`s in Julia. ### Macros Macro hygiene is represented through the expression head pair `escape` and `hygienic-scope`. The result of a macro expansion is automatically wrapped in `(hygienic-scope block module)`, to represent the result of the new scope. The user can insert `(escape block)` inside to interpolate code from the caller. ## Lowered form Lowered form (IR) is more important to the compiler, since it is used for type inference, optimizations like inlining, and code generation. It is also less obvious to the human, since it results from a significant rearrangement of the input syntax. In addition to `Symbol`s and some number types, the following data types exist in lowered form: * `Expr` Has a node type indicated by the `head` field, and an `args` field which is a `Vector{Any}` of subexpressions. While almost every part of a surface AST is represented by an `Expr`, the IR uses only a limited number of `Expr`s, mostly for calls and some top-level-only forms. * `Slot` Identifies arguments and local variables by consecutive numbering. `Slot` is an abstract type with subtypes `SlotNumber` and `TypedSlot`. Both types have an integer-valued `id` field giving the slot index. Most slots have the same type at all uses, and so are represented with `SlotNumber`. The types of these slots are found in the `slottypes` field of their `CodeInfo` object. Slots that require per-use type annotations are represented with `TypedSlot`, which has a `typ` field. * `Argument` The same as `SlotNumber`, but appears only post-optimization. Indicates that the referenced slot is an argument of the enclosing function. * `CodeInfo` Wraps the IR of a group of statements. Its `code` field is an array of expressions to execute. * `GotoNode` Unconditional branch. The argument is the branch target, represented as an index in the code array to jump to. * `GotoIfNot` Conditional branch. If the `cond` field evaluates to false, goes to the index identified by the `dest` field. * `ReturnNode` Returns its argument (the `val` field) as the value of the enclosing function. If the `val` field is undefined, then this represents an unreachable statement. * `QuoteNode` Wraps an arbitrary value to reference as data. For example, the function `f() = :a` contains a `QuoteNode` whose `value` field is the symbol `a`, in order to return the symbol itself instead of evaluating it. * `GlobalRef` Refers to global variable `name` in module `mod`. * `SSAValue` Refers to a consecutively-numbered (starting at 1) static single assignment (SSA) variable inserted by the compiler. The number (`id`) of an `SSAValue` is the code array index of the expression whose value it represents. * `NewvarNode` Marks a point where a variable (slot) is created. This has the effect of resetting a variable to undefined. ### `Expr` types These symbols appear in the `head` field of [`Expr`](@ref)s in lowered form. * `call` Function call (dynamic dispatch). `args[1]` is the function to call, `args[2:end]` are the arguments. * `invoke` Function call (static dispatch). `args[1]` is the MethodInstance to call, `args[2:end]` are the arguments (including the function that is being called, at `args[2]`). * `static_parameter` Reference a static parameter by index. * `=` Assignment. In the IR, the first argument is always a Slot or a GlobalRef. * `method` Adds a method to a generic function and assigns the result if necessary. Has a 1-argument form and a 3-argument form. The 1-argument form arises from the syntax `function foo end`. In the 1-argument form, the argument is a symbol. If this symbol already names a function in the current scope, nothing happens. If the symbol is undefined, a new function is created and assigned to the identifier specified by the symbol. If the symbol is defined but names a non-function, an error is raised. The definition of "names a function" is that the binding is constant, and refers to an object of singleton type. The rationale for this is that an instance of a singleton type uniquely identifies the type to add the method to. When the type has fields, it wouldn't be clear whether the method was being added to the instance or its type. The 3-argument form has the following arguments: * `args[1]` A function name, or `nothing` if unknown or unneeded. If a symbol, then the expression first behaves like the 1-argument form above. This argument is ignored from then on. It can be `nothing` when methods are added strictly by type, `(::T)(x) = x`, or when a method is being added to an existing function, `MyModule.f(x) = x`. * `args[2]` A `SimpleVector` of argument type data. `args[2][1]` is a `SimpleVector` of the argument types, and `args[2][2]` is a `SimpleVector` of type variables corresponding to the method's static parameters. * `args[3]` A `CodeInfo` of the method itself. For "out of scope" method definitions (adding a method to a function that also has methods defined in different scopes) this is an expression that evaluates to a `:lambda` expression. * `struct_type` A 7-argument expression that defines a new `struct`: * `args[1]` The name of the `struct` * `args[2]` A `call` expression that creates a `SimpleVector` specifying its parameters * `args[3]` A `call` expression that creates a `SimpleVector` specifying its fieldnames * `args[4]` A `Symbol`, `GlobalRef`, or `Expr` specifying the supertype (e.g., `:Integer`, `GlobalRef(Core, :Any)`, or `:(Core.apply_type(AbstractArray, T, N))`) * `args[5]` A `call` expression that creates a `SimpleVector` specifying its fieldtypes * `args[6]` A Bool, true if `mutable` * `args[7]` The number of arguments to initialize. This will be the number of fields, or the minimum number of fields called by an inner constructor's `new` statement. * `abstract_type` A 3-argument expression that defines a new abstract type. The arguments are the same as arguments 1, 2, and 4 of `struct_type` expressions. * `primitive_type` A 4-argument expression that defines a new primitive type. Arguments 1, 2, and 4 are the same as `struct_type`. Argument 3 is the number of bits. !!! compat "Julia 1.5" `struct_type`, `abstract_type`, and `primitive_type` were removed in Julia 1.5 and replaced by calls to new builtins. * `global` Declares a global binding. * `const` Declares a (global) variable as constant. * `new` Allocates a new struct-like object. First argument is the type. The [`new`](@ref) pseudo-function is lowered to this, and the type is always inserted by the compiler. This is very much an internal-only feature, and does no checking. Evaluating arbitrary `new` expressions can easily segfault. * `splatnew` Similar to `new`, except field values are passed as a single tuple. Works similarly to `Base.splat(new)` if `new` were a first-class function, hence the name. * `isdefined` `Expr(:isdefined, :x)` returns a Bool indicating whether `x` has already been defined in the current scope. * `the_exception` Yields the caught exception inside a `catch` block, as returned by `jl_current_exception()`. * `enter` Enters an exception handler (`setjmp`). `args[1]` is the label of the catch block to jump to on error. Yields a token which is consumed by `pop_exception`. * `leave` Pop exception handlers. `args[1]` is the number of handlers to pop. * `pop_exception` Pop the stack of current exceptions back to the state at the associated `enter` when leaving a catch block. `args[1]` contains the token from the associated `enter`. !!! compat "Julia 1.1" `pop_exception` is new in Julia 1.1. * `inbounds` Controls turning bounds checks on or off. A stack is maintained; if the first argument of this expression is true or false (`true` means bounds checks are disabled), it is pushed onto the stack. If the first argument is `:pop`, the stack is popped. * `boundscheck` Has the value `false` if inlined into a section of code marked with `@inbounds`, otherwise has the value `true`. * `loopinfo` Marks the end of the a loop. Contains metadata that is passed to `LowerSimdLoop` to either mark the inner loop of `@simd` expression, or to propagate information to LLVM loop passes. * `copyast` Part of the implementation of quasi-quote. The argument is a surface syntax AST that is simply copied recursively and returned at run time. * `meta` Metadata. `args[1]` is typically a symbol specifying the kind of metadata, and the rest of the arguments are free-form. The following kinds of metadata are commonly used: * `:inline` and `:noinline`: Inlining hints. * `foreigncall` Statically-computed container for `ccall` information. The fields are: * `args[1]` : name The expression that'll be parsed for the foreign function. * `args[2]::Type` : RT The (literal) return type, computed statically when the containing method was defined. * `args[3]::SimpleVector` (of Types) : AT The (literal) vector of argument types, computed statically when the containing method was defined. * `args[4]::Int` : nreq The number of required arguments for a varargs function definition. * `args[5]::QuoteNode{Symbol}` : calling convention The calling convention for the call. * `args[6:length(args[3])]` : arguments The values for all the arguments (with types of each given in args[3]). * `args[(length(args[3]) + 1):end]` : gc-roots The additional objects that may need to be gc-rooted for the duration of the call. See [Working with LLVM](@ref Working-with-LLVM) for where these are derived from and how they get handled. ### [Method](@id ast-lowered-method) A unique'd container describing the shared metadata for a single method. * `name`, `module`, `file`, `line`, `sig` Metadata to uniquely identify the method for the computer and the human. * `ambig` Cache of other methods that may be ambiguous with this one. * `specializations` Cache of all MethodInstance ever created for this Method, used to ensure uniqueness. Uniqueness is required for efficiency, especially for incremental precompile and tracking of method invalidation. * `source` The original source code (if available, usually compressed). * `generator` A callable object which can be executed to get specialized source for a specific method signature. * `roots` Pointers to non-AST things that have been interpolated into the AST, required by compression of the AST, type-inference, or the generation of native code. * `nargs`, `isva`, `called`, `isstaged`, `pure` Descriptive bit-fields for the source code of this Method. * `primary_world` The world age that "owns" this Method. ### MethodInstance A unique'd container describing a single callable signature for a Method. See especially [Proper maintenance and care of multi-threading locks](@ref) for important details on how to modify these fields safely. * `specTypes` The primary key for this MethodInstance. Uniqueness is guaranteed through a `def.specializations` lookup. * `def` The `Method` that this function describes a specialization of. Or a `Module`, if this is a top-level Lambda expanded in Module, and which is not part of a Method. * `sparam_vals` The values of the static parameters in `specTypes` indexed by `def.sparam_syms`. For the `MethodInstance` at `Method.unspecialized`, this is the empty `SimpleVector`. But for a runtime `MethodInstance` from the `MethodTable` cache, this will always be defined and indexable. * `uninferred` The uncompressed source code for a toplevel thunk. Additionally, for a generated function, this is one of many places that the source code might be found. * `backedges` We store the reverse-list of cache dependencies for efficient tracking of incremental reanalysis/recompilation work that may be needed after a new method definitions. This works by keeping a list of the other `MethodInstance` that have been inferred or optimized to contain a possible call to this `MethodInstance`. Those optimization results might be stored somewhere in the `cache`, or it might have been the result of something we didn't want to cache, such as constant propagation. Thus we merge all of those backedges to various cache entries here (there's almost always only the one applicable cache entry with a sentinel value for max_world anyways). * `cache` Cache of `CodeInstance` objects that share this template instantiation. ### CodeInstance * `def` The `MethodInstance` that this cache entry is derived from. * `rettype`/`rettype_const` The inferred return type for the `specFunctionObject` field, which (in most cases) is also the computed return type for the function in general. * `inferred` May contain a cache of the inferred source for this function, or it could be set to `nothing` to just indicate `rettype` is inferred. * `ftpr` The generic jlcall entry point. * `jlcall_api` The ABI to use when calling `fptr`. Some significant ones include: * 0 - Not compiled yet * 1 - JL_CALLABLE `jl_value_t *(*)(jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)` * 2 - Constant (value stored in `rettype_const`) * 3 - With Static-parameters forwarded `jl_value_t *(*)(jl_svec_t *sparams, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)` * 4 - Run in interpreter `jl_value_t *(*)(jl_method_instance_t *meth, jl_function_t *f, jl_value_t *args[nargs], uint32_t nargs)` * `min_world` / `max_world` The range of world ages for which this method instance is valid to be called. If max_world is the special token value `-1`, the value is not yet known. It may continue to be used until we encounter a backedge that requires us to reconsider. ### CodeInfo A (usually temporary) container for holding lowered source code. * `code` An `Any` array of statements * `slotnames` An array of symbols giving names for each slot (argument or local variable). * `slotflags` A `UInt8` array of slot properties, represented as bit flags: * 2 - assigned (only false if there are *no* assignment statements with this var on the left) * 8 - const (currently unused for local variables) * 16 - statically assigned once * 32 - might be used before assigned. This flag is only valid after type inference. * `ssavaluetypes` Either an array or an `Int`. If an `Int`, it gives the number of compiler-inserted temporary locations in the function (the length of `code` array). If an array, specifies a type for each location. * `ssaflags` Statement-level flags for each expression in the function. Many of these are reserved, but not yet implemented: * 0 = inbounds * 1,2 = <reserved> inlinehint,always-inline,noinline * 3 = <reserved> strict-ieee (strictfp) * 4-6 = <unused> * 7 = <reserved> has out-of-band info * `linetable` An array of source location objects * `codelocs` An array of integer indices into the `linetable`, giving the location associated with each statement. Optional Fields: * `slottypes` An array of types for the slots. * `rettype` The inferred return type of the lowered form (IR). Default value is `Any`. * `method_for_inference_limit_heuristics` The `method_for_inference_heuristics` will expand the given method's generator if necessary during inference. * `parent` The `MethodInstance` that "owns" this object (if applicable). * `min_world`/`max_world` The range of world ages for which this code was valid at the time when it had been inferred. Boolean properties: * `inferred` Whether this has been produced by type inference. * `inlineable` Whether this should be eligible for inlining. * `propagate_inbounds` Whether this should propagate `@inbounds` when inlined for the purpose of eliding `@boundscheck` blocks. * `pure` Whether this is known to be a pure function of its arguments, without respect to the state of the method caches or other mutable global state.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
5206
# 报告和分析崩溃(段错误) So you managed to break Julia. Congratulations! Collected here are some general procedures you can undergo for common symptoms encountered when something goes awry. Including the information from these debugging steps can greatly help the maintainers when tracking down a segfault or trying to figure out why your script is running slower than expected. If you've been directed to this page, find the symptom that best matches what you're experiencing and follow the instructions to generate the debugging information requested. Table of symptoms: * [Segfaults during bootstrap (`sysimg.jl`)](@ref) * [Segfaults when running a script](@ref) * [Errors during Julia startup](@ref) * [Other generic segfaults or unreachables reached](@ref) ## [Version/Environment info](@id dev-version-info) No matter the error, we will always need to know what version of Julia you are running. When Julia first starts up, a header is printed out with a version number and date. Please also include the output of `versioninfo()` (exported from the [`InteractiveUtils`](@ref InteractiveUtils.versioninfo) standard library) in any report you create: ```@repl using InteractiveUtils versioninfo() ``` ## Segfaults during bootstrap (`sysimg.jl`) Segfaults toward the end of the `make` process of building Julia are a common symptom of something going wrong while Julia is preparsing the corpus of code in the `base/` folder. Many factors can contribute toward this process dying unexpectedly, however it is as often as not due to an error in the C-code portion of Julia, and as such must typically be debugged with a debug build inside of `gdb`. Explicitly: Create a debug build of Julia: ``` $ cd <julia_root> $ make debug ``` Note that this process will likely fail with the same error as a normal `make` incantation, however this will create a debug executable that will offer `gdb` the debugging symbols needed to get accurate backtraces. Next, manually run the bootstrap process inside of `gdb`: ``` $ cd base/ $ gdb -x ../contrib/debug_bootstrap.gdb ``` This will start `gdb`, attempt to run the bootstrap process using the debug build of Julia, and print out a backtrace if (when) it segfaults. You may need to hit `<enter>` a few times to get the full backtrace. Create a [gist](https://gist.github.com) with the backtrace, the [version info](@ref dev-version-info), and any other pertinent information you can think of and open a new [issue](https://github.com/JuliaLang/julia/issues?q=is%3Aopen) on Github with a link to the gist. ## Segfaults when running a script The procedure is very similar to [Segfaults during bootstrap (`sysimg.jl`)](@ref). Create a debug build of Julia, and run your script inside of a debugged Julia process: ``` $ cd <julia_root> $ make debug $ gdb --args usr/bin/julia-debug <path_to_your_script> ``` Note that `gdb` will sit there, waiting for instructions. Type `r` to run the process, and `bt` to generate a backtrace once it segfaults: ``` (gdb) r Starting program: /home/sabae/src/julia/usr/bin/julia-debug ./test.jl ... (gdb) bt ``` Create a [gist](https://gist.github.com) with the backtrace, the [version info](@ref dev-version-info), and any other pertinent information you can think of and open a new [issue](https://github.com/JuliaLang/julia/issues?q=is%3Aopen) on Github with a link to the gist. ## Errors during Julia startup Occasionally errors occur during Julia's startup process (especially when using binary distributions, as opposed to compiling from source) such as the following: ```julia $ julia exec: error -5 ``` These errors typically indicate something is not getting loaded properly very early on in the bootup phase, and our best bet in determining what's going wrong is to use external tools to audit the disk activity of the `julia` process: * On Linux, use `strace`: ``` $ strace julia ``` * On OSX, use `dtruss`: ``` $ dtruss -f julia ``` Create a [gist](https://gist.github.com) with the `strace`/ `dtruss` output, the [version info](@ref dev-version-info), and any other pertinent information and open a new [issue](https://github.com/JuliaLang/julia/issues?q=is%3Aopen) on Github with a link to the gist. ## Other generic segfaults or unreachables reached As mentioned elsewhere, `julia` has good integration with `rr` for generating traces; this includes, on Linux, the ability to automatically run `julia` under `rr` and share the trace after a crash. This can be immensely helpful when debugging such crashes and is strongly encouraged when reporting crash issues to the JuliaLang/julia repo. To run `julia` under `rr` automatically, do: ```julia julia --bug-report=rr ``` To generate the `rr` trace locally, but not share, you can do: ```julia julia --bug-report=rr-local ``` Note that this is only works on Linux. The blog post on [Time Travelling Bug Reporting](https://julialang.org/blog/2020/05/rr/) has many more details. ## Glossary A few terms have been used as shorthand in this guide: * `<julia_root>` refers to the root directory of the Julia source tree; e.g. it should contain folders such as `base`, `deps`, `src`, `test`, etc.....
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3666
# 边界检查 和许多其他现代编程语言一样,Julia 在访问数组元素的时候也要通过边界检查来确保程序安全。当循环次数很多,或者在其他性能敏感的场景下,你可能希望不进行边界检查以提高运行时性能。比如要使用矢量 (SIMD) 指令,循环体就不能有分支语句,因此无法进行边界检查。Julia 提供了一个宏 `@inbounds(...)` 来告诉编译器在指定语句块不进行边界检查。用户自定义的数组类型可以通过宏 `@boundscheck(...)` 来达到上下文敏感的代码选择目的。 ## 移除边界检查 宏 `@boundscheck(...)` 把代码块标记为要执行边界检查。但当这些代码块被被宏 `@inbounds(...)` 标记的代码包裹时,它们可能会被编译器移除。仅当`@boundscheck(...)` 代码块被调用函数包裹时,编译器会移除它们。比如你可能这样写的 `sum` 方法: ```julia function sum(A::AbstractArray) r = zero(eltype(A)) for i in eachindex(A) @inbounds r += A[i] end return r end ``` 使用自定义的类数组类型 `MyArray`,我们有: ```julia @inline getindex(A::MyArray, i::Real) = (@boundscheck checkbounds(A,i); A.data[to_index(i)]) ``` 当 `getindex` 被 `sum` 包裹时,对 `checkbounds(A,i)` 的调用会被忽略。如果存在多层包裹,最多只有一个 `@boundscheck` 被忽略。这个规则用来防止将来代码被改变时潜在的多余忽略。 ## Propagating inbounds There may be certain scenarios where for code-organization reasons you want more than one layer between the `@inbounds` and `@boundscheck` declarations. For instance, the default `getindex` methods have the chain `getindex(A::AbstractArray, i::Real)` calls `getindex(IndexStyle(A), A, i)` calls `_getindex(::IndexLinear, A, i)`. To override the "one layer of inlining" rule, a function may be marked with [`Base.@propagate_inbounds`](@ref) to propagate an inbounds context (or out of bounds context) through one additional layer of inlining. ## The bounds checking call hierarchy The overall hierarchy is: * `checkbounds(A, I...)` which calls * `checkbounds(Bool, A, I...)` which calls * `checkbounds_indices(Bool, axes(A), I)` which recursively calls * `checkindex` for each dimension Here `A` is the array, and `I` contains the "requested" indices. `axes(A)` returns a tuple of "permitted" indices of `A`. `checkbounds(A, I...)` throws an error if the indices are invalid, whereas `checkbounds(Bool, A, I...)` returns `false` in that circumstance. `checkbounds_indices` discards any information about the array other than its `axes` tuple, and performs a pure indices-vs-indices comparison: this allows relatively few compiled methods to serve a huge variety of array types. Indices are specified as tuples, and are usually compared in a 1-1 fashion with individual dimensions handled by calling another important function, `checkindex`: typically, ```julia checkbounds_indices(Bool, (IA1, IA...), (I1, I...)) = checkindex(Bool, IA1, I1) & checkbounds_indices(Bool, IA, I) ``` so `checkindex` checks a single dimension. All of these functions, including the unexported `checkbounds_indices` have docstrings accessible with `?` . If you have to customize bounds checking for a specific array type, you should specialize `checkbounds(Bool, A, I...)`. However, in most cases you should be able to rely on `checkbounds_indices` as long as you supply useful `axes` for your array type. If you have novel index types, first consider specializing `checkindex`, which handles a single index for a particular dimension of an array. If you have a custom multidimensional index type (similar to `CartesianIndex`), then you may have to consider specializing `checkbounds_indices`. Note this hierarchy has been designed to reduce the likelihood of method ambiguities. We try to make `checkbounds` the place to specialize on array type, and try to avoid specializations on index types; conversely, `checkindex` is intended to be specialized only on index type (especially, the last argument). ## Emit bounds checks Julia can be launched with `--check-bounds={yes|no|auto}` to emit bounds checks always, never, or respect @inbounds declarations.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1650
# Calling Conventions Julia uses three calling conventions for four distinct purposes: | Name | Prefix | Purpose | |:------- |:--------- |:-------------------------------- | | Native | `julia_` | Speed via specialized signatures | | JL Call | `jlcall_` | Wrapper for generic calls | | JL Call | `jl_` | Builtins | | C ABI | `jlcapi_` | Wrapper callable from C | ## Julia Native Calling Convention The native calling convention is designed for fast non-generic calls. It usually uses a specialized signature. * LLVM ghosts (zero-length types) are omitted. * LLVM scalars and vectors are passed by value. * LLVM aggregates (arrays and structs) are passed by reference. A small return values is returned as LLVM return values. A large return values is returned via the "structure return" (`sret`) convention, where the caller provides a pointer to a return slot. An argument or return values that is a homogeneous tuple is sometimes represented as an LLVM vector instead of an LLVM array. ## JL Call Convention The JL Call convention is for builtins and generic dispatch. Hand-written functions using this convention are declared via the macro `JL_CALLABLE`. The convention uses exactly 3 parameters: * `F` - Julia representation of function that is being applied * `args` - pointer to array of pointers to boxes * `nargs` - length of the array The return value is a pointer to a box. ## C ABI C ABI wrappers enable calling Julia from C. The wrapper calls a function using the native calling convention. Tuples are always represented as C arrays.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4195
# 笛卡尔 The (non-exported) Cartesian module provides macros that facilitate writing multidimensional algorithms. Most often you can write such algorithms with [straightforward techniques](https://julialang.org/blog/2016/02/iteration); however, there are a few cases where `Base.Cartesian` is still useful or necessary. ## Principles of usage A simple example of usage is: ```julia @nloops 3 i A begin s += @nref 3 A i end ``` which generates the following code: ```julia for i_3 = axes(A, 3) for i_2 = axes(A, 2) for i_1 = axes(A, 1) s += A[i_1, i_2, i_3] end end end ``` In general, Cartesian allows you to write generic code that contains repetitive elements, like the nested loops in this example. Other applications include repeated expressions (e.g., loop unwinding) or creating function calls with variable numbers of arguments without using the "splat" construct (`i...`). ## 基本语法 The (basic) syntax of `@nloops` is as follows: * The first argument must be an integer (*not* a variable) specifying the number of loops. * The second argument is the symbol-prefix used for the iterator variable. Here we used `i`, and variables `i_1, i_2, i_3` were generated. * The third argument specifies the range for each iterator variable. If you use a variable (symbol) here, it's taken as `axes(A, dim)`. More flexibly, you can use the anonymous-function expression syntax described below. * The last argument is the body of the loop. Here, that's what appears between the `begin...end`. There are some additional features of `@nloops` described in the [reference section](@ref dev-cartesian-reference). `@nref` follows a similar pattern, generating `A[i_1,i_2,i_3]` from `@nref 3 A i`. The general practice is to read from left to right, which is why `@nloops` is `@nloops 3 i A expr` (as in `for i_2 = axes(A, 2)`, where `i_2` is to the left and the range is to the right) whereas `@nref` is `@nref 3 A i` (as in `A[i_1,i_2,i_3]`, where the array comes first). If you're developing code with Cartesian, you may find that debugging is easier when you examine the generated code, using `@macroexpand`: ```@meta DocTestSetup = quote import Base.Cartesian: @nref end ``` ```jldoctest julia> @macroexpand @nref 2 A i :(A[i_1, i_2]) ``` ```@meta DocTestSetup = nothing ``` ### Supplying the number of expressions The first argument to both of these macros is the number of expressions, which must be an integer. When you're writing a function that you intend to work in multiple dimensions, this may not be something you want to hard-code. The recommended approach is to use a `@generated function`. Here's an example: ```julia @generated function mysum(A::Array{T,N}) where {T,N} quote s = zero(T) @nloops $N i A begin s += @nref $N A i end s end end ``` Naturally, you can also prepare expressions or perform calculations before the `quote` block. ### Anonymous-function expressions as macro arguments Perhaps the single most powerful feature in `Cartesian` is the ability to supply anonymous-function expressions that get evaluated at parsing time. Let's consider a simple example: ```julia @nexprs 2 j->(i_j = 1) ``` `@nexprs` generates `n` expressions that follow a pattern. This code would generate the following statements: ```julia i_1 = 1 i_2 = 1 ``` In each generated statement, an "isolated" `j` (the variable of the anonymous function) gets replaced by values in the range `1:2`. Generally speaking, Cartesian employs a LaTeX-like syntax. This allows you to do math on the index `j`. Here's an example computing the strides of an array: ```julia s_1 = 1 @nexprs 3 j->(s_{j+1} = s_j * size(A, j)) ``` would generate expressions ```julia s_1 = 1 s_2 = s_1 * size(A, 1) s_3 = s_2 * size(A, 2) s_4 = s_3 * size(A, 3) ``` Anonymous-function expressions have many uses in practice. #### [Macro reference](@id dev-cartesian-reference) ```@docs Base.Cartesian.@nloops Base.Cartesian.@nref Base.Cartesian.@nextract Base.Cartesian.@nexprs Base.Cartesian.@ncall Base.Cartesian.@ntuple Base.Cartesian.@nall Base.Cartesian.@nany Base.Cartesian.@nif ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4755
# 本机代码生成过程的高级概述 ## 指针的表示 When emitting code to an object file, pointers will be emitted as relocations. The deserialization code will ensure any object that pointed to one of these constants gets recreated and contains the right runtime pointer. Otherwise, they will be emitted as literal constants. To emit one of these objects, call `literal_pointer_val`. It'll handle tracking the Julia value and the LLVM global, ensuring they are valid both for the current runtime and after deserialization. When emitted into the object file, these globals are stored as references in a large `gvals` table. This allows the deserializer to reference them by index, and implement a custom manual mechanism similar to a Global Offset Table (GOT) to restore them. Function pointers are handled similarly. They are stored as values in a large `fvals` table. Like globals, this allows the deserializer to reference them by index. Note that `extern` functions are handled separately, with names, via the usual symbol resolution mechanism in the linker. Note too that `ccall` functions are also handled separately, via a manual GOT and Procedure Linkage Table (PLT). ## Representation of Intermediate Values Values are passed around in a `jl_cgval_t` struct. This represents an R-value, and includes enough information to determine how to assign or pass it somewhere. They are created via one of the helper constructors, usually: `mark_julia_type` (for immediate values) and `mark_julia_slot` (for pointers to values). The function `convert_julia_type` can transform between any two types. It returns an R-value with `cgval.typ` set to `typ`. It'll cast the object to the requested representation, making heap boxes, allocating stack copies, and computing tagged unions as needed to change the representation. By contrast `update_julia_type` will change `cgval.typ` to `typ`, only if it can be done at zero-cost (i.e. without emitting any code). ## Union representation Inferred union types may be stack allocated via a tagged type representation. The primitive routines that need to be able to handle tagged unions are: - mark-type - load-local - store-local - isa - is - emit_typeof - emit_sizeof - boxed - unbox - specialized cc-ret Everything else should be possible to handle in inference by using these primitives to implement union-splitting. The representation of the tagged-union is as a pair of `< void* union, byte selector >`. The selector is fixed-size as `byte & 0x7f`, and will union-tag the first 126 isbits. It records the one-based depth-first count into the type-union of the isbits objects inside. An index of zero indicates that the `union*` is actually a tagged heap-allocated `jl_value_t*`, and needs to be treated as normal for a boxed object rather than as a tagged union. The high bit of the selector (`byte & 0x80`) can be tested to determine if the `void*` is actually a heap-allocated (`jl_value_t*`) box, thus avoiding the cost of re-allocating a box, while maintaining the ability to efficiently handle union-splitting based on the low bits. It is guaranteed that `byte & 0x7f` is an exact test for the type, if the value can be represented by a tag – it will never be marked `byte = 0x80`. It is not necessary to also test the type-tag when testing `isa`. The `union*` memory region may be allocated at *any* size. The only constraint is that it is big enough to contain the data currently specified by `selector`. It might not be big enough to contain the union of all types that could be stored there according to the associated Union type field. Use appropriate care when copying. ## Specialized Calling Convention Signature Representation A `jl_returninfo_t` object describes the calling convention details of any callable. If any of the arguments or return type of a method can be represented unboxed, and the method is not varargs, it'll be given an optimized calling convention signature based on its `specTypes` and `rettype` fields. The general principles are that: - Primitive types get passed in int/float registers. - Tuples of VecElement types get passed in vector registers. - Structs get passed on the stack. - Return values are handle similarly to arguments, with a size-cutoff at which they will instead be returned via a hidden sret argument. The total logic for this is implemented by `get_specsig_function` and `deserves_sret`. Additionally, if the return type is a union, it may be returned as a pair of values (a pointer and a tag). If the union values can be stack-allocated, then sufficient space to store them will also be passed as a hidden first argument. It is up to the callee whether the returned pointer will point to this space, a boxed object, or even other constant memory.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
9384
# gdb 调试提示 ## 显示 Julia 变量 在 `gdb` 中, 任何 `jl_value_t*` 类型的变量 `obj` 的展示可以通过使用: ``` (gdb) call jl_(obj) ``` 这个对象会在 `julia` 会话中展示,而不是在 gdb 会话中。这是一种行之有效的方式来发现由 Julia 的 C 代码操控的对象的类型和值。 同样,如果你在调试一些 Julia 内部的东西 (比如 `compiler.jl` ),你可以通过使用这些来打印 `obj` : ```julia ccall(:jl_, Cvoid, (Any,), obj) ``` 这是一种很好的方法,可以避免 Julia 的输出流初始化顺序引起的问题。 Julia的 flisp 解释器使用 `value_t` 对象;能够通过 `call fl_print(fl_ctx, ios_stdout, obj)` 来展示。 ## 有用的用于检查的 Julia 变量 While the addresses of many variables, like singletons, can be useful to print for many failures, there are a number of additional variables (see `julia.h` for a complete list) that are even more useful. * (when in `jl_apply_generic`) `mfunc` and `jl_uncompress_ast(mfunc->def, mfunc->code)` :: for figuring out a bit about the call-stack * `jl_lineno` and `jl_filename` :: for figuring out what line in a test to go start debugging from (or figure out how far into a file has been parsed) * `$1` :: not really a variable, but still a useful shorthand for referring to the result of the last gdb command (such as `print`) * `jl_options` :: sometimes useful, since it lists all of the command line options that were successfully parsed * `jl_uv_stderr` :: because who doesn't like to be able to interact with stdio ## Useful Julia functions for Inspecting those variables * `jl_gdblookup($rip)` :: For looking up the current function and line. (use `$eip` on i686 platforms) * `jlbacktrace()` :: For dumping the current Julia backtrace stack to stderr. Only usable after `record_backtrace()` has been called. * `jl_dump_llvm_value(Value*)` :: For invoking `Value->dump()` in gdb, where it doesn't work natively. For example, `f->linfo->functionObject`, `f->linfo->specFunctionObject`, and `to_function(f->linfo)`. * `Type->dump()` :: only works in lldb. Note: add something like `;1` to prevent lldb from printing its prompt over the output * `jl_eval_string("expr")` :: for invoking side-effects to modify the current state or to lookup symbols * `jl_typeof(jl_value_t*)` :: for extracting the type tag of a Julia value (in gdb, call `macro define jl_typeof jl_typeof` first, or pick something short like `ty` for the first arg to define a shorthand) ## Inserting breakpoints for inspection from gdb In your `gdb` session, set a breakpoint in `jl_breakpoint` like so: ``` (gdb) break jl_breakpoint ``` Then within your Julia code, insert a call to `jl_breakpoint` by adding ```julia ccall(:jl_breakpoint, Cvoid, (Any,), obj) ``` where `obj` can be any variable or tuple you want to be accessible in the breakpoint. It's particularly helpful to back up to the `jl_apply` frame, from which you can display the arguments to a function using, e.g., ``` (gdb) call jl_(args[0]) ``` Another useful frame is `to_function(jl_method_instance_t *li, bool cstyle)`. The `jl_method_instance_t*` argument is a struct with a reference to the final AST sent into the compiler. However, the AST at this point will usually be compressed; to view the AST, call `jl_uncompress_ast` and then pass the result to `jl_`: ``` #2 0x00007ffff7928bf7 in to_function (li=0x2812060, cstyle=false) at codegen.cpp:584 584 abort(); (gdb) p jl_(jl_uncompress_ast(li, li->ast)) ``` ## Inserting breakpoints upon certain conditions ### Loading a particular file Let's say the file is `sysimg.jl`: ``` (gdb) break jl_load if strcmp(fname, "sysimg.jl")==0 ``` ### Calling a particular method ``` (gdb) break jl_apply_generic if strcmp((char*)(jl_symbol_name)(jl_gf_mtable(F)->name), "method_to_break")==0 ``` Since this function is used for every call, you will make everything 1000x slower if you do this. ## Dealing with signals Julia requires a few signal to function property. The profiler uses `SIGUSR2` for sampling and the garbage collector uses `SIGSEGV` for threads synchronization. If you are debugging some code that uses the profiler or multiple threads, you may want to let the debugger ignore these signals since they can be triggered very often during normal operations. The command to do this in GDB is (replace `SIGSEGV` with `SIGUSRS` or other signals you want to ignore): ``` (gdb) handle SIGSEGV noprint nostop pass ``` The corresponding LLDB command is (after the process is started): ``` (lldb) pro hand -p true -s false -n false SIGSEGV ``` If you are debugging a segfault with threaded code, you can set a breakpoint on `jl_critical_error` (`sigdie_handler` should also work on Linux and BSD) in order to only catch the actual segfault rather than the GC synchronization points. ## Debugging during Julia's build process (bootstrap) Errors that occur during `make` need special handling. Julia is built in two stages, constructing `sys0` and `sys.ji`. To see what commands are running at the time of failure, use `make VERBOSE=1`. At the time of this writing, you can debug build errors during the `sys0` phase from the `base` directory using: ``` julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys0 sysimg.jl ``` You might need to delete all the files in `usr/lib/julia/` to get this to work. You can debug the `sys.ji` phase using: ``` julia/base$ gdb --args ../usr/bin/julia-debug -C native --build ../usr/lib/julia/sys -J ../usr/lib/julia/sys0.ji sysimg.jl ``` By default, any errors will cause Julia to exit, even under gdb. To catch an error "in the act", set a breakpoint in `jl_error` (there are several other useful spots, for specific kinds of failures, including: `jl_too_few_args`, `jl_too_many_args`, and `jl_throw`). Once an error is caught, a useful technique is to walk up the stack and examine the function by inspecting the related call to `jl_apply`. To take a real-world example: ``` Breakpoint 1, jl_throw (e=0x7ffdf42de400) at task.c:802 802 { (gdb) p jl_(e) ErrorException("auto_unbox: unable to determine argument type") $2 = void (gdb) bt 10 #0 jl_throw (e=0x7ffdf42de400) at task.c:802 #1 0x00007ffff65412fe in jl_error (str=0x7ffde56be000 <_j_str267> "auto_unbox: unable to determine argument type") at builtins.c:39 #2 0x00007ffde56bd01a in julia_convert_16886 () #3 0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281 ... ``` The most recent `jl_apply` is at frame #3, so we can go back there and look at the AST for the function `julia_convert_16886`. This is the uniqued name for some method of `convert`. `f` in this frame is a `jl_function_t*`, so we can look at the type signature, if any, from the `specTypes` field: ``` (gdb) f 3 #3 0x00007ffff6541154 in jl_apply (f=0x7ffdf367f630, args=0x7fffffffc2b0, nargs=2) at julia.h:1281 1281 return f->fptr((jl_value_t*)f, args, nargs); (gdb) p f->linfo->specTypes $4 = (jl_tupletype_t *) 0x7ffdf39b1030 (gdb) p jl_( f->linfo->specTypes ) Tuple{Type{Float32}, Float64} # <-- type signature for julia_convert_16886 ``` Then, we can look at the AST for this function: ``` (gdb) p jl_( jl_uncompress_ast(f->linfo, f->linfo->ast) ) Expr(:lambda, Array{Any, 1}[:#s29, :x], Array{Any, 1}[Array{Any, 1}[], Array{Any, 1}[Array{Any, 1}[:#s29, :Any, 0], Array{Any, 1}[:x, :Any, 0]], Array{Any, 1}[], 0], Expr(:body, Expr(:line, 90, :float.jl)::Any, Expr(:return, Expr(:call, :box, :Float32, Expr(:call, :fptrunc, :Float32, :x)::Any)::Any)::Any)::Any)::Any ``` Finally, and perhaps most usefully, we can force the function to be recompiled in order to step through the codegen process. To do this, clear the cached `functionObject` from the `jl_lamdbda_info_t*`: ``` (gdb) p f->linfo->functionObject $8 = (void *) 0x1289d070 (gdb) set f->linfo->functionObject = NULL ``` Then, set a breakpoint somewhere useful (e.g. `emit_function`, `emit_expr`, `emit_call`, etc.), and run codegen: ``` (gdb) p jl_compile(f) ... # your breakpoint here ``` ## Debugging precompilation errors Module precompilation spawns a separate Julia process to precompile each module. Setting a breakpoint or catching failures in a precompile worker requires attaching a debugger to the worker. The easiest approach is to set the debugger watch for new process launches matching a given name. For example: ``` (gdb) attach -w -n julia-debug ``` or: ``` (lldb) process attach -w -n julia-debug ``` Then run a script/command to start precompilation. As described earlier, use conditional breakpoints in the parent process to catch specific file-loading events and narrow the debugging window. (some operating systems may require alternative approaches, such as following each `fork` from the parent process) ## Mozilla's Record and Replay Framework (rr) Julia now works out of the box with [rr](http://rr-project.org/), the lightweight recording and deterministic debugging framework from Mozilla. This allows you to replay the trace of an execution deterministically. The replayed execution's address spaces, register contents, syscall data etc are exactly the same in every run. A recent version of rr (3.1.0 or higher) is required. ### Reproducing concurrency bugs with rr rr simulates a single-threaded machine by default. In order to debug concurrent code you can use `rr record --chaos` which will cause rr to simulate between one to eight cores, chosen randomly. You might therefore want to set `JULIA_NUM_THREADS=8` and rerun your code under rr until you have caught your bug.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
11215
# Julia 代码的 eval 学习 Julia 语言如何运行代码的最难的一部分是 学习如何让所有的小部分工作协同工作来执行一段代码。 每个代码块通常会通过许多步骤来执行,在转变为期望的结果之前(但愿如此)。并且你可能不熟悉它们的名称,例如(非特定顺序): flisp,AST,C++,LLVM,`eval`,`typeinf`,`macroexpand`,sysimg(或 system image),启动,变异,解析,执行,即时编译器,解释器解释,装箱,拆箱,内部函数,原始函数 !!! sidebar "Definitions" * REPL REPL 表示 读取-求值-输出-循环(Read-Eval-Print Loop)。 我们管这个命令行环境的简称就叫REPL。 * AST 抽象语法树(Abstract Syntax Tree)是代码结构的数据表现。在这种表现形式下代码被符号化,因此更加方便操作和执行。 ## Julia Execution 整个进程的千里之行如下: 1. 用户打开了 `julia`。 2. The C function `main()` from `cli/loader_exe.c` gets called. This function processes the command line arguments, filling in the `jl_options` struct and setting the variable `ARGS`. It then initializes 在 `ui/repl.c` 中的 C 语言的函数 `main()` 被调用。这个函数处理命令行参数,填充到 `jl_options` 结构图并且设置变了 `ARGS` 。接下来初始化 Julia (通过调用 [`julia_init` in `task.c`](https://github.com/JuliaLang/julia/blob/master/src/task.c) which may load a previously compiled [sysimg](@ref dev-sysimg)). Finally, it passes off control to Julia by calling [`Base._start()`](https://github.com/JuliaLang/julia/blob/master/base/client.jl). 3. When `_start()` takes over control, the subsequent sequence of commands depends on the command line arguments given. For example, if a filename was supplied, it will proceed to execute that file. Otherwise, it will start an interactive REPL. 4. Skipping the details about how the REPL interacts with the user, let's just say the program ends up with a block of code that it wants to run. 5. If the block of code to run is in a file, [`jl_load(char *filename)`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) gets invoked to load the file and [parse](@ref dev-parsing) it. Each fragment of code is then passed to `eval` to execute. 6. Each fragment of code (or AST), is handed off to [`eval()`](@ref) to turn into results. 7. [`eval()`](@ref) takes each code fragment and tries to run it in [`jl_toplevel_eval_flex()`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c). 8. `jl_toplevel_eval_flex()` decides whether the code is a "toplevel" action (such as `using` or `module`), which would be invalid inside a function. If so, it passes off the code to the toplevel interpreter. 9. `jl_toplevel_eval_flex()` then [expands](@ref dev-macro-expansion) the code to eliminate any macros and to "lower" the AST to make it simpler to execute. 10. `jl_toplevel_eval_flex()` then uses some simple heuristics to decide whether to JIT compiler the AST or to interpret it directly. 11. The bulk of the work to interpret code is handled by [`eval` in `interpreter.c`](https://github.com/JuliaLang/julia/blob/master/src/interpreter.c). 12. If instead, the code is compiled, the bulk of the work is handled by `codegen.cpp`. Whenever a Julia function is called for the first time with a given set of argument types, [type inference](@ref dev-type-inference) will be run on that function. This information is used by the [codegen](@ref dev-codegen) step to generate faster code. 13. Eventually, the user quits the REPL, or the end of the program is reached, and the `_start()` method returns. 14. Just before exiting, `main()` calls [`jl_atexit_hook(exit_code)`](https://github.com/JuliaLang/julia/blob/master/src/init.c). This calls `Base._atexit()` (which calls any functions registered to [`atexit()`](@ref) inside Julia). Then it calls [`jl_gc_run_all_finalizers()`](https://github.com/JuliaLang/julia/blob/master/src/gc.c). Finally, it gracefully cleans up all `libuv` handles and waits for them to flush and close. ## [Parsing](@id dev-parsing) The Julia parser is a small lisp program written in femtolisp, the source-code for which is distributed inside Julia in [src/flisp](https://github.com/JuliaLang/julia/tree/master/src/flisp). The interface functions for this are primarily defined in [`jlfrontend.scm`](https://github.com/JuliaLang/julia/blob/master/src/jlfrontend.scm). The code in [`ast.c`](https://github.com/JuliaLang/julia/blob/master/src/ast.c) handles this handoff on the Julia side. The other relevant files at this stage are [`julia-parser.scm`](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm), which handles tokenizing Julia code and turning it into an AST, and [`julia-syntax.scm`](https://github.com/JuliaLang/julia/blob/master/src/julia-syntax.scm), which handles transforming complex AST representations into simpler, "lowered" AST representations which are more suitable for analysis and execution. If you want to test the parser without re-building Julia in its entirety, you can run the frontend on its own as follows: $ cd src $ flisp/flisp > (load "jlfrontend.scm") > (jl-parse-file "<filename>") ## [Macro Expansion](@id dev-macro-expansion) When [`eval()`](@ref) encounters a macro, it expands that AST node before attempting to evaluate the expression. Macro expansion involves a handoff from [`eval()`](@ref) (in Julia), to the parser function `jl_macroexpand()` (written in `flisp`) to the Julia macro itself (written in - what else - Julia) via `fl_invoke_julia_macro()`, and back. Typically, macro expansion is invoked as a first step during a call to [`Meta.lower()`](@ref)/`jl_expand()`, although it can also be invoked directly by a call to [`macroexpand()`](@ref)/`jl_macroexpand()`. ## [Type Inference](@id dev-type-inference) Type inference is implemented in Julia by [`typeinf()` in `compiler/typeinfer.jl`](https://github.com/JuliaLang/julia/blob/master/base/compiler/typeinfer.jl). Type inference is the process of examining a Julia function and determining bounds for the types of each of its variables, as well as bounds on the type of the return value from the function. This enables many future optimizations, such as unboxing of known immutable values, and compile-time hoisting of various run-time operations such as computing field offsets and function pointers. Type inference may also include other steps such as constant propagation and inlining. !!! sidebar "More Definitions" * JIT Just-In-Time Compilation The process of generating native-machine code into memory right when it is needed. * LLVM Low-Level Virtual Machine (a compiler) The Julia JIT compiler is a program/library called libLLVM. Codegen in Julia refers both to the process of taking a Julia AST and turning it into LLVM instructions, and the process of LLVM optimizing that and turning it into native assembly instructions. * C++ The programming language that LLVM is implemented in, which means that codegen is also implemented in this language. The rest of Julia's library is implemented in C, in part because its smaller feature set makes it more usable as a cross-language interface layer. * box This term is used to describe the process of taking a value and allocating a wrapper around the data that is tracked by the garbage collector (gc) and is tagged with the object's type. * unbox The reverse of boxing a value. This operation enables more efficient manipulation of data when the type of that data is fully known at compile-time (through type inference). * generic function A Julia function composed of multiple "methods" that are selected for dynamic dispatch based on the argument type-signature * anonymous function or "method" A Julia function without a name and without type-dispatch capabilities * primitive function A function implemented in C but exposed in Julia as a named function "method" (albeit without generic function dispatch capabilities, similar to a anonymous function) * intrinsic function A low-level operation exposed as a function in Julia. These pseudo-functions implement operations on raw bits such as add and sign extend that cannot be expressed directly in any other way. Since they operate on bits directly, they must be compiled into a function and surrounded by a call to `Core.Intrinsics.box(T, ...)` to reassign type information to the value. ## [JIT Code Generation](@id dev-codegen) Codegen is the process of turning a Julia AST into native machine code. The JIT environment is initialized by an early call to [`jl_init_codegen` in `codegen.cpp`](https://github.com/JuliaLang/julia/blob/master/src/codegen.cpp). On demand, a Julia method is converted into a native function by the function `emit_function(jl_method_instance_t*)`. (note, when using the MCJIT (in LLVM v3.4+), each function must be JIT into a new module.) This function recursively calls `emit_expr()` until the entire function has been emitted. Much of the remaining bulk of this file is devoted to various manual optimizations of specific code patterns. For example, `emit_known_call()` knows how to inline many of the primitive functions (defined in [`builtins.c`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c)) for various combinations of argument types. Other parts of codegen are handled by various helper files: * [`debuginfo.cpp`](https://github.com/JuliaLang/julia/blob/master/src/debuginfo.cpp) Handles backtraces for JIT functions * [`ccall.cpp`](https://github.com/JuliaLang/julia/blob/master/src/ccall.cpp) Handles the ccall and llvmcall FFI, along with various `abi_*.cpp` files * [`intrinsics.cpp`](https://github.com/JuliaLang/julia/blob/master/src/intrinsics.cpp) Handles the emission of various low-level intrinsic functions !!! sidebar "Bootstrapping" The process of creating a new system image is called "bootstrapping". The etymology of this word comes from the phrase "pulling oneself up by the bootstraps", and refers to the idea of starting from a very limited set of available functions and definitions and ending with the creation of a full-featured environment. ## [System Image](@id dev-sysimg) The system image is a precompiled archive of a set of Julia files. The `sys.ji` file distributed with Julia is one such system image, generated by executing the file [`sysimg.jl`](https://github.com/JuliaLang/julia/blob/master/base/sysimg.jl), and serializing the resulting environment (including Types, Functions, Modules, and all other defined values) into a file. Therefore, it contains a frozen version of the `Main`, `Core`, and `Base` modules (and whatever else was in the environment at the end of bootstrapping). This serializer/deserializer is implemented by [`jl_save_system_image`/`jl_restore_system_image` in `staticdata.c`](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c). If there is no sysimg file (`jl_options.image_file == NULL`), this also implies that `--build` was given on the command line, so the final result should be a new sysimg file. During Julia initialization, minimal `Core` and `Main` modules are created. Then a file named `boot.jl` is evaluated from the current directory. Julia then evaluates any file given as a command line argument until it reaches the end. Finally, it saves the resulting environment to a "sysimg" file for use as a starting point for a future Julia run.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
5301
# Julia 函数 本文档将解释函数、方法定义以及方法表是如何工作的。 ## 方法表 Julia 中的每个函数都是泛型函数。泛型函数在概念上是单个函数,但由许多定义或方法组成。泛型函数的方法储存在方法表中。方法表(类型 `MethodTable`)与 `TypeName` 相关。`TypeName` 描述了一系列参数化类型。例如,`Complex{Float32}` 和 `Complex{Float64}` 共享相同的 type name 对象 `Complex`。 Julia 中的所有对象都可能是可调用的,因为每个对象都有类型,而类型又有 `TypeName`。 ## 函数调用 给定调用 `f(x,y)`,会执行以下步骤:首先,用 `typeof(f).name.mt` 访问要使用的方法表。其次,生成一个参数元组类型 `Tuple{typeof(f), typeof(x), typeof(y)}`。请注意,函数本身的类型是第一个元素。这因为该类型可能有参数,所以需要参与派发。这个元组类型会在方法表中查找。 这个派发过程由 `jl_apply_generic` 执行,它有两个参数:一个指向由值 f、x 和 y 组成的数组的指针,以及值的数量(此例中是 3)。 在整个系统中,处理函数和参数列表的 API 有两种:一种单独接收函数和参数,一种接收一个单独的参数结构。在第一种 API 中,「参数」部分*不*包含函数的相关信息,因为它是单独传递的。在第二种 API 中,函数是参数结构的第一个元素。 例如,以下用于执行调用的函数只接收 `args` 指针,因此 args 数组的第一个元素将会是要调用的函数: ```c jl_value_t *jl_apply(jl_value_t **args, uint32_t nargs) ``` 这个用于相同功能的入口点单独接收该函数,因此 `args` 数组中不包含该函数: ```c jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs); ``` ## 添加方法 在上述派发过程中,添加一个新方法在概念上所需的只是(1)一个元组类型,以及(2)方法体的代码。`jl_method_def` 实现了此操作。`jl_first_argument_datatype` 会被调用,用来从第一个参数的类型中提取相关的方法表。这比派发期间的相应过程复杂得多,因为参数元组类型可能是抽象类型。例如,我们可以定义: ```julia (::Union{Foo{Int},Foo{Int8}})(x) = 0 ``` 这是可行的,因为所有可能的匹配方法都属于同一方法表。 ## 创建泛型函数 因为每个对象都是可调用的,所以创建泛型函数不需要特殊的东西。因此,`jl_new_generic_function` 只是创建一个新的 `Function` 的单态类型(大小为 0)并返回它的实例。函数可有一个帮助记忆的「显示名称」,用于调试信息和打印对象。例如,`Base.sin` 的名称为 `sin`。按照约定,所创建*类型*的名称与函数名称相同,带前缀 `#`。所以 `typeof(sin)` 即 `Base.#sin`。 ## 闭包 闭包只是一个可调用对象,其字段名称对应于被捕获的变量。例如,以下代码: ```julia function adder(x) return y->x+y end ``` (大致)降低为: ```julia struct ##1{T} x::T end (_::##1)(y) = _.x + y function adder(x) return ##1(x) end ``` ## 构造函数 构造函数调用只是对类型的调用。`Type` 的方法表包含所有的构造函数定义。`Type` 的所有子类型(`Type`、`UnionAll`、`Union` 和 `DataType`)目前通过特殊的安排方式共享一个方法表。 ## 内置函数 「内置」函数定义在 `Core` 模块中,有: ``` === typeof sizeof <: isa typeassert throw tuple getfield setfield! fieldtype nfields isdefined arrayref arrayset arraysize applicable invoke apply_type _apply _expr svec ``` 这些都是单态对象,其类型为 `Builtin` 的子类型,而或后者为 `Function` 的子类型。它们的用处是在运行时暴露遵循「jlcall」调用约定的入口点。 ```c jl_value_t *(jl_value_t*, jl_value_t**, uint32_t) ``` 内建函数的方法表是空的。相反地,它们具有单独的 catch-all 方法缓存条目(`Tuple{Vararg{Any}}`),其 jlcall fptr 指向正确的函数。这是一种 hack,但效果相当不错。 ## 关键字参数 关键字参数的工作方式是将每个具有关键字参数的方法表与一个特殊的隐藏函数对象相关联。该函数称为「keyword argument sorter」、「keyword sorter」或「kwsorter」,存储在 `MethodTable` 对象的 `kwsorter` 字段中。在 kwsorter 函数的每个定义与通常的方法表中的某个函数具有相同的参数,除了前面还有一个 `NamedTuple` 参数,该参数给出所传递关键字参数的名称和值。kwsorter 的作用是根据名称将关键字参数移到预先要求的位置,并对任何所需的默认值表达式进行求值和替换。其返回结果是一个通常的位置参数列表,接着会被传递给另一个由编译器生成的函数。 理解该过程的最简单方法是查看关键字参数方法的定义的降低方式。代码: ```julia function circle(center, radius; color = black, fill::Bool = true, options...) # draw end ``` 实际上生成*三个*方法定义。第一个方法是一个接收所有参数(包括关键字参数)作为其位置参数的函数,其代码包含该方法体。它有一个自动生成的名称: ```julia function #circle#1(color, fill::Bool, options, circle, center, radius) # draw end ``` 第二个方法是原始 `circle` 函数的普通定义,负责处理没有传递关键字参数的情况: ```julia function circle(center, radius) #circle#1(black, true, pairs(NamedTuple()), circle, center, radius) end ``` 这只是派发到第一个方法,传递默认值。`pairs` 应用于其余的参数组成的具名元组,以提供键值对迭代。请注意,如果方法不接受其余的关键字参数,那么此参数不存在。 最后,kwsorter 定义为: ``` function (::Core.kwftype(typeof(circle)))(kws, circle, center, radius) if haskey(kws, :color) color = kws.color else color = black end # etc. # put remaining kwargs in `options` options = structdiff(kws, NamedTuple{(:color, :fill)}) # if the method doesn't accept rest keywords, throw an error # unless `options` is empty #circle#1(color, fill, pairs(options), circle, center, radius) end ``` 函数 `Core.kwftype(t)` 创建字段 `t.name.mt.kwsorter`(如果它未被创建),并返回该函数的类型。 此设计的特点是不使用关键字参数的调用点不需要特殊处理;这一切的工作方式好像它们根本不是语言的一部分。不使用关键字参数的调用点直接派发到被调用函数的 kwsorter。例如,调用: ```julia circle((0,0), 1.0, color = red; other...) ``` 降低为: ```julia kwfunc(circle)(merge((color = red,), other), circle, (0,0), 1.0) ``` `kwfunc`(也在 `Core` 中)可获取被调用函数的 kwsorter。关键字 splatting 函数(编写为 `other...`)调用具名元组 `merge` 函数。此函数进一步解包了 `other` 的每个*元素*,预期中每个元素包含两个值(一个符号和一个值)。当然,如果所有 splatted 参数都是具名元组,则可使用更高效的实现。请注意,原来的 `circle` 被传递,以处理闭包。 ## [Compiler efficiency issues](@id compiler-efficiency-issues) 为每个函数生成新类型在与 Julia 的「默认专门化所有参数」这一设计理念结合使用时,可能对编译器资源的使用产生严重后果。实际上,此设计的初始实现经历了更长的测试和构造时间、高内存占用以及比基线大近乎 2 倍的系统镜像。在一个幼稚的实现中,该问题非常严重,以至于系统几乎无法使用。需要进行几项重要的优化才能使设计变得可行。 第一个问题是函数值参数的不同值导致函数的过度专门化。许多函数只是将参数「传递」到其它地方,例如,到另一个函数或存储位置。这种函数不需要为每个可能传入的闭包专门化。幸运的是,这种情况很容易区分,只需考虑函数是否*调用*它的某个参数(即,参数出现在某处的「头部位置」)。性能关键的高阶函数,如 `map`,肯定会直接调用它们的参数函数,因此仍然会按预期进行专门化。此优化通过在前端记录 `analyze-variables` 传递期间所调用的参数来实现。当 `cache_method` 看到某个在 `Function` 类型层次结构的参数传递到声明为 `Any` 或 `Function` 的槽时,它的行为就好像应用了 `@nospecialize` 注释一样。这种启发式方法在实践中似乎非常有效。 下一个问题涉及方法缓存哈希表的结构。经验研究表明,绝大多数动态分派调用只涉及一个或两个元素。反过来看,只考虑第一个元素便可解决许多这些情况。(旁白:单派发的支持者根本不会对此感到惊讶。但是,这个观点意味着「多重派发在实践中很容易优化」,因此我们应该使用它,而*不是*「我们应该使用单派发」!)因此,方法缓存使用第一个参数作为其主键。但请注意,这对应于函数调用的元组类型的*第二个*元素(第一个元素是函数本身的类型)。通常,头部位置的类型非常少变化——实际上,大多数函数属于没有参数的单态类型。但是,构造函数不是这种情况,一个方法表便保存了所有类型的构造函数。因此,`Type` 方法表是特殊的,使用元组类型的*第一个*元素而不是第二个。 前端为所有闭包生成类型声明。起初,这通过生成通常的类型声明来实现。但是,这产生了大量的构造函数,这些构造函数全都很简单(只是将所有参数传递给 [`new`](@ref))。因为方法是部分排序的,所以插入所有这些方法是 O(n^2),此外要保留的方法实在太多了。这可通过直接生成 `struct_type` 表达式(绕过默认的构造函数生成)并直接使用 `new` 来创建闭包的实例来优化。这事并不漂亮,但你需要做你该做的。 下个问题是 `@test` 宏,它为每个测试用例生成一个 0 参数闭包。这不是必需的,因为每个用例只需运行一次。因此,`@test` 被改写以展开到一个 try-catch 块中,该块记录测试结果(true、false 或所引发的异常)并对它调用测试套件处理程序。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
12224
# Static analyzer annotations for GC correctness in C code ## Running the analysis The analyzer plugin that drives the anlysis ships with julia. Its source code can be found in `src/clangsa`. Running it requires the clang dependency to be build. Set the `BUILD_LLVM_CLANG` variable in your Make.user in order to build an appropriate version of clang. You may also want to use the prebuilt binaries using the `USE_BINARYBUILDER_LLVM` options. Afterwards, running the analysis over the source tree is as simple as running `make -C src analyzegc`. ## General Overview Since Julia's GC is precise, it needs to maintain correct rooting information for any value that may be referenced at any time GC may occur. These places are known as `safepoints` and in the function local context, we extend this designation to any function call that may recursively end up at a safepoint. In generated code, this is taken care of automatically by the GC root placement pass (see the chapter on GC rooting in the LLVM codegen devdocs). However, in C code, we need to inform the runtime of any GC roots manually. This is done using the following macros: ``` // The value assigned to any slot passed as an argument to these // is rooted for the duration of this GC frame. JL_GC_PUSH{1,...,6}(args...) // The values assigned into the size `n` array `rts` are rooted // for the duration of this GC frame. JL_GC_PUSHARGS(rts, n) // Pop a GC frame JL_GC_POP ``` If these macros are not used where they need to be, or they are used incorrectly, the result is silent memory corruption. As such it is very important that they are placed correctly in all applicable code. As such, we employ static analysis (and in particular the clang static analyzer) to help ensure that these macros are used correctly. The remainder of this document gives an overview of this static analysis and describes the support needed in the julia code base to make things work. ## GC Invariants There is two simple invariants correctness: - All `GC_PUSH` calls need to be followed by an appropriate `GC_POP` (in practice we enforce this at the function level) - If a value was previously not rooted at any safepoint, it may no longer be referenced afterwards Of course the devil is in the details here. In particular to satisfy the second of the above conditions, we need to know: - Which calls are safepoints and which are not - Which values are rooted at any given safepoint and which are not - When is a value referenced For the second point in particular, we need to know which memory locations will be considered rooting at runtime (i.e. values assigned to such locations are rooted). This includes locations explicitly designated as such by passing them to one of the `GC_PUSH` macros, globally rooted locations and values, as well as any location recursively reachable from one of those locations. ## Static Analysis Algorithm The idea itself is very simple, although the implementation is quite a bit more complicated (mainly due to a large number of special cases and intricacies of C and C++). In essence, we keep track of all locations that are rooting, all values that are rootable and any expression (assignments, allocations, etc) affect the rootedness of any rootable values. Then, at any safepoint, we perform a "symbolic GC" and poison any values that are not rooted at said location. If these values are later referenced, we emit an error. The clang static analyzer works by constructing a graph of states and exploring this graph for sources of errors. Several nodes in this graph are generated by the analyzer itself (e.g. for control flow), but the definitions above augment this graph with our own state. The static analyzer is interprocedural and can analyze control flow across function boundaries. However, the static analyzer is not fully recursive and makes heuristic decisions about which calls to explore (additionally some calls are cross-translation unit and invisible to the analyzer). In our case, our definition of correctness requires total information. As such, we need to annotate the prototypes of all function calls with whatever information the analysis required, even if that information would otherwise be available by interprocedural static analysis. Luckily however, we can still use this interprocedural analysis to ensure that the annotations we place on a given function are indeed correct given the implementation of said function. ## The analyzer annotations These annotations are found in src/support/analyzer_annotations.h. The are only active when the analyzer is being used and expand either to nothing (for prototype annotations) or to no-ops (for function like annotations). ### `JL_NOTSAFEPOINT` This is perhaps the most common annotation, and should be placed on any function that is known not to possibly lead to reaching a GC safepoint. In general, it is only safe for such a function to perform arithmetic, memory accesses and calls to functions either annotated `JL_NOTSAFEPOINT` or otherwise known not to be safepoints (e.g. function in the C standard library, which are hardcoded as such in the analyzer) It is valid to keep values unrooted across calls to any function annotated with this attribute: Usage Example: ```c void jl_get_one() JL_NOTSAFEPOINT { return 1; } jl_value_t *example() { jl_value_t *val = jl_alloc_whatever(); // This is valid, even though `val` is unrooted, because // jl_get_one is not a safepoint jl_get_one(); return val; } ``` ### `JL_MAYBE_UNROOTED`/`JL_ROOTS_TEMPORARILY` When `JL_MAYBE_UNROOTED` is annotated as an argument on a function, indicates that said argument may be passed, even if it is not rooted. In the ordinary course of events, the julia ABI guarantees that callers root values before passing them to callees. However, some functions do not follow this ABI and allow values to be passed to them even though they are not rooted. Note however, that this does not automatically imply that said argument will be preserved. The `ROOTS_TEMPORARILY` annotation provides the stronger guarantee that, not only may the value be unrooted when passed, it will also be preserved across any internal safepoints by the callee. Note that `JL_NOTSAFEPOINT` essentially implies `JL_MAYBE_UNROOTED`/`JL_ROOTS_TEMPORARILY`, because the rootedness of an argument is irrelevant if the function contains no safepoints. One additional point to note is that these annotations apply on both the caller and the callee side. On the caller side, they lift rootedness restrictions that are normally required for julia ABI functions. On the callee side, they have the reverse effect of preventing these arguments from being considered implicitly rooted. If either of these annotations is applied to the function as a whole, it applies to all arguments of the function. This should generally only be necessary for varargs functions. Usage example: ```c JL_DLLEXPORT void JL_NORETURN jl_throw(jl_value_t *e JL_MAYBE_UNROOTED); jl_value_t *jl_alloc_error(); void example() { // The return value of the allocation is unrooted. This would normally // be an error, but is allowed because of the above annotation. jl_throw(jl_alloc_error()); } ``` ### `JL_PROPAGATES_ROOT` This annotation is commonly found on accessor functions that return one rootable object stored within another. When annotated on a function argument, it tells the analyzer that the root for that argument also applies to the value returned by the function. Usage Example: ```c jl_value_t *jl_svecref(jl_svec_t *t JL_PROPAGATES_ROOT, size_t i) JL_NOTSAFEPOINT; size_t example(jl_svec_t *svec) { jl_value_t *val = jl_svecref(svec, 1) // This is valid, because, as annotated by the PROPAGATES_ROOT annotation, // jl_svecref propagates the rooted-ness from `svec` to `val` jl_gc_safepoint(); return jl_unbox_long(val); } ``` ### `JL_ROOTING_ARGUMENT`/`JL_ROOTED_ARGUMENT` This is essentially the assignment counterpart to `JL_PROPAGATES_ROOT`. When assigning a value to a field of another value that is already rooted, the assigned value will inherit the root of the value it is assigned into. Usage Example: ```c void jl_svecset(void *t JL_ROOTING_ARGUMENT, size_t i, void *x JL_ROOTED_ARGUMENT) JL_NOTSAFEPOINT size_t example(jl_svec_t *svec) { jl_value_t *val = jl_box_long(10000); jl_svecset(svec, val); // This is valid, because the annotations imply that the // jl_svecset propagates the rooted-ness from `svec` to `val` jl_gc_safepoint(); return jl_unbox_long(val); } ``` ### `JL_GC_DISABLED` This annotation implies that this function is only called with the GC runtime-disabled. Functions of this kind are most often encountered during startup and in the GC code itself. Note that this annotation is checked against the runtime enable/disable calls, so clang will know if you lie. This is not a good way to disable processing of a given function if the GC is not actually disabled (use `ifdef __clang_analyzer__` for that if you must). Usage example: ```c void jl_do_magic() JL_GC_DISABLED { // Wildly allocate here with no regard for roots } void example() { int en = jl_gc_enable(0); jl_do_magic(); jl_gc_enable(en); } ``` ### `JL_REQUIRE_ROOTED_SLOT` This annotation requires the caller to pass in a slot that is rooted (i.e. values assigned to this slot will be rooted). Usage example: ```c void jl_do_processing(jl_value_t **slot JL_REQUIRE_ROOTED_SLOT) { *slot = jl_box_long(1); // Ok, only, because the slot was annotated as rooting jl_gc_safepoint(); } void example() { jl_value_t *slot = NULL; JL_GC_PUSH1(&slot); jl_do_processing(&slot); JL_GC_POP(); } ``` ### `JL_GLOBALLY_ROOTED` This annotation implies that a given value is always globally rooted. It can be applied to global variable declarations, in which case it will apply to the value of those variables (or values if the declaration if for an array), or to functions, in which case it will apply to the return value of such functions (e.g. for functions that always return some private, globally rooted value). Usage example: ``` extern JL_DLLEXPORT jl_datatype_t *jl_any_type JL_GLOBALLY_ROOTED; jl_ast_context_t *jl_ast_ctx(fl_context_t *fl) JL_GLOBALLY_ROOTED; ``` ### `JL_ALWAYS_LEAFTYPE` This annotations is essentially equivalent to `JL_GLOBALLY_ROOTED`, except that is should only be used if those values are globally rooted by virtue of being a leaftype. The rooting of leaftypes is a bit complicated. They are generally rooted through `cache` field of the corresponding `TypeName`, which itself is rooted by the containing module (so they're rooted as long as the containing module is ok) and we can generally assume that leaftypes are rooted where they are used, but we may refine this property in the future, so the separate annotation helps split out the reason for being globally rooted. The analyzer also automatically detects checks for leaftype-ness and will not complain about missing GC roots on these paths. ``` JL_DLLEXPORT jl_value_t *jl_apply_array_type(jl_value_t *type, size_t dim) JL_ALWAYS_LEAFTYPE; ``` ### `JL_GC_PROMISE_ROOTED` This is a function-like annotation. Any value passed to this annotation will be considered rooted for the scope of the current function. It is designed as an escape hatch for analyzer inadequacy or complicated situations. However, it should be used sparingly, in favor of improving the analyzer itself. ``` void example() { jl_value_t *val = jl_alloc_something(); if (some_condition) { // We happen to know for complicated external reasons // that val is rooted under these conditions JL_GC_PROMISE_ROOTED(val); } } ``` ## Completeness of analysis The analyzer only looks at local information. In particular, e.g. in the `PROPAGATES_ROOT` case above, it assumes that such memory is only modified in ways it can see, not in any called functions (unless it happens to decide to consider them in its analysis) and not in any concurrently running threads. As such, it may miss a few problematic cases, though in practice such concurrent modification is fairly rare. Improving the analyzer to handle more such cases may be an interesting topic for future work.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
5485
# 类型推导 ## 类型推导是如何工作的 [Type inference](https://en.wikipedia.org/wiki/Type_inference) refers to the process of deducing the types of later values from the types of input values. Julia's approach to inference has been described in blog posts ([1](https://juliacomputing.com/blog/2016/04/inference-convergence/), [2](https://juliacomputing.com/blog/2017/05/inference-converage2/)). ## 调试 compiler.jl You can start a Julia session, edit `compiler/*.jl` (for example to insert `print` statements), and then replace `Core.Compiler` in your running session by navigating to `base` and executing `include("compiler/compiler.jl")`. This trick typically leads to much faster development than if you rebuild Julia for each change. Alternatively, you can use the [Revise.jl](https://github.com/timholy/Revise.jl) package to track the compiler changes by using the command `Revise.track(Core.Compiler)` at the beginning of your Julia session. As explained in the [Revise documentation](https://timholy.github.io/Revise.jl/stable/), the modifications to the compiler will be reflected when the modified files are saved. A convenient entry point into inference is `typeinf_code`. Here's a demo running inference on `convert(Int, UInt(1))`: ```julia # Get the method atypes = Tuple{Type{Int}, UInt} # argument types mths = methods(convert, atypes) # worth checking that there is only one m = first(mths) # Create variables needed to call `typeinf_code` interp = Core.Compiler.NativeInterpreter() sparams = Core.svec() # this particular method doesn't have type-parameters optimize = true # run all inference optimizations types = Tuple{typeof(convert), atypes.parameters...} # Tuple{typeof(convert), Type{Int}, UInt} Core.Compiler.typeinf_code(interp, m, types, sparams, optimize) ``` If your debugging adventures require a `MethodInstance`, you can look it up by calling `Core.Compiler.specialize_method` using many of the variables above. A `CodeInfo` object may be obtained with ```julia # Returns the CodeInfo object for `convert(Int, ::UInt)`: ci = (@code_typed convert(Int, UInt(1)))[1] ``` ## The inlining algorithm (inline_worthy) Much of the hardest work for inlining runs in `inlining_pass`. However, if your question is "why didn't my function inline?" then you will most likely be interested in `isinlineable` and its primary callee, `inline_worthy`. `isinlineable` handles a number of special cases (e.g., critical functions like `next` and `done`, incorporating a bonus for functions that return tuples, etc.). The main decision-making happens in `inline_worthy`, which returns `true` if the function should be inlined. `inline_worthy` implements a cost-model, where "cheap" functions get inlined; more specifically, we inline functions if their anticipated run-time is not large compared to the time it would take to [issue a call](https://en.wikipedia.org/wiki/Calling_convention) to them if they were not inlined. The cost-model is extremely simple and ignores many important details: for example, all `for` loops are analyzed as if they will be executed once, and the cost of an `if...else...end` includes the summed cost of all branches. It's also worth acknowledging that we currently lack a suite of functions suitable for testing how well the cost model predicts the actual run-time cost, although [BaseBenchmarks](https://github.com/JuliaCI/BaseBenchmarks.jl) provides a great deal of indirect information about the successes and failures of any modification to the inlining algorithm. The foundation of the cost-model is a lookup table, implemented in `add_tfunc` and its callers, that assigns an estimated cost (measured in CPU cycles) to each of Julia's intrinsic functions. These costs are based on [standard ranges for common architectures](http://ithare.com/wp-content/uploads/part101_infographics_v08.png) (see [Agner Fog's analysis](https://www.agner.org/optimize/instruction_tables.pdf) for more detail). We supplement this low-level lookup table with a number of special cases. For example, an `:invoke` expression (a call for which all input and output types were inferred in advance) is assigned a fixed cost (currently 20 cycles). In contrast, a `:call` expression, for functions other than intrinsics/builtins, indicates that the call will require dynamic dispatch, in which case we assign a cost set by `Params.inline_nonleaf_penalty` (currently set at 1000). Note that this is not a "first-principles" estimate of the raw cost of dynamic dispatch, but a mere heuristic indicating that dynamic dispatch is extremely expensive. Each statement gets analyzed for its total cost in a function called `statement_cost`. You can display the cost associated with each statement as follows: ```jldoctest; filter=r"tuple.jl:\d+" julia> Base.print_statement_costs(stdout, map, (typeof(sqrt), Tuple{Int},)) # map(sqrt, (2,)) map(f, t::Tuple{Any}) in Base at tuple.jl:179 0 1 ─ %1 = Base.getfield(_3, 1, true)::Int64 1 │ %2 = Base.sitofp(Float64, %1)::Float64 2 │ %3 = Base.lt_float(%2, 0.0)::Bool 0 └── goto #3 if not %3 0 2 ─ invoke Base.Math.throw_complex_domainerror(:sqrt::Symbol, %2::Float64)::Union{} 0 └── unreachable 20 3 ─ %7 = Base.Math.sqrt_llvm(%2)::Float64 0 └── goto #4 0 4 ─ goto #5 0 5 ─ %10 = Core.tuple(%7)::Tuple{Float64} 0 └── return %10 ``` The line costs are in the left column. This includes the consequences of inlining and other forms of optimization.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
14698
# Julia 运行时的初始化 How does the Julia runtime execute `julia -e 'println("Hello World!")'` ? ## `main()` Execution starts at [`main()` in `cli/loader_exe.c`](https://github.com/JuliaLang/julia/blob/master/cli/loader_exe.c), which calls `jl_load_repl()` in [`cli/loader_lib.c`](https://github.com/JuliaLang/julia/blob/master/cli/loader_lib.c) which loads a few libraries, eventually calling [`repl_entrypoint()` in `src/jlapi.c`](https://github.com/JuliaLang/julia/blob/master/src/jlapi.c). `repl_entrypoint()` calls [`libsupport_init()`](https://github.com/JuliaLang/julia/blob/master/src/support/libsupportinit.c) to set the C library locale and to initialize the "ios" library (see [`ios_init_stdstreams()`](https://github.com/JuliaLang/julia/blob/master/src/support/ios.c) and [Legacy `ios.c` library](@ref)). Next [`jl_parse_opts()`](https://github.com/JuliaLang/julia/blob/master/src/jloptions.c) is called to process command line options. Note that `jl_parse_opts()` only deals with options that affect code generation or early initialization. Other options are handled later by [`process_options()` in `base/client.jl`](https://github.com/JuliaLang/julia/blob/master/base/client.jl). `jl_parse_opts()` stores command line options in the [global `jl_options` struct](https://github.com/JuliaLang/julia/blob/master/src/julia.h). ## `julia_init()` [`julia_init()` in `task.c`](https://github.com/JuliaLang/julia/blob/master/src/task.c) is called by `main()` and calls [`_julia_init()` in `init.c`](https://github.com/JuliaLang/julia/blob/master/src/init.c). `_julia_init()` begins by calling `libsupport_init()` again (it does nothing the second time). [`restore_signals()`](https://github.com/JuliaLang/julia/blob/master/src/signals-unix.c) is called to zero the signal handler mask. [`jl_resolve_sysimg_location()`](https://github.com/JuliaLang/julia/blob/master/src/init.c) searches configured paths for the base system image. See [Building the Julia system image](@ref). [`jl_gc_init()`](https://github.com/JuliaLang/julia/blob/master/src/gc.c) sets up allocation pools and lists for weak refs, preserved values and finalization. [`jl_init_frontend()`](https://github.com/JuliaLang/julia/blob/master/src/ast.c) loads and initializes a pre-compiled femtolisp image containing the scanner/parser. [`jl_init_types()`](https://github.com/JuliaLang/julia/blob/master/src/jltypes.c) creates `jl_datatype_t` type description objects for the [built-in types defined in `julia.h`](https://github.com/JuliaLang/julia/blob/master/src/julia.h). e.g. ```c jl_any_type = jl_new_abstracttype(jl_symbol("Any"), core, NULL, jl_emptysvec); jl_any_type->super = jl_any_type; jl_type_type = jl_new_abstracttype(jl_symbol("Type"), core, jl_any_type, jl_emptysvec); jl_int32_type = jl_new_primitivetype(jl_symbol("Int32"), core, jl_any_type, jl_emptysvec, 32); ``` [`jl_init_tasks()`](https://github.com/JuliaLang/julia/blob/master/src/task.c) creates the `jl_datatype_t* jl_task_type` object; initializes the global `jl_root_task` struct; and sets `jl_current_task` to the root task. [`jl_init_codegen()`](https://github.com/JuliaLang/julia/blob/master/src/codegen.cpp) initializes the [LLVM library](http://llvm.org). [`jl_init_serializer()`](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c) initializes 8-bit serialization tags for builtin `jl_value_t` values. If there is no sysimg file (`!jl_options.image_file`) then the `Core` and `Main` modules are created and `boot.jl` is evaluated: `jl_core_module = jl_new_module(jl_symbol("Core"))` creates the Julia `Core` module. [`jl_init_intrinsic_functions()`](https://github.com/JuliaLang/julia/blob/master/src/intrinsics.cpp) creates a new Julia module `Intrinsics` containing constant `jl_intrinsic_type` symbols. These define an integer code for each [intrinsic function](https://github.com/JuliaLang/julia/blob/master/src/intrinsics.cpp). [`emit_intrinsic()`](https://github.com/JuliaLang/julia/blob/master/src/intrinsics.cpp) translates these symbols into LLVM instructions during code generation. [`jl_init_primitives()`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c) hooks C functions up to Julia function symbols. e.g. the symbol `Core.:(===)()` is bound to C function pointer `jl_f_is()` by calling `add_builtin_func("===", jl_f_is)`. [`jl_new_main_module()`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) creates the global "Main" module and sets `jl_current_task->current_module = jl_main_module`. Note: `_julia_init()` [then sets](https://github.com/JuliaLang/julia/blob/master/src/init.c) `jl_root_task->current_module = jl_core_module`. `jl_root_task` is an alias of `jl_current_task` at this point, so the `current_module` set by `jl_new_main_module()` above is overwritten. [`jl_load("boot.jl", sizeof("boot.jl"))`](https://github.com/JuliaLang/julia/blob/master/src/init.c) calls [`jl_parse_eval_all`](https://github.com/JuliaLang/julia/blob/master/src/ast.c) which repeatedly calls [`jl_toplevel_eval_flex()`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) to execute [`boot.jl`](https://github.com/JuliaLang/julia/blob/master/base/boot.jl). <!-- TODO – drill down into eval? --> [`jl_get_builtin_hooks()`](https://github.com/JuliaLang/julia/blob/master/src/init.c) initializes global C pointers to Julia globals defined in `boot.jl`. [`jl_init_box_caches()`](https://github.com/JuliaLang/julia/blob/master/src/datatype.c) pre-allocates global boxed integer value objects for values up to 1024. This speeds up allocation of boxed ints later on. e.g.: ```c jl_value_t *jl_box_uint8(uint32_t x) { return boxed_uint8_cache[(uint8_t)x]; } ``` [`_julia_init()` iterates](https://github.com/JuliaLang/julia/blob/master/src/init.c) over the `jl_core_module->bindings.table` looking for `jl_datatype_t` values and sets the type name's module prefix to `jl_core_module`. [`jl_add_standard_imports(jl_main_module)`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) does "using Base" in the "Main" module. Note: `_julia_init()` now reverts to `jl_root_task->current_module = jl_main_module` as it was before being set to `jl_core_module` above. Platform specific signal handlers are initialized for `SIGSEGV` (OSX, Linux), and `SIGFPE` (Windows). Other signals (`SIGINFO, SIGBUS, SIGILL, SIGTERM, SIGABRT, SIGQUIT, SIGSYS` and `SIGPIPE`) are hooked up to [`sigdie_handler()`](https://github.com/JuliaLang/julia/blob/master/src/signals-unix.c) which prints a backtrace. [`jl_init_restored_modules()`](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c) calls [`jl_module_run_initializer()`](https://github.com/JuliaLang/julia/blob/master/src/module.c) for each deserialized module to run the `__init__()` function. Finally [`sigint_handler()`](https://github.com/JuliaLang/julia/blob/master/src/signals-unix.c) is hooked up to `SIGINT` and calls `jl_throw(jl_interrupt_exception)`. `_julia_init()` then returns [back to `main()` in `cli/loader_exe.c`](https://github.com/JuliaLang/julia/blob/master/cli/loader_exe.c) and `main()` calls `repl_entrypoint(argc, (char**)argv)`. !!! sidebar "sysimg" If there is a sysimg file, it contains a pre-cooked image of the `Core` and `Main` modules (and whatever else is created by `boot.jl`). See [Building the Julia system image](@ref). [`jl_restore_system_image()`](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c) deserializes the saved sysimg into the current Julia runtime environment and initialization continues after `jl_init_box_caches()` below... Note: [`jl_restore_system_image()` (and `staticdata.c` in general)](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c) uses the [Legacy `ios.c` library](@ref). ## `repl_entrypoint()` [`repl_entrypoint()`](https://github.com/JuliaLang/julia/blob/master/src/jlapi.c) loads the contents of `argv[]` into [`Base.ARGS`](@ref). If a `.jl` "program" file was supplied on the command line, then [`exec_program()`](https://github.com/JuliaLang/julia/blob/master/src/jlapi.c) calls [`jl_load(program,len)`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) which calls [`jl_parse_eval_all`](https://github.com/JuliaLang/julia/blob/master/src/ast.c) which repeatedly calls [`jl_toplevel_eval_flex()`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) to execute the program. However, in our example (`julia -e 'println("Hello World!")'`), [`jl_get_global(jl_base_module, jl_symbol("_start"))`](https://github.com/JuliaLang/julia/blob/master/src/module.c) looks up [`Base._start`](https://github.com/JuliaLang/julia/blob/master/base/client.jl) and [`jl_apply()`](https://github.com/JuliaLang/julia/blob/master/src/julia.h) executes it. ## `Base._start` [`Base._start`](https://github.com/JuliaLang/julia/blob/master/base/client.jl) calls [`Base.process_options`](https://github.com/JuliaLang/julia/blob/master/base/client.jl) which calls [`jl_parse_input_line("println("Hello World!")")`](https://github.com/JuliaLang/julia/blob/master/src/ast.c) to create an expression object and [`Base.eval()`](@ref eval) to execute it. ## `Base.eval` [`Base.eval()`](@ref eval) was [mapped to `jl_f_top_eval`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c) by `jl_init_primitives()`. [`jl_f_top_eval()`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c) calls [`jl_toplevel_eval_in(jl_main_module, ex)`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c), where `ex` is the parsed expression `println("Hello World!")`. [`jl_toplevel_eval_in()`](https://github.com/JuliaLang/julia/blob/master/src/builtins.c) calls [`jl_toplevel_eval_flex()`](https://github.com/JuliaLang/julia/blob/master/src/toplevel.c) which calls [`eval()` in `interpreter.c`](https://github.com/JuliaLang/julia/blob/master/src/interpreter.c). The stack dump below shows how the interpreter works its way through various methods of [`Base.println()`](@ref) and [`Base.print()`](@ref) before arriving at [`write(s::IO, a::Array{T}) where T`](https://github.com/JuliaLang/julia/blob/master/base/stream.jl) which does `ccall(jl_uv_write())`. [`jl_uv_write()`](https://github.com/JuliaLang/julia/blob/master/src/jl_uv.c) calls `uv_write()` to write "Hello World!" to `JL_STDOUT`. See [Libuv wrappers for stdio](@ref).: ``` Hello World! ``` | Stack frame | Source code | Notes | |:------------------------------ |:--------------- |:---------------------------------------------------- | | `jl_uv_write()` | `jl_uv.c` | called though [`ccall`](@ref) | | `julia_write_282942` | `stream.jl` | function `write!(s::IO, a::Array{T}) where T` | | `julia_print_284639` | `ascii.jl` | `print(io::IO, s::String) = (write(io, s); nothing)` | | `jlcall_print_284639` |   |   | | `jl_apply()` | `julia.h` |   | | `jl_trampoline()` | `builtins.c` |   | | `jl_apply()` | `julia.h` |   | | `jl_apply_generic()` | `gf.c` | `Base.print(Base.TTY, String)` | | `jl_apply()` | `julia.h` |   | | `jl_trampoline()` | `builtins.c` |   | | `jl_apply()` | `julia.h` |   | | `jl_apply_generic()` | `gf.c` | `Base.print(Base.TTY, String, Char, Char...)` | | `jl_apply()` | `julia.h` |   | | `jl_f_apply()` | `builtins.c` |   | | `jl_apply()` | `julia.h` |   | | `jl_trampoline()` | `builtins.c` |   | | `jl_apply()` | `julia.h` |   | | `jl_apply_generic()` | `gf.c` | `Base.println(Base.TTY, String, String...)` | | `jl_apply()` | `julia.h` |   | | `jl_trampoline()` | `builtins.c` |   | | `jl_apply()` | `julia.h` |   | | `jl_apply_generic()` | `gf.c` | `Base.println(String,)` | | `jl_apply()` | `julia.h` |   | | `do_call()` | `interpreter.c` |   | | `eval()` | `interpreter.c` |   | | `jl_interpret_toplevel_expr()` | `interpreter.c` |   | | `jl_toplevel_eval_flex()` | `toplevel.c` |   | | `jl_toplevel_eval()` | `toplevel.c` |   | | `jl_toplevel_eval_in()` | `builtins.c` |   | | `jl_f_top_eval()` | `builtins.c` |   | Since our example has just one function call, which has done its job of printing "Hello World!", the stack now rapidly unwinds back to `main()`. ## `jl_atexit_hook()` `main()` calls [`jl_atexit_hook()`](https://github.com/JuliaLang/julia/blob/master/src/init.c). This calls `Base._atexit`, then calls [`jl_gc_run_all_finalizers()`](https://github.com/JuliaLang/julia/blob/master/src/gc.c) and cleans up libuv handles. ## `julia_save()` Finally, `main()` calls [`julia_save()`](https://github.com/JuliaLang/julia/blob/master/src/init.c), which if requested on the command line, saves the runtime state to a new system image. See [`jl_compile_all()`](https://github.com/JuliaLang/julia/blob/master/src/gf.c) and [`jl_save_system_image()`](https://github.com/JuliaLang/julia/blob/master/src/staticdata.c).
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4095
# isbits Union Optimizations In Julia, the `Array` type holds both "bits" values as well as heap-allocated "boxed" values. The distinction is whether the value itself is stored inline (in the direct allocated memory of the array), or if the memory of the array is simply a collection of pointers to objects allocated elsewhere. In terms of performance, accessing values inline is clearly an advantage over having to follow a pointer to the actual value. The definition of "isbits" generally means any Julia type with a fixed, determinate size, meaning no "pointer" fields, see `?isbitstype`. Julia also supports Union types, quite literally the union of a set of types. Custom Union type definitions can be extremely handy for applications wishing to "cut across" the nominal type system (i.e. explicit subtype relationships) and define methods or functionality on these, otherwise unrelated, set of types. A compiler challenge, however, is in determining how to treat these Union types. The naive approach (and indeed, what Julia itself did pre-0.7), is to simply make a "box" and then a pointer in the box to the actual value, similar to the previously mentioned "boxed" values. This is unfortunate, however, because of the number of small, primitive "bits" types (think `UInt8`, `Int32`, `Float64`, etc.) that would easily fit themselves inline in this "box" without needing any indirection for value access. There are two main ways Julia can take advantage of this optimization as of 0.7: isbits Union fields in types, and isbits Union Arrays. ## isbits Union Structs Julia now includes an optimization wherein "isbits Union" fields in types (`mutable struct`, `struct`, etc.) will be stored inline. This is accomplished by determining the "inline size" of the Union type (e.g. `Union{UInt8, Int16}` will have a size of two bytes, which represents the size needed of the largest Union type `Int16`), and in addition, allocating an extra "type tag byte" (`UInt8`), whose value signals the type of the actual value stored inline of the "Union bytes". The type tag byte value is the index of the actual value's type in the Union type's order of types. For example, a type tag value of `0x02` for a field with type `Union{Nothing, UInt8, Int16}` would indicate that an `Int16` value is stored in the 16 bits of the field in the structure's memory; a `0x01` value would indicate that a `UInt8` value was stored in the first 8 bits of the 16 bits of the field's memory. Lastly, a value of `0x00` signals that the `nothing` value will be returned for this field, even though, as a singleton type with a single type instance, it technically has a size of 0. The type tag byte for a type's Union field is stored directly after the field's computed Union memory. ## isbits Union Arrays Julia can now also store "isbits Union" values inline in an Array, as opposed to requiring an indirection box. The optimization is accomplished by storing an extra "type tag array" of bytes, one byte per array element, alongside the bytes of the actual array data. This type tag array serves the same function as the type field case: its value signals the type of the actual stored Union value in the array. In terms of layout, a Julia Array can include extra "buffer" space before and after its actual data values, which are tracked in the `a->offset` and `a->maxsize` fields of the `jl_array_t*` type. The "type tag array" is treated exactly as another `jl_array_t*`, but which shares the same `a->offset`, `a->maxsize`, and `a->len` fields. So the formula to access an isbits Union Array's type tag bytes is `a->data + (a->maxsize - a->offset) * a->elsize + a->offset`; i.e. the Array's `a->data` pointer is already shifted by `a->offset`, so correcting for that, we follow the data all the way to the max of what it can hold `a->maxsize`, then adjust by `a->offset` more bytes to account for any present "front buffering" the array might be doing. This layout in particular allows for very efficient resizing operations as the type tag data only ever has to move when the actual array's data has to move.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
17540
# Working with LLVM This is not a replacement for the LLVM documentation, but a collection of tips for working on LLVM for Julia. ## Overview of Julia to LLVM Interface Julia dynamically links against LLVM by default. Build with `USE_LLVM_SHLIB=0` to link statically. The code for lowering Julia AST to LLVM IR or interpreting it directly is in directory `src/`. | File | Description | |:------------------- |:---------------------------------------------------------- | | `builtins.c` | Builtin functions | | `ccall.cpp` | Lowering [`ccall`](@ref) | | `cgutils.cpp` | Lowering utilities, notably for array and tuple accesses | | `codegen.cpp` | Top-level of code generation, pass list, lowering builtins | | `debuginfo.cpp` | Tracks debug information for JIT code | | `disasm.cpp` | Handles native object file and JIT code diassembly | | `gf.c` | Generic functions | | `intrinsics.cpp` | Lowering intrinsics | | `llvm-simdloop.cpp` | Custom LLVM pass for [`@simd`](@ref) | | `sys.c` | I/O and operating system utility functions | Some of the `.cpp` files form a group that compile to a single object. The difference between an intrinsic and a builtin is that a builtin is a first class function that can be used like any other Julia function. An intrinsic can operate only on unboxed data, and therefore its arguments must be statically typed. ### Alias Analysis Julia currently uses LLVM's [Type Based Alias Analysis](http://llvm.org/docs/LangRef.html#tbaa-metadata). To find the comments that document the inclusion relationships, look for `static MDNode*` in `src/codegen.cpp`. The `-O` option enables LLVM's [Basic Alias Analysis](http://llvm.org/docs/AliasAnalysis.html#the-basicaa-pass). ## Building Julia with a different version of LLVM The default version of LLVM is specified in `deps/Versions.make`. You can override it by creating a file called `Make.user` in the top-level directory and adding a line to it such as: ``` LLVM_VER = 12.0.1 ``` Besides the LLVM release numerals, you can also use `LLVM_VER = svn` to build against the latest development version of LLVM. You can also specify to build a debug version of LLVM, by setting either `LLVM_DEBUG = 1` or `LLVM_DEBUG = Release` in your `Make.user` file. The former will be a fully unoptimized build of LLVM and the latter will produce an optimized build of LLVM. Depending on your needs the latter will suffice and it quite a bit faster. If you use `LLVM_DEBUG = Release` you will also want to set `LLVM_ASSERTIONS = 1` to enable diagnostics for different passes. Only `LLVM_DEBUG = 1` implies that option by default. ## Passing options to LLVM You can pass options to LLVM via the environment variable `JULIA_LLVM_ARGS`. Here are example settings using `bash` syntax: * `export JULIA_LLVM_ARGS=-print-after-all` dumps IR after each pass. * `export JULIA_LLVM_ARGS=-debug-only=loop-vectorize` dumps LLVM `DEBUG(...)` diagnostics for loop vectorizer. If you get warnings about "Unknown command line argument", rebuild LLVM with `LLVM_ASSERTIONS = 1`. ## Debugging LLVM transformations in isolation On occasion, it can be useful to debug LLVM's transformations in isolation from the rest of the Julia system, e.g. because reproducing the issue inside `julia` would take too long, or because one wants to take advantage of LLVM's tooling (e.g. bugpoint). To get unoptimized IR for the entire system image, pass the `--output-unopt-bc unopt.bc` option to the system image build process, which will output the unoptimized IR to an `unopt.bc` file. This file can then be passed to LLVM tools as usual. `libjulia` can function as an LLVM pass plugin and can be loaded into LLVM tools, to make julia-specific passes available in this environment. In addition, it exposes the `-julia` meta-pass, which runs the entire Julia pass-pipeline over the IR. As an example, to generate a system image, one could do: ``` opt -load libjulia-internal.so -julia -o opt.bc unopt.bc llc -o sys.o opt.bc cc -shared -o sys.so sys.o ``` This system image can then be loaded by `julia` as usual. It is also possible to dump an LLVM IR module for just one Julia function, using: ```julia fun, T = +, Tuple{Int,Int} # Substitute your function of interest here optimize = false open("plus.ll", "w") do file println(file, InteractiveUtils._dump_function(fun, T, false, false, false, true, :att, optimize, :default)) end ``` These files can be processed the same way as the unoptimized sysimg IR shown above. ## Improving LLVM optimizations for Julia Improving LLVM code generation usually involves either changing Julia lowering to be more friendly to LLVM's passes, or improving a pass. If you are planning to improve a pass, be sure to read the [LLVM developer policy](http://llvm.org/docs/DeveloperPolicy.html). The best strategy is to create a code example in a form where you can use LLVM's `opt` tool to study it and the pass of interest in isolation. 1. Create an example Julia code of interest. 2. Use `JULIA_LLVM_ARGS=-print-after-all` to dump the IR. 3. Pick out the IR at the point just before the pass of interest runs. 4. Strip the debug metadata and fix up the TBAA metadata by hand. The last step is labor intensive. Suggestions on a better way would be appreciated. ## The jlcall calling convention Julia has a generic calling convention for unoptimized code, which looks somewhat as follows: ```c jl_value_t *any_unoptimized_call(jl_value_t *, jl_value_t **, int); ``` where the first argument is the boxed function object, the second argument is an on-stack array of arguments and the third is the number of arguments. Now, we could perform a straightforward lowering and emit an alloca for the argument array. However, this would betray the SSA nature of the uses at the call site, making optimizations (including GC root placement), significantly harder. Instead, we emit it as follows: ```llvm %bitcast = bitcast @any_unoptimized_call to %jl_value_t *(*)(%jl_value_t *, %jl_value_t *) call cc 37 %jl_value_t *%bitcast(%jl_value_t *%arg1, %jl_value_t *%arg2) ``` The special `cc 37` annotation marks the fact that this call site is really using the jlcall calling convention. This allows us to retain the SSA-ness of the uses throughout the optimizer. GC root placement will later lower this call to the original C ABI. In the code the calling convention number is represented by the `JLCALL_F_CC` constant. In addition, there is the `JLCALL_CC` calling convention which functions similarly, but omits the first argument. ## GC root placement GC root placement is done by an LLVM pass late in the pass pipeline. Doing GC root placement this late enables LLVM to make more aggressive optimizations around code that requires GC roots, as well as allowing us to reduce the number of required GC roots and GC root store operations (since LLVM doesn't understand our GC, it wouldn't otherwise know what it is and is not allowed to do with values stored to the GC frame, so it'll conservatively do very little). As an example, consider an error path ```julia if some_condition() #= Use some variables maybe =# error("An error occurred") end ``` During constant folding, LLVM may discover that the condition is always false, and can remove the basic block. However, if GC root lowering is done early, the GC root slots used in the deleted block, as well as any values kept alive in those slots only because they were used in the error path, would be kept alive by LLVM. By doing GC root lowering late, we give LLVM the license to do any of its usual optimizations (constant folding, dead code elimination, etc.), without having to worry (too much) about which values may or may not be GC tracked. However, in order to be able to do late GC root placement, we need to be able to identify a) which pointers are GC tracked and b) all uses of such pointers. The goal of the GC placement pass is thus simple: Minimize the number of needed GC roots/stores to them subject to the constraint that at every safepoint, any live GC-tracked pointer (i.e. for which there is a path after this point that contains a use of this pointer) is in some GC slot. ### Representation The primary difficulty is thus choosing an IR representation that allows us to identify GC-tracked pointers and their uses, even after the program has been run through the optimizer. Our design makes use of three LLVM features to achieve this: - Custom address spaces - Operand Bundles - Non-integral pointers Custom address spaces allow us to tag every point with an integer that needs to be preserved through optimizations. The compiler may not insert casts between address spaces that did not exist in the original program and it must never change the address space of a pointer on a load/store/etc operation. This allows us to annotate which pointers are GC-tracked in an optimizer-resistant way. Note that metadata would not be able to achieve the same purpose. Metadata is supposed to always be discardable without altering the semantics of the program. However, failing to identify a GC-tracked pointer alters the resulting program behavior dramatically - it'll probably crash or return wrong results. We currently use three different address spaces (their numbers are defined in `src/codegen_shared.cpp`): - GC Tracked Pointers (currently 10): These are pointers to boxed values that may be put into a GC frame. It is loosely equivalent to a `jl_value_t*` pointer on the C side. N.B. It is illegal to ever have a pointer in this address space that may not be stored to a GC slot. - Derived Pointers (currently 11): These are pointers that are derived from some GC tracked pointer. Uses of these pointers generate uses of the original pointer. However, they need not themselves be known to the GC. The GC root placement pass MUST always find the GC tracked pointer from which this pointer is derived and use that as the pointer to root. - Callee Rooted Pointers (currently 12): This is a utility address space to express the notion of a callee rooted value. All values of this address space MUST be storable to a GC root (though it is possible to relax this condition in the future), but unlike the other pointers need not be rooted if passed to a call (they do still need to be rooted if they are live across another safepoint between the definition and the call). - Pointers loaded from tracked object (currently 13): This is used by arrays, which themselves contain a pointer to the managed data. This data area is owned by the array, but is not a GC-tracked object by itself. The compiler guarantees that as long as this pointer is live, the object that this pointer was loaded from will keep being live. ### Invariants The GC root placement pass makes use of several invariants, which need to be observed by the frontend and are preserved by the optimizer. First, only the following address space casts are allowed: - 0->{Tracked,Derived,CalleeRooted}: It is allowable to decay an untracked pointer to any of the others. However, do note that the optimizer has broad license to not root such a value. It is never safe to have a value in address space 0 in any part of the program if it is (or is derived from) a value that requires a GC root. - Tracked->Derived: This is the standard decay route for interior values. The placement pass will look for these to identify the base pointer for any use. - Tracked->CalleeRooted: Addrspace CalleeRooted serves merely as a hint that a GC root is not required. However, do note that the Derived->CalleeRooted decay is prohibited, since pointers should generally be storable to a GC slot, even in this address space. Now let us consider what constitutes a use: - Loads whose loaded values is in one of the address spaces - Stores of a value in one of the address spaces to a location - Stores to a pointer in one of the address spaces - Calls for which a value in one of the address spaces is an operand - Calls in jlcall ABI, for which the argument array contains a value - Return instructions. We explicitly allow load/stores and simple calls in address spaces Tracked/Derived. Elements of jlcall argument arrays must always be in address space Tracked (it is required by the ABI that they are valid `jl_value_t*` pointers). The same is true for return instructions (though note that struct return arguments are allowed to have any of the address spaces). The only allowable use of an address space CalleeRooted pointer is to pass it to a call (which must have an appropriately typed operand). Further, we disallow `getelementptr` in addrspace Tracked. This is because unless the operation is a noop, the resulting pointer will not be validly storable to a GC slot and may thus not be in this address space. If such a pointer is required, it should be decayed to addrspace Derived first. Lastly, we disallow `inttoptr`/`ptrtoint` instructions in these address spaces. Having these instructions would mean that some `i64` values are really GC tracked. This is problematic, because it breaks that stated requirement that we're able to identify GC-relevant pointers. This invariant is accomplished using the LLVM "non-integral pointers" feature, which is new in LLVM 5.0. It prohibits the optimizer from making optimizations that would introduce these operations. Note we can still insert static constants at JIT time by using `inttoptr` in address space 0 and then decaying to the appropriate address space afterwards. ### Supporting [`ccall`](@ref) One important aspect missing from the discussion so far is the handling of [`ccall`](@ref). [`ccall`](@ref) has the peculiar feature that the location and scope of a use do not coincide. As an example consider: ```julia A = randn(1024) ccall(:foo, Cvoid, (Ptr{Float64},), A) ``` In lowering, the compiler will insert a conversion from the array to the pointer which drops the reference to the array value. However, we of course need to make sure that the array does stay alive while we're doing the [`ccall`](@ref). To understand how this is done, first recall the lowering of the above code: ```julia return $(Expr(:foreigncall, :(:foo), Cvoid, svec(Ptr{Float64}), 0, :(:ccall), Expr(:foreigncall, :(:jl_array_ptr), Ptr{Float64}, svec(Any), 0, :(:ccall), :(A)), :(A))) ``` The last `:(A)`, is an extra argument list inserted during lowering that informs the code generator which Julia level values need to be kept alive for the duration of this [`ccall`](@ref). We then take this information and represent it in an "operand bundle" at the IR level. An operand bundle is essentially a fake use that is attached to the call site. At the IR level, this looks like so: ```llvm call void inttoptr (i64 ... to void (double*)*)(double* %5) [ "jl_roots"(%jl_value_t addrspace(10)* %A) ] ``` The GC root placement pass will treat the `jl_roots` operand bundle as if it were a regular operand. However, as a final step, after the GC roots are inserted, it will drop the operand bundle to avoid confusing instruction selection. ### Supporting [`pointer_from_objref`](@ref) [`pointer_from_objref`](@ref) is special because it requires the user to take explicit control of GC rooting. By our above invariants, this function is illegal, because it performs an address space cast from 10 to 0. However, it can be useful, in certain situations, so we provide a special intrinsic: ```llvm declared %jl_value_t *julia.pointer_from_objref(%jl_value_t addrspace(10)*) ``` which is lowered to the corresponding address space cast after GC root lowering. Do note however that by using this intrinsic, the caller assumes all responsibility for making sure that the value in question is rooted. Further this intrinsic is not considered a use, so the GC root placement pass will not provide a GC root for the function. As a result, the external rooting must be arranged while the value is still tracked by the system. I.e. it is not valid to attempt to use the result of this operation to establish a global root - the optimizer may have already dropped the value. ### Keeping values alive in the absence of uses In certain cases it is necessary to keep an object alive, even though there is no compiler-visible use of said object. This may be case for low level code that operates on the memory-representation of an object directly or code that needs to interface with C code. In order to allow this, we provide the following intrinsics at the LLVM level: ``` token @llvm.julia.gc_preserve_begin(...) void @llvm.julia.gc_preserve_end(token) ``` (The `llvm.` in the name is required in order to be able to use the `token` type). The semantics of these intrinsics are as follows: At any safepoint that is dominated by a `gc_preserve_begin` call, but that is not not dominated by a corresponding `gc_preserve_end` call (i.e. a call whose argument is the token returned by a `gc_preserve_begin` call), the values passed as arguments to that `gc_preserve_begin` will be kept live. Note that the `gc_preserve_begin` still counts as a regular use of those values, so the standard lifetime semantics will ensure that the values will be kept alive before entering the preserve region.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
5524
# Proper maintenance and care of multi-threading locks The following strategies are used to ensure that the code is dead-lock free (generally by addressing the 4th Coffman condition: circular wait). > 1. structure code such that only one lock will need to be acquired at a time > 2. always acquire shared locks in the same order, as given by the table below > 3. avoid constructs that expect to need unrestricted recursion ## Locks Below are all of the locks that exist in the system and the mechanisms for using them that avoid the potential for deadlocks (no Ostrich algorithm allowed here): The following are definitely leaf locks (level 1), and must not try to acquire any other lock: > * safepoint > > > Note that this lock is acquired implicitly by `JL_LOCK` and `JL_UNLOCK`. use the `_NOGC` variants > > to avoid that for level 1 locks. > > > > While holding this lock, the code must not do any allocation or hit any safepoints. Note that > > there are safepoints when doing allocation, enabling / disabling GC, entering / restoring exception > > frames, and taking / releasing locks. > * shared_map > * finalizers > * pagealloc > * gc_perm_lock > * flisp > * jl_in_stackwalk (Win32) > > > flisp itself is already threadsafe, this lock only protects the `jl_ast_context_list_t` pool The following is a leaf lock (level 2), and only acquires level 1 locks (safepoint) internally: > * typecache > * Module->lock The following is a level 3 lock, which can only acquire level 1 or level 2 locks internally: > * Method->writelock The following is a level 4 lock, which can only recurse to acquire level 1, 2, or 3 locks: > * MethodTable->writelock No Julia code may be called while holding a lock above this point. The following are a level 6 lock, which can only recurse to acquire locks at lower levels: > * codegen > * jl_modules_mutex The following is an almost root lock (level end-1), meaning only the root look may be held when trying to acquire it: > * typeinf > > > this one is perhaps one of the most tricky ones, since type-inference can be invoked from many > > points > > > > currently the lock is merged with the codegen lock, since they call each other recursively The following lock synchronizes IO operation. Be aware that doing any I/O (for example, printing warning messages or debug information) while holding any other lock listed above may result in pernicious and hard-to-find deadlocks. BE VERY CAREFUL! > * iolock > * Individual ThreadSynchronizers locks > > > this may continue to be held after releasing the iolock, or acquired without it, > > but be very careful to never attempt to acquire the iolock while holding it The following is the root lock, meaning no other lock shall be held when trying to acquire it: > * toplevel > > > this should be held while attempting a top-level action (such as making a new type or defining > > a new method): trying to obtain this lock inside a staged function will cause a deadlock condition! > > > > > > additionally, it's unclear if *any* code can safely run in parallel with an arbitrary toplevel > > expression, so it may require all threads to get to a safepoint first ## Broken Locks The following locks are broken: * toplevel > doesn't exist right now > > fix: create it * Module->lock > This is vulnerable to deadlocks since it can't be certain it is acquired in sequence. > Some operations (such as `import_module`) are missing a lock. > > fix: replace with `jl_modules_mutex`? * loading.jl: `require` and `register_root_module` > This file potentially has numerous problems. > > fix: needs locks ## Shared Global Data Structures These data structures each need locks due to being shared mutable global state. It is the inverse list for the above lock priority list. This list does not include level 1 leaf resources due to their simplicity. MethodTable modifications (def, cache, kwsorter type) : MethodTable->writelock Type declarations : toplevel lock Type application : typecache lock Global variable tables : Module->lock Module serializer : toplevel lock JIT & type-inference : codegen lock MethodInstance/CodeInstance updates : Method->writelock, codegen lock > * These are set at construction and immutable: > * specTypes > * sparam_vals > * def > * These are set by `jl_type_infer` (while holding codegen lock): > * cache > * rettype > * inferred * valid ages > * `inInference` flag: > * optimization to quickly avoid recurring into `jl_type_infer` while it is already running > * actual state (of setting `inferred`, then `fptr`) is protected by codegen lock > * Function pointers: > * these transition once, from `NULL` to a value, while the codegen lock is held > > * Code-generator cache (the contents of `functionObjectsDecls`): > * these can transition multiple times, but only while the codegen lock is held > * it is valid to use old version of this, or block for new versions of this, so races are benign, > as long as the code is careful not to reference other data in the method instance (such as `rettype`) > and assume it is coordinated, unless also holding the codegen lock > LLVMContext : codegen lock Method : Method->writelock * roots array (serializer and codegen) * invoke / specializations / tfunc modifications
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1869
# Talking to the compiler (the `:meta` mechanism) In some circumstances, one might wish to provide hints or instructions that a given block of code has special properties: you might always want to inline it, or you might want to turn on special compiler optimization passes. Starting with version 0.4, Julia has a convention that these instructions can be placed inside a `:meta` expression, which is typically (but not necessarily) the first expression in the body of a function. `:meta` expressions are created with macros. As an example, consider the implementation of the `@inline` macro: ```julia macro inline(ex) esc(isa(ex, Expr) ? pushmeta!(ex, :inline) : ex) end ``` Here, `ex` is expected to be an expression defining a function. A statement like this: ```julia @inline function myfunction(x) x*(x+3) end ``` gets turned into an expression like this: ```julia quote function myfunction(x) Expr(:meta, :inline) x*(x+3) end end ``` `Base.pushmeta!(ex, :symbol, args...)` appends `:symbol` to the end of the `:meta` expression, creating a new `:meta` expression if necessary. If `args` is specified, a nested expression containing `:symbol` and these arguments is appended instead, which can be used to specify additional information. To use the metadata, you have to parse these `:meta` expressions. If your implementation can be performed within Julia, `Base.popmeta!` is very handy: `Base.popmeta!(body, :symbol)` will scan a function *body* expression (one without the function signature) for the first `:meta` expression containing `:symbol`, extract any arguments, and return a tuple `(found::Bool, args::Array{Any})`. If the metadata did not have any arguments, or `:symbol` was not found, the `args` array will be empty. Not yet provided is a convenient infrastructure for parsing `:meta` expressions from C++.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
6895
# Memory layout of Julia Objects ## Object layout (`jl_value_t`) The `jl_value_t` struct is the name for a block of memory owned by the Julia Garbage Collector, representing the data associated with a Julia object in memory. Absent any type information, it is simply an opaque pointer: ```c typedef struct jl_value_t* jl_pvalue_t; ``` Each `jl_value_t` struct is contained in a `jl_typetag_t` struct that contains metadata information about the Julia object, such as its type and garbage collector (gc) reachability: ```c typedef struct { opaque metadata; jl_value_t value; } jl_typetag_t; ``` The type of any Julia object is an instance of a leaf `jl_datatype_t` object. The `jl_typeof()` function can be used to query for it: ```c jl_value_t *jl_typeof(jl_value_t *v); ``` The layout of the object depends on its type. Reflection methods can be used to inspect that layout. A field can be accessed by calling one of the get-field methods: ```c jl_value_t *jl_get_nth_field_checked(jl_value_t *v, size_t i); jl_value_t *jl_get_field(jl_value_t *o, char *fld); ``` If the field types are known, a priori, to be all pointers, the values can also be extracted directly as an array access: ```c jl_value_t *v = value->fieldptr[n]; ``` As an example, a "boxed" `uint16_t` is stored as follows: ```c struct { opaque metadata; struct { uint16_t data; // -- 2 bytes } jl_value_t; }; ``` This object is created by `jl_box_uint16()`. Note that the `jl_value_t` pointer references the data portion, not the metadata at the top of the struct. A value may be stored "unboxed" in many circumstances (just the data, without the metadata, and possibly not even stored but just kept in registers), so it is unsafe to assume that the address of a box is a unique identifier. The "egal" test (corresponding to the `===` function in Julia), should instead be used to compare two unknown objects for equivalence: ```c int jl_egal(jl_value_t *a, jl_value_t *b); ``` This optimization should be relatively transparent to the API, since the object will be "boxed" on-demand, whenever a `jl_value_t` pointer is needed. Note that modification of a `jl_value_t` pointer in memory is permitted only if the object is mutable. Otherwise, modification of the value may corrupt the program and the result will be undefined. The mutability property of a value can be queried for with: ```c int jl_is_mutable(jl_value_t *v); ``` If the object being stored is a `jl_value_t`, the Julia garbage collector must be notified also: ```c void jl_gc_wb(jl_value_t *parent, jl_value_t *ptr); ``` However, the [Embedding Julia](@ref) section of the manual is also required reading at this point, for covering other details of boxing and unboxing various types, and understanding the gc interactions. Mirror structs for some of the built-in types are [defined in `julia.h`](https://github.com/JuliaLang/julia/blob/master/src/julia.h). The corresponding global `jl_datatype_t` objects are created by [`jl_init_types` in `jltypes.c`](https://github.com/JuliaLang/julia/blob/master/src/jltypes.c). ## Garbage collector mark bits The garbage collector uses several bits from the metadata portion of the `jl_typetag_t` to track each object in the system. Further details about this algorithm can be found in the comments of the [garbage collector implementation in `gc.c`](https://github.com/JuliaLang/julia/blob/master/src/gc.c). ## Object allocation Most new objects are allocated by `jl_new_structv()`: ```c jl_value_t *jl_new_struct(jl_datatype_t *type, ...); jl_value_t *jl_new_structv(jl_datatype_t *type, jl_value_t **args, uint32_t na); ``` Although, [`isbits`](@ref) objects can be also constructed directly from memory: ```c jl_value_t *jl_new_bits(jl_value_t *bt, void *data) ``` And some objects have special constructors that must be used instead of the above functions: Types: ```c jl_datatype_t *jl_apply_type(jl_datatype_t *tc, jl_tuple_t *params); jl_datatype_t *jl_apply_array_type(jl_datatype_t *type, size_t dim); ``` While these are the most commonly used options, there are more low-level constructors too, which you can find declared in [`julia.h`](https://github.com/JuliaLang/julia/blob/master/src/julia.h). These are used in `jl_init_types()` to create the initial types needed to bootstrap the creation of the Julia system image. Tuples: ```c jl_tuple_t *jl_tuple(size_t n, ...); jl_tuple_t *jl_tuplev(size_t n, jl_value_t **v); jl_tuple_t *jl_alloc_tuple(size_t n); ``` The representation of tuples is highly unique in the Julia object representation ecosystem. In some cases, a [`Base.tuple()`](@ref) object may be an array of pointers to the objects contained by the tuple equivalent to: ```c typedef struct { size_t length; jl_value_t *data[length]; } jl_tuple_t; ``` However, in other cases, the tuple may be converted to an anonymous [`isbits`](@ref) type and stored unboxed, or it may not stored at all (if it is not being used in a generic context as a `jl_value_t*`). Symbols: ```c jl_sym_t *jl_symbol(const char *str); ``` Functions and MethodInstance: ```c jl_function_t *jl_new_generic_function(jl_sym_t *name); jl_method_instance_t *jl_new_method_instance(jl_value_t *ast, jl_tuple_t *sparams); ``` Arrays: ```c jl_array_t *jl_new_array(jl_value_t *atype, jl_tuple_t *dims); jl_array_t *jl_new_arrayv(jl_value_t *atype, ...); jl_array_t *jl_alloc_array_1d(jl_value_t *atype, size_t nr); jl_array_t *jl_alloc_array_2d(jl_value_t *atype, size_t nr, size_t nc); jl_array_t *jl_alloc_array_3d(jl_value_t *atype, size_t nr, size_t nc, size_t z); jl_array_t *jl_alloc_vec_any(size_t n); ``` Note that many of these have alternative allocation functions for various special-purposes. The list here reflects the more common usages, but a more complete list can be found by reading the [`julia.h` header file](https://github.com/JuliaLang/julia/blob/master/src/julia.h). Internal to Julia, storage is typically allocated by `newstruct()` (or `newobj()` for the special types): ```c jl_value_t *newstruct(jl_value_t *type); jl_value_t *newobj(jl_value_t *type, size_t nfields); ``` And at the lowest level, memory is getting allocated by a call to the garbage collector (in `gc.c`), then tagged with its type: ```c jl_value_t *jl_gc_allocobj(size_t nbytes); void jl_set_typeof(jl_value_t *v, jl_datatype_t *type); ``` Note that all objects are allocated in multiples of 4 bytes and aligned to the platform pointer size. Memory is allocated from a pool for smaller objects, or directly with `malloc()` for large objects. !!! sidebar "Singleton Types" Singleton types have only one instance and no data fields. Singleton instances have a size of 0 bytes, and consist only of their metadata. e.g. `nothing::Nothing`. See [Singleton Types](@ref man-singleton-types) and [Nothingness and missing values](@ref)
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
10357
# [Arrays with custom indices](@id man-custom-indices) Conventionally, Julia's arrays are indexed starting at 1, whereas some other languages start numbering at 0, and yet others (e.g., Fortran) allow you to specify arbitrary starting indices. While there is much merit in picking a standard (i.e., 1 for Julia), there are some algorithms which simplify considerably if you can index outside the range `1:size(A,d)` (and not just `0:size(A,d)-1`, either). To facilitate such computations, Julia supports arrays with arbitrary indices. The purpose of this page is to address the question, "what do I have to do to support such arrays in my own code?" First, let's address the simplest case: if you know that your code will never need to handle arrays with unconventional indexing, hopefully the answer is "nothing." Old code, on conventional arrays, should function essentially without alteration as long as it was using the exported interfaces of Julia. If you find it more convenient to just force your users to supply traditional arrays where indexing starts at one, you can add ```julia Base.require_one_based_indexing(arrays...) ``` where `arrays...` is a list of the array objects that you wish to check for anything that violates 1-based indexing. ## Generalizing existing code As an overview, the steps are: * replace many uses of `size` with `axes` * replace `1:length(A)` with `eachindex(A)`, or in some cases `LinearIndices(A)` * replace explicit allocations like `Array{Int}(undef, size(B))` with `similar(Array{Int}, axes(B))` These are described in more detail below. ### Things to watch out for Because unconventional indexing breaks many people's assumptions that all arrays start indexing with 1, there is always the chance that using such arrays will trigger errors. The most frustrating bugs would be incorrect results or segfaults (total crashes of Julia). For example, consider the following function: ```julia function mycopy!(dest::AbstractVector, src::AbstractVector) length(dest) == length(src) || throw(DimensionMismatch("vectors must match")) # OK, now we're safe to use @inbounds, right? (not anymore!) for i = 1:length(src) @inbounds dest[i] = src[i] end dest end ``` This code implicitly assumes that vectors are indexed from 1; if `dest` starts at a different index than `src`, there is a chance that this code would trigger a segfault. (If you do get segfaults, to help locate the cause try running julia with the option `--check-bounds=yes`.) ### Using `axes` for bounds checks and loop iteration `axes(A)` (reminiscent of `size(A)`) returns a tuple of `AbstractUnitRange{<:Integer}` objects, specifying the range of valid indices along each dimension of `A`. When `A` has unconventional indexing, the ranges may not start at 1. If you just want the range for a particular dimension `d`, there is `axes(A, d)`. Base implements a custom range type, `OneTo`, where `OneTo(n)` means the same thing as `1:n` but in a form that guarantees (via the type system) that the lower index is 1. For any new [`AbstractArray`](@ref) type, this is the default returned by `axes`, and it indicates that this array type uses "conventional" 1-based indexing. For bounds checking, note that there are dedicated functions `checkbounds` and `checkindex` which can sometimes simplify such tests. ### Linear indexing (`LinearIndices`) Some algorithms are most conveniently (or efficiently) written in terms of a single linear index, `A[i]` even if `A` is multi-dimensional. Regardless of the array's native indices, linear indices always range from `1:length(A)`. However, this raises an ambiguity for one-dimensional arrays (a.k.a., [`AbstractVector`](@ref)): does `v[i]` mean linear indexing , or Cartesian indexing with the array's native indices? For this reason, your best option may be to iterate over the array with `eachindex(A)`, or, if you require the indices to be sequential integers, to get the index range by calling `LinearIndices(A)`. This will return `axes(A, 1)` if A is an AbstractVector, and the equivalent of `1:length(A)` otherwise. By this definition, 1-dimensional arrays always use Cartesian indexing with the array's native indices. To help enforce this, it's worth noting that the index conversion functions will throw an error if shape indicates a 1-dimensional array with unconventional indexing (i.e., is a `Tuple{UnitRange}` rather than a tuple of `OneTo`). For arrays with conventional indexing, these functions continue to work the same as always. Using `axes` and `LinearIndices`, here is one way you could rewrite `mycopy!`: ```julia function mycopy!(dest::AbstractVector, src::AbstractVector) axes(dest) == axes(src) || throw(DimensionMismatch("vectors must match")) for i in LinearIndices(src) @inbounds dest[i] = src[i] end dest end ``` ### Allocating storage using generalizations of `similar` Storage is often allocated with `Array{Int}(undef, dims)` or `similar(A, args...)`. When the result needs to match the indices of some other array, this may not always suffice. The generic replacement for such patterns is to use `similar(storagetype, shape)`. `storagetype` indicates the kind of underlying "conventional" behavior you'd like, e.g., `Array{Int}` or `BitArray` or even `dims->zeros(Float32, dims)` (which would allocate an all-zeros array). `shape` is a tuple of [`Integer`](@ref) or `AbstractUnitRange` values, specifying the indices that you want the result to use. Note that a convenient way of producing an all-zeros array that matches the indices of A is simply `zeros(A)`. Let's walk through a couple of explicit examples. First, if `A` has conventional indices, then `similar(Array{Int}, axes(A))` would end up calling `Array{Int}(undef, size(A))`, and thus return an array. If `A` is an `AbstractArray` type with unconventional indexing, then `similar(Array{Int}, axes(A))` should return something that "behaves like" an `Array{Int}` but with a shape (including indices) that matches `A`. (The most obvious implementation is to allocate an `Array{Int}(undef, size(A))` and then "wrap" it in a type that shifts the indices.) Note also that `similar(Array{Int}, (axes(A, 2),))` would allocate an `AbstractVector{Int}` (i.e., 1-dimensional array) that matches the indices of the columns of `A`. ## Writing custom array types with non-1 indexing Most of the methods you'll need to define are standard for any `AbstractArray` type, see [Abstract Arrays](@ref man-interface-array). This page focuses on the steps needed to define unconventional indexing. ### Custom `AbstractUnitRange` types If you're writing a non-1 indexed array type, you will want to specialize `axes` so it returns a `UnitRange`, or (perhaps better) a custom `AbstractUnitRange`. The advantage of a custom type is that it "signals" the allocation type for functions like `similar`. If we're writing an array type for which indexing will start at 0, we likely want to begin by creating a new `AbstractUnitRange`, `ZeroRange`, where `ZeroRange(n)` is equivalent to `0:n-1`. In general, you should probably *not* export `ZeroRange` from your package: there may be other packages that implement their own `ZeroRange`, and having multiple distinct `ZeroRange` types is (perhaps counterintuitively) an advantage: `ModuleA.ZeroRange` indicates that `similar` should create a `ModuleA.ZeroArray`, whereas `ModuleB.ZeroRange` indicates a `ModuleB.ZeroArray` type. This design allows peaceful coexistence among many different custom array types. Note that the Julia package [CustomUnitRanges.jl](https://github.com/JuliaArrays/CustomUnitRanges.jl) can sometimes be used to avoid the need to write your own `ZeroRange` type. ### Specializing `axes` Once you have your `AbstractUnitRange` type, then specialize `axes`: ```julia Base.axes(A::ZeroArray) = map(n->ZeroRange(n), A.size) ``` where here we imagine that `ZeroArray` has a field called `size` (there would be other ways to implement this). In some cases, the fallback definition for `axes(A, d)`: ```julia axes(A::AbstractArray{T,N}, d) where {T,N} = d <= N ? axes(A)[d] : OneTo(1) ``` may not be what you want: you may need to specialize it to return something other than `OneTo(1)` when `d > ndims(A)`. Likewise, in `Base` there is a dedicated function `axes1` which is equivalent to `axes(A, 1)` but which avoids checking (at runtime) whether `ndims(A) > 0`. (This is purely a performance optimization.) It is defined as: ```julia axes1(A::AbstractArray{T,0}) where {T} = OneTo(1) axes1(A::AbstractArray) = axes(A)[1] ``` If the first of these (the zero-dimensional case) is problematic for your custom array type, be sure to specialize it appropriately. ### Specializing `similar` Given your custom `ZeroRange` type, then you should also add the following two specializations for `similar`: ```julia function Base.similar(A::AbstractArray, T::Type, shape::Tuple{ZeroRange,Vararg{ZeroRange}}) # body end function Base.similar(f::Union{Function,DataType}, shape::Tuple{ZeroRange,Vararg{ZeroRange}}) # body end ``` Both of these should allocate your custom array type. ### Specializing `reshape` Optionally, define a method ``` Base.reshape(A::AbstractArray, shape::Tuple{ZeroRange,Vararg{ZeroRange}}) = ... ``` and you can `reshape` an array so that the result has custom indices. ### For objects that mimic AbstractArray but are not subtypes `has_offset_axes` depends on having `axes` defined for the objects you call it on. If there is some reason you don't have an `axes` method defined for your object, consider defining a method ```julia Base.has_offset_axes(obj::MyNon1IndexedArraylikeObject) = true ``` This will allow code that assumes 1-based indexing to detect a problem and throw a helpful error, rather than returning incorrect results or segfaulting julia. ### Catching errors If your new array type triggers errors in other code, one helpful debugging step can be to comment out `@boundscheck` in your `getindex` and `setindex!` implementation. This will ensure that every element access checks bounds. Or, restart julia with `--check-bounds=yes`. In some cases it may also be helpful to temporarily disable `size` and `length` for your new array type, since code that makes incorrect assumptions frequently uses these functions.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3831
# 反射 与 自我检查 Julia 提供了多种运行时的反射功能。 ## 模块绑定 由 `Module` 导出的名称可用 [`names(m::Module)`](@ref) 获得,它会返回一个元素为 [`Symbol`](@ref) 的数组来表示模块导出的绑定。不管导出状态如何,`names(m::Module, all = true)` 返回 `m` 中所有绑定的符号。 ## DateType 字段 `DataType` 的所有字段名称可以使用 [`fieldnames`](@ref) 来获取。例如,对于下面给定的类型,`fieldnames(Point)` 会返回一个表示字段名称的 [`Symbol`](@ref) 元组: ```jldoctest struct_point julia> struct Point x::Int y end julia> fieldnames(Point) (:x, :y) ``` `Point` 对象中每个字段的类型存储在 `Point` 本身的 `types` 变量中: ```jldoctest struct_point julia> Point.types svec(Int64, Any) ``` 虽然 `x` 被注释为 `Int`,但 `y` 在类型定义里没有注释,因此 `y` 默认为 `Any` 类型。 类型本身表示为一个叫做 `DataType` 的结构: ```jldoctest struct_point julia> typeof(Point) DataType ``` Note that `fieldnames(DataType)` gives the names for each field of `DataType` itself, and one of these fields is the `types` field observed in the example above. ## Subtypes The *direct* subtypes of any `DataType` may be listed using [`subtypes`](@ref). For example, the abstract `DataType` [`AbstractFloat`](@ref) has four (concrete) subtypes: ```jldoctest; setup = :(using InteractiveUtils) julia> subtypes(AbstractFloat) 4-element Vector{Any}: BigFloat Float16 Float32 Float64 ``` 任何抽象子类型也包括此列表中,但子类型的子类型不在其中。递归使用 [`subtypes`](@ref) 可以遍历出整个类型树。 ## DataType 布局 用 C 代码接口时,`DataType` 的内部表现非常重要。有几个函数可以检查这些细节。 [`isbits(T::DataType)`](@ref) 如果 `T` 类型是以 C 兼容的对齐方式存储,则为 true。 [`fieldoffset(T::DataType, i::Integer)`](@ref) 返回字段 *i* 相对于类型开始的 (字节) 偏移量。 ## 函数方法 任何泛型函数的方法都可以使用 [`methods`](@ref) 来列出。用 [`methodswith`](@ref) 搜索 方法调度表 来查找 接收给定类型的方法。 ## 扩展和更底层 As discussed in the [Metaprogramming](@ref) section, the [`macroexpand`](@ref) function gives the unquoted and interpolated expression ([`Expr`](@ref)) form for a given macro. To use `macroexpand`, `quote` the expression block itself (otherwise, the macro will be evaluated and the result will be passed instead!). For example: ```jldoctest; setup = :(using InteractiveUtils) julia> macroexpand(@__MODULE__, :(@edit println("")) ) :(InteractiveUtils.edit(println, (Base.typesof)(""))) ``` The functions `Base.Meta.show_sexpr` and [`dump`](@ref) are used to display S-expr style views and depth-nested detail views for any expression. Finally, the [`Meta.lower`](@ref) function gives the `lowered` form of any expression and is of particular interest for understanding how language constructs map to primitive operations such as assignments, branches, and calls: ```jldoctest julia> Meta.lower(@__MODULE__, :( [1+2, sin(0.5)] )) :($(Expr(:thunk, CodeInfo( @ none within `top-level scope` 1 ─ %1 = 1 + 2 │ %2 = sin(0.5) │ %3 = Base.vect(%1, %2) └── return %3 )))) ``` ## 中间表示和编译后表示 检查函数的底层形式 需要选择所要显示的特定方法,因为泛型函数可能会有许多具有不同类型签名的方法。为此, 用 [`code_lowered`](@ref) 可以指定代码底层中的方法。 并且可以用 [`code_typed`](@ref) 来进行类型推断。 [`code_warntype`](@ref) 增加 [`code_typed`](@ref) 输出的高亮。 更加接近于机器, 一个函数的 LLVM-IR 可以通过使用 [`code_llvm`](@ref) 打印出。 最终编译的机器码使用 [`code_native`](@ref) 查看(这将触发 之前未调用过的任何函数的 JIT 编译/代码生成)。 为方便起见,上述函数有 宏的版本,它们接受标准函数调用并自动展开参数类型: ```julia-repl julia> @code_llvm +(1,1) define i64 @"julia_+_130862"(i64, i64) { top: %2 = add i64 %1, %0 ret i64 %2 } ``` For more informations see [`@code_lowered`](@ref), [`@code_typed`](@ref), [`@code_warntype`](@ref), [`@code_llvm`](@ref), and [`@code_native`](@ref). ### Printing of debug information The aforementioned functions and macros take the keyword argument `debuginfo` that controls the level debug information printed. ``` julia> @code_typed debuginfo=:source +(1,1) CodeInfo( @ int.jl:53 within `+' 1 ─ %1 = Base.add_int(x, y)::Int64 └── return %1 ) => Int64 ``` Possible values for `debuginfo` are: `:none`, `:source`, and`:default`. Per default debug information is not printed, but that can be changed by setting `Base.IRShow.default_debuginfo[] = :source`.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1084
# Module loading [`Base.require`](@ref) is responsible for loading modules and it also manages the precompilation cache. It is the implementation of the `import` statement. ## Experimental features The features below are experimental and not part of the stable Julia API. Before building upon them inform yourself about the current thinking and whether they might change soon. ### Module loading callbacks It is possible to listen to the modules loaded by `Base.require`, by registering a callback. ```julia loaded_packages = Channel{Symbol}() callback = (mod::Symbol) -> put!(loaded_packages, mod) push!(Base.package_callbacks, callback) ``` Please note that the symbol given to the callback is a non-unique identifier and it is the responsibility of the callback provider to walk the module chain to determine the fully qualified name of the loaded binding. The callback below is an example of how to do that: ```julia # Get the fully-qualified name of a module. function module_fqn(name::Symbol) fqn = fullname(Base.root_module(name)) return join(fqn, '.') end ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3056
# Sanitizer support ## General considerations Using Clang's sanitizers obviously require you to use Clang (`USECLANG=1`), but there's another catch: most sanitizers require a run-time library, provided by the host compiler, while the instrumented code generated by Julia's JIT relies on functionality from that library. This implies that the LLVM version of your host compiler matches that of the LLVM library used within Julia. An easy solution is to have an dedicated build folder for providing a matching toolchain, by building with `BUILD_LLVM_CLANG=1`. You can then refer to this toolchain from another build folder by specifying `USECLANG=1` while overriding the `CC` and `CXX` variables. To use one of of the sanitizers set `SANITIZE=1` and then the appropriate flag for the sanitizer you want to use. On macOS, this might need some extra flags also to work. Altogether, it might look like this, plus one or more of the `SANITIZE_*` flags listed below: make -C deps USE_BINARYBUILDER_LLVM=0 LLVM_VER=svn stage-llvm make -C src SANITIZE=1 USECLANG=1 \ CC=~+/deps/scratch/llvm-svn/build_Release/bin/clang \ CXX=~+/deps/scratch/llvm-svn/build_Release/bin/clang++ \ CPPFLAGS="-isysroot $(xcode-select -p)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk" \ CXXFLAGS="-isystem $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1" (or put these into your `Make.user`, so you don't need to remember them every time). ## Address Sanitizer (ASAN) For detecting or debugging memory bugs, you can use Clang's [address sanitizer (ASAN)](http://clang.llvm.org/docs/AddressSanitizer.html). By compiling with `SANITIZE_ADDRESS=1` you enable ASAN for the Julia compiler and its generated code. In addition, you can specify `LLVM_SANITIZE=1` to sanitize the LLVM library as well. Note that these options incur a high performance and memory cost. For example, using ASAN for Julia and LLVM makes `testall1` takes 8-10 times as long while using 20 times as much memory (this can be reduced to respectively a factor of 3 and 4 by using the options described below). By default, Julia sets the `allow_user_segv_handler=1` ASAN flag, which is required for signal delivery to work properly. You can define other options using the `ASAN_OPTIONS` environment flag, in which case you'll need to repeat the default option mentioned before. For example, memory usage can be reduced by specifying `fast_unwind_on_malloc=0` and `malloc_context_size=2`, at the cost of backtrace accuracy. For now, Julia also sets `detect_leaks=0`, but this should be removed in the future. ## Memory Sanitizer (MSAN) For detecting use of uninitialized memory, you can use Clang's [memory sanitizer (MSAN)](http://clang.llvm.org/docs/MemorySanitizer.html) by compiling with `SANITIZE_MEMORY=1`. ## Thread Sanitizer (TSAN) For debugging data-races and other threading related issues you can use Clang's [thread sanitizer (TSAN)](https://clang.llvm.org/docs/ThreadSanitizer.html) by compiling with `SANITIZE_THREAD=1`.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
10401
# Julia SSA-form IR ## Background Beginning in Julia 0.7, parts of the compiler use a new [SSA-form](https://en.wikipedia.org/wiki/Static_single_assignment_form) intermediate representation. Historically, the compiler used to directly generate LLVM IR, from a lowered form of the Julia AST. This form had most syntactic abstractions removed, but still looked a lot like an abstract syntax tree. Over time, in order to facilitate optimizations, SSA values were introduced to this IR and the IR was linearized (i.e. a form where function arguments may only be SSA values or constants). However, non-SSA values (slots) remained in the IR due to the lack of Phi nodes in the IR (necessary for back-edges and re-merging of conditional control flow), negating much of the usefulness of the SSA form representation to perform middle end optimizations. Some heroic effort was put into making these optimizations work without a complete SSA form representation, but the lack of such a representation ultimately proved prohibitive. ## New IR nodes With the new IR representation, the compiler learned to handle four new IR nodes, Phi nodes, Pi nodes as well as PhiC nodes and Upsilon nodes (the latter two are only used for exception handling). ### Phi nodes and Pi nodes Phi nodes are part of generic SSA abstraction (see the link above if you're not familiar with the concept). In the Julia IR, these nodes are represented as: ``` struct PhiNode edges::Vector{Int} values::Vector{Any} end ``` where we ensure that both vectors always have the same length. In the canonical representation (the one handled by codegen and the interpreter), the edge values indicate come-from statement numbers (i.e. if edge has an entry of `15`, there must be a `goto`, `gotoifnot` or implicit fall through from statement `15` that targets this phi node). Values are either SSA values or constants. It is also possible for a value to be unassigned if the variable was not defined on this path. However, undefinedness checks get explicitly inserted and represented as booleans after middle end optimizations, so code generators may assume that any use of a Phi node will have an assigned value in the corresponding slot. It is also legal for the mapping to be incomplete, i.e. for a Phi node to have missing incoming edges. In that case, it must be dynamically guaranteed that the corresponding value will not be used. PiNodes encode statically proven information that may be implicitly assumed in basic blocks dominated by a given pi node. They are conceptually equivalent to the technique introduced in the paper [ABCD: Eliminating Array Bounds Checks on Demand](https://dl.acm.org/citation.cfm?id=358438.349342) or the predicate info nodes in LLVM. To see how they work, consider, e.g. ```julia %x::Union{Int, Float64} # %x is some Union{Int, Float64} typed ssa value if isa(x, Int) # use x else # use x end ``` We can perform predicate insertion and turn this into: ```julia %x::Union{Int, Float64} # %x is some Union{Int, Float64} typed ssa value if isa(x, Int) %x_int = PiNode(x, Int) # use %x_int else %x_float = PiNode(x, Float64) # use %x_float end ``` Pi nodes are generally ignored in the interpreter, since they don't have any effect on the values, but they may sometimes lead to code generation in the compiler (e.g. to change from an implicitly union split representation to a plain unboxed representation). The main usefulness of PiNodes stems from the fact that path conditions of the values can be accumulated simply by def-use chain walking that is generally done for most optimizations that care about these conditions anyway. ### PhiC nodes and Upsilon nodes Exception handling complicates the SSA story moderately, because exception handling introduces additional control flow edges into the IR across which values must be tracked. One approach to do so, which is followed by LLVM is to make calls which may throw exceptions into basic block terminators and add an explicit control flow edge to the catch handler: ``` invoke @function_that_may_throw() to label %regular unwind to %catch regular: # Control flow continues here catch: # Exceptions go here ``` However, this is problematic in a language like julia where at the start of the optimization pipeline, we do not know which calls throw. We would have to conservatively assume that every call (which in julia is every statement) throws. This would have several negative effects. On the one hand, it would essentially reduce the scope of every basic block to a single call, defeating the purpose of having operations be performed at the basic block level. On the other hand, every catch basic block would have `n*m` phi node arguments (`n`, the number of statements in the critical region, `m` the number of live values through the catch block). To work around this, we use a combination of `Upsilon` and `PhiC` (the C standing for `catch`, written `φᶜ` in the IR pretty printer, because unicode subscript c is not available) nodes. There are several ways to think of these nodes, but perhaps the easiest is to think of each `PhiC` as a load from a unique store-many, read-once slot, with `Upsilon` being the corresponding store operation. The `PhiC` has an operand list of all the upsilon nodes that store to its implicit slot. The `Upsilon` nodes however, do not record which `PhiC` node they store to. This is done for more natural integration with the rest of the SSA IR. E.g. if there are no more uses of a `PhiC` node, it is safe to delete it, and the same is true of an `Upsilon` node. In most IR passes, `PhiC` nodes can be treated like `Phi` nodes. One can follow use-def chains through them, and they can be lifted to new `PhiC` nodes and new `Upsilon` nodes (in the same places as the original `Upsilon` nodes). The result of this scheme is that the number of `Upsilon` nodes (and `PhiC` arguments) is proportional to the number of assigned values to a particular variable (before SSA conversion), rather than the number of statements in the critical region. To see this scheme in action, consider the function ```julia @noinline opaque() = invokelatest(identity, nothing) # Something opaque function foo() local y x = 1 try y = 2 opaque() y = 3 error() catch end (x, y) end ``` The corresponding IR (with irrelevant types stripped) is: ``` 1 ─ nothing::Nothing 2 ─ %2 = $(Expr(:enter, #4)) 3 ─ %3 = ϒ (false) │ %4 = ϒ (#undef) │ %5 = ϒ (1) │ %6 = ϒ (true) │ %7 = ϒ (2) │ invoke Main.opaque()::Any │ %9 = ϒ (true) │ %10 = ϒ (3) │ invoke Main.error()::Union{} └── $(Expr(:unreachable))::Union{} 4 ┄ %13 = φᶜ (%3, %6, %9)::Bool │ %14 = φᶜ (%4, %7, %10)::Core.Compiler.MaybeUndef(Int64) │ %15 = φᶜ (%5)::Core.Const(1) └── $(Expr(:leave, 1)) 5 ─ $(Expr(:pop_exception, :(%2)))::Any │ $(Expr(:throw_undef_if_not, :y, :(%13)))::Any │ %19 = Core.tuple(%15, %14) └── return %19 ``` Note in particular that every value live into the critical region gets an upsilon node at the top of the critical region. This is because catch blocks are considered to have an invisible control flow edge from outside the function. As a result, no SSA value dominates the catch blocks, and all incoming values have to come through a `φᶜ` node. ## Main SSA data structure The main `SSAIR` data structure is worthy of discussion. It draws inspiration from LLVM and Webkit's B3 IR. The core of the data structure is a flat vector of statements. Each statement is implicitly assigned an SSA value based on its position in the vector (i.e. the result of the statement at idx 1 can be accessed using `SSAValue(1)` etc). For each SSA value, we additionally maintain its type. Since, SSA values are definitionally assigned only once, this type is also the result type of the expression at the corresponding index. However, while this representation is rather efficient (since the assignments don't need to be explicitly encoded), it of course carries the drawback that order is semantically significant, so reorderings and insertions change statement numbers. Additionally, we do not keep use lists (i.e. it is impossible to walk from a def to all its uses without explicitly computing this map--def lists however are trivial since you can look up the corresponding statement from the index), so the LLVM-style RAUW (replace-all-uses-with) operation is unavailable. Instead, we do the following: - We keep a separate buffer of nodes to insert (including the position to insert them at, the type of the corresponding value and the node itself). These nodes are numbered by their occurrence in the insertion buffer, allowing their values to be immediately used elsewhere in the IR (i.e. if there are 12 statements in the original statement list, the first new statement will be accessible as `SSAValue(13)`). - RAUW style operations are performed by setting the corresponding statement index to the replacement value. - Statements are erased by setting the corresponding statement to `nothing` (this is essentially just a special-case convention of the above. - If there are any uses of the statement being erased, they will be set to `nothing`. There is a `compact!` function that compacts the above data structure by performing the insertion of nodes in the appropriate place, trivial copy propagation, and renaming of uses to any changed SSA values. However, the clever part of this scheme is that this compaction can be done lazily as part of the subsequent pass. Most optimization passes need to walk over the entire list of statements, performing analysis or modifications along the way. We provide an `IncrementalCompact` iterator that can be used to iterate over the statement list. It will perform any necessary compaction and return the new index of the node, as well as the node itself. It is legal at this point to walk def-use chains, as well as make any modifications or deletions to the IR (insertions are disallowed however). The idea behind this arrangement is that, since the optimization passes need to touch the corresponding memory anyway and incur the corresponding memory access penalty, performing the extra housekeeping should have comparatively little overhead (and save the overhead of maintaining these data structures during IR modification).
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4260
# printf() and stdio in the Julia runtime ## Libuv wrappers for stdio `julia.h` defines [libuv](http://docs.libuv.org) wrappers for the `stdio.h` streams: ```c uv_stream_t *JL_STDIN; uv_stream_t *JL_STDOUT; uv_stream_t *JL_STDERR; ``` ... and corresponding output functions: ```c int jl_printf(uv_stream_t *s, const char *format, ...); int jl_vprintf(uv_stream_t *s, const char *format, va_list args); ``` These `printf` functions are used by the `.c` files in the `src/` and `cli/` directories wherever stdio is needed to ensure that output buffering is handled in a unified way. In special cases, like signal handlers, where the full libuv infrastructure is too heavy, `jl_safe_printf()` can be used to [`write(2)`](@ref) directly to `STDERR_FILENO`: ```c void jl_safe_printf(const char *str, ...); ``` ## Interface between JL_STD* and Julia code [`Base.stdin`](@ref), [`Base.stdout`](@ref) and [`Base.stderr`](@ref) are bound to the `JL_STD*` libuv streams defined in the runtime. Julia's `__init__()` function (in `base/sysimg.jl`) calls `reinit_stdio()` (in `base/stream.jl`) to create Julia objects for [`Base.stdin`](@ref), [`Base.stdout`](@ref) and [`Base.stderr`](@ref). `reinit_stdio()` uses [`ccall`](@ref) to retrieve pointers to `JL_STD*` and calls `jl_uv_handle_type()` to inspect the type of each stream. It then creates a Julia `Base.IOStream`, `Base.TTY` or `Base.PipeEndpoint` object to represent each stream, e.g.: ``` $ julia -e 'println(typeof((stdin, stdout, stderr)))' Tuple{Base.TTY,Base.TTY,Base.TTY} $ julia -e 'println(typeof((stdin, stdout, stderr)))' < /dev/null 2>/dev/null Tuple{IOStream,Base.TTY,IOStream} $ echo hello | julia -e 'println(typeof((stdin, stdout, stderr)))' | cat Tuple{Base.PipeEndpoint,Base.PipeEndpoint,Base.TTY} ``` The [`Base.read`](@ref) and [`Base.write`](@ref) methods for these streams use [`ccall`](@ref) to call libuv wrappers in `src/jl_uv.c`, e.g.: ``` stream.jl: function write(s::IO, p::Ptr, nb::Integer) -> ccall(:jl_uv_write, ...) jl_uv.c: -> int jl_uv_write(uv_stream_t *stream, ...) -> uv_write(uvw, stream, buf, ...) ``` ## printf() during initialization The libuv streams relied upon by `jl_printf()` etc., are not available until midway through initialization of the runtime (see `init.c`, `init_stdio()`). Error messages or warnings that need to be printed before this are routed to the standard C library `fwrite()` function by the following mechanism: In `sys.c`, the `JL_STD*` stream pointers are statically initialized to integer constants: `STD*_FILENO (0, 1 and 2)`. In `jl_uv.c` the `jl_uv_puts()` function checks its `uv_stream_t* stream` argument and calls `fwrite()` if stream is set to `STDOUT_FILENO` or `STDERR_FILENO`. This allows for uniform use of `jl_printf()` throughout the runtime regardless of whether or not any particular piece of code is reachable before initialization is complete. ## Legacy `ios.c` library The `src/support/ios.c` library is inherited from [femtolisp](https://github.com/JeffBezanson/femtolisp). It provides cross-platform buffered file IO and in-memory temporary buffers. `ios.c` is still used by: * `src/flisp/*.c` * `src/dump.c` – for serialization file IO and for memory buffers. * `src/staticdata.c` – for serialization file IO and for memory buffers. * `base/iostream.jl` – for file IO (see `base/fs.jl` for libuv equivalent). Use of `ios.c` in these modules is mostly self-contained and separated from the libuv I/O system. However, there is [one place](https://github.com/JuliaLang/julia/blob/master/src/flisp/print.c#L654) where femtolisp calls through to `jl_printf()` with a legacy `ios_t` stream. There is a hack in `ios.h` that makes the `ios_t.bm` field line up with the `uv_stream_t.type` and ensures that the values used for `ios_t.bm` to not overlap with valid `UV_HANDLE_TYPE` values. This allows `uv_stream_t` pointers to point to `ios_t` streams. This is needed because `jl_printf()` caller `jl_static_show()` is passed an `ios_t` stream by femtolisp's `fl_print()` function. Julia's `jl_uv_puts()` function has special handling for this: ```c if (stream->type > UV_HANDLE_TYPE_MAX) { return ios_write((ios_t*)stream, str, n); } ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
10388
# 子数组 Julia 的 `SubArray` 类型是编码父类型 [`AbstractArray`](@ref) 的“视图”的一个容器。本页介绍了 `SubArray` 的一些设计原则和实现。 One of the major design goals is to ensure high performance for views of both [`IndexLinear`](@ref) and [`IndexCartesian`](@ref) arrays. Furthermore, views of `IndexLinear` arrays should themselves be `IndexLinear` to the extent that it is possible. ## Index replacement Consider making 2d slices of a 3d array: ```@meta DocTestSetup = :(import Random; Random.seed!(1234)) ``` ```jldoctest subarray julia> A = rand(2,3,4); julia> S1 = view(A, :, 1, 2:3) 2×2 view(::Array{Float64, 3}, :, 1, 2:3) with eltype Float64: 0.342284 0.831961 0.237287 0.435938 julia> S2 = view(A, 1, :, 2:3) 3×2 view(::Array{Float64, 3}, 1, :, 2:3) with eltype Float64: 0.342284 0.831961 0.988944 0.927795 0.178426 0.404876 ``` ```@meta DocTestSetup = nothing ``` `view` drops "singleton" dimensions (ones that are specified by an `Int`), so both `S1` and `S2` are two-dimensional `SubArray`s. Consequently, the natural way to index these is with `S1[i,j]`. To extract the value from the parent array `A`, the natural approach is to replace `S1[i,j]` with `A[i,1,(2:3)[j]]` and `S2[i,j]` with `A[1,i,(2:3)[j]]`. The key feature of the design of SubArrays is that this index replacement can be performed without any runtime overhead. ## SubArray design ### Type parameters and fields The strategy adopted is first and foremost expressed in the definition of the type: ```julia struct SubArray{T,N,P,I,L} <: AbstractArray{T,N} parent::P indices::I offset1::Int # for linear indexing and pointer, only valid when L==true stride1::Int # used only for linear indexing ... end ``` `SubArray` has 5 type parameters. The first two are the standard element type and dimensionality. The next is the type of the parent `AbstractArray`. The most heavily-used is the fourth parameter, a `Tuple` of the types of the indices for each dimension. The final one, `L`, is only provided as a convenience for dispatch; it's a boolean that represents whether the index types support fast linear indexing. More on that later. If in our example above `A` is a `Array{Float64, 3}`, our `S1` case above would be a `SubArray{Float64,2,Array{Float64,3},Tuple{Base.Slice{Base.OneTo{Int64}},Int64,UnitRange{Int64}},false}`. Note in particular the tuple parameter, which stores the types of the indices used to create `S1`. Likewise, ```jldoctest subarray julia> S1.indices (Base.Slice(Base.OneTo(2)), 1, 2:3) ``` Storing these values allows index replacement, and having the types encoded as parameters allows one to dispatch to efficient algorithms. ### Index translation Performing index translation requires that you do different things for different concrete `SubArray` types. For example, for `S1`, one needs to apply the `i,j` indices to the first and third dimensions of the parent array, whereas for `S2` one needs to apply them to the second and third. The simplest approach to indexing would be to do the type-analysis at runtime: ```julia parentindices = Vector{Any}() for thisindex in S.indices ... if isa(thisindex, Int) # Don't consume one of the input indices push!(parentindices, thisindex) elseif isa(thisindex, AbstractVector) # Consume an input index push!(parentindices, thisindex[inputindex[j]]) j += 1 elseif isa(thisindex, AbstractMatrix) # Consume two input indices push!(parentindices, thisindex[inputindex[j], inputindex[j+1]]) j += 2 elseif ... end S.parent[parentindices...] ``` Unfortunately, this would be disastrous in terms of performance: each element access would allocate memory, and involves the running of a lot of poorly-typed code. The better approach is to dispatch to specific methods to handle each type of stored index. That's what `reindex` does: it dispatches on the type of the first stored index and consumes the appropriate number of input indices, and then it recurses on the remaining indices. In the case of `S1`, this expands to ```julia Base.reindex(S1, S1.indices, (i, j)) == (i, S1.indices[2], S1.indices[3][j]) ``` for any pair of indices `(i,j)` (except [`CartesianIndex`](@ref)s and arrays thereof, see below). This is the core of a `SubArray`; indexing methods depend upon `reindex` to do this index translation. Sometimes, though, we can avoid the indirection and make it even faster. ### Linear indexing Linear indexing can be implemented efficiently when the entire array has a single stride that separates successive elements, starting from some offset. This means that we can pre-compute these values and represent linear indexing simply as an addition and multiplication, avoiding the indirection of `reindex` and (more importantly) the slow computation of the cartesian coordinates entirely. For `SubArray` types, the availability of efficient linear indexing is based purely on the types of the indices, and does not depend on values like the size of the parent array. You can ask whether a given set of indices supports fast linear indexing with the internal `Base.viewindexing` function: ```jldoctest subarray julia> Base.viewindexing(S1.indices) IndexCartesian() julia> Base.viewindexing(S2.indices) IndexLinear() ``` This is computed during construction of the `SubArray` and stored in the `L` type parameter as a boolean that encodes fast linear indexing support. While not strictly necessary, it means that we can define dispatch directly on `SubArray{T,N,A,I,true}` without any intermediaries. Since this computation doesn't depend on runtime values, it can miss some cases in which the stride happens to be uniform: ```jldoctest julia> A = reshape(1:4*2, 4, 2) 4×2 reshape(::UnitRange{Int64}, 4, 2) with eltype Int64: 1 5 2 6 3 7 4 8 julia> diff(A[2:2:4,:][:]) 3-element Vector{Int64}: 2 2 2 ``` A view constructed as `view(A, 2:2:4, :)` happens to have uniform stride, and therefore linear indexing indeed could be performed efficiently. However, success in this case depends on the size of the array: if the first dimension instead were odd, ```jldoctest julia> A = reshape(1:5*2, 5, 2) 5×2 reshape(::UnitRange{Int64}, 5, 2) with eltype Int64: 1 6 2 7 3 8 4 9 5 10 julia> diff(A[2:2:4,:][:]) 3-element Vector{Int64}: 2 3 2 ``` then `A[2:2:4,:]` does not have uniform stride, so we cannot guarantee efficient linear indexing. Since we have to base this decision based purely on types encoded in the parameters of the `SubArray`, `S = view(A, 2:2:4, :)` cannot implement efficient linear indexing. ### A few details * Note that the `Base.reindex` function is agnostic to the types of the input indices; it simply determines how and where the stored indices should be reindexed. It not only supports integer indices, but it supports non-scalar indexing, too. This means that views of views don't need two levels of indirection; they can simply re-compute the indices into the original parent array! * Hopefully by now it's fairly clear that supporting slices means that the dimensionality, given by the parameter `N`, is not necessarily equal to the dimensionality of the parent array or the length of the `indices` tuple. Neither do user-supplied indices necessarily line up with entries in the `indices` tuple (e.g., the second user-supplied index might correspond to the third dimension of the parent array, and the third element in the `indices` tuple). What might be less obvious is that the dimensionality of the stored parent array must be equal to the number of effective indices in the `indices` tuple. Some examples: ```julia A = reshape(1:35, 5, 7) # A 2d parent Array S = view(A, 2:7) # A 1d view created by linear indexing S = view(A, :, :, 1:1) # Appending extra indices is supported ``` Naively, you'd think you could just set `S.parent = A` and `S.indices = (:,:,1:1)`, but supporting this dramatically complicates the reindexing process, especially for views of views. Not only do you need to dispatch on the types of the stored indices, but you need to examine whether a given index is the final one and "merge" any remaining stored indices together. This is not an easy task, and even worse: it's slow since it implicitly depends upon linear indexing. Fortunately, this is precisely the computation that `ReshapedArray` performs, and it does so linearly if possible. Consequently, `view` ensures that the parent array is the appropriate dimensionality for the given indices by reshaping it if needed. The inner `SubArray` constructor ensures that this invariant is satisfied. * [`CartesianIndex`](@ref) and arrays thereof throw a nasty wrench into the `reindex` scheme. Recall that `reindex` simply dispatches on the type of the stored indices in order to determine how many passed indices should be used and where they should go. But with `CartesianIndex`, there's no longer a one-to-one correspondence between the number of passed arguments and the number of dimensions that they index into. If we return to the above example of `Base.reindex(S1, S1.indices, (i, j))`, you can see that the expansion is incorrect for `i, j = CartesianIndex(), CartesianIndex(2,1)`. It should *skip* the `CartesianIndex()` entirely and return: ```julia (CartesianIndex(2,1)[1], S1.indices[2], S1.indices[3][CartesianIndex(2,1)[2]]) ``` Instead, though, we get: ```julia (CartesianIndex(), S1.indices[2], S1.indices[3][CartesianIndex(2,1)]) ``` Doing this correctly would require *combined* dispatch on both the stored and passed indices across all combinations of dimensionalities in an intractable manner. As such, `reindex` must never be called with `CartesianIndex` indices. Fortunately, the scalar case is easily handled by first flattening the `CartesianIndex` arguments to plain integers. Arrays of `CartesianIndex`, however, cannot be split apart into orthogonal pieces so easily. Before attempting to use `reindex`, `view` must ensure that there are no arrays of `CartesianIndex` in the argument list. If there are, it can simply "punt" by avoiding the `reindex` calculation entirely, constructing a nested `SubArray` with two levels of indirection instead.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
6106
# System Image Building ## Building the Julia system image Julia ships with a preparsed system image containing the contents of the `Base` module, named `sys.ji`. This file is also precompiled into a shared library called `sys.{so,dll,dylib}` on as many platforms as possible, so as to give vastly improved startup times. On systems that do not ship with a precompiled system image file, one can be generated from the source files shipped in Julia's `DATAROOTDIR/julia/base` folder. This operation is useful for multiple reasons. A user may: * Build a precompiled shared library system image on a platform that did not ship with one, thereby improving startup times. * Modify `Base`, rebuild the system image and use the new `Base` next time Julia is started. * Include a `userimg.jl` file that includes packages into the system image, thereby creating a system image that has packages embedded into the startup environment. The [`PackageCompiler.jl` package](https://github.com/JuliaLang/PackageCompiler.jl) contains convenient wrapper functions to automate this process. ## System image optimized for multiple microarchitectures The system image can be compiled simultaneously for multiple CPU microarchitectures under the same instruction set architecture (ISA). Multiple versions of the same function may be created with minimum dispatch point inserted into shared functions in order to take advantage of different ISA extensions or other microarchitecture features. The version that offers the best performance will be selected automatically at runtime based on available CPU features. ### Specifying multiple system image targets A multi-microarchitecture system image can be enabled by passing multiple targets during system image compilation. This can be done either with the `JULIA_CPU_TARGET` make option or with the `-C` command line option when running the compilation command manually. Multiple targets are separated by `;` in the option string. The syntax for each target is a CPU name followed by multiple features separated by `,`. All features supported by LLVM are supported and a feature can be disabled with a `-` prefix. (`+` prefix is also allowed and ignored to be consistent with LLVM syntax). Additionally, a few special features are supported to control the function cloning behavior. 1. `clone_all` By default, only functions that are the most likely to benefit from the microarchitecture features will be cloned. When `clone_all` is specified for a target, however, **all** functions in the system image will be cloned for the target. The negative form `-clone_all` can be used to prevent the built-in heuristic from cloning all functions. 2. `base(<n>)` Where `<n>` is a placeholder for a non-negative number (e.g. `base(0)`, `base(1)`). By default, a partially cloned (i.e. not `clone_all`) target will use functions from the default target (first one specified) if a function is not cloned. This behavior can be changed by specifying a different base with the `base(<n>)` option. The `n`th target (0-based) will be used as the base target instead of the default (`0`th) one. The base target has to be either `0` or another `clone_all` target. Specifying a non-`clone_all` target as the base target will cause an error. 3. `opt_size` This causes the function for the target to be optimized for size when there isn't a significant runtime performance impact. This corresponds to `-Os` GCC and Clang option. 4. `min_size` This causes the function for the target to be optimized for size that might have a significant runtime performance impact. This corresponds to `-Oz` Clang option. As an example, at the time of this writing, the following string is used in the creation of the official `x86_64` Julia binaries downloadable from julialang.org: ``` generic;sandybridge,-xsaveopt,clone_all;haswell,-rdrnd,base(1) ``` This creates a system image with three separate targets; one for a generic `x86_64` processor, one with a `sandybridge` ISA (explicitly excluding `xsaveopt`) that explicitly clones all functions, and one targeting the `haswell` ISA, based off of the `sandybridge` sysimg version, and also excluding `rdrnd`. When a Julia implementation loads the generated sysimg, it will check the host processor for matching CPU capability flags, enabling the highest ISA level possible. Note that the base level (`generic`) requires the `cx16` instruction, which is disabled in some virtualization software and must be enabled for the `generic` target to be loaded. Alternatively, a sysimg could be generated with the target `generic,-cx16` for greater compatibility, however note that this may cause performance and stability problems in some code. ### Implementation overview This is a brief overview of different part involved in the implementation. See code comments for each components for more implementation details. 1. System image compilation The parsing and cloning decision are done in `src/processor*`. We currently support cloning of function based on the present of loops, simd instructions, or other math operations (e.g. fastmath, fma, muladd). This information is passed on to `src/llvm-multiversioning.cpp` which does the actual cloning. In addition to doing the cloning and insert dispatch slots (see comments in `MultiVersioning::runOnModule` for how this is done), the pass also generates metadata so that the runtime can load and initialize the system image correctly. A detail description of the metadata is available in `src/processor.h`. 2. System image loading The loading and initialization of the system image is done in `src/processor*` by parsing the metadata saved during system image generation. Host feature detection and selection decision are done in `src/processor_*.cpp` depending on the ISA. The target selection will prefer exact CPU name match, larger vector register size, and larger number of features. An overview of this process is in `src/processor.cpp`.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
11415
# More about types 使用Julia一段时间之后,你就会体会到类型在其中的基础性作用。本部分我们将深入到类型体系的内部,并着重关注 [Parametric Types](@ref)。 ## Types and sets (and `Any` and `Union{}`/`Bottom`) Julia的类型系统很容易会被看作是一种集合(set)。程序处理个体值,类型处理值的集合。但是集合与类型是两个不同的概念。一组值组成的集合 [`Set`](@ref) 本身也是一个值的集合。而类型描述的是一个组*可能*值组成的集合,即类型的值是不确定的。 函数 [`typeof`](@ref) 可以返回*具体类型* `T` 包含的值的直接标签 `T`。而*抽象类型*描述的集合则可能会更大。 类型 [`Any`](@ref) 包含所有可能值。类型 [`Integer`](@ref) 是 `Any` 的一个子类型,而 `Integer`的子类型有包括 `Int`,[`Int8`](@ref) 等其他具体类型。在内部表征上,Julia 类型系统还非常依赖类型 `Bottom`,也记做`Union{}`。这对应于集合中的空集。 Julia类型系统支持集合理论的标准操作:你可以用 `T1 <: T2` 来判断类型 `T1` 是否是`T2` 的子集(子类型)。 [`typeintersect`](@ref) 和 [`typejoin`](@ref) 可用来计算两个类型的交集和合集;用 [`Union`](@ref) 用于集合所有列出的类型。 ```jldoctest julia> typeintersect(Int, Float64) Union{} julia> Union{Int, Float64} Union{Float64, Int64} julia> typejoin(Int, Float64) Real julia> typeintersect(Signed, Union{UInt8, Int8}) Int8 julia> Union{Signed, Union{UInt8, Int8}} Union{UInt8, Signed} julia> typejoin(Signed, Union{UInt8, Int8}) Integer julia> typeintersect(Tuple{Integer, Float64}, Tuple{Int, Real}) Tuple{Int64, Float64} julia> Union{Tuple{Integer, Float64}, Tuple{Int, Real}} Union{Tuple{Int64, Real}, Tuple{Integer, Float64}} julia> typejoin(Tuple{Integer, Float64}, Tuple{Int, Real}) Tuple{Integer, Real} ``` 这些操作看起来很抽象,但是他们处于 Julia 语言的核心位置。例如,方法的派发过程就是对方法列表中的项目进行逐步搜索,直到找到一个其类型是方法标签子类型的参数元组为止。该算法有效的前提是方法必须按照特异性(specificity)进行排序,搜索过程必须从最具特异性的开始。所以,Julia 也需要对类型进行偏序排序(partial order),该函数与 `<:` 类似但又不完全相同。 ## `UnionAll`类型 Julia 的类型系统也可以表征类型的*迭代合集*(iterated union),即某个变量的所有值的集合。当参数化类型的某些参数值是未知数时,迭代合集是非常有用的。 例如,下面这个数组 `Array{Int,2}` 有两个参数。如果其成分类型未知,该数组可以写成 `Array{T,2} where T`。该数组是取所有不同 `T` 值后的所有数组`Array{T,2}` 的合集:`Union{Array{Int8,2}, Array{Int16,2}, ...}`。 类型的迭代集合由类型为`UnionAll`的对象表征。`UnionAll`对象有一个类型为 `TypeVar` 的变量,此处为`T`,和一个包裹化的类型,此处为 `Array{T,2}`。 考虑下面的例子: ```julia f1(A::Array) = 1 f2(A::Array{Int}) = 2 f3(A::Array{T}) where {T<:Any} = 3 f4(A::Array{Any}) = 4 ``` 如 [Function calls](@ref) 中描述的,函数 `f3` 的签名是元组类型的 `UnionAll` 类型包裹:`Tuple{typeof(f3), Array{T}} where T`。此处除 `f4` 外所有函数都可以被`a = [1,2]`调用;除 `f2` 外所有函数都可以被 `b = Any[1,2]` 调用。 `dump()` 函数可用于进一步查看这些类型: ```jldoctest julia> dump(Array) UnionAll var: TypeVar name: Symbol T lb: Union{} ub: Any body: UnionAll var: TypeVar name: Symbol N lb: Union{} ub: Any body: Array{T, N} <: DenseArray{T, N} ``` 这说明数组 `Array` 实际上命名了一个 `UnionAll` 类型。嵌套其中的参数也都是 `UnionAll` 类型。句法 `Array{Int,2}` 等价于`Array{Int}{2}`。`UnionAll` 在内部会被实例化为变量的特定值,每次一个,从最外侧开始。这使得省略尾端参数是自然而有意义的:类型 `Array{Int}` 与类型 `Array{Int, N} where N`。 `TypeVar` 本身不是类型,而是 `UnionAll` 类型的一个内部结构成分。类型变量的值会有上界和下界,分别由字段`lb` 和 `ub` 表示。符号 `name` 是纯装饰性的(cosmetic)。在内部 `TypeVar` 是通过地址比较的。所以为了区分“不同”变量类型,`TypeVar` 是一个可更改类型,但通常不应修改它们。 你也可以手动创建 `TypeVar`: ```jldoctest julia> TypeVar(:V, Signed, Real) Signed<:V<:Real ``` 你可以用更简便的方式省掉除 `name` 之外的任意参数。 句法 `Array{T} where T<:Integer` 会被降级为如下格式。 ```julia let T = TypeVar(:T,Integer) UnionAll(T, Array{T}) end ``` 所以极少需要手动建构 `TypeVar`(实际上这也应该是尽量避免的)。 ## 自由变量 *自由*类型变量在类型系统中是至关重要的。如果类型 `T` 不包含一个引入变量 `V` 的 `UnionAll` 类型,那么类型 `T` 中的变量 `V` 就是自由的 (free)。例如,类型 `Array{Array{V} where V<:Integer}` 没有自由变量,但该类型的子成分 `Array{V}` 则包含了一个自由变量 `V`。 从某种程度上讲,一个包含自由变量的类型根本就不是一个类型。例如,类型 `Array{Array{T}} where T` 是一个成分为数组的数组,且所有子数组元素的类型都相同。其内部类型 `Array{T}` 乍一看似乎包含所有数组类型。但外部数组的成分必须有*相同*类型,所以 `Array{T}` 不能指向所有数组。我们可以说 `Array{T}` 出现了很多次,但每次 `T` 值都必须相同。 故此, C 应用程序接口函数 `jl_has_free_typevars` 是非常重要的。若该函数的返回值为真,则说明类型中存在自由变量。此时子类型判断和其他类型函数中的返回结果没有太多意义。 ## 类型名称`TypeNames` 下面两个数组 [`Array`](@ref) 类型在功能上是相同的,但有不同的打印方式: ```jldoctest julia> TV, NV = TypeVar(:T), TypeVar(:N) (T, N) julia> Array Array julia> Array{TV, NV} Array{T, N} ``` 二者之间的差别可以通过类型的名称 `name` 字段来区分。名称 `name` 字段是一个类型为 `TypeName` 的对象。 ```julia-repl julia> dump(Array{Int,1}.name) TypeName name: Symbol Array module: Module Core names: empty SimpleVector wrapper: UnionAll var: TypeVar name: Symbol T lb: Union{} ub: Any body: UnionAll var: TypeVar name: Symbol N lb: Union{} ub: Any body: Array{T, N} <: DenseArray{T, N} cache: SimpleVector ... linearcache: SimpleVector ... hash: Int64 -7900426068641098781 mt: MethodTable name: Symbol Array defs: Nothing nothing cache: Nothing nothing max_args: Int64 0 kwsorter: #undef module: Module Core : Int64 0 : Int64 0 ``` 与此相关的字段是包装器 `wrapper`,该字段存储了一个指向顶层类型(tip-level)的引用,用以产生新的数组 `Array` 类型。 ```julia-repl julia> pointer_from_objref(Array) Ptr{Cvoid} @0x00007fcc7de64850 julia> pointer_from_objref(Array.body.body.name.wrapper) Ptr{Cvoid} @0x00007fcc7de64850 julia> pointer_from_objref(Array{TV,NV}) Ptr{Cvoid} @0x00007fcc80c4d930 julia> pointer_from_objref(Array{TV,NV}.name.wrapper) Ptr{Cvoid} @0x00007fcc7de64850 ``` 数组 [`Array`](@ref) 的包装器 `wrapper` 字段指向它自己,而在数组 `Array{TV,NV}` 中,该字段则指回该类型的原始定义。 那其他字段都是什么作用呢?字段`hash` 会给每个类型指派一个整数。要查看 `cache` 字段的内容,最好选不像数组那么常用的类型。我们可以自己创造一个类型: ```jldoctest julia> struct MyType{T,N} end julia> MyType{Int,2} MyType{Int64, 2} julia> MyType{Float32, 5} MyType{Float32, 5} ``` 当参数类型被实例化时,每个具体类型都会被存储到类型缓存中(`MyType.body.body.name.cache`)。不过含有自由变量的实例是不会被缓存的。 ## 元组类型 元组类型是一个有趣的特例。为了使派发在诸如 `x::Tuple` 之类的声明中正常工作,该类型必须能包含所有元组。我们可以查看一下元组的参数: ```jldoctest julia> Tuple Tuple julia> Tuple.parameters svec(Vararg{Any}) ``` 与其他类型不同,元组类型的参数是共变的(covariant),所以类型 `Tuple` 能与任何类型的元组相匹配。 ```jldoctest julia> typeintersect(Tuple, Tuple{Int,Float64}) Tuple{Int64, Float64} julia> typeintersect(Tuple{Vararg{Any}}, Tuple{Int,Float64}) Tuple{Int64, Float64} ``` 但是,如果一个可变元组 (`Vararg`) 类型含有自由变量,那么他描述的元组类型则可能就是不同的: ```jldoctest julia> typeintersect(Tuple{Vararg{T} where T}, Tuple{Int,Float64}) Tuple{Int64, Float64} julia> typeintersect(Tuple{Vararg{T}} where T, Tuple{Int,Float64}) Union{} ``` 当 `T` 绑定的 `UnionAll` 类型位于元组 `Tuple` 之外,即 `T` 是元组 `Tuple` 的自由变量时,一个唯一的 `T` 值必须作用与整个类型。此时异质的元组是不匹配的。 最后,意识到元组 `Tuple{}` 的独特性是有意义的: ```jldoctest julia> Tuple{} Tuple{} julia> Tuple{}.parameters svec() julia> typeintersect(Tuple{}, Tuple{Int}) Union{} ``` 那么什么是元组类型的基本(primary)类型呢? ```julia-repl julia> pointer_from_objref(Tuple) Ptr{Cvoid} @0x00007f5998a04370 julia> pointer_from_objref(Tuple{}) Ptr{Cvoid} @0x00007f5998a570d0 julia> pointer_from_objref(Tuple.name.wrapper) Ptr{Cvoid} @0x00007f5998a04370 julia> pointer_from_objref(Tuple{}.name.wrapper) Ptr{Cvoid} @0x00007f5998a04370 ``` 所以 `Tuple == Tuple{Vararg{Any}}` 事实上就是其基本类型。 ## 对角变量 考虑类型 `Tuple{T,T} where T`。使用该标签的方法看起来会是下面的样子: ```julia f(x::T, y::T) where {T} = ... ``` 根据对类型 `UnionAll` 的通常理解, `T` 将覆盖所有的类型,包括 `T`,所以此类型应该等价于 `Tuple{Any,Any}`。但是这种理解会面临很多实际的问题。 首先,`T` 值需要在方法定之内可及。对诸如 `f(1, 1.0)` 的调用来说,`T` 的值是不明确的。`T` 可以是 `Union{Int,Float64}` 或 [`Real`](@ref)。直觉上,声明 `x::T` 意味着 `T` 应该为 `x` 的类型,即 `T === typeof(x)`。为了保有这种不变性, 该方法应满足如下关系: `typeof(x) === typeof(y) === T`。 这说明该方法只能被拥有相同类型的参数元组调用。 能依据两个值的类型是否相同进行派发是非常有用的(例如类型提升系统就用到了该机制)。所以我们有很多理由给 `Tuple{T,T} where T` 一个不同的含义。为此,我们在子类型系统中增加了如下规则:\textbf{如果一个变量在共变位置上出现了不止一次,那么其作用范围将仅局限于具体类型}。共变位置指在一个变量和引入该变量的 `UnionAll` 类型之间,只出现了元组 `Tuple` 类型和联合 `Union` 类型。这些变量被称为对角变量(diagonal variables)或具体变量(concrete variables)。 例如,元组 `Tuple{T,T} where T` 可以被看作是如下元组的集合 `Union{Tuple{Int8,Int8}, Tuple{Int16,Int16}, ...}`, 即 `T` 包括所有的具体类型。该规则会产生一些有趣的子类型结果。例如 `Tuple{Real,Real}` 不是 `Tuple{T,T} where T` 的子类型,因为前者包含了诸如 `Tuple{Int8,Int16}` 的子类型,该子类型的元素类型是不同的。`Tuple{Real,Real}` 和 `Tuple{T,T} where T` 又一个不容小视的交集 `Tuple{T,T} where T<:Real`。但是 `Tuple{Real}` 是 `Tuple{T} where T` 的子集,因为此时 `T` 只出现了一次,所以是不对角的。 现在考虑如下签名: ```julia f(a::Array{T}, x::T, y::T) where {T} = ... ``` 此例中, `T` 出现在了非共变位置,即 `Array{T}` 之内。 这意味着无论数组传递的类型是什么,该类型都会无歧义的决定 `T`,即 `T` 又一个等价性限制(equality constraint)。此时是不需要对角规则的,因为数组决定了 `T`,然后 `x` 和 `y` 则可以是 `T` 的任何子类型。所以非共变位置的变量均不受对角线规则的限制。上述定义的行为选择有一点矛盾,或许应该写成: ```julia f(a::Array{T}, x::S, y::S) where {T, S<:T} = ... ``` 为明确 `x` 和 `y` 应该有相同的类型。如果 `x` 和 `y` 可以有不同类型,这个版本的签名可以引入针对类型 `y` 的第三个变量。 下面一个难题是合集 `Union{}` 和对角线变量的交互作用,例如 ```julia f(x::Union{Nothing,T}, y::T) where {T} = ... ``` 考虑一下这个生命的含义。`y` 的类型是 `T`。 而 `x` 的类型或者与 `y` 相同 `T` 或类型为空 [`Nothing`](@ref)。下面调用都是匹配的。 ```julia f(1, 1) f("", "") f(2.0, 2.0) f(nothing, 1) f(nothing, "") f(nothing, 2.0) ``` 上述例子告诉我们:当 `x` 的类型是空集 `nothing::Nothing` 时,`y` 的类型就没有任何限制了。此时方法标签中字段 `y` 可以是任何类型,即 `y::Any`。确实,下面两个类型是等价的: ```julia (Tuple{Union{Nothing,T},T} where T) == Union{Tuple{Nothing,Any}, Tuple{T,T} where T} ``` 一般的规则是:如果出现在共变位置的一个具体变量只被子类型算法(subtyping algorithm)*使用一次*,则该具体变量的行为就会像一个抽象变量。上例中,当 `x` 类型为空时 `Nothing`,集合 `Union{Nothing,T}` 中的类型 `T` 不起作用,即 `T` 只在第二个槽中被用到。此时,无论把 `Tuple{T} where T` 中的 `T` 限制为具体类型还是不限制,该类型都等价于 `Tuple{Any}`。 当变量出现在*非共变* 位置时,无论是否被使用,该变量都不再是具体变量。否则类型的行为就会因为比较对象类型的不同而不同,从而违反传递律(transitive)。例如, ```julia Tuple{Int,Int8,Vector{Integer}} <: Tuple{T,T,Vector{Union{Integer,T}}} where T ``` 如果忽略掉合集 `Union` 内部的 `T`,则 `T` 就是具体的,且上述判断结果是 “否”,因为左侧元组前两个成分的类型是不同的。这两个类型不相同。再看下例: ```julia Tuple{Int,Int8,Vector{Any}} <: Tuple{T,T,Vector{Union{Integer,T}}} where T ``` 此处合集 `Union` 内的 `T` 是不能被忽略的,因为 `T` 必须等于 `Any`,即 `T == Any`。所以 `T` 不能是具体的,且判断结果为“真”。所以,类型 `T` 的具体还是抽象是受制于其他类型特征的。这是不被接受的,因为类型的含义必须是清晰和自洽的。所以,向量 `Vector` 之内的 `T` 需要同时考虑这两种情况。 ## 对角变量的子类型 对角变量的子系统算法(substyping algorithm)有两个成分:(1)确定变量出现次数;(2)确保对角变量只包含具体类型。 第一个任务由两个计数器完成。环境中的每个自由变量都有两个计数器 `occurs_inv` 和 `occurs_cov` (在文件 `src/subtype.c` 中),分别用于追踪不变和共变的出现次数。如果 `occurs_inv == 0 && occurs_cov > 1` 则这个变量就是对角的。 第二个任务通过在变量下界添加一个条件实现。子类型算法在运行过程中会逐渐压缩每个变量的界限(提高下界和降低上界),以保证子类型关系在该变量范围内能继续保持。评估完对角变量合集类型 `UnionAll` 后,可以查看边界的最终值。因为变量必须是具体的,所以如果其下边界不是具体类型的子类型,就会产生矛盾。例如,抽象类型 [`AbstractArray`](@ref) 不可能是一个具体类型的子类型,而具体类型 `Int` 则可以,空类型 `Bottom` 也可以。如果下边界没通过该测试,算法将终止并返回 `false`。 例如,如果 `T` 是 `Union{Int,String}` 的上位类型,则 `Tuple{Int,String}` 将是 `Tuple{T,T} where T` 的子集,即 `Tuple{Int,String} <: Tuple{T,T} where T` 的返回值将为真。但 `Union{Int,String}` 是一个抽象类型,所以上述关系不成立。 具体性判断是由函数 `is_leaf_bound` 完成的。注意该函数与函数 `jl_is_leaf_type` 稍微有点不同,因为其对类型 `Bottom` 的返回值也为真 `true`。该函数目前是启发式的,无法捕获所有的具体类型。该函数的困难在于,其他变量类型的界限会影响当下变量下界限的具体与否。例如,只有当 `T` 的上界限和下界限都是 `Int` 时,类型 `Vector{T}` 才和具体类型 `Vector{Int}` 相同。目前,设计者还没有想出一个完备的算法来解决该问题。 ## 内部机制 大部分类型处理操作都存储在 `jltypes.c` 和 `subtype.c` 这两个文件中。了解自类型系统的最好方式是查看其工作方式。用 `make debug` 创建且在调试器中运行程序。手册[gdb debugging tips](@ref)章中有一些有用的建议。 因为 REPL 中也经常使用子类型代码 -- 这些代码中的断点也经常被触发。所以定义下面函数并在 `jl_breakpoint` 中设定一个断点将非常方便: ```julia-repl julia> function mysubtype(a,b) ccall(:jl_breakpoint, Cvoid, (Any,), nothing) a <: b end ``` 一旦该断点被触发,你就可以在其他函数中设定断点了。 作为热身,试一下下面代码 ```julia mysubtype(Tuple{Int, Float64}, Tuple{Integer, Real}) ``` 你也可以用一个更复杂的例子让其变得更有趣: ```julia mysubtype(Tuple{Array{Int,2}, Int8}, Tuple{Array{T}, T} where T) ``` ## 子类型和方法排序 函数 `type_morespecific` 可用来对函数的方法列表从最具特异行到最不具特异性进行部分排序(partial order)。特异性是严格的:如果 `a` 比 `b` 更特异,则 `b` 就不比 `a` 更特异。 如果 `a` 是 `b` 的严格子类型(strict subtype),那么 `a` 就自动的比 `b` 更特异。接下来,函数 `type_morespecific` 还引进了一些不太形式化的规则。例如,子类型 `subtype` 对参数的数量敏感,而函数 `type_morespecific` 则不敏感。特别的,`Tuple{Int,AbstractFloat}` 比 `Tuple{Integer}` 更特异,虽然前者不是后者的子类型。此外, `Tuple{Int,AbstractFloat}` 和 `Tuple{Integer,Float64}` 不存在特异性关系。类似的,`Tuple{Int,Vararg{Int}}` 不是 `Tuple{Integer}` 的子类型,但前者比后者更特异。但是,长度确实也影响特异性关系`morespecific`,如 `Tuple{Int,Int}` 比 `Tuple{Int,Vararg{Int}}` 更特异。 要调试方法的排序,定义下面的函数很方便: ```julia type_morespecific(a, b) = ccall(:jl_type_morespecific, Cint, (Any,Any), a, b) ``` 它可以被用来测试元组 `a` 是否比元组 `b` 更特异。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3151
# 在Julia中使用Valgrind [Valgrind](http://valgrind.org/) is a tool for memory debugging, memory leak detection, and profiling. This section describes things to keep in mind when using Valgrind to debug memory issues with Julia. ## General considerations By default, Valgrind assumes that there is no self modifying code in the programs it runs. This assumption works fine in most instances but fails miserably for a just-in-time compiler like `julia`. For this reason it is crucial to pass `--smc-check=all-non-file` to `valgrind`, else code may crash or behave unexpectedly (often in subtle ways). In some cases, to better detect memory errors using Valgrind it can help to compile `julia` with memory pools disabled. The compile-time flag `MEMDEBUG` disables memory pools in Julia, and `MEMDEBUG2` disables memory pools in FemtoLisp. To build `julia` with both flags, add the following line to `Make.user`: ```julia CFLAGS = -DMEMDEBUG -DMEMDEBUG2 ``` Another thing to note: if your program uses multiple workers processes, it is likely that you want all such worker processes to run under Valgrind, not just the parent process. To do this, pass `--trace-children=yes` to `valgrind`. ## Suppressions Valgrind will typically display spurious warnings as it runs. To reduce the number of such warnings, it helps to provide a [suppressions file](http://valgrind.org/docs/manual/manual-core.html#manual-core.suppress) to Valgrind. A sample suppressions file is included in the Julia source distribution at `contrib/valgrind-julia.supp`. The suppressions file can be used from the `julia/` source directory as follows: ``` $ valgrind --smc-check=all-non-file --suppressions=contrib/valgrind-julia.supp ./julia progname.jl ``` Any memory errors that are displayed should either be reported as bugs or contributed as additional suppressions. Note that some versions of Valgrind are [shipped with insufficient default suppressions](https://github.com/JuliaLang/julia/issues/8314#issuecomment-55766210), so that may be one thing to consider before submitting any bugs. ## Running the Julia test suite under Valgrind It is possible to run the entire Julia test suite under Valgrind, but it does take quite some time (typically several hours). To do so, run the following command from the `julia/test/` directory: ``` valgrind --smc-check=all-non-file --trace-children=yes --suppressions=$PWD/../contrib/valgrind-julia.supp ../julia runtests.jl all ``` If you would like to see a report of "definite" memory leaks, pass the flags `--leak-check=full --show-leak-kinds=definite` to `valgrind` as well. ## Caveats Valgrind currently [does not support multiple rounding modes](https://bugs.kde.org/show_bug.cgi?id=136779), so code that adjusts the rounding mode will behave differently when run under Valgrind. In general, if after setting `--smc-check=all-non-file` you find that your program behaves differently when run under Valgrind, it may help to pass `--tool=none` to `valgrind` as you investigate further. This will enable the minimal Valgrind machinery but will also run much faster than when the full memory checker is enabled.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
28049
# [多维数组](@id man-multi-dim-arrays) 与大多数科学计算语言一样,Julia 提供原生的数组实现。 大多数科学计算语言非常重视其数组实现,而牺牲了其他容器。Julia 没有以任何特殊方式处理数组。就像和其它用 Julia 写的代码一样,Julia 的数组库几乎完全是用 Julia 自身实现的,并且由编译器保证其性能。因此,也可以通过继承 [`AbstractArray`](@ref) 来定义自定义数组类型。 有关实现自定义数组类型的更多详细信息,请参阅 [AbstractArray 接口的手册部分](@ref man-interface-array)。 数组是存储在多维网格中对象的集合。在最一般的情况下, 数组中的对象可能是 [`Any`](@ref) 类型。 对于大多数计算上的需求,数组中对象的类型应该更加具体,例如 [`Float64`](@ref) 或 [`Int32`](@ref)。 一般来说,与许多其他科学计算语言不同,Julia 不希望为了性能而以向量化的方式编写程序。Julia 的编译器使用类型推断,并为标量数组索引生成优化的代码,从而能够令用户方便地编写可读性良好的程序,而不牺牲性能,并且时常会减少内存使用。 在 Julia 中,所有函数的参数都是 [非复制的方式进行传递](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing)的(比如说,通过指针传递)。一些科学计算语言用传值的方式传递数组,尽管这样做可以防止数组在被调函数中被意外地篡改,但这也会导致不必要的数组拷贝。作为 Julia 的一个惯例,以一个 `!` 结尾的函数名它会对自己的一个或者多个参数的值进行修改或者销毁(例如,请比较 [`sort`](@ref) 和 [`sort!`](@ref))。被调函数必须进行显式拷贝,以确保它们不会无意中修改输入参数。很多不以`!`结尾的函数在实现的时候,都会先进行显式拷贝,然后调用一个以 `!` 结尾的同名函数,最后返回之前拷贝的副本。 ## 基本函数 | 函数 | 描述 | |:---------------------- |:-------------------------------------------------------------------------------- | | [`eltype(A)`](@ref) | `A` 中元素的类型 | | [`length(A)`](@ref) | `A` 中元素的数量 | | [`ndims(A)`](@ref) | `A` 的维数 | | [`size(A)`](@ref) | 一个包含 `A` 各个维度上元素数量的元组 | | [`size(A,n)`](@ref) | `A` 第 `n` 维中的元素数量 | | [`axes(A)`](@ref) | 一个包含 `A` 有效索引的元组 | | [`axes(A,n)`](@ref) | 第 `n` 维有效索引的范围 | | [`eachindex(A)`](@ref) | 一个访问 `A` 中每一个位置的高效迭代器 | | [`stride(A,k)`](@ref) | 在第 `k` 维上的间隔(stride)(相邻元素间的线性索引距离) | | [`strides(A)`](@ref) | 包含每一维上的间隔(stride)的元组 | ## 构造和初始化 Julia 提供了许多用于构造和初始化数组的函数。在下列函数中,参数 `dims ...` 可以是一个元组 tuple 来表示维数,也可以是一个可变长度的整数值作为维数。大部分函数的第一个参数都表示数组的元素类型 `T` 。如果类型 `T` 被省略,那么将默认为 [`Float64`](@ref)。 | 函数 | 描述 | |:---------------------------------- |:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [`Array{T}(undef, dims...)`](@ref) | 一个没有初始化的密集 [`Array`](@ref) | | [`zeros(T, dims...)`](@ref) | 一个全零 `Array` | | [`ones(T, dims...)`](@ref) | 一个元素均为 1 的 `Array` | | [`trues(dims...)`](@ref) | 一个每个元素都为 `true` 的 [`BitArray`](@ref) | | [`falses(dims...)`](@ref) | 一个每个元素都为 `false` 的 `BitArray` | | [`reshape(A, dims...)`](@ref) | 一个包含跟 `A` 相同数据但维数不同的数组 | | [`copy(A)`](@ref) | 拷贝 `A` | | [`deepcopy(A)`](@ref) | 深拷贝,即拷贝 `A`,并递归地拷贝其元素 | | [`similar(A, T, dims...)`](@ref) | 一个与`A`具有相同类型(这里指的是密集,稀疏等)的未初始化数组,但具有指定的元素类型和维数。第二个和第三个参数都是可选的,如果省略则默认为元素类型和 `A` 的维数。 | | [`reinterpret(T, A)`](@ref) | 与 `A` 具有相同二进制数据的数组,但元素类型为 `T` | | [`rand(T, dims...)`](@ref) | 一个随机 `Array`,元素值是 ``[0, 1)`` 半开区间中的均匀分布且服从一阶独立同分布 [^1] | | [`randn(T, dims...)`](@ref) | 一个随机 `Array`,元素为标准正态分布,服从独立同分布 | | [`Matrix{T}(I, m, n)`](@ref) | `m` 行 `n` 列的单位矩阵 (需要先执行 `using LinearAlgebra` 来才能使用 [`I`](@ref)) | | [`range(start, stop=stop, length=n)`](@ref) | 从 `start` 到 `stop` 的带有 `n` 个线性间隔元素的范围 | | [`fill!(A, x)`](@ref) | 用值 `x` 填充数组 `A` | | [`fill(x, dims...)`](@ref) | 一个被值 `x` 填充的 `Array` | [^1]: *iid*,独立同分布 要查看各种方法,我们可以将不同维数传递给这些构造函数,请考虑以下示例: ```jldoctest julia> zeros(Int8, 2, 3) 2×3 Matrix{Int8}: 0 0 0 0 0 0 julia> zeros(Int8, (2, 3)) 2×3 Matrix{Int8}: 0 0 0 0 0 0 julia> zeros((2, 3)) 2×3 Matrix{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 ``` 此处, `(2, 3)` 是一个元组 [`Tuple`](@ref) 并且第一个参数——元素类型是可选的, 默认值为 `Float64`. ## [数组常量](@id man-array-literals) 数组也可以直接用方括号来构造; 语法为 `[A, B, C, ...]` 创建一个一维数组(即一个向量),该一维数组的元素用逗号分隔。所创建的数组中元素的类型([`eltype`](@ref)) 自动由括号内参数的类型确定。如果所有参数类型都相同,则该类型称为数组的 `eltype`。 如果所有元素都有相同的[promotion type](@ref conversion-and-promotion),那么个元素都由[`convert`](@ref)转换成该类型并且该类型为数组的 `eltype`. 否则, 生成一个可以包含任意类型的异构数组—— `Vector{Any}` ;该构造方法包含字符 `[]`,此时构造过程无参数给出。 ```jldoctest julia> [1,2,3] # 元素类型为 Int 的向量 3-element Vector{Int64}: 1 2 3 julia> promote(1, 2.3, 4//5) # Int, Float64 以及 Rational 类型放在一起则会提升到 Float64 (1.0, 2.3, 0.8) julia> [1, 2.3, 4//5] # 从而它就是这个矩阵的元素类型 3-element Vector{Float64}: 1.0 2.3 0.8 julia> [] Any[] ``` ### [数组拼接](@id man-array-concatenation) 如果方括号里的参数不是由逗号分隔,而是由单个分号(`;`) 或者换行符分隔,那么每一个参数就不再解析为一个单独的数组元素,而是纵向拼接起来。   ```jldoctest julia> [1:2, 4:5] # 这里有一个逗号,因此并不会发生矩阵的拼接。这里居然的元素本身就是这些 range 2-element Vector{UnitRange{Int64}}: 1:2 4:5 julia> [1:2; 4:5] 4-element Vector{Int64}: 1 2 4 5 julia> [1:2 4:5 6] 5-element Vector{Int64}: 1 2 4 5 6 ``` 类似的,如果这些参数是被制表符、空格符或者两个分号所分隔,那么它们的内容就_横向拼接_在一起。 ```jldoctest julia> [1:2 4:5 7:8] 2×3 Matrix{Int64}: 1 4 7 2 5 8 julia> [[1,2] [4,5] [7,8]] 2×3 Matrix{Int64}: 1 4 7 2 5 8 julia> [1 2 3] # 数字可以被横向拼接 1×3 Matrix{Int64}: 1 2 3 julia> [1;; 2;; 3;; 4] 1×4 Matrix{Int64}: 1 2 3 4 ``` 单个分号(或换行符)和空格(或制表符)可以被结合起来使用进行横向或者纵向的拼接。 ```jldoctest julia> [1 2 3 4] 2×2 Matrix{Int64}: 1 2 3 4 julia> [zeros(Int, 2, 2) [1; 2] [3 4] 5] 3×3 Matrix{Int64}: 0 0 1 0 0 2 3 4 5 julia> [[1 1]; 2 3; [4 4]] 3×2 Matrix{Int64}: 1 1 2 3 4 4 ``` 空格(和制表符)的优先级高于分号,首先执行任何纵向拼接,然后拼接结果。 另一方面,使用双分号进行水平连接时,先纵向拼接再横向拼接。 ```jldoctest julia> [zeros(Int, 2, 2) ; [3 4] ;; [1; 2] ; 5] 3×3 Matrix{Int64}: 0 0 1 0 0 2 3 4 5 julia> [1:2; 4;; 1; 3:4] 3×2 Matrix{Int64}: 1 1 2 3 4 4 ``` 正如 `;` 和 `;;` 在第一维和第二维中拼接一样,使用更多的分号扩展了相同的通用方案。 分隔符中的分号数指定了特定的维度,因此`;;;` 在第三个维度中拼接,`;;;;` 在第四个维度中,依此类推。 较少的分号优先级高,因此较低的维度通常首先拼接。 ```jldoctest julia> [1; 2;; 3; 4;; 5; 6;;; 7; 8;; 9; 10;; 11; 12] 2×3×2 Array{Int64, 3}: [:, :, 1] = 1 3 5 2 4 6 [:, :, 2] = 7 9 11 8 10 12 ``` 像之前一样,用于水平拼接的空格(和制表符)的优先级高于任何数量的分号。 因此,高维数组也可以通过首先指定它们的行来编写,它们的元素以类似于它们的布局的方式进行文本排列: ```jldoctest julia> [1 3 5 2 4 6;;; 7 9 11 8 10 12] 2×3×2 Array{Int64, 3}: [:, :, 1] = 1 3 5 2 4 6 [:, :, 2] = 7 9 11 8 10 12 julia> [1 2;;; 3 4;;;; 5 6;;; 7 8] 1×2×2×2 Array{Int64, 4}: [:, :, 1, 1] = 1 2 [:, :, 2, 1] = 3 4 [:, :, 1, 2] = 5 6 [:, :, 2, 2] = 7 8 julia> [[1 2;;; 3 4];;;; [5 6];;; [7 8]] 1×2×2×2 Array{Int64, 4}: [:, :, 1, 1] = 1 2 [:, :, 2, 1] = 3 4 [:, :, 1, 2] = 5 6 [:, :, 2, 2] = 7 8 ``` 尽管它们都表示第二维中的连接,但空格(或制表符)和 `;;` 不能出现在同一个数组表达式中,除非双分号只是作为“行继续”字符。 这允许单个水平拼接跨越多行(不会将换行符解释为垂直拼接)。 ```jldoctest julia> [1 2 ;; 3 4] 1×4 Matrix{Int64}: 1 2 3 4 ``` 终止分号也可用于在最后添加 1 个长度为1的维度。 ```jldoctest julia> [1;;] 1×1 Matrix{Int64}: 1 julia> [2; 3;;;] 2×1×1 Array{Int64, 3}: [:, :, 1] = 2 3 ``` 更一般地,可以通过[`cat`](@ref) 函数来实现数组元素的拼接功能。 以下这些的语法为这些函数的简写形式,它们本身也是非常方便使用的: | 语法 | 函数 | 描述 | |:---------------------- |:---------------- |:---------------------------------------------------------------------------------------------------------- | | | [`cat`](@ref) | 沿着 s 的第 `k` 维拼接数组 | | `[A; B; C; ...]` | [`vcat`](@ref) | `cat(A...; dims=1) 的简写 | | `[A B C ...]` | [`hcat`](@ref) | `cat(A...; dims=2) 的简写 | | `[A B; C D; ...]` | [`hvcat`](@ref) | 同时沿垂直和水平方向拼接 | | `[A; C;; B; D;;; ...]` | [`hvncat`](@ref) | 同时进行 n 维拼接,其中分号的数量表示拼接所在的维度 | ### 指定类型的数组字面量 可以用 `T[A, B, C, ...]` 的方式声明一个元素为某种特定类型的数组。该方法定义一个元素类型为 `T` 的一维数组并且初始化元素为 `A`, `B`, `C`, ....。比如,`Any[x, y, z]` 会构建一个异构数组,该数组可以包含任意类型的元素。 类似的,拼接也可以用类型为前缀来指定结果的元素类型。 ```jldoctest julia> [[1 2] [3 4]] 1×4 Matrix{Int64}: 1 2 3 4 julia> Int8[[1 2] [3 4]] 1×4 Matrix{Int8}: 1 2 3 4 ``` ## [数组推导](@id man-comprehensions) (数组)推导提供了构造数组的通用且强大的方法。其语法类似于数学中的集合构造的写法: ``` A = [ F(x,y,...) for x=rx, y=ry, ... ] ``` 这种形式的含义是 `F(x,y,...)` 取其给定列表中变量 `x`,`y` 等的每个值进行计算。值可以指定为任何可迭代对象,但通常是 `1:n` 或 `2:(n-1)` 之类的范围,或者像 `[1.2, 3.4, 5.7]` 这样的显式数组值。结果是一个 N 维密集数组,将变量范围 `rx`,`ry` 等的维数拼接起来得到其维数,并且每次 `F(x,y,...)` 计算返回一个标量。 下面的示例计算当前元素和沿一维网格其左,右相邻元素的加权平均值: ```julia-repl julia> x = rand(8) 8-element Array{Float64,1}: 0.843025 0.869052 0.365105 0.699456 0.977653 0.994953 0.41084 0.809411 julia> [ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ] 6-element Array{Float64,1}: 0.736559 0.57468 0.685417 0.912429 0.8446 0.656511 ``` 生成的数组的类型取决于参与计算元素的类型,就像[数组字面量](@ref man-array-literals)一样。为了显式地控制类型,可以在数组推导之前指定类型。例如,我们可以要求推导的结果为单精度类型: ```julia Float32[ 0.25*x[i-1] + 0.5*x[i] + 0.25*x[i+1] for i=2:length(x)-1 ] ``` ## 生成器表达式 也可以在没有方括号的情况下编写(数组)推导,从而产生称为生成器的对象。可以迭代此对象以按需生成值,而不是预先分配数组并存储它们(请参阅 [迭代](@ref Iteration))。例如,以下表达式在不分配内存的情况下对一个序列进行求和: ```jldoctest julia> sum(1/n^2 for n=1:1000) 1.6439345666815615 ``` 在参数列表中使用具有多个维度的生成器表达式时,需要使用括号将生成器与后续参数分开: ```julia-repl julia> map(tuple, 1/(i+j) for i=1:2, j=1:2, [1:4;]) ERROR: syntax: invalid iteration specification ``` `for` 后面所有逗号分隔的表达式都被解释为范围。 添加括号让我们可以向 [`map`](@ref) 中添加第三个参数: ```jldoctest julia> map(tuple, (1/(i+j) for i=1:2, j=1:2), [1 3; 2 4]) 2×2 Matrix{Tuple{Float64, Int64}}: (0.5, 1) (0.333333, 3) (0.333333, 2) (0.25, 4) ``` 生成器是通过内部函数实现。 与本语言中别处使用的内部函数一样,封闭作用域中的变量可以在内部函数中被「捕获」。例如,`sum(p[i] - q[i] for i=1:n)` 从封闭作用域中捕获三个变量 `p`、`q` 和 `n`。但是变量捕获可能会带来性能挑战;请参阅 [性能提示](@ref man-performance-tips)。 通过编写多个 `for` 关键字,生成器和推导中的范围可以取决于之前的范围: ```jldoctest julia> [(i,j) for i=1:3 for j=1:i] 6-element Vector{Tuple{Int64, Int64}}: (1, 1) (2, 1) (2, 2) (3, 1) (3, 2) (3, 3) ``` 在这些情况下,结果都是一维的。 可以使用 `if` 关键字过滤生成的值: ```jldoctest julia> [(i,j) for i=1:3 for j=1:i if i+j == 4] 2-element Vector{Tuple{Int64, Int64}}: (2, 2) (3, 1) ``` ## [索引](@id man-array-indexing) 索引 n 维数组 `A` 的一般语法是: ``` X = A[I_1, I_2, ..., I_n] ``` 其中每个 `I_k` 可以是标量整数,整数数组或任何其他[支持的索引类型](@ref man-supported-index-types)。这包括 [`Colon`](@ref) (`:`) 来选择整个维度中的所有索引,形式为 `a:c` 或 `a:b:c` 的范围来选择连续或跨步的子区间,以及布尔数组以选择索引为 `true` 的元素。 如果所有索引都是标量,则结果 `X` 是数组 `A` 中的单个元素。否则,`X` 是一个数组,其维数与所有索引的维数之和相同。 如果所有索引 `I_k` 都是向量,则 `X` 的形状将是 `(length(I_1), length(I_2), ..., length(I_n))`,其中,`X` 中位于 `i_1, i_2, ..., i_n` 处的元素为 `A[I_1[i_1], I_2[i_2], ..., I_n[i_n]]`。 例如: ```jldoctest julia> A = reshape(collect(1:16), (2, 2, 2, 2)) 2×2×2×2 Array{Int64, 4}: [:, :, 1, 1] = 1 3 2 4 [:, :, 2, 1] = 5 7 6 8 [:, :, 1, 2] = 9 11 10 12 [:, :, 2, 2] = 13 15 14 16 julia> A[1, 2, 1, 1] # 全部为标量索引 3 julia> A[[1, 2], [1], [1, 2], [1]] # 全部为向量索引 2×1×2×1 Array{Int64, 4}: [:, :, 1, 1] = 1 2 [:, :, 2, 1] = 5 6 julia> A[[1, 2], [1], [1, 2], 1] # 标量与向量索引的混合使用 2×1×2 Array{Int64, 3}: [:, :, 1] = 1 2 [:, :, 2] = 5 6 ``` 请注意最后两种情况下得到的数组大小为何是不同的。 如果 `I_1` 是二维矩阵,则 `X` 是 `n+1` 维数组,其形状为 `(size(I_1, 1), size(I_1, 2), length(I_2), ..., length(I_n))`。矩阵会添加一个维度。 例如: ```jldoctest julia> A = reshape(collect(1:16), (2, 2, 2, 2)); julia> A[[1 2; 1 2]] 2×2 Matrix{Int64}: 1 2 1 2 julia> A[[1 2; 1 2], 1, 2, 1] 2×2 Matrix{Int64}: 5 6 5 6 ``` 位于 `i_1, i_2, i_3, ..., i_{n+1}` 处的元素值是 `A[I_1[i_1, i_2], I_2[i_3], ..., I_n[i_{n+1}]]`。所有使用标量索引的维度都将被丢弃,例如,假设 `J` 是索引数组,那么 `A[2,J,3]` 的结果是一个大小为 `size(J)` 的数组、其第 j 个元素由 `A[2, J[j], 3]` 填充。 作为此语法的特殊部分,`end` 关键字可用于表示索引括号内每个维度的最后一个索引,由索引的最内层数组的大小决定。没有 `end` 关键字的索引语法相当于调用[`getindex`](@ref): ``` X = getindex(A, I_1, I_2, ..., I_n) ``` 例如: ```jldoctest julia> x = reshape(1:16, 4, 4) 4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 julia> x[2:3, 2:end-1] 2×2 Matrix{Int64}: 6 10 7 11 julia> x[1, [2 3; 4 1]] 2×2 Matrix{Int64}: 5 9 13 1 ``` ## [索引赋值](@id man-indexed-assignment) 在 n 维数组 `A` 中赋值的一般语法是: ``` A[I_1, I_2, ..., I_n] = X ``` 其中每个 `I_k` 可以是标量整数,整数数组或任何其他[支持的索引类型](@ref man-supported-index-types)。这包括 [`Colon`](@ref) (`:`) 来选择整个维度中的所有索引,形式为 `a:c` 或 `a:b:c` 的范围来选择连续或跨步的子区间,以及布尔数组以选择索引为 `true` 的元素。 如果所有 `I_k` 都为整数,则数组 `A` 中 `I_1, I_2, ..., I_n` 位置的值将被 `X` 的值覆盖,必要时将 [`convert`](@ref) 为数组 `A` 的 [`eltype`](@ref)。 如果索引 `I_k` 本身就是一个数组,那么右侧的 `X` 也必须是一个与索引 `A[I_1, I_2, ..., I_n]` 的结果具有相同形状的数组或是具有相同数量元素的向量。 `A` 的位置 `I_1[i_1], I_2[i_2], ..., I_n[i_n]` 中的值被值 `X[I_1, I_2, ..., I_n]` 覆盖,如果必要也会进行类型转换。 元素分配运算符 `.=` 可以用于沿着所选区域 [广播](@ref Broadcasting) `X`: ``` A[I_1, I_2, ..., I_n] .= X ``` 就像在[索引](@ref man-array-indexing)中一样,`end`关键字可用于表示索引括号中每个维度的最后一个索引,由被赋值的数组大小决定。 没有`end`关键字的索引赋值语法相当于调用[`setindex!`](@ref): ``` setindex!(A, X, I_1, I_2, ..., I_n) ``` 例如: ```jldoctest julia> x = collect(reshape(1:9, 3, 3)) 3×3 Matrix{Int64}: 1 4 7 2 5 8 3 6 9 julia> x[3, 3] = -9; julia> x[1:2, 1:2] = [-1 -4; -2 -5]; julia> x 3×3 Matrix{Int64}: -1 -4 7 -2 -5 8 3 6 -9 ``` ## [支持的索引类型](@id man-supported-index-types) 在表达式 `A[I_1, I_2, ..., I_n]` 中,每个 `I_k` 可以是标量索引,标量索引数组,或者用 [`to_indices`](@ref) 转换成的表示标量索引数组的对象: 1. 标量索引。默认情况下,这包括: * 非布尔的整数 * [`CartesianIndex{N}`](@ref) 用来表达多个维度的信息(详见下文),其内部实际为 N个整数组成的元组。 2. 标量索引数组。这包括: * 整数向量和多维整数数组 * 像 `[]` 这样的空数组,它不选择任何元素 * 如 `a:c` 或 `a:b:c` 的范围,从 `a` 到 `c`(包括)选择连续或间隔的部分元素 * 任何自定义标量索引数组,它是 `AbstractArray` 的子类型 * `CartesianIndex{N}` 数组(详见下文) 3. 一个表示标量索引数组的对象,可以通过[`to_indices`](@ref)转换为这样的对象。 默认情况下,这包括: * [`Colon()`](@ref) (`:`),表示整个维度内或整个数组中的所有索引 * 布尔数组,选择其中值为 `true` 的索引对应的元素(更多细节见下文) 一些例子: ```jldoctest julia> A = reshape(collect(1:2:18), (3, 3)) 3×3 Matrix{Int64}: 1 7 13 3 9 15 5 11 17 julia> A[4] 7 julia> A[[2, 5, 8]] 3-element Vector{Int64}: 3 9 15 julia> A[[1 4; 3 8]] 2×2 Matrix{Int64}: 1 7 5 15 julia> A[[]] Int64[] julia> A[1:2:5] 3-element Vector{Int64}: 1 5 9 julia> A[2, :] 3-element Vector{Int64}: 3 9 15 julia> A[:, 3] 3-element Vector{Int64}: 13 15 17 ``` ### 笛卡尔索引 特殊的 `CartesianIndex{N}` 对象表示一个标量索引,其行为类似于张成多个维度的 `N` 维整数元组。例如: ```jldoctest cartesianindex julia> A = reshape(1:32, 4, 4, 2); julia> A[3, 2, 1] 7 julia> A[CartesianIndex(3, 2, 1)] == A[3, 2, 1] == 7 true ``` 单独来看的话,这看起来很平凡:`CartesianIndex` 单纯只是将多个整数捆绑在一起作为一个对象来表示一个多维下标。当与其他取下标方式和生成 `CartesianIndex` 的迭代器进行工作的时候,它才真正能展现出它的简洁与高效。关于这个你可以参考 [迭代器](@ref Iteration) 这一部分,你也可以参考 [关于多维算法和迭代器的介绍](https://julialang.org/blog/2016/02/iteration) 这篇博客来了解更进阶的用法。 元素类型为 `CartesianIndex{N}` 的矩阵也是支持的。每一个元素都单独表示一个 `N` 维空间的 索引下标,作为一个整体这样一个矩阵则表示一些 `N` 维空间的点的坐标,因此这种形式有时 也称为逐点索引。例如:你可以通过它来访问上面所定义的三维矩阵 `A` 的第一页 (第三维指标为1)的对角线元素: ```jldoctest cartesianindex julia> page = A[:,:,1] 4×4 Matrix{Int64}: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 julia> page[[CartesianIndex(1,1), CartesianIndex(2,2), CartesianIndex(3,3), CartesianIndex(4,4)]] 4-element Vector{Int64}: 1 6 11 16 ``` 这可以通过 [dot broadcasting](@ref man-vectorized) 以及普通整数索引(而不是把从 `A` 中提取第一“页”作为单独的步骤)更加简单地表达。它甚至可以与 `:` 结合使用,同时从两个页面中提取两个对角线: ```jldoctest cartesianindex julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), 1] 4-element Vector{Int64}: 1 6 11 16 julia> A[CartesianIndex.(axes(A, 1), axes(A, 2)), :] 4×2 Matrix{Int64}: 1 17 6 22 11 27 16 32 ``` !!! warning `CartesianIndex` 和 `CartesianIndex` 数组与用来表示维度的最后一个索引的 `end` 关键字不兼容。 不要在可能包含`CartesianIndex`或其数组的索引表达式中使用`end`。 ### 逻辑索引 通常被称为逻辑索引或带有逻辑掩码的索引,通过布尔数组进行索引选择其值为`true`的索引处的元素。 通过布尔向量`B`进行索引实际上与通过[`findall(B)`](@ref)返回的整数向量进行索引相同。 类似地,通过`N`维布尔数组进行索引与通过其值为`true`的`CartesianIndex{N}`的向量进行索引实际上是相同的。 一个逻辑索引必须是一个与它所索引的维度长度相同的向量,或者它必须是唯一提供的索引并且匹配它所索引到的数组的大小和维度。 通常直接使用布尔数组作为索引更有效,而不是调用 [`findall`](@ref)。 ```jldoctest julia> x = reshape(1:16, 4, 4) 4×4 reshape(::UnitRange{Int64}, 4, 4) with eltype Int64: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 julia> x[[false, true, true, false], :] 2×4 Matrix{Int64}: 2 6 10 14 3 7 11 15 julia> mask = map(ispow2, x) 4×4 Matrix{Bool}: 1 0 0 0 1 0 0 0 0 0 0 0 1 1 0 1 julia> x[mask] 5-element Vector{Int64}: 1 2 4 8 16 ``` ### 索引数 #### 笛卡尔索引 通常,为一个N维数组元素使用索引的方式是使用N个数字作为索引,每一个索引值确定一个具体的维度。例如,一个三维数组`A = rand(4, 3, 2)`, `A[2, 3, 1]` 将选择的第二行第三列第一“页”中的元素。这种方式通常也被成为笛卡尔索引。 #### 线性索引 当恰好提供了一个索引`i`时,该索引不再表示数组特定维度中的位置。 相反,它使用线性遍历整个数组的列主迭代顺序选择第 `i` 个元素。 这称为_线性索引_。 它本质上将数组视为使用 [`vec`](@ref) 将其重新整形为一维向量。 ```jldoctest linindexing julia> A = [2 6; 4 7; 3 1] 3×2 Matrix{Int64}: 2 6 4 7 3 1 julia> A[5] 7 julia> vec(A)[5] 7 ``` 数组 `A` 中的线性索引可以转换为 `CartesianIndex` 以使用 `CartesianIndices(A)[i]` 进行笛卡尔索引(参见 [`CartesianIndices`](@ref)),一组 `N` 维笛卡尔索引可以通过`LinearIndices(A)[i_1, i_2, ..., i_N]` 转换为线性索引(参见[`LinearIndices`](@ref))。 ```jldoctest linindexing julia> CartesianIndices(A)[5] CartesianIndex(2, 2) julia> LinearIndices(A)[2, 2] 5 ``` 需要注意的是,这些转换的性能存在很大的不对称性。 将线性索引转换为一组笛卡尔索引需要做除法取余数,而相反的转换只是相乘和相加。 在现代处理器中,整数除法比乘法慢 10-50 倍。 虽然一些数组——比如 [`Array`](@ref) 本身——是使用线性内存块实现的,并在它们的实现中直接使用线性索引,但其他数组——比如 [`Diagonal`](@ref)——需要完整的笛卡尔索引集进行查找(请参阅 [`IndexStyle`](@ref) 以仔细推敲)。 因此,当遍历整个数组时,最好遍历 [`eachindex(A)`](@ref) 而不是 `1:length(A)`。 在 `A` 是 `IndexCartesian` 的情况下,前者不仅会快得多,而且它还支持 OffsetArrays(译者注:OffsetArrays.jl是Julia的一个包,支持矩阵的下标不从1开始)。 #### [省略和额外的索引](@id Omitted-and-extra-indices) 除了线性索引,在某些情况下, `N` 维数组的可能少于或多余 `N` 。 如果未索引的剩余维度的长度均为 1,则可以省略索引。 换句话说,只有当那些省略的索引对于索引表达式只有一个可能的值时,才可以省略剩余索引。 例如,一个大小为`(3, 4, 2, 1)`的四维数组可能只用三个索引进行索引,因为被跳过的维度(第四维)的长度为 1。 请注意,线性索引优先级高于此规则。 ```jldoctest julia> A = reshape(1:24, 3, 4, 2, 1) 3×4×2×1 reshape(::UnitRange{Int64}, 3, 4, 2, 1) with eltype Int64: [:, :, 1, 1] = 1 4 7 10 2 5 8 11 3 6 9 12 [:, :, 2, 1] = 13 16 19 22 14 17 20 23 15 18 21 24 julia> A[1, 3, 2] # Omits the fourth dimension (length 1) 19 julia> A[1, 3] # Attempts to omit dimensions 3 & 4 (lengths 2 and 1) ERROR: BoundsError: attempt to access 3×4×2×1 reshape(::UnitRange{Int64}, 3, 4, 2, 1) with eltype Int64 at index [1, 3] julia> A[19] # Linear indexing 19 ``` 当用`A[]` 省略_全部_ 索引时,这种语义提供了一种简单的习惯用法来检索数组中的唯一元素,同时确保只有一个元素。 类似地,如果超出数组维数的所有索引都是`1`(或更一般地说是`axes(A, d)`的第一个也是唯一的元素,其中`d`是特定的维数),可以使用超过`N`维的索引。这允许向量像一列矩阵一样被索引,例如: ```jldoctest julia> A = [8,6,7] 3-element Vector{Int64}: 8 6 7 julia> A[2,1] 6 ``` ## [迭代](@id Iteration) 迭代整个数组的推荐方法是 ```julia for a in A # Do something with the element a end for i in eachindex(A) # Do something with i and/or A[i] end ``` 当你需要每个元素的值而不是索引时,使用第一个构造。 在第二个构造中,如果 `A` 是具有快速线性索引的数组类型,`i` 将是 `Int`; 否则,它将是一个 `CartesianIndex`: ```jldoctest julia> A = rand(4,3); julia> B = view(A, 1:3, 2:3); julia> for i in eachindex(B) @show i end i = CartesianIndex(1, 1) i = CartesianIndex(2, 1) i = CartesianIndex(3, 1) i = CartesianIndex(1, 2) i = CartesianIndex(2, 2) i = CartesianIndex(3, 2) ``` 与 `for i = 1:length(A)` 相比,[`eachindex`](@ref) 提供了一种迭代任何数组类型的有效方法。 ## Array traits 如果你编写一个自定义的 [`AbstractArray`](@ref) 类型,你可以用以下代码指定它使用快速线性索引 ```julia Base.IndexStyle(::Type{<:MyArray}) = IndexLinear() ``` 此设置将导致 `myArray` 上的 `eachindex` 迭代使用整数。如果未指定此特征,则使用默认值 `IndexCartesian()`。 ## [数组和向量化的算子与函数](@id man-array-and-vectorized-operators-and-functions) 以下运算符支持对数组操作 1. 一元运算符 -- `-`, `+` 2. 二元运算符 -- `-`, `+`, `*`, `/`, `\`, `^` 3. 比较操作符 -- `==`, `!=`, `≈` ([`isapprox`](@ref)), `≉` 另外,为了便于数学上和其他运算的向量化,Julia [提供了点语法(dot syntax)](@ref man-vectorized) `f.(args...)`,例如,`sin.(x)` 或 `min.(x,y)`,用于数组或数组和标量的混合上的按元素运算([广播](@ref Broadcasting)运算);当与其他点调用(dot call)结合使用时,它们的额外优点是能「融合」到单个循环中,例如,`sin.(cos.(x))`。 此外,*每个*二元运算符支持相应的[点操作版本](@ref man-dot-operators),可以应用于此类[融合 broadcasting 操作](@ref man-vectorized)的数组(以及数组和标量的组合),例如 `z .== sin.(x .* y)`。 请注意,类似 `==` 的比较运算在作用于整个数组时,得到一个布尔结果。使用像 `.==` 这样的点运算符进行按元素的比较。(对于像 `<` 这样的比较操作,*只有*按元素运算的版本 `.<` 适用于数组。) 还要注意 `max.(a,b)` 和 [`maximum(a)`](@ref) 之间的区别,`max.(a,b)` 对 `a` 和 `b` 的每个元素 [`broadcast`](@ref)s [`max`](@ref),[`maximum(a)`](@ref) 寻找在 `a` 中的最大值。`min.(a,b)` 和 `minimum(a)` 也有同样的关系。 ## [广播](@id Broadcasting) 有时需要在不同尺寸的数组上执行元素对元素的操作,例如将矩阵的每一列加一个向量。一种低效的方法是将向量复制成矩阵的大小: ```julia-repl julia> a = rand(2,1); A = rand(2,3); julia> repeat(a,1,3)+A 2×3 Array{Float64,2}: 1.20813 1.82068 1.25387 1.56851 1.86401 1.67846 ``` 当维度较大的时候,这种方法将会十分浪费,所以 Julia 提供了广播 [`broadcast`](@ref),它将会将参数中低维度的参数扩展,使得其与其他维度匹配,且不会使用额外的内存,并将所给的函数逐元素地应用。 ```julia-repl julia> broadcast(+, a, A) 2×3 Array{Float64,2}: 1.20813 1.82068 1.25387 1.56851 1.86401 1.67846 julia> b = rand(1,2) 1×2 Array{Float64,2}: 0.867535 0.00457906 julia> broadcast(+, a, b) 2×2 Array{Float64,2}: 1.71056 0.847604 1.73659 0.873631 ``` [点运算符](@ref man-dot-operators) 如`.+` 和`.*` 等价于`broadcast` 调用(除了它们结合使用,[如上所述](@ref man-array-and-vectorized-operators-and-functions))。 还有一个 [`broadcast!`](@ref) 函数来指定一个明确的方式(也可以通过`.=` 赋值以融合方式访问)。 事实上,`f.(args...)` 等价于`broadcast(f, args...)`,提供了一种方便的语法来广播任何函数([dot syntax](@ref man-vectorized))。 嵌套的“点运算符调用”`f.(...)`(包括对`.+` 等的调用)[自动融合](@ref man-dot-operators) 到单个`broadcast` 调用中。 此外,[`broadcast`](@ref) 不限于数组(参见函数文档); 它还处理标量、元组和其它容器。 默认情况下,只有一些参数类型被认为是标量,包括(但不限于)`Number`s、`String`s、`Symbol`s、`Type`s、`Function`s 和一些常见的单例,如 `missing` 和`nothing`。 所有其他参数都被迭代或逐个索引。 ```jldoctest julia> convert.(Float32, [1, 2]) 2-element Vector{Float32}: 1.0 2.0 julia> ceil.(UInt8, [1.2 3.4; 5.6 6.7]) 2×2 Matrix{UInt8}: 0x02 0x04 0x06 0x07 julia> string.(1:3, ". ", ["First", "Second", "Third"]) 3-element Vector{String}: "1. First" "2. Second" "3. Third" ``` 有时,你希望一个通常参与广播的容器(如数组)受到“保护”,使其免受广播迭代其所有元素的行为的影响。 通过将其放置在另一个容器中(如单个元素 [`Tuple`](@ref)),广播会将其视为单个值。 ```jldoctest julia> ([1, 2, 3], [4, 5, 6]) .+ ([1, 2, 3],) ([2, 4, 6], [5, 7, 9]) julia> ([1, 2, 3], [4, 5, 6]) .+ tuple([1, 2, 3]) ([2, 4, 6], [5, 7, 9]) ``` ## 实现 Julia 中的基本数组类型是抽象类型 [`AbstractArray{T,N}`](@ref)。它通过维数 `N` 和元素类型 `T` 进行参数化。[`AbstractVector`](@ref) 和 [`AbstractMatrix`](@ref) 是一维和二维情况下的别名。`AbstractArray` 对象的操作是使用更高级别的运算符和函数定义的,其方式独立于底层存储。这些操作可以正确地被用于任何特定数组实现的回退操作。 `AbstractArray` 类型包括任何类似数组的东西,它的实现可能与传统数组完全不同。例如,元素可能根据请求计算而不是存储。然而,任何具体的 `AbstractArray{T,N}` 类型通常应该至少实现 [`size(A)`](@ref)(返回一个 `Int` 元组),[`getindex(A,i)`]( @ref) 和 [`getindex(A,i1,...,iN)`](@ref getindex);可变数组也应该实现 [`setindex!`](@ref)。建议这些操作具有常数时间复杂度,否则某些数组函数可能会出乎意料的慢。具体类型通常还应该提供一个 [`similar(A,T=eltype(A),dims=size(A))`](@ref) 方法,用于为 [`copy`]( @ref) 和其他不合适的操作。无论 `AbstractArray{T,N}` 在内部如何表示,`T` 都是由 *整数* 索引(`A[1, ..., 1]`,当 `A` 非空) 返回的对象类型并且 `N` 应该是 [`size`](@ref) 返回的元组的长度。有关自定义 `AbstractArray` 实现的更多详细信息,请参阅 [接口章节中的数组接口指南](@ref man-interface-array)。 `DenseArray` 是 `AbstractArray` 的抽象子类型,旨在包括元素以列优先顺序连续存储的所有数组(请参阅 [性能提示中的附加说明](@ref man-performance-column-major))。 [`Array`](@ref) 类型是`DenseArray` 的一个特定实例; [`Vector`](@ref) 和 [`Matrix`](@ref) 是一维和二维情况的别名。 除了所有`AbstractArray`s所需的操作之外,很少有专门为`Array`实现的操作;大部分数组库都是以泛型方式实现的,允许所有自定义数组的行为类似。 `SubArray` 是 `AbstractArray` 的特例,它通过与原始数组共享内存而不是复制它来执行索引。 使用[`view`](@ref) 函数创建 `SubArray`,它的调用方式与[`getindex`](@ref) 相同(作用于数组和一系列索引参数)。 [`view`](@ref) 的结果看起来与 [`getindex`](@ref) 的结果相同,只是数据保持不变。 [`view`](@ref) 将输入索引向量存储在 `SubArray` 对象中,该对象稍后可用于间接索引原始数组。 通过将 [`@views`](@ref) 宏放在表达式或代码块之前,该表达式中的任何 `array [...]` 切片将被转换为创建一个 `SubArray` 视图。 [`BitArray`](@ref) 是节省空间“压缩”的布尔数组,每个比特(bit)存储一个布尔值。 它们可以类似于 `Array{Bool}` 数组(每个字节(byte)存储一个布尔值),并且可以分别通过 `Array(bitarray)` 和 `BitArray(array)` 相互转换。 如果数组存储在内存中,其元素之间具有明确定义的间距(步长),则该数组是“等步长的”的。 通过简单地传递其 [`pointer`](@ref) 和每个维度的步长,可以将有支持元素类型的等步长数组传递给外部(非 Julia)库,如 BLAS 或 LAPACK。 [`stride(A, d)`](@ref) 是元素之间沿维度 `d` 的距离。 例如,`rand(5,7,2)` 返回的内置 `Array` 的元素按列优先顺序连续排列。 这意味着第一个维度的步长——同一列中元素之间的间距——是`1`: ```julia-repl julia> A = rand(5,7,2); julia> stride(A,1) 1 ``` 第二个维度的步长是同一行中元素之间的间距,跳过与单列(`5`)中的元素一样多的元素。 类似地,在两个“页面”(在第三维中)之间跳转需要跳过 `5*7 == 35` 元素。 这个数组的 [`strides`](@ref) 是这三个数字组成的元组: ```julia-repl julia> strides(A) (1, 5, 35) ``` 在这种特殊情况下,在_内存_中跳过的元素数与跳过的_线性索引_数相匹配。 这仅适用于像 `Array`(和其他 `DenseArray` 子类型)这样的连续数组,通常情况下并非如此。 具有范围索引的视图是 _非连续_ 等步长数组的一个很好的例子; 考虑`V = @view A[1:3:4, 2:2:6, 2:-1:1]`。 这个视图 `V` 与 `A` 引用了相同的内存,但它跳过并重新排列了它的一些元素。 `V` 的第一维的步幅是 `3`,因为我们只从原始数组中选择每第三行: ```julia-repl julia> V = @view A[1:3:4, 2:2:6, 2:-1:1]; julia> stride(V, 1) 3 ``` 这个视图类似于从我们原来的`A`中每隔一列选择一列——因此当在第二维的索引之间移动时,它需要跳过相当于两个五元素列的内容: ```julia-repl julia> stride(V, 2) 10 ``` 第三维很有趣因为它的顺序颠倒了! 因此从第一 "页" 到第二页它必须在内存中到 _backwards_,所以它在这一维的 strides 是负的! ```julia-repl julia> stride(V, 3) -35 ``` 这意味着`V` 的`pointer` 实际上指向`A` 的内存块的中间,并且它在内存中指向元素是同时向后和向前的。 有关定义你自己的跨距数组的更多详细信息,请参阅 [等步长数组的接口指南](@ref man-interface-strided-arrays)。 [`StridedVector`](@ref) 和 [`StridedMatrix`](@ref) 被认为是等步长数组的内置数组类型的方便别名,允许它们仅使用指针和步幅,来分派选择调用调整和优化后的 BLAS 和 LAPACK 函数。 需要强调的是 strides 是关于内存而不是索引中的偏移。如果你在找在线性(单索引)索引和笛卡尔(多索引)索引间切换的方法,见 [`LinearIndices`](@ref) 和 [`CartesianIndices`](@ref).
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
8309
# [异步编程](@id man-asynchronous) 当程序需要与外部世界交互时,例如通过互联网与另一台机器通信时,程序中的操作可能需要以无法预测的顺序发生。假设你的程序需要下载一个文件。我们想启动下载操作,在等待下载完成的同时执行其他操作,然后在空闲时继续执行下载文件的代码。这种场景属于异步编程,有时也称为并发编程(因为从概念上讲,同时发生多种事情)。 为了解决这些可能的情况,Julia 提供了任务 [`Task`](@ref)(也有其他几个名称,例如对称协程、轻量级线程、协作多任务处理或one-shot continuations)。当一项计算工作(实际上,执行特定功能)被指定为 [`Task`](@ref) 时,可以通过切换到另一个 [`Task`](@ref) 来中断它。 最初的 [`Task`](@ref) 稍后可以恢复,此时它将从上次中断的地方开始。 初看这似乎类似于函数调用。 但是,有两个关键区别。 首先,切换任务不占用任何空间,因此可以在不消耗调用堆栈的情况下进行任意数量的任务切换。 其次,任务之间的切换可以以任何顺序发生,这与函数调用不同,在函数调用中,被调用的函数必须在返回到调用函数之前完成执行。 ## 基本 `Task` 操作 你可以将`Task`视为要执行的计算工作单元的句柄。 它有一个创建-开始-运行-结束的生命周期。 Task 是通过在要运行的 0 参数函数上调用 `Task` 构造函数来创建的,或者使用 [`@task`](@ref) 宏: ```julia-repl julia> t = @task begin; sleep(5); println("done"); end Task (runnable) @0x00007f13a40c0eb0 ``` `@task x` 等价于 `Task(()->x)`。 此任务将等待五秒钟,然后打印`done`。 但是,它还没有开始运行。 我们可以随时通过调用 [`schedule`](@ref) 来运行它: ```julia-repl julia> schedule(t); ``` 如果你在 REPL 中尝试这个,你会看到 `schedule` 立即有返回值。那是因为它只是将 `t` 添加到要运行的内部任务队列中。然后,REPL 将打印下一个提示并等待更多输入。等待键盘输入为其他任务提供了运行的机会,因此此时 `t` 将启动。 `t` 调用 [`sleep`](@ref),它设置一个计时器并停止执行。 如果已经安排了其他任务,那么它们就可以运行了。五秒后,计时器触发并重新启动`t`,你将看到打印的`done`。 然后`t` 执行完毕了。 [`wait`](@ref) 函数会阻塞调用任务,直到其他任务完成。 例如,如果输入: ```julia-repl julia> schedule(t); wait(t) ``` 在下一个输入提示出现之前,你将看到五秒钟的停顿,而不是只调用 `schedule`。 那是因为 REPL 等待 `t` 完成之后才继续。 一般来说,创建一个任务会想立即执行它,为此提供了宏 [`@async`](@ref) --- `@async x` 等价于 `schedule(@task x )`。 ## 在 Channel 中进行通信 在某些问题中,所需的各种工作并不是通过函数调用自然关联的; 在需要完成的工作中没有明显的“调用者”或“被调用者”。 一个典型的例子是生产者-消费者问题,其中一个复杂的过程正在生成值,而另一个复杂的过程正在消耗它们。消费者不能简单地调用生产者函数来获取一个值,因为生产者可能有更多的值要生成,因此可能还没有准备好返回。对于任务,生产者和消费者都可以根据需要运行,根据需要来回传递值。 Julia 提供了 [`Channel`](@ref) 机制来解决这个问题。一个 [`Channel`](@ref) 是一个先进先出的队列,允许多个 `Task` 对它可以进行读和写。 让我们定义一个生产者任务,调用 [`put!`](@ref) 来生产数值。为了消费数值,我们需要对生产者开始新任务进行排班。可以使用一个特殊的 [`Channel`](@ref) 组件来运行一个与其绑定的 `Task`,它能接受单参数函数作为其参数,然后可以用 [`take!`](@ref) 从 [`Channel`](@ref) 对象里不断地提取值: ```jldoctest producer julia> function producer(c::Channel) put!(c, "start") for n=1:4 put!(c, 2n) end put!(c, "stop") end; julia> chnl = Channel(producer); julia> take!(chnl) "start" julia> take!(chnl) 2 julia> take!(chnl) 4 julia> take!(chnl) 6 julia> take!(chnl) 8 julia> take!(chnl) "stop" ``` 一种思考这种行为的方式是,“生产者”能够多次返回。在两次调用 [`put!`](@ref) 之间,生产者的执行是挂起的,此时由消费者接管控制。 返回的 [`Channel`](@ref) 可以被用作一个 `for` 循环的迭代对象,此时循环变量会依次取到所有产生的值。当 [`Channel`](@ref) 关闭时,循环就会终止。 ```jldoctest producer julia> for x in Channel(producer) println(x) end start 2 4 6 8 stop ``` 注意我们并不需要显式地在生产者中关闭 [`Channel`](@ref)。这是因为 [`Channel`](@ref) 对 [`Task`](@ref) 的绑定同时也意味着 `Channel` 的生命周期与绑定的 `Task` 一致。当 `Task` 结束时,`Channel` 对象会自动关闭。多个 `Channel` 可以绑定到一个 `Task`,反之亦然。 [`Task`](@ref) 构造函数需要一个不带参数的函数,而创建任务绑定的 channel 的 [`Channel`](@ref) 方法需要一个接受 [`Channel`](@ref)类型的单个参数的函数。 一个常见的模式是对生产者进行参数化,在这种情况下,需要一个偏函数来创建一个 0 或 1 个参数 [匿名函数](@ref man-anonymous-functions)。 对于 [`Task`](@ref) 对象,可以直接用,也可以为了方便用宏。 ```julia function mytask(myarg) ... end taskHdl = Task(() -> mytask(7)) # or, equivalently taskHdl = @task mytask(7) ``` 为了安排更高级的工作分配模式,[`bind`](@ref) 和 [`schedule`](@ref) 可以与 [`Task`](@ref) 和 [`Channel`](@ref) 构造函数配合使用,显式地连接一些 `Channel` 和生产者或消费者 `Task`。 ### 更多关于 Channel 的知识 一个管道可以形象得看做是一个管子,一端可读,另一端可写: * 不同的 task 可以通过 [`put!`](@ref) 往同一个 channel 并发地写入。 * 不同的 task 也可以通过 [`take!`](@ref) 从同一个 channel 并发地取数据 * 举个例子: ```julia # Given Channels c1 and c2, c1 = Channel(32) c2 = Channel(32) # and a function `foo` which reads items from c1, processes the item read # and writes a result to c2, function foo() while true data = take!(c1) [...] # process data put!(c2, result) # write out result end end # we can schedule `n` instances of `foo` to be active concurrently. for _ in 1:n errormonitor(@async foo()) end ``` * Channel 可以通过 `Channel{T}(sz)` 构造,得到的 channel 只能存储类型 `T` 的数据。如果 `T` 没有指定,那么 channel 可以存任意类型。`sz` 表示该 channel 能够存储的最大元素个数。比如 `Channel(32)` 得到的 channel 最多可以存储32个元素。而 `Channel{MyType}(64)` 则可以最多存储64个 `MyType` 类型的数据。 * 如果一个 [`Channel`](@ref) 是空的,读取的 task(即执行 [`take!`](@ref) 的 task)会被阻塞直到有新的数据准备好了。 * 如果一个 [`Channel`](@ref) 是满的,那么写入的 task(即执行 [`put!`](@ref) 的 task)则会被阻塞,直到 Channel 有空余。 * * 一个 [`Channel`](@ref) 一开始处于开启状态,也就是说可以被 [`take!`](@ref) 读取和 [`put!`](@ref) 写入。[`close`](@ref) 会关闭一个 [`Channel`](@ref),对于一个已经关闭的 [`Channel`](@ref),[`put!`](@ref) 会失败,例如: ```julia-repl julia> c = Channel(2); julia> put!(c, 1) # `put!` on an open channel succeeds 1 julia> close(c); julia> put!(c, 2) # `put!` on a closed channel throws an exception. ERROR: InvalidStateException("Channel is closed.",:closed) Stacktrace: [...] ``` * [`take!`](@ref) 和 [`fetch`](@ref) (只读取,不会将元素从 channel 中删掉)仍然可以从一个已经关闭的 channel 中读数据,直到 channel 被取空了为止。继续上面的例子: ```julia-repl julia> fetch(c) # Any number of `fetch` calls succeed. 1 julia> fetch(c) 1 julia> take!(c) # The first `take!` removes the value. 1 julia> take!(c) # No more data available on a closed channel. ERROR: InvalidStateException("Channel is closed.",:closed) Stacktrace: [...] ``` 考虑这样一个用 channel 做 task 之间通信的例子。首先,起 4 个 task 来处理一个 `jobs` channel 中的数据。`jobs` 中的每个任务通过 `job_id` 来表示,然后每个 task 模拟读取一个 `job_id`,然后随机等待一会儿,然后往一个 results channel 中写入一个元组,它分别包含 `job_id` 和执行的时间,最后将结果打印出来: ```julia-repl julia> const jobs = Channel{Int}(32); julia> const results = Channel{Tuple}(32); julia> function do_work() for job_id in jobs exec_time = rand() sleep(exec_time) # simulates elapsed time doing actual work # typically performed externally. put!(results, (job_id, exec_time)) end end; julia> function make_jobs(n) for i in 1:n put!(jobs, i) end end; julia> n = 12; julia> errormonitor(@async make_jobs(n)); # feed the jobs channel with "n" jobs julia> for i in 1:4 # start 4 tasks to process requests in parallel errormonitor(@async do_work()) end julia> @elapsed while n > 0 # print out results job_id, exec_time = take!(results) println("$job_id finished in $(round(exec_time; digits=2)) seconds") global n = n - 1 end 4 finished in 0.22 seconds 3 finished in 0.45 seconds 1 finished in 0.5 seconds 7 finished in 0.14 seconds 2 finished in 0.78 seconds 5 finished in 0.9 seconds 9 finished in 0.36 seconds 6 finished in 0.87 seconds 8 finished in 0.79 seconds 10 finished in 0.64 seconds 12 finished in 0.5 seconds 11 finished in 0.97 seconds 0.029772311 ``` 不用 `errormonitor(t)`,一个更稳健的解决方案是使用 `bind(results, t)`,这不仅会记录任何意外故障,还会强制相关资源关闭并向上抛出错误。 ## 更多任务操作 任务操作建立在称为 [`yieldto`](@ref) 的底层原始运算上。 `yieldto(task, value)` 挂起当前 task,然后切换到指定的 `task`,并使该任务的最后一个 [`yieldto`](@ref) 调用返回指定的 `value`。 请注意,[`yieldto`](@ref) 是使用任务式流程控制所需的唯一操作;我们总是切换到不同的任务,而不是调用和返回。 这就是为什么这个特性也被称为“对称协程”; 每个任务都使用相同的机制来回切换。 [`yieldto`](@ref) 功能强大,但大多数 `Task` 的使用都不会直接调用它。思考为什么会这样。如果你切换当前 `Task`,你很可能会在某个时候想切换回来。但知道什么时候切换回来和那个 `Task` 负责切换回来需要大量的协调。例如,[`put!`](@ref) 和 [`take!`](@ref) 是阻塞操作,当在渠道环境中使用时,维持状态以记住消费者是谁。不需要人为地记录消费 `Task`,正是使得 [`put!`](@ref) 比底层 [`yieldto`](@ref) 易用的原因。 除了 [`yieldto`](@ref) 之外,也需要一些其它的基本函数来更高效地使用 `Task`。 * [`current_task`](@ref) 获取当前运行 `Task` 的索引。 * [`istaskdone`](@ref) 查询一个 `Task` 是否退出. * [`istaskstarted`](@ref) 查询一个 `Task` 是否已经开始运行。 * [`task_local_storage`](@ref) 操纵针对当前 `Task` 的键值存储。 ## `Task` 和事件 多数 `Task` 切换是在等待如 I/O 请求的事件,由 Julia Base 里的调度器执行。调度器维持一个可运行 `Task` 的队列,并执行一个事件循环,来根据例如收到消息等外部事件来重启 `Task`。 等待一个事件的基本函数是 [`wait`](@ref)。很多对象都实现了 [`wait`](@ref) 函数;例如,给定一个 `Process` 对象,[`wait`](@ref) 将等待它退出。[`wait`](@ref) 通常是隐式的,例如,[`wait`](@ref) 可能发生在调用 [`read`](@ref) 时等待数据可用。 在所有这些情况下,[`wait`](@ref) 最终会操作一个 [`Condition`](@ref) 对象,由它负责排队和重启 `Task`。当 `Task` 在一个 [`Condition`](@ref) 上调用 [`wait`](@ref) 时,该 Task 就被标记为不可执行,加到条件的队列中,并切回调度器。调度器将选择另一个 `Task` 来运行,或者阻止外部事件的等待。如果所有运行良好,最终一个事件处理器将在这个条件下调用 [`notify`](@ref),使得等待该条件的 `Task` 又变成可运行。 通过调用 [`Task`](@ref) 显式创建的任务,一开始并不被调度器知道。这允许你根据需要使用 [`yieldto`](@ref) 手动管理任务。 但是,当此类任务等待事件时,它仍会在事件发生时自动重新启动,正如你所期望。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
37926
# [调用 C 和 Fortran 代码](@id Calling-C-and-Fortran-Code) 在数值计算领域,尽管有很多用 C 语言或 Fortran 写的高质量且成熟的库都可以用 Julia 重写,但为了便捷利用现有的 C 或 Fortran 代码,Julia 提供简洁且高效的调用方式。Julia 的哲学是 `no boilerplate`: Julia 可以直接调用 C/Fortran 的函数,不需要任何"胶水"代码,代码生成或其它编译过程 -- 即使在交互式会话 (REPL/Jupyter notebook) 中使用也一样. 在 Julia 中,上述特性可以仅仅通过调用 [`ccall`](@ref) 实现,它的语法看起来就像是普通的函数调用。 被调用的代码必须是一个共享库(.so, .dylib, .dll)。大多数 C 和 Fortran 库都已经是以共享库的形式发布的,但在用 GCC 或 Clang 编译自己的代码时,需要添加 `-shared` 和 `-fPIC` 编译器选项。由于 Julia 的 JIT 生成的机器码跟原生 C 代码的调用是一样,所以在 Julia 里调用 C/Fortran 库的额外开销与直接从 C 里调用是一样的。[^1] 可以通过元组 `(:function, "library")` 或 `("function", "library")` 这两种形式来索引库中的函数,其中 `function` 是函数名,`library` 是库名。(特定平台/操作系统的)加载路径中可用的共享库将按名称解析。 也可以指定库的完整路径。 可以单独使用函数名来代替元组(只用 `:function` 或 `"function"`)。在这种情况下,函数名在当前进程中进行解析。这一调用形式可用于调用 C 库函数、Julia 运行时中的函数或链接到 Julia 的应用程序中的函数。 默认情况下,Fortran 编译器会[进行名称修饰](https://en.wikipedia.org/wiki/Name_mangling#Fortran)(例如,将函数名转换为小写或大写,通常会添加下划线),要通过 [`ccall`](@ref) 调用 Fortran 函数,传递的标识符必须与 Fortran 编译器名称修饰之后的一致。此外,在调用 Fortran 函数时,**所有**输入必须以指针形式传递,并已在堆或栈上分配内存。这不仅适用于通常是堆分配的数组及可变对象,而且适用于整数和浮点数等标量值,尽管这些值通常是栈分配的,且在使用 C 或 Julia 调用约定时通常是通过寄存器传递的。 最终,你能使用 [`ccall`](@ref) 来实际生成一个对库函数的调用。[`ccall`](@ref) 的参数是: 1. 一个 `(:function, "library")` 对(最常见) 或 一个 `:function` 名称符号或 `"function"` 名称字符串(用于当前进程或 libc 中的符号), 或 一个函数指针(例如,从 `dlsym` 获得的指针)。 2. 函数的返回值类型 3. 输入类型的元组,对应于函数签名 4. 要传递给函数的实际参数值,如果有的话; 每个都是一个单独的参数。 !!! note `(:function, "library")` 对、返回类型和输入类型必须是字面量(即,它们不能是变量,但请参阅下面的 [非常量函数规范](@ref Non-constant-Function-Specifications))。 当定义包含方法时,将在编译时评估其余参数。 !!! note 请参阅下文了解如何 [将 C 类型映射到 Julia 类型](@ref mapping-c-types-to-julia)。 作为一个完整但简单的例子,下面从大多数 Unix 派生系统上的标准 C 库中调用 `clock` 函数: ```julia-repl julia> t = ccall(:clock, Int32, ()) 2292761 julia> t 2292761 julia> typeof(t) Int32 ``` `clock` 不接受任何参数并返回一个 [`Int32`](@ref)。 一个常见的错误是忘记了参数类型的单元组必须用逗号结尾。 例如,要调用 `getenv` 函数来获取指向环境变量值的指针,可以这样调用: ```julia-repl julia> path = ccall(:getenv, Cstring, (Cstring,), "SHELL") Cstring(@0x00007fff5fbffc45) julia> unsafe_string(path) "/bin/bash" ``` 请注意,参数类型元组必须是 `(Cstring,)`,而不是 `(Cstring)` 。这是因为 `(Cstring)` 只是括号括起来的表达式 `Cstring`,而不是包含 `Cstring` 的单元组: ```jldoctest julia> (Cstring) Cstring julia> (Cstring,) (Cstring,) ``` 在实践中,尤其是在提供可重用功能时,通常会在 Julia 函数中包装 [`ccall`](@ref) 使用,这些函数设置参数,然后以 C 或 Fortran 函数指定的任何方式检查错误。 如果发生错误,它会作为普通的 Julia 异常抛出。 这一点尤其重要,因为 C 和 Fortran API 在它们指示错误条件的方式上是出了名的不一致。 例如,`getenv` C 库函数被包裹在下面的 Julia 函数中,它是 [`env.jl`](https://github.com/JuliaLang/julia/blob/master/base/env.jl): ```julia function getenv(var::AbstractString) val = ccall(:getenv, Cstring, (Cstring,), var) if val == C_NULL error("getenv: undefined variable: ", var) end return unsafe_string(val) end ``` C 函数 `getenv` 通过返回 `NULL` 的方式进行报错,但是其他 C 标准库函数也会通过多种不同的方式来报错,这包括返回 -1,0,1 以及其它特殊值。此封装能够明确地抛出异常信息,即是否调用者在尝试获取一个不存在的环境变量: ```julia-repl julia> getenv("SHELL") "/bin/bash" julia> getenv("FOOBAR") getenv: undefined variable: FOOBAR ``` 这是一个稍微复杂的示例,用于发现本地计算机的主机名。 在此示例中,假设网络库代码位于名为“libc”的共享库中。 在实践中,这个函数通常是 C 标准库的一部分,因此“libc”部分应该被省略,但我们希望在这里展示这个语法的用法。 ```julia function gethostname() hostname = Vector{UInt8}(undef, 256) # MAXHOSTNAMELEN err = ccall((:gethostname, "libc"), Int32, (Ptr{UInt8}, Csize_t), hostname, sizeof(hostname)) Base.systemerror("gethostname", err != 0) hostname[end] = 0 # ensure null-termination return GC.@preserve hostname unsafe_string(pointer(hostname)) end ``` 此示例首先分配一个字节数组。 然后它调用 C 库函数 `gethostname` 以使用主机名填充数组。 最后,它接受一个指向主机名缓冲区的指针,并将该指针转换为一个 Julia 字符串,假设它是一个以 NUL 结尾的 C 字符串。 C 库通常使用这种模式,要求调用者分配要传递给被调用者并填充的内存。 像这样从 Julia 分配内存通常是通过创建一个未初始化的数组并将指向其数据的指针传递给 C 函数来完成的。 这就是我们在这里不使用 `Cstring` 类型的原因:由于数组未初始化,它可能包含 NUL 字节。 作为 [`ccall`](@ref) 的一部分,转换为 `Cstring` 会检查包含的 NUL 字节,因此可能会引发类型转换错误。 用 `unsafe_string` 取消引用 `pointer(hostname)` 是一种不安全的操作,因为它需要访问为 `hostname` 分配的内存,而这些内存可能在同时被垃圾收集。 宏 [`GC.@preserve`](@ref) 防止这种情况发生,从而防止访问无效的内存位置。 ## 创建和C兼容的Julia函数指针 可以将Julia函数传递给接受函数指针参数的原生C函数。例如,要匹配满足下面的C原型: ```c typedef returntype (*functiontype)(argumenttype, ...) ``` 宏 [`@cfunction`](@ref) 为调用 Julia 函数生成 C 兼容函数指针。 [`@cfunction`](@ref) 的参数是: 1. 一个Julia函数 2. 函数的返回值类型 3. 输入类型的元组,对应于函数签名 !!! note 与 `ccall` 一样,返回类型和输入类型的元组必须是字面量常量。 !!! note 目前,仅支持平台默认的C调用约定。这意味着,`@cfunction`生成的指针不能用于WINAPI要求在32位Windows上使用`stdcall`函数的调用中,但可以在WIN64上使用(其中`stdcall`与C调用约定统一)。 一个典型的例子就是标准C库函数`qsort`,定义为: ```c void qsort(void *base, size_t nmemb, size_t size, int (*compare)(const void*, const void*)); ``` `base` 参数是一个指向长度为 `nmemb` 的数组的指针,每个元素都有 `size` 字节。 `compare` 是一个回调函数,它采用指向两个元素 `a` 和 `b` 的指针,如果 `a` 出现在 `b` 之前/之后,则返回小于/大于零的整数(如果允许任何顺序,则返回零) 。 现在,假设我们在 Julia 中有一个 1 维数组 `A`,我们希望使用`qsort`函数(而不是 Julia 的内置`sort`函数)对其进行排序。 在我们考虑调用 `qsort` 并传递参数之前,我们需要编写一个比较函数: ```jldoctest mycompare julia> function mycompare(a, b)::Cint return (a < b) ? -1 : ((a > b) ? +1 : 0) end mycompare (generic function with 1 method) ``` `qsort` 需要一个返回 C `int` 的比较函数,因此我们将返回类型注释为 `Cint`。 为了将此函数传递给 C,我们使用宏`@cfunction` 获取它的地址: ```jldoctest mycompare julia> mycompare_c = @cfunction(mycompare, Cint, (Ref{Cdouble}, Ref{Cdouble})); ``` [`@cfunction`](@ref) 需要三个参数: Julia函数 (`mycompare`), 返回值类型(`Cint`), 和一个输入参数类型的字面量元组, 此处是要排序的`Cdouble`([`Float64`](@ref)) 元素的数组. `qsort`的最终调用看起来是这样的: ```jldoctest mycompare julia> A = [1.3, -2.7, 4.4, 3.1] 4-element Vector{Float64}: 1.3 -2.7 4.4 3.1 julia> ccall(:qsort, Cvoid, (Ptr{Cdouble}, Csize_t, Csize_t, Ptr{Cvoid}), A, length(A), sizeof(eltype(A)), mycompare_c) julia> A 4-element Vector{Float64}: -2.7 1.3 3.1 4.4 ``` 如示例所示,原始 Julia 数组 `A` 现在已排序:`[-2.7, 1.3, 3.1, 4.4]`。 请注意,Julia [负责将数组转换为`Ptr{Cdouble}`](@ref automatic-type-conversion)),计算元素类型的大小(以字节为单位),等等。 为了好玩,尝试在 `mycompare` 中插入一行 `println("mycompare($a, $b)")`,这将允许你查看 `qsort` 正在执行的比较(并验证它是否真的在调用你传递给它的 Julia 函数)。 ## [将 C 类型映射到 Julia](@id mapping-c-types-to-julia) 将声明的 C 类型与其在 Julia 中的声明完全匹配至关重要。 不一致会导致在一个系统上正常工作的代码在另一个系统上失败或产生不确定的结果。 请注意,在调用 C 函数的过程中没有任何地方使用 C 头文件:您有责任确保您的 Julia 类型和调用签名准确反映 C 头文件中的那些。[^2] ### [自动类型转换](@id automatic-type-conversion) Julia 会自动插入对 [`Base.cconvert`](@ref) 函数的调用,以将每个参数转换为指定的类型。 例如,以下调用: ```julia ccall((:foo, "libfoo"), Cvoid, (Int32, Float64), x, y) ``` 将表现得好像它是这样写的: ```julia ccall((:foo, "libfoo"), Cvoid, (Int32, Float64), Base.unsafe_convert(Int32, Base.cconvert(Int32, x)), Base.unsafe_convert(Float64, Base.cconvert(Float64, y))) ``` [`Base.cconvert`](@ref) 通常只调用 [`convert`](@ref),但可以定义为返回一个更适合传递给 C 的任意新对象。这应该用于执行 C 代码将访问的内存。 例如,这用于将对象(例如字符串)的 `Array` 转换为指针数组。 [`Base.unsafe_convert`](@ref) 处理到 [`Ptr`](@ref) 类型转换。 它被认为是不安全的,因为将对象转换为本地指针会隐藏垃圾收集器中的对象,导致它过早地被释放。 ### 类型对应 首先,让我们回顾一些相关的 Julia 类型术语: | 语法 / 关键字 | 例子 | 描述 | |:----------------------------- |:------------------------------------------- |:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `mutable struct` | `BitSet` | `Leaf Type`:包含 `type-tag` 的一组相关数据,由 Julia GC 管理,通过 `object-identity` 来定义。为了保证实例可以被构造,`Leaf Type` 必须是完整定义的,即不允许使用 `TypeVars`。 | | `abstract type` | `Any`, `AbstractArray{T, N}`, `Complex{T}` | `Super Type`:用于描述一组类型,它不是 `Leaf-Type`,也无法被实例化。 | | `T{A}` | `Vector{Int}` | `Type Parameter`:某种类型的一种具体化,通常用于分派或存储优化。 | | | | `TypeVar`:`Type parameter` 声明中的 `T` 是一个 `TypeVar`,它是类型变量的简称。 | | `primitive type` | `Int`, `Float64` | `Primitive Type`:一种没有成员变量的类型,但是它有大小。它是按值存储和定义的。 | | `struct` | `Pair{Int, Int}` | "Struct" :: 所有字段都定义为常量的类型。 它是按值定义的,并且可以与类型标签一起存储。 | | | `ComplexF64` (`isbits`) | "Is-Bits" :: 一个 `primitive type`,或者一个 `struct` 类型,其中所有字段都是其他 `isbits` 类型。 它是按值定义的,并且在没有类型标签的情况下存储。 | | `struct ...; end` | `nothing` | `Singleton`:没有成员变量的 `Leaf Type` 或 `Struct`。 | | `(...)` or `tuple(...)` | `(1, 2, 3)` | “元组” :: 类似于匿名结构类型或常量数组的不可变数据结构。 表示为数组或结构。 | ### [Bits Types](@id man-bits-types) 有几种特殊类型需要注意,因为没有其他类型可以定义为具有相同的行为: * `Float32` 和C语言中的 `float` 类型完全对应(以及Fortran中的 `REAL*4` ) * `Float64` 和C语言中的 `double` 类型完全对应(以及Fortran中的 `REAL*8` ) * `ComplexF32` 和C语言中的 `complex float` 类型完全对应(以及Fortran中的 `COMPLEX*8` ) * `ComplexF64` 和C语言中的 `complex double` 类型完全对应(以及Fortran中的 `COMPLEX*16` ) * `Signed` 和C语言中的 `signed` 类型标识完全对应(以及Fortran中的任意 `INTEGER` 类型) Julia中任何不是[`Signed`](@ref) 的子类型的类型,都会被认为是unsigned类型。 * `Ref{T}` 和 `Ptr{T}` 行为相同,能通过Julia的GC管理其内存。 * `Array{T,N}` 当数组作为 `Ptr{T}` 参数传递给 C 时,它不是重新解释转换:Julia 要求数组的元素类型与 `T` 匹配,并传递第一个元素的地址。 因此,如果一个 `Array` 中的数据格式不正确,它必须被显式地转换 ,通过类似 `trunc(Int32, a)` 的函数。 若要将一个数组 `A` 以不同类型的指针传递,而*不提前转换数据*, (比如,将一个 `Float64` 数组传给一个处理原生字节的函数时),你 可以将这一参数声明为 `Ptr{Cvoid}` 。 如果一个元素类型为 `Ptr{T}` 的数组作为 `Ptr{Ptr{T}}` 类型的参数传递, [`Base.cconvert`](@ref) 将会首先尝试进行 null-terminated copy(即直到下一个元素为null才停止复制),并将每一个元素使用其通过 [`Base.cconvert`](@ref) 转换后的版本替换。 这允许,比如,将一个 `argv` 的指针数组,其类型为 `Vector{String}` ,传递给一个类型为 `Ptr{Ptr{Cchar}}` 的参数。 在我们目前支持的所有系统上,基本的 C/C++ 值类型可以转换为 Julia 类型,如下所示。 每个 C 类型还有一个对应的同名 Julia 类型,以 C 为前缀。这在编写可移植代码时很有帮助(记住 C 中的 `int` 与 Julia 中的 `Int` 不同)。 **独立于系统的类型** | C 类型 | Fortran 类型 | 标准 Julia 别名 | Julia 基本类型 | |:------------------------------------------------------- |:------------------------ |:-------------------- |:-------------------------------------------------------------------------------------------------------------- | | `unsigned char` | `CHARACTER` | `Cuchar` | `UInt8` | | `bool` (_Bool in C99+) | | `Cuchar` | `UInt8` | | `short` | `INTEGER*2`, `LOGICAL*2` | `Cshort` | `Int16` | | `unsigned short` | | `Cushort` | `UInt16` | | `int`, `BOOL` (C, typical) | `INTEGER*4`, `LOGICAL*4` | `Cint` | `Int32` | | `unsigned int` | | `Cuint` | `UInt32` | | `long long` | `INTEGER*8`, `LOGICAL*8` | `Clonglong` | `Int64` | | `unsigned long long` | | `Culonglong` | `UInt64` | | `intmax_t` | | `Cintmax_t` | `Int64` | | `uintmax_t` | | `Cuintmax_t` | `UInt64` | | `float` | `REAL*4i` | `Cfloat` | `Float32` | | `double` | `REAL*8` | `Cdouble` | `Float64` | | `complex float` | `COMPLEX*8` | `ComplexF32` | `Complex{Float32}` | | `complex double` | `COMPLEX*16` | `ComplexF64` | `Complex{Float64}` | | `ptrdiff_t` | | `Cptrdiff_t` | `Int` | | `ssize_t` | | `Cssize_t` | `Int` | | `size_t` | | `Csize_t` | `UInt` | | `void` | | | `Cvoid` | | `void` and `[[noreturn]]` or `_Noreturn` | | | `Union{}` | | `void*` | | | `Ptr{Cvoid}` (或类似的 `Ref{Cvoid}`) | | `T*` (where T represents an appropriately defined type) | | | `Ref{T}` (只有当 T 是 isbits 类型时,T 才可以安全地转变) | | `char*` (or `char[]`, e.g. a string) | `CHARACTER*N` | | `Cstring` if NUL-terminated, or `Ptr{UInt8}` if not | | `char**` (or `*char[]`) | | | `Ptr{Ptr{UInt8}}` | | `jl_value_t*` (any Julia Type) | | | `Any` | | `jl_value_t* const*` (一个 Julia 值的引用) | | | `Ref{Any}`(常量,因为转变需要写屏障,不可能正确插入) | | `va_arg` | | | Not supported | | `...` (variadic function specification) | | | `T...`(其中 `T` 是上述类型之一,当使用 `ccall` 函数时) | | `...` (variadic function specification) | | | `; va_arg1::T、va_arg2::S 等`(仅支持`@ccall` 宏) | [`Cstring`](@ref) 类型本质上是`Ptr{UInt8}`的同义词,但如果Julia字符串包含任何嵌入的NUL字符,则类型转换为`Cstring`会引发错误(如果C例程将NUL视为终止符,则会导致字符串被静默截断)。如果要将`char*`传递给不采用NUL终止的C例程(例如,因为传递的是显式字符串长度),或者如果确定Julia字符串不包含NUL并希望跳过检查,则可以使用`Ptr{UInt8}`作为参数类型。`Cstring`也可以用作 [`ccall`](@ref) 返回类型,但在这种情况下,它显然不会引入任何额外的检查,只是为了提高调用的可读性。 **系统独立类型** | C 类型 | 标准 Julia 别名 | Julia 基本类型 | |:--------------- |:-------------------- |:-------------------------------------------- | | `char` | `Cchar` | `Int8` (x86, x86_64), `UInt8` (powerpc, arm) | | `long` | `Clong` | `Int` (UNIX), `Int32` (Windows) | | `unsigned long` | `Culong` | `UInt` (UNIX), `UInt32` (Windows) | | `wchar_t` | `Cwchar_t` | `Int32` (UNIX), `UInt16` (Windows) | !!! note 调用 Fortran 时,所有输入都必须通过指向堆分配或堆栈分配值的指针传递,因此上述所有类型对应都应在其类型规范周围包含一个额外的 `Ptr{..}` 或 `Ref{..}` 包装器。 !!! warning 对于字符串参数 (`char*`),Julia 类型应该是 `Cstring`(如果需要以 NUL 结尾的数据),否则为 `Ptr{Cchar}` 或 `Ptr{UInt8}`(这两种指针类型具有相同的效果),如上所述,而不是 `String`。 类似地,对于数组参数(`T[]` 或 `T*`),Julia 类型应该还是 `Ptr{T}`,而不是 `Vector{T}`。 !!! warning Julia 的 `Char` 类型是 32 位,这与所有平台上的宽字符类型(`wchar_t` 或 `wint_t`)不同。 !!! warning `Union{}` 的返回类型意味着函数不会返回,即 C++11 `[[noreturn]]` 或 C11 `_Noreturn`(例如 `jl_throw` 或 `longjmp`)。 不要将此用于不返回值(`void`)但返回的函数,而是使用`Cvoid`。 !!! note 对于 `wchar_t*` 参数,Julia 类型应为 [`Cwstring`](@ref)(如果 C 例程需要以 NUL 结尾的字符串),否则为 `Ptr{Cwchar_t}`。 另请注意,Julia 中的 UTF-8 字符串数据在内部以 NUL 结尾,因此可以将其传递给需要以 NUL 结尾的数据的 C 函数,而无需进行复制(但使用 `Cwstring` 类型将导致抛出错误,如果字符串本身包含 NUL 字符)。 !!! note 可以在 Julia 中使用 `Ptr{Ptr{UInt8}}` 类型调用采用 `char**` 类型参数的 C 函数。 例如,以下形式的 C 函数: ```c int main(int argc, char **argv); ``` 可以通过以下 Julia 代码调用: ```julia argv = [ "a.out", "arg1", "arg2" ] ccall(:main, Int32, (Int32, Ptr{Ptr{UInt8}}), length(argv), argv) ``` !!! note 对于采用 `character(len=*)` 类型的可变长度字符串的 Fortran 函数,字符串长度作为*隐藏参数*提供。 这些参数在列表中的类型和位置是特定于编译器的,编译器供应商通常默认使用 `Csize_t` 作为类型并将隐藏的参数附加到参数列表的末尾。 虽然此行为对于某些编译器 (GNU) 是固定的,但其他编译器*可选* 允许将隐藏参数直接放置在字符参数(Intel、PGI)之后。 例如,如下的 Fortran 子程序 ```fortran subroutine test(str1, str2) character(len=*) :: str1,str2 ``` can be called via the following Julia code, where the lengths are appended ```julia str1 = "foo" str2 = "bar" ccall(:test, Cvoid, (Ptr{UInt8}, Ptr{UInt8}, Csize_t, Csize_t), str1, str2, sizeof(str1), sizeof(str2)) ``` !!! warning Fortran 编译器还*可以*为指针、假定形状(`:`)和假定大小(`*`)数组添加其他隐藏参数。 这种行为可以通过使用`ISO_C_BINDING`并在子例程的定义中包含`bind(c)`来避免,强烈推荐用于可互操作的代码。 在这种情况下,将没有隐藏的参数,代价是一些语言特性(例如,只允许 `character(len=1)` 传递字符串)。 !!! note 声明为返回 `Cvoid` 的 C 函数将在 Julia 中返回值 `nothing`。 ### 结构类型对应 复合类型,例如 C 中的`struct`或 Fortran90 中的`TYPE`(或 F77 的某些变体中的`STRUCTURE`/`RECORD`),可以通过创建具有相同字段布局的`struct`定义在 Julia 中进行镜像复制。 当递归使用时,`isbits` 类型被内联存储。 所有其他类型都存储为指向数据的指针。 在 C 中的另一个结构中镜像复制按值使用的结构时,不要尝试手动复制字段,因为这不会保留正确的字段对齐。 相反,建议声明一个 `isbits` 结构类型并使用它。 未命名的结构在翻译为 Julia 时是不可能的。 Julia不支持压缩结构和联合声明。 如果你事先地知道将具有最大大小(可能包括填充)的字段,则可以获得 `union` 的近似。 将你的字段转换为 Julia 时,将 Julia 字段声明为仅属于该类型。 参数数组可以用 `NTuple` 表示。例如,C 符号中的 struct 写成 ```c struct B { int A[3]; }; b_a_2 = B.A[2]; ``` 可以用 Julia 写成 ```julia struct B A::NTuple{3, Cint} end b_a_2 = B.A[3] # note the difference in indexing (1-based in Julia, 0-based in C) ``` 不直接支持未知大小的数组(由`[]` 或`[0]` 指定的符合C99 的可变长度结构)。 通常处理这些的最好方法是直接处理字节偏移量。 例如,如果一个 C 库声明了一个正确的字符串类型并返回一个指向它的指针: ```c struct String { int strlen; char data[]; }; ``` 在 Julia 中,我们可以独立访问这些部分以制作该字符串的副本: ```julia str = from_c::Ptr{Cvoid} len = unsafe_load(Ptr{Cint}(str)) unsafe_string(str + Core.sizeof(Cint), len) ``` ### 类型参数 当定义了方法时,`ccall` 和 `@cfunction` 的类型参数被静态地评估。 因此,它们必须采用字面量元组的形式,而不是变量,并且不能引用局部变量。 这听起来像是一个奇怪的限制,但请记住,由于 C 不是像 Julia 那样的动态语言,它的函数只能接受具有静态已知的固定签名的参数类型。 然而,虽然必须静态地知道类型布局才能计算预期的 C ABI,但函数的静态参数被视为此静态环境的一部分。函数的静态参数可以用作调用签名中的类型参数,只要它们不影响类型的布局即可。例如, `f(x::T) where {T} = ccall(:valid, Ptr{T}, (Ptr{T},), x)` 是有效的,因为 `Ptr` 始终是字大小的原始类型。但是, `g(x::T) where {T} = ccall(:notvalid, T, (T,), x)` 是无效的,因为 `T` 的类型布局不是静态已知的。 ### SIMD 值 注意:此功能目前仅在 64 位 x86 和 AArch64 平台上实现。 如果 C/C++ 例程具有本机 SIMD 类型的参数或返回值,则相应的 Julia 类型是自然映射到 SIMD 类型的`VecElement` 的同构元组。 具体来说: > * 元组的大小必须与 SIMD 类型相同。 例如,一个表示 `__m128` 的元组 > 在 x86 上必须有 16 字节的大小。 > * 元组的元素类型必须是 `VecElement{T}` 的一个实例,其中 `T` 是一个原始类型 > 是 1、2、4 或 8 个字节。 例如,考虑这个使用 AVX 内在函数的 C 例程: ```c #include <immintrin.h> __m256 dist( __m256 a, __m256 b ) { return _mm256_sqrt_ps(_mm256_add_ps(_mm256_mul_ps(a, a), _mm256_mul_ps(b, b))); } ``` 以下 Julia 代码使用 `ccall` 调用 `dist`: ```julia const m256 = NTuple{8, VecElement{Float32}} a = m256(ntuple(i -> VecElement(sin(Float32(i))), 8)) b = m256(ntuple(i -> VecElement(cos(Float32(i))), 8)) function call_dist(a::m256, b::m256) ccall((:dist, "libdist"), m256, (m256, m256), a, b) end println(call_dist(a,b)) ``` 主机必须具有必要的 SIMD 寄存器。 例如,上面的代码将无法在没有 AVX 支持的主机上运行。 ### 内存所有权 **malloc/free** 此类对象的内存分配和释放必须通过调用正在使用的库中的适当清理例程来处理,就像在任何 C 程序中一样。 不要尝试在 Julia 中使用 [`Libc.free`](@ref) 释放从 C 库接收的对象,因为这可能会导致通过错误的库调用 `free` 函数并导致进程中止。 反过来(传递在 Julia 中分配的对象以供外部库释放)同样无效。 ### 何时使用 T、Ptr{T} 以及 Ref{T} 在对外部C例程的Julia代码包装调用中,普通(非指针)数据应该在[`ccall`](@ref) 中声明为`T`类型,因为它们是通过值传递的。对于接受指针的C代码,[`Ref{T}`](@ref) 通常应用于输入参数的类型,允许通过对[`Base.cconvert`](@ref) 的隐式调用使用指向Julia或C管理的内存的指针。相反,被调用的C函数返回的指针应该声明为输出类型[`Ptr{T}`](@ref),这反映了指向的内存仅由C管理。C结构中包含的指针应在相应的Julia结构类型中表示为`Ptr{T}`类型的字段,这些结构类型旨在模拟相应C结构的内部结构。 在 Julia 代码包装对外部 Fortran 例程的调用中,所有输入参数都应声明为`Ref{T}`类型,因为 Fortran 通过指向内存位置的指针传递所有变量。 Fortran 子程序的返回类型应该是 `Cvoid`,或者 Fortran 函数的返回类型应该是 `T`,返回类型是 `T`。 ## Mapping C Functions to Julia ### `ccall` / `@cfunction` argument translation guide For translating a C argument list to Julia: * `T`, where `T` is one of the primitive types: `char`, `int`, `long`, `short`, `float`, `double`, `complex`, `enum` or any of their `typedef` equivalents * `T`, where `T` is an equivalent Julia Bits Type (per the table above) * if `T` is an `enum`, the argument type should be equivalent to `Cint` or `Cuint` * argument value will be copied (passed by value) * `struct T` (including typedef to a struct) * `T`, where `T` is a Julia leaf type * argument value will be copied (passed by value) * `void*` * depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list * this argument may be declared as `Ptr{Cvoid}`, if it really is just an unknown pointer * `jl_value_t*` * `Any` * argument value must be a valid Julia object * `jl_value_t* const*` * `Ref{Any}` * 参数列表必须是有效的 Julia 对象(或 C_NULL) * 不能用于输出参数,除非用户能够单独安排要GC保留的对象 * `T*` * `Ref{T}`, where `T` is the Julia type corresponding to `T` * 如果参数值是 `inlinealloc` 类型(否则包括 `isbits`,该值必须是有效的 Julia 对象)将被复制 * `T (*)(...)` (e.g. a pointer to a function) * `Ptr{Cvoid}`(你可能需要显式使用 [`@cfunction`](@ref) 来创建这个指针) * `...` (e.g. a vararg) * [[for `ccall`]: `T...`,其中 `T` 是所有剩余参数的单个 Julia 类型]: `T...`, where `T` is the single Julia type of all * [[for `@ccall`]:`; va_arg1::T、va_arg2::S` 等,其中 `T` 和 `S` 是 Julia 类型(即用 `;` 将常规参数与可变参数分开)]: `; va_arg1::T, va_arg2::S, etc`, where `T` and `S` are * `@cfunction` 目前不支持 * `va_arg` * `ccall` 或 `@cfunction` 不支持 ### `ccall` / `@cfunction` return type translation guide For translating a C return type to Julia: * `void` * `Cvoid` (this will return the singleton instance `nothing::Cvoid`) * `T`, where `T` is one of the primitive types: `char`, `int`, `long`, `short`, `float`, `double`, `complex`, `enum` or any of their `typedef` equivalents * `T`, where `T` is an equivalent Julia Bits Type (per the table above) * if `T` is an `enum`, the argument type should be equivalent to `Cint` or `Cuint` * argument value will be copied (returned by-value) * `struct T` (including typedef to a struct) * `T`, where `T` is a Julia Leaf Type * argument value will be copied (returned by-value) * `void*` * depends on how this parameter is used, first translate this to the intended pointer type, then determine the Julia equivalent using the remaining rules in this list * this argument may be declared as `Ptr{Cvoid}`, if it really is just an unknown pointer * `jl_value_t*` * `Any` * argument value must be a valid Julia object * `jl_value_t**` * `Ptr{Any}` (`Ref{Any}` is invalid as a return type) * `T*` * If the memory is already owned by Julia, or is an `isbits` type, and is known to be non-null: * `Ref{T}`, where `T` is the Julia type corresponding to `T` * `Ref{Any}` 的返回类型无效,它应该是 `Any`(对应于 `jl_value_t*`)或 `Ptr{Any}`(对应于 `jl_value_t**`) * C **MUST NOT** modify the memory returned via `Ref{T}` if `T` is an `isbits` type * If the memory is owned by C: * `Ptr{T}`, where `T` is the Julia type corresponding to `T` * `T (*)(...)` (e.g. a pointer to a function) * `Ptr{Cvoid}` (you may need to use [`@cfunction`](@ref) explicitly to create this pointer) ### 传递修改输入的指针 因为 C 不支持多个返回值,所以 C 函数通常会使用指向函数将修改的数据的指针。 要在 [`ccall`](@ref) 中完成此操作,你需要首先将值封装在适当类型的 [`Ref{T}`](@ref) 中。 当你将这个 `Ref` 对象作为参数传递时,Julia 会自动传递一个指向封装数据的 C 指针: ```julia width = Ref{Cint}(0) range = Ref{Cfloat}(0) ccall(:foo, Cvoid, (Ref{Cint}, Ref{Cfloat}), width, range) ``` 返回时,可以通过`width[]`和`range[]`检索`width`和`range`的内容(如果它们被`foo`改变的话); 也就是说,它们就像零维数组。 ## C 包装器示例 让我们从一个返回 `Ptr` 类型的 C 包装器的简单示例开始: ```julia mutable struct gsl_permutation end # The corresponding C signature is # gsl_permutation * gsl_permutation_alloc (size_t n); function permutation_alloc(n::Integer) output_ptr = ccall( (:gsl_permutation_alloc, :libgsl), # name of C function and library Ptr{gsl_permutation}, # output type (Csize_t,), # tuple of input types n # name of Julia variable to pass in ) if output_ptr == C_NULL # Could not allocate memory throw(OutOfMemoryError()) end return output_ptr end ``` [GNU 科学图书馆](https://www.gnu.org/software/gsl/)(这里假设可以通过`:libgsl` 访问)定义了一个不透明的指针,`gsl_permutation *`,作为 C 函数`gsl_permutation_alloc` 的返回类型。 由于用户代码永远不必查看 `gsl_permutation` 结构内部,相应的 Julia 包装器只需要一个新的类型声明 `gsl_permutation`,它没有内部字段,其唯一目的是放置在 `Ptr`类型的类型参数中。 [`ccall`](@ref) 的返回类型声明为 `Ptr{gsl_permutation}`,因为 `output_ptr` 分配和指向的内存由 C 控制。 输入 `n` 是按值传递的,因此函数的输入签名被简单地声明为 `(Csize_t,)`,不需要任何 `Ref` 或 `Ptr`。 (如果包装器改为调用 Fortran 函数,则相应的函数输入签名将改为 `(Ref{Csize_t},)`,因为 Fortran 变量是通过指针传递的。)此外,`n` 可以是任何可转换的类型 到一个 `Csize_t` 整数; [`ccall`](@ref) 隐式调用 [`Base.cconvert(Csize_t, n)`](@ref)。 这是包装相应析构函数的第二个示例: ```julia # The corresponding C signature is # void gsl_permutation_free (gsl_permutation * p); function permutation_free(p::Ref{gsl_permutation}) ccall( (:gsl_permutation_free, :libgsl), # name of C function and library Cvoid, # output type (Ref{gsl_permutation},), # tuple of input types p # name of Julia variable to pass in ) end ``` 这里,输入`p`被声明为`Ref{gsl_permutation}`类型,这意味着`p`指向的内存可以由Julia或C管理。由C分配的内存指针应该是类型 `Ptr{gsl_permutation}`,但它可以使用 [`Base.cconvert` ](@ref) 进行转换,因此 现在,如果你仔细观察这个例子,你可能会注意到它是不正确的,因为我们上面对首选声明类型的解释。 你看到了吗? 我们正在调用的函数将释放内存。 这种类型的操作不能被赋予 Julia 对象(它会崩溃或导致内存损坏)。因此,将 `p` 类型声明为 `Ptr{gsl_permutation }` 可能更可取,这样用户就更难错误地传递另一种对象,而不是通过 `gsl_permutation_alloc` 获得的对象。 如果 C 包装器从不希望用户将指针传递给 Julia 管理的内存,那么使用 `p::Ptr{gsl_permutation}` 作为包装器的方法签名,类似地在 [`ccall`](@ref) 中也是可以接受。 这是传递 Julia 数组的第三个示例: ```julia # The corresponding C signature is # int gsl_sf_bessel_Jn_array (int nmin, int nmax, double x, # double result_array[]) function sf_bessel_Jn_array(nmin::Integer, nmax::Integer, x::Real) if nmax < nmin throw(DomainError()) end result_array = Vector{Cdouble}(undef, nmax - nmin + 1) errorcode = ccall( (:gsl_sf_bessel_Jn_array, :libgsl), # name of C function and library Cint, # output type (Cint, Cint, Cdouble, Ref{Cdouble}),# tuple of input types nmin, nmax, x, result_array # names of Julia variables to pass in ) if errorcode != 0 error("GSL error code $errorcode") end return result_array end ``` 包装的 C 函数返回一个整数错误代码; Bessel J 函数的实际评估结果填充 Julia 数组 `result_array`。 这个变量被声明为一个 `Ref{Cdouble}`,因为它的内存是由 Julia 分配和管理的。 对 [`Base.cconvert(Ref{Cdouble}, result_array)`](@ref) 的隐式调用将指向 Julia 数组数据结构的 Julia 指针解包为 C 可以理解的形式。 ## Fortran 包装器示例 以下示例利用 ccall 调用通用 Fortran 库 (libBLAS) 中的函数来计算点积。 请注意,这里的参数映射与上面的有点不同,因为我们需要从 Julia 映射到 Fortran。 在每个参数类型上,我们指定 `Ref` 或 `Ptr`。 此修改约定可能特定于你的 Fortran 编译器和操作系统,并且可能未记录在案。 但是,将每个包装在一个 `Ref`(或 `Ptr`,等效地)中是 Fortran 编译器实现的一个常见要求: ```julia function compute_dot(DX::Vector{Float64}, DY::Vector{Float64}) @assert length(DX) == length(DY) n = length(DX) incx = incy = 1 product = ccall((:ddot_, "libLAPACK"), Float64, (Ref{Int32}, Ptr{Float64}, Ref{Int32}, Ptr{Float64}, Ref{Int32}), n, DX, incx, DY, incy) return product end ``` ## 垃圾回收安全 将数据传递给 [`ccall`](@ref) 时,最好避免使用 [`pointer`](@ref) 函数。 而是定义一个转换方法并将变量直接传递给 [`ccall`](@ref)。 [`ccall`](@ref) 自动安排它的所有参数都将从垃圾收集中保留,直到调用返回。 如果 C API 将存储对 Julia 分配的内存的引用,则在 [`ccall`](@ref) 返回后,你必须确保该对象对垃圾收集器保持可见。 建议的方法是创建一个类型为 `Array{Ref,1}` 的全局变量来保存这些值,直到 C 库通知你它已完成使用它们。 每当你创建了一个指向 Julia 数据的指针时,你必须确保原始数据存在,直到你完成使用该指针。 Julia 中的许多方法,例如 [`unsafe_load`](@ref) 和 [`String`](@ref) 复制数据而不是获取缓冲区的所有权,因此可以安全地释放(或更改)原始数而不影响 Julia。 一个值得注意的例外是 [`unsafe_wrap`](@ref),出于性能原因,它共享(或可以被告知拥有)底层缓冲区。 垃圾收集器不保证任何终结顺序。 也就是说,如果 `a` 包含对 `b` 的引用,并且 `a` 和 `b` 都需要进行垃圾回收,则不能保证 `b` 会在 `a` 之后完成。 如果 `a` 的正确终结取决于 `b` 是否有效,则必须以其他方式处理。 ## [非常数函数规范](@id Non-constant-Function-Specifications) 在某些情况下,所需库的确切名称或路径是事先未知的,必须在运行时计算。 为了处理这种情况,`(name, library)` 规范的库组件可以是一个函数调用,例如 `(:dgemm_, find_blas())`。 调用表达式将在执行 `ccall` 本身时执行。 但是,假设库位置一旦确定就不会改变,因此调用的结果可以被缓存和重用。 因此,表达式执行的次数是未指定的,多次调用返回不同的值会导致未指定的行为。 如果需要更大的灵活性,可以通过 [`eval`](@ref) 分段使用计算值作为函数名称,如下所示: ``` @eval ccall(($(string("a", "b")), "lib"), ... ``` 此表达式使用 `string` 构造一个名称,然后将此名称替换为一个新的 [`ccall`](@ref) 表达式,然后对其进行评估。 请记住,`eval` 仅在顶层运行,因此在此表达式中局部变量将不可用(除非它们的值被替换为 `$`)。 出于这个原因,`eval` 通常仅用于形成顶级定义,例如在包装包含许多类似函数的库时。 可以为 [`@cfunction`](@ref) 构造一个类似的示例。 但是,这样做也会很慢并且会泄漏内存,因此你通常应该避免这种情况,而是继续阅读。 下一节讨论如何使用间接调用来有效地实现类似的效果。 ## 非直接调用 [`ccall`](@ref) 的第一个参数也可以是在运行时计算的表达式。 在这种情况下,表达式的计算结果必须为 `Ptr`,它将用作要调用的本地函数的地址。 当第一个 [`ccall`](@ref) 参数包含对非常量(例如局部变量、函数参数或非常量全局变量)的引用时,会发生此行为。 例如,你可以通过 `dlsym` 查找函数,然后将其缓存在该会话的共享引用中。 例如: ```julia macro dlsym(func, lib) z = Ref{Ptr{Cvoid}}(C_NULL) quote let zlocal = $z[] if zlocal == C_NULL zlocal = dlsym($(esc(lib))::Ptr{Cvoid}, $(esc(func)))::Ptr{Cvoid} $z[] = zlocal end zlocal end end end mylibvar = Libdl.dlopen("mylib") ccall(@dlsym("myfunc", mylibvar), Cvoid, ()) ``` ## cfunction 闭包 [`@cfunction`](@ref) 的第一个参数可以用 `$` 标记,在这种情况下,返回值将改为结束参数的 `struct CFunction`。 你必须确保此返回对象保持活动状态,直到完成对它的所有使用。 当这个引用被删除和 atexit 时,cfunction 指针处的内容和代码将通过 [`finalizer`](@ref) 删除。 这通常不是必需的,因为此功能在 C 中不存在,但对于处理不提供单独的闭包环境参数的设计不良的 API 很有用。 ```julia function qsort(a::Vector{T}, cmp) where T isbits(T) || throw(ArgumentError("this method can only qsort isbits arrays")) callback = @cfunction $cmp Cint (Ref{T}, Ref{T}) # Here, `callback` isa Base.CFunction, which will be converted to Ptr{Cvoid} # (and protected against finalization) by the ccall ccall(:qsort, Cvoid, (Ptr{T}, Csize_t, Csize_t, Ptr{Cvoid}), a, length(a), Base.elsize(a), callback) # We could instead use: # GC.@preserve callback begin # use(Base.unsafe_convert(Ptr{Cvoid}, callback)) # end # if we needed to use it outside of a `ccall` return a end ``` !!! note 闭包 [`@cfunction`](@ref) 依赖于 LLVM Trampolines,并非在所有平台(例如 ARM 和 PowerPC)上都可用。 ## 关闭库 关闭(卸载)库以便重新加载有时很有用。 例如,在开发与 Julia 一起使用的 C 代码时,可能需要编译、从 Julia 调用 C 代码,然后关闭库、进行编辑、重新编译并加载新的更改。 可以重新启动 Julia 或使用 `Libdl` 函数来显式管理库,例如: ```julia lib = Libdl.dlopen("./my_lib.so") # 显式打开库 sym = Libdl.dlsym(lib, :my_fcn) # 获得用于调用函数的符号 ccall(sym, ...) # 直接用指针 `sym` 而不是 (symbol, library) 元组,其余参数保持不变 Libdl.dlclose(lib) # 显式关闭库 ``` 请注意,当将 `ccall` 与输入元组(例如,`ccall((:my_fcn, "./my_lib.so"), ...)`)一起使用时,库会隐式打开,并且可能不会显式关闭。 ## 调用规约 [`ccall`](@ref) 的第二个参数可以选择是调用约定说明符(直接在返回类型之前)。 没有任何说明符,使用平台默认的 C 调用约定。 其他支持的约定是:`stdcall`、`cdecl`、`fastcall` 和`thiscall`(64 位Windows 上无操作)。 例如(来自`base/libc.jl`)我们看到与上面相同的`gethostname`[`ccall`](@ref),但具有正确的Windows签名: ```julia hn = Vector{UInt8}(undef, 256) err = ccall(:gethostname, stdcall, Int32, (Ptr{UInt8}, UInt32), hn, length(hn)) ``` 请参阅 [LLVM Language Reference](http://llvm.org/docs/LangRef.html#calling-conventions) 来获得更多信息。 还有一个额外的特殊调用约定 [`llvmcall`](@ref Base.llvmcall),它允许直接插入对 LLVM 内部函数的调用。 这在针对不常见的平台(例如 GPGPU)时特别有用。 例如,对于[CUDA](http://llvm.org/docs/NVPTXUsage.html),我们需要能够读取线程索引: ```julia ccall("llvm.nvvm.read.ptx.sreg.tid.x", llvmcall, Int32, ()) ``` 与任何 `ccall` 一样,参数签名必须完全正确。另外,请注意,与`Core.Intrinsics`开放的等效Julia函数不同,没有兼容层级可以确保内在函数有意义并在当前目标上工作。 ## 访问全局变量 可以使用 [`cglobal`](@ref) 函数按名称访问本地库导出的全局变量。 [`cglobal`](@ref) 的参数与 [`ccall`](@ref) 使用相同的符号规范,以及描述存储在变量中的值的类型: ```julia-repl julia> cglobal((:errno, :libc), Int32) Ptr{Int32} @0x00007f418d0816b8 ``` 结果是一个给出值地址的指针。 可以使用 [`unsafe_load`](@ref) 和 [`unsafe_store!`](@ref) 通过这个指针来操作该值。 !!! note 在名为“libc”的库中可能找不到此 `errno` 符号,因为这是系统编译器的实现细节。 通常标准库符号应该只通过名称访问,允许编译器填写正确的符号。 然而,这个例子中显示的 `errno` 符号在大多数编译器中都是特殊的,所以这里看到的值可能不是你所期望或想要的。 在任何支持多线程的系统上用 C 编译等效代码通常实际上会调用不同的函数(通过宏预处理器重载),并且可能给出与此处打印的遗留值不同的结果。 ## 通过指针来访问数据 以下方法被描述为“不安全”,因为错误的指针或类型声明会导致 Julia 突然终止。 给定一个 `Ptr{T}`,通常可以使用 `unsafe_load(ptr, [index])` 将 `T` 类型的内容从引用的内存复制到 Julia 对象中。 index 参数是可选的(默认为 1),并遵循基于 1 的索引的 Julia 惯例。 此函数类似于 [`getindex`](@ref) 和 [`setindex!`](@ref) 的行为(例如`[]` 访问语法)。 返回值将是一个初始化为包含引用内存内容副本的新对象。 引用的内存可以安全地释放或释放。 如果 `T` 是 `Any`,则假定内存包含对 Julia 对象的引用(`jl_value_t*`),结果将是对该对象的引用,并且不会复制该对象。 在这种情况下,你必须小心确保对象始终对垃圾收集器可见(指针不计数,但新引用计数)以确保内存不会过早释放。 请注意,如果对象最初不是由 Julia 分配的,则新对象将永远不会被 Julia 的垃圾收集器终结。 如果 `Ptr` 本身实际上是一个 `jl_value_t*`,它可以通过 [`unsafe_pointer_to_objref(ptr)`](@ref) 转换回 Julia 对象引用。 (Julia 值 `v` 可以通过调用 [`pointer_from_objref(v)`](@ref) 转换为 `jl_value_t*` 指针,如 `Ptr{Cvoid}`。) 可以使用 [`unsafe_store!(ptr, value, [index])`](@ref) 执行反向操作(将数据写入 `Ptr{T}`)。 目前,这仅支持原始类型或其他无指针(`isbits`)不可变结构类型。 任何引发错误的操作目前可能尚未实现,应作为错误发布,以便解决。 如果感兴趣的指针是纯数据数组(原始类型或不可变结构),则函数 [`unsafe_wrap(Array, ptr,dims, own = false)`](@ref) 可能更有用。 如果 Julia 应该“获得”底层缓冲区的所有权并在返回的 `Array` 对象最终确定时调用 `free(ptr)`,则最后一个参数应该为 true。 如果省略了 `own` 参数或为 false,则调用者必须确保缓冲区一直存在,直到所有访问完成。 Julia 中 `Ptr` 类型的算术(例如使用 `+`)与 C 的指针算术的行为不同。 将整数添加到 Julia 中的 `Ptr` 总是将指针移动一定数量的 *bytes*,而不是元素。 这样,通过指针运算获得的地址值不依赖于指针的元素类型。 ## 线程安全 一些 C 库从不同的线程执行它们的回调,并且由于 Julia 不是线程安全的,因此你需要采取一些额外的预防措施。 特别是,你需要设置一个两层系统:C 回调应该只 *安排*(通过 Julia 的事件循环)执行“真实”回调。 为此,创建一个 [`AsyncCondition`](@ref Base.AsyncCondition) 对象并在其上创建 [`wait`](@ref): ```julia cond = Base.AsyncCondition() wait(cond) ``` 传递给 C 的回调应该只通过 [`ccall`](@ref) 将 `cond.handle` 作为参数传递给 `:uv_async_send` 并调用,注意避免任何内存分配操作或与 Julia 运行时的其他交互。 注意,事件可能会合并,因此对 `uv_async_send` 的多个调用可能会导致对该条件的单个唤醒通知。 ## 关于 Callbacks 的更多内容 关于如何传递 callback 到 C 库的更多细节,请参考此[博客](https://julialang.org/blog/2013/05/callback)。 ## C++ 如需要直接易用的C++接口,即直接用Julia写封装代码,请参考 [Cxx](https://github.com/Keno/Cxx.jl)。如需封装C++库的工具,即用C++写封装/胶水代码,请参考[CxxWrap](https://github.com/JuliaInterop/CxxWrap.jl)。 [^1]: Non-library function calls in both C and Julia can be inlined and thus may have even less overhead than calls to shared library functions. The point above is that the cost of actually doing foreign function call is about the same as doing a call in either native language. [^2]: The [Clang package](https://github.com/ihnorton/Clang.jl) can be used to auto-generate Julia code from a C header file.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
15177
# [代码加载](@id code-loading) !!! note 这一章包含了加载包的技术细节。如果要安装包,使用 Julia 的内置包管理器[`Pkg`](@ref Pkg)将包加入到你的活跃环境中。如果要使用已经在你的活跃环境中的包,使用 `import X` 或 `using X`,正如在[模块](@ref 模块)中所描述的那样。 ## 定义 Julia加载代码有两种机制: 1. **代码包含:**例如 `include("source.jl")`。包含允许你把一个程序拆分为多个源文件。表达式 `include("source.jl")` 使得文件 `source.jl` 的内容在出现 `include` 调用的模块的全局作用域中执行。如果多次调用 `include("source.jl")`,`source.jl` 就被执行多次。`source.jl` 的包含路径解释为相对于出现 `include` 调用的文件路径。重定位源文件子树因此变得简单。在 REPL 中,包含路径为当前工作目录,即 [`pwd()`](@ref)。 2. **加载包:**例如 `import X` 或 `using X`。`import` 通过加载包(一个独立的,可重用的 Julia 代码集合,包含在一个模块中),并导入模块内部的名称 `X`,使得模块 `X` 可用。 如果在同一个 Julia 会话中,多次导入包 `X`,那么后续导入模块为第一次导入模块的引用。但请注意,`import X` 可以在不同的上下文中加载不同的包:`X` 可以引用主工程中名为 `X` 的一个包,但它在各个依赖中可以引用不同的、名称同为 `X` 的包。更多机制说明如下。 代码包含是非常直接和简单的:其在调用者的上下文中解释运行给定的源文件。包加载是建立在代码包含之上的,它具有不同的[用途](@ref modules)。本章的其余部分将重点介绍程序包加载的行为和机制。 一个 *包(package)* 就是一个源码树,其标准布局中提供了其他 Julia 项目可以复用的功能。包可以使用 `import X` 或 `using X` 语句加载,名为 `X` 的模块在加载包代码时生成,并在包含该 import 语句的模块中可用。`import X` 中 `X` 的含义与上下文有关:程序加载哪个 `X` 包取决于 import 语句出现的位置。因此,处理 `import X` 分为两步:首先,确定在此上下文中是**哪个**包被定义为 `X`;其次,确定到**哪里**找特定的 `X` 包。 这些问题可通过查询各项目文件(`Project.toml` 或 `JuliaProject.toml`)、清单文件(`Manifest.toml` 或 `JuliaManifest.toml`),或是源文件的文件夹列在[`LOAD_PATH`](@ref) 中的项目环境解决。 ## [包的联合生态](@id Federation-of-packages) 大多数时候,一个包可以通过它的名字唯一确定。但有时在一个项目中,可能需要使用两个有着相同名字的不同的包。尽管你可以通过重命名其中一个包来解决这个问题,但在一个大型的、共享的代码库中被迫做这件事可能是有高度破坏性的。相反,Julia的包加载机制允许相同的包名在一个应用的不同部分指向不同的包。 Julia 支持联合的包管理,这意味着多个独立的部分可以维护公有包、私有包以及包的注册表,并且项目可以依赖于一系列来自不同注册表的公有包和私有包。您也可以使用一组通用工具和工作流(workflow)来安装和管理来自各种注册表的包。Julia 附带的 `Pkg` 软件包管理器允许安装和管理项目的依赖项,它会帮助创建并操作项目文件(其描述了项目所依赖的其他项目)和清单文件(其为项目完整依赖库的确切版本的快照)。 联合管理的一个可能后果是没有包命名的中央权限。不同组织可以使用相同的名称来引用不相关的包。这并不是没有可能的,因为这些组织可能没有协作,甚至不知道彼此。由于缺乏中央命名权限,单个项目可能最终依赖着具有相同名称的不同包。Julia 的包加载机制不要求包名称是全局唯一的,即使在单个项目的依赖关系图中也是如此。相反,包由[通用唯一标识符](https://en.wikipedia.org/wiki/Universally_unique_identifier) (UUID)进行标识,它在每个包创建时进行分配。通常,您不必直接使用这些有点麻烦的 128 位标识符,因为 `Pkg` 将负责生成和跟踪它们。但是,这些 UUID 为问题*「`X` 所指的包是什么?」*提供了确定的答案 由于去中心化的命名问题有些抽象,因此可以通过具体情境来理解问题。假设你正在开发一个名为 `App` 的应用程序,它使用两个包:`Pub` 和 `Priv`。`Priv` 是你创建的私有包,而 `Pub` 是你使用但不控制的公共包。当你创建 `Priv` 时,没有名为 `Priv` 的公共包。然而,随后一个名为 `Priv` 的不相关软件包发布并变得流行起来,而且 `Pub` 包已经开始使用它了。因此,当你下次升级 `Pub` 以获取最新的错误修复和特性时,`App` 将依赖于两个名为 `Priv` 的不同包——尽管你除了升级之外什么都没做。`App` 直接依赖于你的私有 `Priv` 包,以及通过 `Pub` 在新的公共 `Priv` 包上的间接依赖。由于这两个 `Priv` 包是不同的,但是 `App` 继续正常工作依赖于他们两者,因此表达式 `import Priv` 必须引用不同的 `Priv` 包,具体取决于它是出现在 `App` 的代码中还是出现在 `Pub` 的代码中。为了处理这种情况,Julia 的包加载机制通过 UUID 区分两个 `Priv` 包并根据它(调用 `import` 的模块)的上下文选择正确的包。这种区分的工作原理取决于环境,如以下各节所述。 ## 环境(Environments) **环境**决定了 `import X` 和 `using X` 语句在不同的代码上下文中的含义以及什么文件会被加载。Julia 有两类环境(environment): 1. **项目环境(project environment)**是包含项目文件和清单文件(可选)的目录,并形成一个*显式环境*。项目文件确定项目的直接依赖项的名称和标识。清单文件(如果存在)提供完整的依赖关系图,包括所有直接和间接依赖关系,每个依赖的确切版本以及定位和加载正确版本的足够信息。 2. **包目录(package directory)**是包含一组包的源码树子目录的目录,并形成一个*隐式环境*。如果 `X` 是包目录的子目录并且存在 `X/src/X.jl`,那么程序包 `X` 在包目录环境中可用,而 `X/src/X.jl` 是加载它使用的源文件。 这些环境可以混合并用来创建**堆栈环境(stacked environment)**:是一组有序的项目环境和包目录,重叠为一个复合环境。然后,结合优先级规则和可见性规则,确定哪些包是可用的以及从哪里加载它们。例如,Julia 的负载路径是一个堆栈环境。 这些环境各有不同的用途: * 项目环境提供**可迁移性**。通过将项目环境以及项目源代码的其余部分存放到版本控制(例如一个 git 存储库),您可以重现项目的确切状态和所有依赖项。特别是,清单文件会记录每个依赖项的确切版本,而依赖项由其源码树的加密哈希值标识;这使得 `Pkg` 可以检索出正确的版本,并确保你正在运行准确的已记录的所有依赖项的代码。 * 当不需要完全仔细跟踪的项目环境时,包目录更**方便**。当你想要把一组包放在某处,并且希望能够直接使用它们而不必为之创建项目环境时,包目录是很实用的。 * 堆栈环境允许向基本环境**添加**工具。您可以将包含开发工具在内的环境堆到堆栈环境的末尾,使它们在 REPL 和脚本中可用,但在包内部不可用。 从更高层次上,每个环境在概念上定义了三个映射:roots、graph 和 paths。当解析 `import X` 的含义时,roots 和 graph 映射用于确定 `X` 的身份,同时 paths 映射用于定位 `X` 的源代码。这三个映射的具体作用是: - **roots:** `name::Symbol` ⟶ `uuid::UUID` 环境的 roots 映射将包名称分配给UUID,以获取环境可用于主项目的所有顶级依赖项(即可以在 `Main` 中加载的那些依赖项)。当 Julia 在主项目中遇到 `import X` 时,它会将 `X` 的标识作为 `roots[:X]`。 - **graph:** `context::UUID` ⟶ `name::Symbol` ⟶ `uuid::UUID` 环境的 graph 是一个多级映射,它为每个 `context` UUID 分配一个从名称到 UUID 的映射——类似于 roots 映射,但专一于那个 `context`。当 Julia 在 UUID 为 `context` 的包代码中运行到 `import X` 时,它会将 `X` 的标识看作为 `graph[context][:X]`。正是因为如此,`import X` 可以根据 `context` 引用不同的包。 - **paths:** `uuid::UUID` × `name::Symbol` ⟶ `path::String` paths 映射会为每个包分配 UUID-name 对,即该包的入口点源文件的位置。在 `import X` 中,`X` 的标识已经通过 roots 或 graph 解析为 UUID(取决于它是从主项目还是从依赖项加载),Julia 确定要加载哪个文件来获取 `X` 是通过在环境中查找 `paths[uuid,:X]`。要包含此文件应该定义一个名为 `X` 的模块。一旦加载了此包,任何解析为相同的 `uuid` 的后续导入只会创建一个到同一个已加载的包模块的绑定。 每种环境都以不同的方式定义这三种映射,详见以下各节。 !!! note 为了清楚地说明,本章中的示例包括 roots、graph 和 paths 的完整数据结构。但是,为了提高效率,Julia 的包加载代码并没有显式地创建它们。相反,加载一个给定包只会简单地计算所需的结构。 ### 项目环境(Project environments) 项目环境由包含名为 `Project.toml` 的项目文件的目录以及名为 `Manifest.toml` 的清单文件(可选)确定。这些文件也可以命名为 `JuliaProject.toml` 和 `JuliaManifest.toml`,此时 `Project.toml` 和 `Manifest.toml` 被忽略——这允许项目与可能需要名为 `Project.toml` 和 `Manifest.toml` 文件的其他重要工具共存。但是对于纯 Julia 项目,名称 `Project.toml` 和 `Manifest.toml` 是首选。 项目环境的 roots、graph 和 paths 映射定义如下: **roots 映射** 在环境中由其项目文件的内容决定,特别是它的顶级 `name` 和 `uuid` 条目及其 `[deps]` 部分(全部是可选的)。考虑以下一个假想的应用程序 `App` 的示例项目文件,如先前所述: ```toml name = "App" uuid = "8f986787-14fe-4607-ba5d-fbff2944afa9" [deps] Priv = "ba13f791-ae1d-465a-978b-69c3ad90f72b" Pub = "c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1" ``` 如果将它表示为 Julia 字典,那么这个项目文件意味着以下 roots 映射: ```julia roots = Dict( :App => UUID("8f986787-14fe-4607-ba5d-fbff2944afa9"), :Priv => UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b"), :Pub => UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"), ) ``` 基于这个 root 映射,在 `App` 的代码中,语句 `import Priv` 将使 Julia 查找 `roots[:Priv]`,这将得到 `ba13f791-ae1d-465a-978b-69c3ad90f72b`,也就是要在这一部分加载的 `Priv` 包的 UUID。当主应用程序解释运行到 `import Priv` 时,此 UUID 标识了要加载和使用的 `Priv` 包。 **依赖图(dependency graph)** 在项目环境中其清单文件的内容决定,如果其存在。如果没有清单文件,则 graph 为空。清单文件包含项目的直接或间接依赖项的节(stanza)。对于每个依赖项,该文件列出该包的 UUID 以及源码树的哈希值或源代码的显式路径。考虑以下 `App` 的示例清单文件: ```toml [[Priv]] # 私有的那个 deps = ["Pub", "Zebra"] uuid = "ba13f791-ae1d-465a-978b-69c3ad90f72b" path = "deps/Priv" [[Priv]] # 公共的那个 uuid = "2d15fe94-a1f7-436c-a4d8-07a9a496e01c" git-tree-sha1 = "1bf63d3be994fe83456a03b874b409cfd59a6373" version = "0.1.5" [[Pub]] uuid = "c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1" git-tree-sha1 = "9ebd50e2b0dd1e110e842df3b433cb5869b0dd38" version = "2.1.4" [Pub.deps] Priv = "2d15fe94-a1f7-436c-a4d8-07a9a496e01c" Zebra = "f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62" [[Zebra]] uuid = "f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62" git-tree-sha1 = "e808e36a5d7173974b90a15a353b564f3494092f" version = "3.4.2" ``` 这个清单文件描述了 `App` 项目可能的完整依赖关系图: - 应用程序使用两个名为 `Priv` 的不同包,一个作为根依赖项的私有包,以及一个通过 `Pub` 作为间接依赖项的公共包。它们通过不同 UUID 来区分,并且有不同的依赖项: * 私有的 `Priv` 依赖于 `Pub` 和 `Zebra` 包。 * 公有的 `Priv` 没有依赖关系。 - 该应用程序还依赖于 `Pub` 包,而后者依赖于公有的 `Priv` 以及私有的 `Priv` 包所依赖的那个 `Zebra` 包。 此依赖图以字典表示后如下所示: ```julia graph = Dict( # Priv——私有的那个: UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b") => Dict( :Pub => UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"), :Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), ), # Priv——公共的那个: UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c") => Dict(), # Pub: UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1") => Dict( :Priv => UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c"), :Zebra => UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), ), # Zebra: UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62") => Dict(), ) ``` 给定这个依赖图,当 Julia 看到 `Pub` 包中的 `import Priv` ——它有 UUID`c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1` 时,它会查找: ```julia graph[UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1")][:Priv] ``` 会得到 `2d15fe94-a1f7-436c-a4d8-07a9a496e01c`,这意味着 `Pub` 包中的内容,`import Priv` 指代的是公有的 `Priv` 内容,而非应用程序直接依赖的私有包。这也是为何 `Priv` 在主项目中可指代不同的包,而不像其在某个依赖包中另有含义。在包生态中,该特性允许重名的出现。 如果在 `App` 主代码库中 `import Zebra` 会如何?因为`Zebra` 不存在于项目文件,即使它 *确实* 存在于清单文件中,其导入会是失败的。此外,`import Zebra` 这个行为若发生在公有的 `Priv` 包——UUID 为 `2d15fe94-a1f7-436c-a4d8-07a9a496e01c` 的包中,同样会失败。因为公有的 `Priv` 包未在清单文件中声明依赖,故而无法加载包。仅有在清单文件:`Pub` 包和一个 `Priv` 包中作为显式依赖的包可用于加载 `Zebra`。 项目环境的 **路径映射** 从 manifest 文件中提取得到。而包的路径 `uuid` 和名称 `X` 则 (循序) 依据这些规则确定。 1. 如果目录中的项目文件与要求的 `uuid` 以及名称 `X` 匹配,那么可能出现以下情况的一种: - 若该文件具有顶层 `路径` 入口,则 `uuid` 会被映射到该路径,文件的执行与包含项目文件的目录相关。 - 此外,`uuid` 依照包含项目文件的目录,映射至与`src/X.jl`。 2. 若非上述情况,且项目文件具有对应的清单文件,且该清单文件包含匹配 `uuid` 的节(stanza),那么: - 若其具有一个 `路径` 入口,则使用该路径(与包含清单文件的目录相关)。 - 若其具有一个 `git-tree-sha1` 入口,计算一个确定的 `uuid` 与 `git-tree-sha1` 函数——我们把这个函数称为 `slug`——并在每个 Julia `DEPOT_PATH` 的全局序列中的目录查询名为 `packages/X/$slug` 的目录。使用存在的第一个此类目录。 若某些结果成功,源码入口点的路径会是这些结果中的某个,结果的相对路径+`src/X.jl`;否则,`uuid` 不存在路径映射。当加载 `X` 时,如果没找到源码路径,查找即告失败,用户可能会被提示安装适当的包版本或采取其他纠正措施(例如,将 `X` 声明为某种依赖性)。 在上述样例清单文件中,为找到首个 `Priv` 包的路径——该包 UUID 为 `ba13f791-ae1d-465a-978b-69c3ad90f72b`——Julia 寻找其在清单中的节(stanza)。发现其有 路径` 入口,查看 `App` 项目目录中相关的 `deps/Priv`——不妨设`App` 代码在 `/home/me/projects/App` 中—则 Julia 发现 `/home/me/projects/App/deps/Priv` 存在,并因此从中加载 `Priv`。 另一方面,如果Julia加载的是带有*other* `Priv` 包——即UUID为`2d15fe94-a1f7-436c-a4d8-07a9a496e01c`——它在清单中找到了它的节,请注意它*没有*`path`条目,但是它有一个`git-tree-sha1` 条目。然后计算这个`slug` 的UUID/SHA-1对,具体是`HDkrT`(这个计算的确切细节并不重要,但它是始终一致的和确定的)。这意味着这个`Priv`包的路径`packages/Priv/HDkrT/src/Priv.jl`将在其中一个包仓库中。假设`DEPOT_PATH` 的内容是`["/home/me/.julia", "/usr/local/julia"]`,Julia将根据下面的路径来查看它们是否存在: 1. `/home/me/.julia/packages/Priv/HDkrT` 2. `/usr/local/julia/packages/Priv/HDkrT` Julia使用以上路径信息在仓库里依次查找 `packages/Priv/HDKrT/src/Priv.jl `文件,并从第一个查找到的文件中加载公共的 `Priv `包。 这是我们的示例App项目环境的可能路径映射的表示, 如上面Manifest 中所提供的依赖关系图, 在 搜索本地文件系统后: ```julia paths = Dict( # Priv – the private one: (UUID("ba13f791-ae1d-465a-978b-69c3ad90f72b"), :Priv) => # relative entry-point inside `App` repo: "/home/me/projects/App/deps/Priv/src/Priv.jl", # Priv – the public one: (UUID("2d15fe94-a1f7-436c-a4d8-07a9a496e01c"), :Priv) => # package installed in the system depot: "/usr/local/julia/packages/Priv/HDkr/src/Priv.jl", # Pub: (UUID("c07ecb7d-0dc9-4db7-8803-fadaaeaf08e1"), :Pub) => # package installed in the user depot: "/home/me/.julia/packages/Pub/oKpw/src/Pub.jl", # Zebra: (UUID("f7a24cb4-21fc-4002-ac70-f0e3a0dd3f62"), :Zebra) => # package installed in the system depot: "/usr/local/julia/packages/Zebra/me9k/src/Zebra.jl", ) ``` 这个例子包含三种不同类型的包位置信息(第一个和第三个是默认加载路径的一部分) 1. 私有 `Priv` 包 "[vendored](https://stackoverflow.com/a/35109534)"包括在`App`仓库中。 2. 公共 `Priv` 与 `Zebra` 包位于系统仓库,系统管理员在此对相关包进行实时安装与管理。这些包允许系统上的所有用户使用。 3. `Pub` 包位于用户仓库,用户实时安装的包都储存在此。 这些包仅限原安装用户使用。 ### 包目录 包目录提供了一种更简单的环境,但不能处理名称冲突。在包目录中, 顶层包集合是“类似”包的子目录集合。`X`包存在于包目录中的条件,是目录包含下列“入口点”文件之一: - `X.jl` - `X/src/X.jl` - `X.jl/src/X.jl` 包目录中的包可以导入哪些依赖项,取决于该包是否含有项目文件: * 如果它有一个项目文件,那么它只能导入那些在项目文件的`[deps]` 部分中已标识的包。 * 如果没有项目文件,它可以导入任何顶层包,即与在`Main` 或者 REPL中可加载的包相同。 **根图**是根据包目录的所有内容而形成的一个列表,包含所有已存在的包。 此外,一个UUID 将被赋予给每一个条目,例如对一个在文件夹`X`中找到的包 1. 如果`X/Project.toml`文件存在并且有一个`uuid` 条目,那么这个 `uuid`就是上述所要赋予的值。 2. 如果`X/Project.toml`文件存在,但*没有*包含一个顶层UUID条目, 该`uuid`将是一个虚构的UUID,是对`X/Project.toml`文件所在的规范(真实的)路径信息进行哈希处理而生成。 3. 否则(如果`Project.toml`文件不存在), `uuid`将是一个全零值 [nil UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier#Nil_UUID)。 项目目录的**依赖关系图**是根据每个包的子目录中其项目文件的存在与否以及内容而形成。规则是: - 如果包子目录没有项目文件,则在该图中忽略它, 其代码中的import语句按顶层处理,与main项目和REPL相同。 - 如果包子目录有一个项目文件,那么图条目的UUID是项目文件的`[deps]`映射, 如果该信息项不存在,则视为空。 作为一个例子,假设包目录具有以下结构和内容: ``` Aardvark/ src/Aardvark.jl: import Bobcat import Cobra Bobcat/ Project.toml: [deps] Cobra = "4725e24d-f727-424b-bca0-c4307a3456fa" Dingo = "7a7925be-828c-4418-bbeb-bac8dfc843bc" src/Bobcat.jl: import Cobra import Dingo Cobra/ Project.toml: uuid = "4725e24d-f727-424b-bca0-c4307a3456fa" [deps] Dingo = "7a7925be-828c-4418-bbeb-bac8dfc843bc" src/Cobra.jl: import Dingo Dingo/ Project.toml: uuid = "7a7925be-828c-4418-bbeb-bac8dfc843bc" src/Dingo.jl: # no imports ``` 下面是相应的根结构,表示为字典: ```julia roots = Dict( :Aardvark => UUID("00000000-0000-0000-0000-000000000000"), # no project file, nil UUID :Bobcat => UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), # dummy UUID based on path :Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), # UUID from project file :Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), # UUID from project file ) ``` 下面是对应的图结构,表示为字典: ```julia graph = Dict( # Bobcat: UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf") => Dict( :Cobra => UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), :Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), ), # Cobra: UUID("4725e24d-f727-424b-bca0-c4307a3456fa") => Dict( :Dingo => UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), ), # Dingo: UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc") => Dict(), ) ``` 值得注意的一些通用规则: 1. 缺少项目文件的包能依赖于任何顶层依赖项, 并且由于包目录中的每个包在顶层依赖中可用,因此它可以导入在环境中的所有包。 2. 含有项目文件的包不能依赖于缺少项目文件的包。 因为有项目文件的包只能加载那些在`graph`中的包,而没有项目文件的包不会出现在`graph`。 3. 具有项目文件但没有明确UUID的包只能被由没有项目文件的包所依赖, since dummy UUIDs assigned to these packages are strictly internal. ,因为赋予给这些包的虚构UUID全是项目内部的。 Observe the following specific instances of these rules in our example: 请注意以下我们例子中的规则具体实例: * `Aardvark` 包可以导入`Bobcat`、`Cobra` 或`Dingo`中的所有包;它确实导入`Bobcat` and `Cobra`包. * `Bobcat` 包能导入`Cobra`与`Dingo`包。因为它们都有带有UUID的项目文件,并在`Bobcat`包的`[deps]`信息项声明为依赖项。 * `Bobcat`包不能依赖于`Aardvark`包,因为`Aardvark`包缺少项目文件。 * `Cobra`包能导入`Dingo`包。因为`Dingo`包有项目文件和UUID,并在`Cobra`的`[deps]` 信息项中声明为依赖项。 * `Cobra`包不能依赖`Aardvark`或`Bobcat`包, 因为两者都没有真实的UUID。 * `Dingo`包不能导入任何包,因为它的项目文件中缺少`[deps]`信息项。 包目录中的**路径映射**很简单: 它将子目录名映射到相应的入口点路径。换句话说,如果指向我们示例项目目录的路径是`/home/me/animals`,那么`路径`映射可以用此字典表示: ```julia paths = Dict( (UUID("00000000-0000-0000-0000-000000000000"), :Aardvark) => "/home/me/AnimalPackages/Aardvark/src/Aardvark.jl", (UUID("85ad11c7-31f6-5d08-84db-0a4914d4cadf"), :Bobcat) => "/home/me/AnimalPackages/Bobcat/src/Bobcat.jl", (UUID("4725e24d-f727-424b-bca0-c4307a3456fa"), :Cobra) => "/home/me/AnimalPackages/Cobra/src/Cobra.jl", (UUID("7a7925be-828c-4418-bbeb-bac8dfc843bc"), :Dingo) => "/home/me/AnimalPackages/Dingo/src/Dingo.jl", ) ``` 根据定义,包目录环境中的所有包都是具有预期入口点文件的子目录,因此它们的`路径` 映射条目始终具有此格式。 ### 环境堆栈 第三种也是最后一种环境是通过覆盖其中的几个环境来组合其他环境,使每个环境中的包在单个组合环境中可用。这些复合环境称为*环境堆栈*。Julia的`LOAD_PATH`全局定义一个环境堆栈——Julia进程在其中运行的环境。如果希望Julia进程只能访问一个项目或包目录中的包,请将其设置为`LOAD_PATH`中的唯一条目。然而,访问一些您喜爱的工具(标准库、探查器、调试器、个人实用程序等)通常是非常有用的,即使它们不是您正在处理的项目的依赖项。通过将包含这些工具的环境添加到加载路径,您可以立即在顶层代码中访问它们,而无需将它们添加到项目中。 组合环境堆栈组件中根、图和路径的数据结构的机制很简单:它们被作为字典进行合并, 在发生键冲突时,优先使用前面的条目而不是后面的条目。换言之,如果我们有`stack = [env₁, env₂, …]`,那么我们有: ```julia roots = reduce(merge, reverse([roots₁, roots₂, …])) graph = reduce(merge, reverse([graph₁, graph₂, …])) paths = reduce(merge, reverse([paths₁, paths₂, …])) ``` 带下标的 `rootsᵢ`, `graphᵢ` and `pathsᵢ`变量对应于在`stack`中包含的下标环境变量`envᵢ`。 使用`reverse` 是因为当参数字典中的键之间发生冲突时,使`merge` 倾向于使用最后一个参数,而不是第一个参数。这种设计有几个值得注意的特点: 1. *主环境*——即堆栈中的第一个环境,被准确地嵌入到堆栈环境中。堆栈中第一个环境的完整依赖关系图是必然被完整包括在含有所有相同版本的依赖项的堆栈环境中。 2. 非主环境中的包能最终使用与其依赖项不兼容的版本,即使它们自己的环境是完全兼容。这种情况可能发生,当它们的一个依赖项被堆栈(通过图或路径,或两者)中某个早期环境中的版本所覆盖。 由于主环境通常是您正在处理的项目所在的环境,而堆栈中稍后的环境包含其他工具, 因此这是正确的权衡:最好改进您的开发工具,但保持项目能工作。当这种不兼容发生时,你通常要将开发工具升级到与主项目兼容的版本。 ## 总结 在软件包系统中,联邦软件包管理和精确的软件可复制性是困难但有价值的目标。结合起来,这些目标导致了一个比大多数动态语言更加复杂的包加载机制,但它也产生了通常与静态语言相关的可伸缩性和可复制性。通常,Julia用户应该能够使用内置的包管理器来管理他们的项目,而无需精确理解这些交互细节。通过调用`Pkg.add("X")`添加`X`包到对应的项目,并清晰显示相关文件,选择`Pkg.activate("Y")`后, 可调用`import X` 即可加载`X`包,而无需作过多考虑。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2678
# [命令行选项](@id command-line-options) 以下是启动 julia 时可用的命令行选项的完整列表: |选项 |描述| |:--- |:---| |`-v`, `--version` |显示版本信息| |`-h`, `--help` |显示命令行参数| |`--project[={<dir>\|@.}]` |将 <dir> 设置为主项目/环境。默认的 @. 选项将搜索父目录,直至找到 Project.toml 或 JuliaProject.toml 文件。| |`-J`, `--sysimage <file>` |用指定的系统镜像文件(system image file)启动| |`-H`, `--home <dir>` |设置 `julia` 可执行文件的路径| |`--startup-file={yes\|no}` |是否载入 `~/.julia/config/startup.jl`| |`--handle-signals={yes\|no}` |开启或关闭 Julia 默认的 signal handlers| |`--sysimage-native-code={yes\|no}` |在可能的情况下,使用系统镜像里的原生代码| |`--compiled-modules={yes\|no}` |开启或关闭 module 的增量预编译功能| |`-e`, `--eval <expr>` |执行 `<expr>`| |`-E`, `--print <expr>` |执行 `<expr>` 并显示结果| |`-L`, `--load <file>` |立即在所有进程中载入 `<file>` | |`-t`, `--threads {N\|auto}` |开启 N 个线程:`auto` 将 N 设置为当前 CPU 线程数,但这个行为可能在以后版本有所变动。| |`-p`, `--procs {N\|auto}` |这里的整数 N 表示启动 N 个额外的工作进程;`auto` 表示启动与 CPU 线程数目(logical cores)一样多的进程| |`--machine-file <file>` |在 `<file>` 中列出的主机上运行进程| |`-i` |交互式模式;REPL 运行且 `isinteractive()` 为 true| |`-q`, `--quiet` |安静的启动;REPL 启动时无横幅,不显示警告| |`--banner={yes\|no\|auto}` |开启或关闭 REPL 横幅| |`--color={yes\|no\|auto}` |开启或关闭文字颜色| |`--history-file={yes\|no}` |载入或导出历史记录| |`--depwarn={yes\|no\|error}` |开启或关闭语法弃用警告,`error` 表示将弃用警告转换为错误。| |`--warn-overwrite={yes\|no}` |开启或关闭“method overwrite”警告| |`-C`, `--cpu-target <target>` |设置 `<target>` 来限制使用 CPU 的某些特性;设置为 `help` 可以查看可用的选项| |`-O`, `--optimize={0,1,2,3}` |设置编译器优化级别(若未配置此选项,则默认等级为2;若配置了此选项却没指定具体级别,则默认级别为3)。| |`--min-optlevel={0,1,2,3}` |设置每个模块加载的优化下限(默认为 0)| |`-g`, `-g <level>` |开启或设置 debug 信息的生成等级。若未配置此选项,则默认 debug 信息的级别为 1;若配置了此选项却没指定具体级别,则默认级别为 2。| |`--inline={yes\|no}` |控制是否允许函数内联,此选项会覆盖源文件中的 `@inline` 声明| |`--check-bounds={yes\|no\|auto}` |进行边界检查,总是、从不、或依照宏@inbounds声明| |`--math-mode={ieee,fast}` |开启或关闭非安全的浮点数代数计算优化,此选项会覆盖源文件中的 `@fastmath` 声明| |`--code-coverage={none\|user\|all}` |对源文件中每行代码执行的次数计数| |`--code-coverage` |等价于 `--code-coverage=user`| |`--track-allocation={none\|user\|all}` |对源文件中每行代码的内存分配计数,单位 byte| |`--track-allocation` |等价于 `--track-allocation=user`| !!! compat "Julia 1.1" 在 Julia 1.0 中,默认的 `--project=@.` 选项不会在 Git 仓库的根目录中寻找 `Project.toml` 文件。从 Julia 1.1 开始,此选项会在其中寻找该文件。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
4406
# 复数和有理数 Julia 语言包含了预定义的复数和有理数类型,并且支持它们的各种标准[数学运算和初等函数](@ref)。由于也定义了复数与分数的[类型转换与类型提升](@ref conversion-and-promotion),因此对预定义数值类型(无论是原始的还是复合的)的任意组合进行的操作都会表现得如预期的一样。 ## 复数 全局常量 [`im`](@ref) 被绑定到复数 *i*,表示 -1 的主平方根。(不应使用数学家习惯的 `i` 或工程师习惯的 `j` 来表示此全局常量,因为它们是非常常用的索引变量名。)由于 Julia 允许数值字面量作为[数值字面量系数](@ref man-numeric-literal-coefficients),这种绑定就足以为复数提供很方便的语法,类似于传统的数学记法: ```jldoctest julia> 1+2im 1 + 2im ``` 你可以对复数进行各种标准算术操作: ```jldoctest julia> (1 + 2im)*(2 - 3im) 8 + 1im julia> (1 + 2im)/(1 - 2im) -0.6 + 0.8im julia> (1 + 2im) + (1 - 2im) 2 + 0im julia> (-3 + 2im) - (5 - 1im) -8 + 3im julia> (-1 + 2im)^2 -3 - 4im julia> (-1 + 2im)^2.5 2.729624464784009 - 6.9606644595719im julia> (-1 + 2im)^(1 + 1im) -0.27910381075826657 + 0.08708053414102428im julia> 3(2 - 5im) 6 - 15im julia> 3(2 - 5im)^2 -63 - 60im julia> 3(2 - 5im)^-1.0 0.20689655172413796 + 0.5172413793103449im ``` 类型提升机制也确保你可以使用不同类型的操作数的组合: ```jldoctest julia> 2(1 - 1im) 2 - 2im julia> (2 + 3im) - 1 1 + 3im julia> (1 + 2im) + 0.5 1.5 + 2.0im julia> (2 + 3im) - 0.5im 2.0 + 2.5im julia> 0.75(1 + 2im) 0.75 + 1.5im julia> (2 + 3im) / 2 1.0 + 1.5im julia> (1 - 3im) / (2 + 2im) -0.5 - 1.0im julia> 2im^2 -2 + 0im julia> 1 + 3/4im 1.0 - 0.75im ``` 注意 `3/4im == 3/(4*im) == -(3/4*im)`,因为系数比除法的优先级更高。 Julia 提供了一些操作复数的标准函数: ```jldoctest julia> z = 1 + 2im 1 + 2im julia> real(1 + 2im) # z 的实部 1 julia> imag(1 + 2im) # z 的虚部 2 julia> conj(1 + 2im) # z 的复共轭 1 - 2im julia> abs(1 + 2im) # z 的绝对值 2.23606797749979 julia> abs2(1 + 2im) # 取平方后的绝对值 5 julia> angle(1 + 2im) # 以弧度为单位的相位角 1.1071487177940904 ``` 按照惯例,复数的绝对值([`abs`](@ref))是从零点到它的距离。[`abs2`](@ref) 给出绝对值的平方,作用于复数上时非常有用,因为它避免了取平方根。[`angle`](@ref) 返回以弧度为单位的相位角(也被称为辐角函数)。所有其它的[初等函数](@ref)在复数上也都有完整的定义: ```jldoctest julia> sqrt(1im) 0.7071067811865476 + 0.7071067811865475im julia> sqrt(1 + 2im) 1.272019649514069 + 0.7861513777574233im julia> cos(1 + 2im) 2.0327230070196656 - 3.0518977991517997im julia> exp(1 + 2im) -1.1312043837568135 + 2.4717266720048188im julia> sinh(1 + 2im) -0.4890562590412937 + 1.4031192506220405im ``` 注意数学函数通常应用于实数就返回实数值,应用于复数就返回复数值。例如,当 [`sqrt`](@ref) 应用于 `-1` 与 `-1 + 0im` 会有不同的表现,虽然 `-1 == -1 + 0im`: ```jldoctest 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: [...] julia> sqrt(-1 + 0im) 0.0 + 1.0im ``` 从变量构建复数时,[文本型数值系数记法](@ref man-numeric-literal-coefficients)不再适用。相反地,乘法必须显式地写出: ```jldoctest julia> a = 1; b = 2; a + b*im 1 + 2im ``` 然而,我们**并不**推荐这样做,而应改为使用更高效的 [`complex`](@ref) 函数直接通过实部与虚部构建一个复数值: ```jldoctest julia> a = 1; b = 2; complex(a, b) 1 + 2im ``` 这种构建避免了乘法和加法操作。 [`Inf`](@ref) 和 [`NaN`](@ref) 可能出现在复数的实部和虚部,正如[特殊的浮点值](@ref)章节所描述的: ```jldoctest julia> 1 + Inf*im 1.0 + Inf*im julia> 1 + NaN*im 1.0 + NaN*im ``` ## 有理数 Julia 有一个用于表示整数精确比值的分数类型。分数通过 [`//`](@ref) 运算符构建: ```jldoctest julia> 2//3 2//3 ``` 如果一个分数的分子和分母含有公因子,它们会被约分到最简形式且分母非负: ```jldoctest julia> 6//9 2//3 julia> -4//8 -1//2 julia> 5//-15 -1//3 julia> -4//-12 1//3 ``` 整数比值的这种标准化形式是唯一的,所以分数值的相等性可由校验分子与分母都相等来测试。分数值的标准化分子和分母可以使用 [`numerator`](@ref) 和 [`denominator`](@ref) 函数得到: ```jldoctest julia> numerator(2//3) 2 julia> denominator(2//3) 3 ``` 分子和分母的直接比较通常是不必要的,因为标准算术和比较操作对分数值也有定义: ```jldoctest julia> 2//3 == 6//9 true julia> 2//3 == 9//27 false julia> 3//7 < 1//2 true julia> 3//4 > 2//3 true julia> 2//4 + 1//6 2//3 julia> 5//12 - 1//4 1//6 julia> 5//8 * 3//12 5//32 julia> 6//5 / 10//7 21//25 ``` 分数可以很容易地转换成浮点数: ```jldoctest julia> float(3//4) 0.75 ``` 对任意整数值 `a` 和 `b`(除了 `a == 0` 且 `b == 0` 时),从分数到浮点数的转换遵从以下的一致性: ```jldoctest julia> a = 1; b = 2; julia> isequal(float(a//b), a/b) true ``` Julia接受构建无穷分数值: ```jldoctest julia> 5//0 1//0 julia> x = -3//0 -1//0 julia> typeof(x) Rational{Int64} ``` 但不接受试图构建一个 [`NaN`](@ref) 分数值: ```jldoctest julia> 0//0 ERROR: ArgumentError: invalid rational: zero(Int64)//zero(Int64) Stacktrace: [...] ``` 像往常一样,类型提升系统使得分数可以轻松地同其它数值类型进行交互: ```jldoctest julia> 3//5 + 1 8//5 julia> 3//5 - 0.5 0.09999999999999998 julia> 2//7 * (1 + 2im) 2//7 + 4//7*im julia> 2//7 * (1.5 + 2im) 0.42857142857142855 + 0.5714285714285714im julia> 3//2 / (1 + 2im) 3//10 - 3//5*im julia> 1//2 + 2im 1//2 + 2//1*im julia> 1 + 2//3im 1//1 - 2//3*im julia> 0.5 == 1//2 true julia> 0.33 == 1//3 false julia> 0.33 < 1//3 true julia> 1//3 - 0.33 0.0033333333333332993 ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
12546
# [构造函数](@id man-constructors) 构造函数 [^1] 是用来创建新对象的函数 -- 确切地说,它创建的是[复合类型](@ref)的实例。在 Julia 中,类型对象也同时充当构造函数的角色:可以用类名加参数元组的方式像函数调用一样来创建新实例。这一点在介绍复合类型(Composite Types)时已经大致谈过了。例如: ```jldoctest footype julia> struct Foo bar baz end julia> foo = Foo(1, 2) Foo(1, 2) julia> foo.bar 1 julia> foo.baz 2 ``` 对很多类型来说,通过给所有字段赋值来创建新对象的这种方式就足以用于产生新实例了。然而,在某些情形下,创建复合对象需要更多的功能。有时必须通过检查或转化参数来确保固有属性不变。[递归数据结构](https://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_data_structures_.28structural_recursion.29),特别是那些可能引用自身的数据结构,它们通常不能被干净地构造,而是需要首先被不完整地构造,然后再通过编程的方式完成补全。为了方便,有时需要用较少的参数或者不同类型的参数来创建对象,Julia 的对象构造系统解决了所有这些问题。 [^1]: 命名法:虽然术语「构造函数」通常是指用于构造类型对象的函数全体,但通常会略微滥用术语将特定的构造方法称为「构造函数」。在这种情况下,通常可以从上下文中清楚地辨别出术语表示的是「构造方法」而不是「构造函数」,尤其是在讨论某个特别的「构造方法」的时候。 ## [外部构造方法](@id man-outer-constructor-methods) 构造函数与 Julia 中的其他任何函数一样,其整体行为由其各个方法的组合行为定义。因此,只要定义新方法就可以向构造函数添加功能。例如,假设你想为 `Foo` 对象添加一个构造方法,该方法只接受一个参数并其作为 `bar` 和 `baz` 的值。这很简单: ```jldoctest footype julia> Foo(x) = Foo(x,x) Foo julia> Foo(1) Foo(1, 1) ``` 你也可以为 `Foo` 添加新的零参数构造方法,它为 `bar` 和 `baz` 提供默认值: ```jldoctest footype julia> Foo() = Foo(0) Foo julia> Foo() Foo(0, 0) ``` 这里零参数构造方法会调用单参数构造方法,单参数构造方法又调用了自动提供默认值的双参数构造方法。上面附加的这类构造方法,它们的声明方式与普通的方法一样,像这样的构造方法被称为**外部**构造方法,下文很快就会揭示这样称呼的原因。外部构造方法只能通过调用其他构造方法来创建新实例,比如自动提供默认值的构造方法。 ## [内部构造方法](@id man-inner-constructor-methods) 尽管外部构造方法可以成功地为构造对象提供了额外的便利,但它无法解决另外两个在本章导言里提到的问题:确保固有属性不变和允许创建自引用对象。因此,我们需要**内部**构造方法。内部构造方法和外部构造方法很相像,但有两点不同: 1. 内部构造方法在类型声明代码块的内部,而不是和普通方法一样在外部。 2. 内部构造方法能够访问一个特殊的局部函数 [`new`](@ref),此函数能够创建该类型的对象。 例如,假设你要声明一个保存一对实数的类型,但要约束第一个数不大于第二个数。你可以像这样声明它: ```jldoctest pairtype julia> struct OrderedPair x::Real y::Real OrderedPair(x,y) = x > y ? error("out of order") : new(x,y) end ``` 现在 `OrderedPair` 对象只能在 `x <= y` 时被成功构造: ```jldoctest pairtype; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> OrderedPair(1, 2) OrderedPair(1, 2) julia> OrderedPair(2,1) ERROR: out of order Stacktrace: [1] error at ./error.jl:33 [inlined] [2] OrderedPair(::Int64, ::Int64) at ./none:4 [3] top-level scope ``` 如果类型被声明为 `mutable`,你可以直接更改字段值来打破这个固有属性,然而,在未经允许的情况下,随意摆弄对象的内核一般都是不好的行为。你(或者其他人)可以在以后任何时候提供额外的外部构造方法,但一旦类型被声明了,就没有办法来添加更多的内部构造方法了。由于外部构造方法只能通过调用其它的构造方法来创建对象,所以最终构造对象的一定是某个内部构造函数。这保证了已声明类型的对象必须通过调用该类型的内部构造方法才得已存在,从而在某种程度上保证了类型的固有属性。 只要定义了任何一个内部构造方法,Julia 就不会再提供默认的构造方法:它会假定你已经为自己提供了所需的所有内部构造方法。默认构造方法等效于一个你自己编写的内部构造函数,该函数将所有成员作为参数(如果相应的字段具有类型,则约束为正确的类型),并将它们传递给 `new`,最后返回结果对象: ```jldoctest julia> struct Foo bar baz Foo(bar,baz) = new(bar,baz) end ``` 这个声明与前面没有显式内部构造方法的 `Foo` 类型的定义效果相同。 以下两个类型是等价的 -- 一个具有默认构造方法,另一个具有显式构造方法: ```jldoctest julia> struct T1 x::Int64 end julia> struct T2 x::Int64 T2(x) = new(x) end julia> T1(1) T1(1) julia> T2(1) T2(1) julia> T1(1.0) T1(1) julia> T2(1.0) T2(1) ``` 提供尽可能少的内部构造方法是一种良好的形式:仅在需要显式地处理所有参数,以及强制执行必要的错误检查和转换时候才使用内部构造。其它用于提供便利的构造方法,比如提供默认值或辅助转换,应该定义为外部构造函数,然后再通过调用内部构造函数来执行繁重的工作。这种解耦是很自然的。 ## 不完整初始化 最后一个还没提到的问题是,如何构造具有自引用的对象,更广义地来说是构造递归数据结构。由于这其中的困难并不是那么显而易见,这里我们来简单解释一下,考虑如下的递归类型声明: ```jldoctest selfrefer julia> mutable struct SelfReferential obj::SelfReferential end ``` 这种类型可能看起来没什么大不了,直到我们考虑如何来构造它的实例。 如果 `a` 是 `SelfReferential` 的一个实例,则第二个实例可以用如下的调用来创建: ```julia-repl julia> b = SelfReferential(a) ``` 但是,当没有实例存在的情况下,即没有可以传递给 `obj` 成员变量的有效值时,如何构造第一个实例?唯一的解决方案是允许使用未初始化的 `obj` 成员来创建一个未完全初始化的 `SelfReferential` 实例,并使用该不完整的实例作为另一个实例的 `obj` 成员的有效值,例如,它本身。 为了允许创建未完全初始化的对象,Julia 允许使用少于该类型成员数的参数来调用 [`new`](@ ref) 函数,并返回一个具有某个未初始化成员的对象。然后,内部构造函数可以使用不完整的对象,在返回之前完成初始化。例如,我们在定义 `SelfReferential` 类型时采用了另一个方法,使用零参数内部构造函数来返回一个实例,此实例的 `obj` 成员指向其自身: ```jldoctest selfrefer2 julia> mutable struct SelfReferential obj::SelfReferential SelfReferential() = (x = new(); x.obj = x) end ``` 我们可以验证这一构造函数有效性,且由其构造的对象确实是自引用的: ```jldoctest selfrefer2 julia> x = SelfReferential(); julia> x === x true julia> x === x.obj true julia> x === x.obj.obj true ``` 虽然从一个内部构造函数中返回一个完全初始化的对象是很好的,但是也可以返回未完全初始化的对象: ```jldoctest incomplete julia> mutable struct Incomplete data Incomplete() = new() end julia> z = Incomplete(); ``` 尽管允许创建含有未初始化成员的对象,然而任何对未初始化引用的访问都会立即报错: ```jldoctest incomplete julia> z.data ERROR: UndefRefError: access to undefined reference ``` 这避免了不断地检测 `null` 值的需要。然而,并不是所有的对象成员都是引用。Julia 会将一些类型当作纯数据("plain data"),这意味着它们的数据是自包含的,并且没有引用其它对象。这些纯数据包括原始类型(比如 `Int` )和由其它纯数据类型构成的不可变结构体。纯数据类型的初始值是未定义的: ```julia-repl julia> struct HasPlain n::Int HasPlain() = new() end julia> HasPlain() HasPlain(438103441441) ``` 由纯数据组成的数组也具有一样的行为。 在内部构造函数中,你可以将不完整的对象传递给其它函数来委托其补全构造: ```jldoctest julia> mutable struct Lazy data Lazy(v) = complete_me(new(), v) end ``` 与构造函数返回的不完整对象一样,如果 `complete_me` 或其任何被调用者尝试在初始化之前访问 `Lazy` 对象的 `data` 字段,就会立刻报错。 ## 参数类型的构造函数 参数类型的存在为构造函数增加了更多的复杂性。首先,让我们回顾一下[参数类型](@ref)。在默认情况下,我们可以用两种方法来实例化参数复合类型,一种是显式地提供类型参数,另一种是让 Julia 根据构造函数输入参数的类型来隐式地推导类型参数。这里有一些例子: ```jldoctest parametric; filter = r"Closest candidates.*\n .*" julia> struct Point{T<:Real} x::T y::T end julia> Point(1,2) ## 隐式的 T ## Point{Int64}(1, 2) julia> Point(1.0,2.5) ## 隐式的 T ## Point{Float64}(1.0, 2.5) julia> Point(1,2.5) ## 隐式的 T ## ERROR: MethodError: no method matching Point(::Int64, ::Float64) Closest candidates are: Point(::T, ::T) where T<:Real at none:2 julia> Point{Int64}(1, 2) ## 显式的 T ## Point{Int64}(1, 2) julia> Point{Int64}(1.0,2.5) ## 显式的 T ## ERROR: InexactError: Int64(2.5) Stacktrace: [...] julia> Point{Float64}(1.0, 2.5) ## 显式的 T ## Point{Float64}(1.0, 2.5) julia> Point{Float64}(1,2) ## 显式的 T ## Point{Float64}(1.0, 2.0) ``` 就像你看到的那样,用类型参数显式地调用构造函数,其参数会被转换为指定的类型:`Point{Int64}(1,2)` 可以正常工作,但是 `Point{Int64}(1.0,2.5)` 则会在将 `2.5` 转换为 [`Int64`](@ref) 的时候报一个 [`InexactError`](@ref)。当类型是从构造函数的参数隐式推导出来的时候,比如在例子 `Point(1,2)` 中,输入参数的类型必须一致,否则就无法确定 `T` 是什么,但 `Point` 的构造函数仍可以适配任意同类型的实数对。 实际上,这里的 `Point`,`Point{Float64}` 以及 `Point{Int64}` 是不同的构造函数。`Point{T}` 表示对于每个类型 `T` 都存在一个不同的构造函数。如果不显式提供内部构造函数,在声明复合类型 `Point{T<:Real}` 的时候,Julia 会对每个满足 `T<:Real` 条件的类型都提供一个默认的内部构造函数 `Point{T}`,它们的行为与非参数类型的默认内部构造函数一致。Julia 同时也会提供了一个通用的外部构造函数 `Point`,用于适配任意同类型的实数对。Julia 默认提供的构造函数等价于下面这种显式的声明: ```jldoctest parametric2 julia> struct Point{T<:Real} x::T y::T Point{T}(x,y) where {T<:Real} = new(x,y) end julia> Point(x::T, y::T) where {T<:Real} = Point{T}(x,y); ``` 注意,每个构造函数定义的方式与调用它们的方式是一样的。调用 `Point{Int64}(1,2)` 会触发 `struct` 块内部的 `Point{T}(x,y)`。另一方面,外部构造函数声明的 `Point` 构造函数只会被同类型的实数对触发,它使得我们可以直接以 `Point(1,2)` 和 `Point(1.0,2.5)` 这种方式来创建实例,而不需要显示地使用类型参数。由于此方法的声明方式已经对输入参数的类型施加了约束,像 `Point(1,2.5)` 这种调用自然会导致 "no method" 错误。 假如我们想让 `Point(1,2.5)` 这种调用方式正常工作,比如,通过将整数 `1` 自动「提升」为浮点数 `1.0`,最简单的方法是像下面这样定义一个额外的外部构造函数: ```jldoctest parametric2 julia> Point(x::Int64, y::Float64) = Point(convert(Float64,x),y); ``` 此方法使用 [`convert`](@ref) 函数将 `x` 显式转换为 [`Float64`](@ref),然后在两个参数都是 [`Float64`](@ref) 的情况下使用通用的构造函数。通过这个方法定义,以前的报[`MethodError`](@ref)的代码现在可以成功地创建一个类型为 `Point{Float64}` 的点: ```jldoctest parametric2 julia> p = Point(1,2.5) Point{Float64}(1.0, 2.5) julia> typeof(p) Point{Float64} ``` 然而,其它类似的调用依然有问题: ```jldoctest parametric2 julia> Point(1.5,2) ERROR: MethodError: no method matching Point(::Float64, ::Int64) Closest candidates are: Point(::T, !Matched::T) where T<:Real at none:1 ``` 如果你想要找到一种方法可以使类似的调用都可以正常工作,请参阅[类型转换与类型提升](@ref conversion-and-promotion)。这里稍稍“剧透”一下,我们可以利用下面的这个外部构造函数来满足需求,无论输入参数的类型如何,它都可以触发通用的 `Point` 构造函数: ```jldoctest parametric2 julia> Point(x::Real, y::Real) = Point(promote(x,y)...); ``` 这里的 `promote` 函数会将它的输入转化为同一类型,在此例中是 [`Float64`](@ref)。定义了这个方法,`Point` 构造函数会自动提升输入参数的类型,且提升机制与算术运算符相同,比如 [`+`](@ref),因此对所有的实数输入参数都适用: ```jldoctest parametric2 julia> Point(1.5,2) Point{Float64}(1.5, 2.0) julia> Point(1,1//2) Point{Rational{Int64}}(1//1, 1//2) julia> Point(1.0,1//2) Point{Float64}(1.0, 0.5) ``` 因此,虽然 Julia 中默认提供的隐式类型参数构造函数相当严格,但可以很容易地使它们以更轻松且明智的方式运行。 此外,由于构造函数可以利用类型系统、方法和多重派发的所有功能,因此定义复杂的行为通常非常简单。 ## 示例学习:有理数 也许将所有这些部分联系在一起的最佳方法是展示参数复合类型及其构造方法的真实示例。 为此,我们实现了自己的有理数类型 `OurRational`,类似于 Julia 的内置 [`Rational`](@ref) 类型,定义在 [`rational.jl`](https://github.com/JuliaLang /julia/blob/master/base/rational.jl): ```jldoctest rational julia> struct OurRational{T<:Integer} <: Real num::T den::T function OurRational{T}(num::T, den::T) where T<:Integer if num == 0 && den == 0 error("invalid rational: 0//0") end num = flipsign(num, den) den = flipsign(den, den) g = gcd(num, den) num = div(num, g) den = div(den, g) new(num, den) end end julia> OurRational(n::T, d::T) where {T<:Integer} = OurRational{T}(n,d) OurRational julia> OurRational(n::Integer, d::Integer) = OurRational(promote(n,d)...) OurRational julia> OurRational(n::Integer) = OurRational(n,one(n)) OurRational julia> ⊘(n::Integer, d::Integer) = OurRational(n,d) ⊘ (generic function with 1 method) julia> ⊘(x::OurRational, y::Integer) = x.num ⊘ (x.den*y) ⊘ (generic function with 2 methods) julia> ⊘(x::Integer, y::OurRational) = (x*y.den) ⊘ y.num ⊘ (generic function with 3 methods) julia> ⊘(x::Complex, y::Real) = complex(real(x) ⊘ y, imag(x) ⊘ y) ⊘ (generic function with 4 methods) julia> ⊘(x::Real, y::Complex) = (x*y') ⊘ real(y*y') ⊘ (generic function with 5 methods) julia> function ⊘(x::Complex, y::Complex) xy = x*y' yy = real(y*y') complex(real(xy) ⊘ yy, imag(xy) ⊘ yy) end ⊘ (generic function with 6 methods) ``` 第一行 -- `struct OurRational{T<:Integer} <: Real` -- 声明了 `OurRational` 会接收一个整数类型的类型参数,且它自己属于实数类型。它声明了两个成员:`num::T` 和 `den::T`。这表明一个 `OurRational{T}` 的实例中会包含一对整数,且类型为 `T`,其中一个表示分子,另一个表示分母。 现在事情变得有趣了。 `OurRational` 有一个内部构造器方法,它检查 `num` 和 `den` 不都为零,并确保每个有理数都是以非负分母的“最低项”构造的。 这是通过首先翻转分子和分母的符号(如果分母为负)来实现的。 然后,两者都除以它们的最大公约数(`gcd` 总是返回一个非负数,无论其参数的符号如何)。 因为这是 `OurRational` 唯一的内部构造函数,我们可以确定 `OurRational` 对象总是以这种规范化形式构造的。 为了方便,`OurRational` 也提供了一些其它的外部构造函数。第一个外部构造函数是“标准的”通用构造函数,当分子和分母的类型一致时,它就可以推导出类型参数 `T`。第二个外部构造函数可以用于分子和分母的类型不一致的情景,它会将分子和分母的类型提升至一个共同的类型,然后再委托第一个外部构造函数进行构造。第三个构造函数会将一个整数转化为分数,方法是将 1 当作分母。 在定义了外部构造函数之后,我们为 `⊘` 算符定义了一系列的方法,之后就可以使用 `⊘` 算符来写分数,(比如 `1 ⊘ 2`)。Julia 的 `Rational` 类型采用的是 [`//`](@ref) 算符。在做上述定义之前,`⊘` 是一个无意的且未被定义的算符。定义之后,它的行为与在 [有理数](@ref Rational-Numbers) 一节中描述的一致——注意它的所有行为都是那短短几行定义的。第一个也是最基础的定义只是将 `a ⊘ b` 中的 `a` 和 `b` 当作参数传递给 `OurRational` 的构造函数来实例化 `OurRational`,这要求 `a` 和 `b` 分别都是整数。在 `⊘` 的某个操作数已经是分数的情况下,我们采用了一个有点不一样的方法来构建新的分数,这实际上等价于用分数除以一个整数。最后,我们也可以让 `⊘` 作用于复数,用来创建一个类型为 `Complex{<:OurRational}` 的对象——即一个实部和虚部都是分数的复数: ```jldoctest rational julia> z = (1 + 2im) ⊘ (1 - 2im); julia> typeof(z) Complex{OurRational{Int64}} julia> typeof(z) <: Complex{<:OurRational} true ``` 因此,尽管 `⊘` 算符通常会返回一个 `OurRational` 的实例,但倘若其中一个操作数是复整数,那么就会返回 `Complex{<:OurRational}`。感兴趣的话可以读一读 [`rational.jl`](https://github.com/JuliaLang/julia/blob/master/base/rational.jl):它实现了一个完整的 Julia 基本类型,但却非常的简短,而且是自恰的。 ## 仅外部的构造函数 正如我们所看到的,典型的参数类型都有一个内部构造函数,它仅在全部的类型参数都已知的情况下才会被调用。例如,可以用 `Point{Int}`调用,但`Point` 就不行。我们可以选择性的添加外部构造函数来自动推导并添加类型参数,比如,调用 `Point(1,2)` 来构造 `Point{Int}`。外部构造函数调用内部构造函数来实际创建实例。然而,在某些情况下,我们可能并不想要内部构造函数,从而达到禁止手动指定类型参数的目的。 例如,假设我们要定义一个类型用于存储向量以及其累加和: ```jldoctest julia> struct SummedArray{T<:Number,S<:Number} data::Vector{T} sum::S end julia> SummedArray(Int32[1; 2; 3], Int32(6)) SummedArray{Int32, Int32}(Int32[1, 2, 3], 6) ``` 问题在于我们想让 `S` 的类型始终比 `T` 大,这样做是为了确保累加过程不会丢失信息。例如,当 `T` 是 [`Int32`](@ref) 时,我们想让 `S` 是 [`Int64`](@ref)。所以我们想要一种接口来禁止用户创建像 `SummedArray{Int32,Int32}` 这种类型的实例。一种实现方式是只提供一个 `SummedArray` 构造函数,当需要将其放入 `struct`-block 中,从而不让 Julia 提供默认的构造函数: ```jldoctest julia> struct SummedArray{T<:Number,S<:Number} data::Vector{T} sum::S function SummedArray(a::Vector{T}) where T S = widen(T) new{T,S}(a, sum(S, a)) end end julia> SummedArray(Int32[1; 2; 3], Int32(6)) ERROR: MethodError: no method matching SummedArray(::Vector{Int32}, ::Int32) Closest candidates are: SummedArray(::Vector{T}) where T at none:4 Stacktrace: [...] ``` 此构造函数将会被 `SummedArray(a)` 这种写法触发。`new{T,S}` 的这种写法允许指定待构建类型的参数,也就是说调用它会返回一个 `SummedArray{T,S}` 的实例。`new{T,S}` 也可以用于其它构造函数的定义中,但为了方便,Julia 会根据正在构造的类型自动推导出 `new{}` 花括号里的参数(如果可行的话)。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
16156
# 流程控制 Julia 提供了大量的流程控制构件: * [复合表达式](@ref man-compound-expressions):`begin` 和 `;`。 * [条件表达式](@ref man-conditional-evaluation):`if`-`elseif`-`else` 和 `?:` (三元运算符)。 * [短路求值](@ref):逻辑运算符 `&&`(与)和 `||`(或),以及链式比较。 * [重复执行:循环](@ref man-loops):`while` 和 `for`。 * [异常处理](@ref):`try`-`catch`、[`error`](@ref) 和 [`throw`](@ref)。 * [`Task`(协程)](@ref man-tasks):[`yieldto`](@ref)。 前五个流程控制机制是高级编程语言的标准。[`Task`](@ref) 不是那么的标准:它提供了非局部的流程控制,这使得在暂时挂起的计算任务之间进行切换成为可能。这是一个功能强大的构件:Julia 中的异常处理和协同多任务都是通过 `Task` 实现的。虽然日常编程并不需要直接使用 `Task`,但某些问题用 `Task` 处理会更加简单。 ## [复合表达式](@id man-compound-expressions) 有时一个表达式能够有序地计算若干子表达式,并返回最后一个子表达式的值作为它的值是很方便的。Julia 有两个组件来完成这个: `begin` 代码块 和 `;` 链。这两个复合表达式组件的值都是最后一个子表达式的值。下面是一个 `begin` 代码块的例子: ```jldoctest julia> z = begin x = 1 y = 2 x + y end 3 ``` 因为这些是非常简短的表达式,它们可以简单地被放到一行里,这也是 `;` 链的由来: ```jldoctest julia> z = (x = 1; y = 2; x + y) 3 ``` 这个语法在定义简洁的单行函数的时候特别有用,参见[函数](@id man-functions)。尽管很典型,但是并不要求 `begin` 代码块是多行的,或者 `;` 链是单行的: ```jldoctest julia> begin x = 1; y = 2; x + y end 3 julia> (x = 1; y = 2; x + y) 3 ``` ## [条件表达式](@id man-conditional-evaluation) 条件表达式(Conditional evaluation)可以根据布尔表达式的值,让部分代码被执行或者不被执行。下面是对 `if`-`elseif`-`else` 条件语法的分析: ```julia if x < y println("x is less than y") elseif x > y println("x is greater than y") else println("x is equal to y") end ``` 如果表达式 `x < y` 是 `true`,那么对应的代码块会被执行;否则判断条件表达式 `x > y`,如果它是 `true`,则执行对应的代码块;如果没有表达式是 true,则执行 `else` 代码块。下面是一个例子: ```jldoctest julia> function test(x, y) if x < y println("x is less than y") elseif x > y println("x is greater than y") else println("x is equal to y") end end test (generic function with 1 method) julia> test(1, 2) x is less than y julia> test(2, 1) x is greater than y julia> test(1, 1) x is equal to y ``` `elseif` 和 `else` 代码块是可选的,并且可以使用任意多个 `elseif` 代码块。 `if`-`elseif`-`else` 组件中的第一个条件表达式为 `true` 时,其他条件表达式才会被执行,当对应的代码块被执行后,其余的表达式或者代码块将不会被执行。 `if` 代码块是"有渗漏的",也就是说它们不会引入局部作用域。这意味着在 `if` 语句中新定义的变量依然可以在 `if` 代码块之后使用,尽管这些变量没有在 `if` 语句之前定义过。所以,我们可以将上面的 `test` 函数定义为 ```jldoctest julia> function test(x,y) if x < y relation = "less than" elseif x == y relation = "equal to" else relation = "greater than" end println("x is ", relation, " y.") end test (generic function with 1 method) julia> test(2, 1) x is greater than y. ``` 变量 `relation` 是在 `if` 代码块内部声明的,但可以在外部使用。然而,在利用这种行为的时候,要保证变量在所有的分支下都进行了定义。对上述函数做如下修改会导致运行时错误 ```jldoctest; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> function test(x,y) if x < y relation = "less than" elseif x == y relation = "equal to" end println("x is ", relation, " y.") end test (generic function with 1 method) julia> test(1,2) x is less than y. julia> test(2,1) ERROR: UndefVarError: relation not defined Stacktrace: [1] test(::Int64, ::Int64) at ./none:7 ``` `if` 代码块也会返回一个值,这可能对于一些从其他语言转过来的用户来说不是很直观。 这个返回值就是被执行的分支中最后一个被执行的语句的返回值。 所以 ```jldoctest julia> x = 3 3 julia> if x > 0 "positive!" else "negative..." end "positive!" ``` 需要注意的是,在 Julia 中,经常会用短路求值来表示非常短的条件表达式(单行),这会在下一节中介绍。 与 C, MATLAB, Perl, Python,以及 Ruby 不同,但跟 Java,还有一些别的严谨的类型语言类似:一个条件表达式的值如果不是 `true` 或者 `false` 的话,会返回错误: ```jldoctest julia> if 1 println("true") end ERROR: TypeError: non-boolean (Int64) used in boolean context ``` 这个错误是说,条件判断结果的类型:[`Int64`](@ref) 是错的,而不是期望的 [`Bool`](@ref)。 所谓的 "三元运算符", `?:`,很类似 `if`-`elseif`-`else` 语法,它用于选择性获取单个表达式的值,而不是选择性执行大段的代码块。它因在很多语言中是唯一一个有三个操作数的运算符而得名: ```julia a ? b : c ``` 在 `?` 之前的表达式 `a`, 是一个条件表达式,如果条件 `a` 是 `true`,三元运算符计算在 `:` 之前的表达式 `b`;如果条件 `a` 是 `false`,则执行 `:` 后面的表达式 `c`。注意,`?` 和 `:` 旁边的空格是强制的,像 `a?b:c` 这种表达式不是一个有效的三元表达式(但在`?` 和 `:` 之后的换行是允许的)。 理解这种行为的最简单方式是看一个实际的例子。在前一个例子中,虽然在三个分支中都有调用 `println`,但实质上是选择打印哪一个字符串。在这种情况下,我们可以用三元运算符更紧凑地改写。为了简明,我们先尝试只有两个分支的版本: ```jldoctest julia> x = 1; y = 2; julia> println(x < y ? "less than" : "not less than") less than julia> x = 1; y = 0; julia> println(x < y ? "less than" : "not less than") not less than ``` 如果表达式 `x < y` 为真,整个三元运算符会执行字符串 `"less than"`,否则执行字符串 `"not less than"`。原本的三个分支的例子需要链式嵌套使用三元运算符: ```jldoctest julia> test(x, y) = println(x < y ? "x is less than y" : x > y ? "x is greater than y" : "x is equal to y") test (generic function with 1 method) julia> test(1, 2) x is less than y julia> test(2, 1) x is greater than y julia> test(1, 1) x is equal to y ``` 为了方便链式传值,运算符从右到左连接到一起。 重要地是,与 `if`-`elseif`-`else` 类似,`:` 之前和之后的表达式只有在条件表达式为 `true` 或者 `false` 时才会被相应地执行: ```jldoctest julia> v(x) = (println(x); x) v (generic function with 1 method) julia> 1 < 2 ? v("yes") : v("no") yes "yes" julia> 1 > 2 ? v("yes") : v("no") no "no" ``` ## 短路求值 Julia 中的 `&&` 和 `||` 运算符分别对应于逻辑“与”和“或”操作,并通常都这样使用。 但是,它们具有 *逻辑短路* 的特殊性质:不一定评估其第二个参数,下面会详细介绍。 (也有按位 `&` 和 `|` 运算符可用作逻辑“与”和“或”的*无*短路行为,但要注意 `&` 和 `|` 的评估时的优先级高于 `&& ` 和 `||` 。) 短路求值与条件求值非常相似。 这种行为在大多数具有 `&&` 和 `||` 布尔运算符的命令式编程语言中都可以找到:在一系列由这些运算符连接的布尔表达式中,为了得到整个链的最终布尔值,仅仅只有最小数量的表达式被计算。 一些语言(如 Python)将它们称为`and`(`&&`)和`or`(`||`)。 更准确地说,这意味着: * 在表达式 `a && b` 中,子表达式 `b` 仅当 `a` 为 `true` 的时候才会被执行。 * 在表达式 `a || b` 中,子表达式 `b` 仅在 `a` 为 `false` 的时候才会被执行。 这里的原因是:如果 `a` 是 `false`,那么无论 `b` 的值是多少,`a && b` 一定是 `false`。同理,如果 `a` 是 `true`,那么无论 `b` 的值是多少,`a || b` 的值一定是 true。`&&` 和 `||` 都依赖于右边,但是 `&&` 比 `||` 有更高的优先级。我们可以简单地测试一下这个行为: ```jldoctest tandf julia> t(x) = (println(x); true) t (generic function with 1 method) julia> f(x) = (println(x); false) f (generic function with 1 method) julia> t(1) && t(2) 1 2 true julia> t(1) && f(2) 1 2 false julia> f(1) && t(2) 1 false julia> f(1) && f(2) 1 false julia> t(1) || t(2) 1 true julia> t(1) || f(2) 1 true julia> f(1) || t(2) 1 2 true julia> f(1) || f(2) 1 2 false ``` 你可以用同样的方式测试不同 `&&` 和 `||` 运算符的组合条件下的关联和优先级。 这种行为在 Julia 中经常被用来作为简短 `if` 语句的替代。 可以用 `<cond> && <statement>` (可读为: <cond> *and then* <statement>)来替换 `if <cond> <statement> end`。 类似的, 可以用 `<cond> || <statement>` (可读为: <cond> *or else* <statement>)来替换 `if ! <cond> <statement> end`. 例如,可以像这样定义递归阶乘: ```jldoctest; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> function fact(n::Int) n >= 0 || error("n must be non-negative") n == 0 && return 1 n * fact(n-1) end fact (generic function with 1 method) julia> fact(5) 120 julia> fact(0) 1 julia> fact(-1) ERROR: n must be non-negative Stacktrace: [1] error at ./error.jl:33 [inlined] [2] fact(::Int64) at ./none:2 [3] top-level scope ``` **无**短路求值的布尔运算可以用位布尔运算符来完成,见[数学运算和初等函数](@ref):`&` 和 `|`。这些是普通的函数,同时也刚好支持中缀运算符语法,但总是会计算它们的所有参数: ```jldoctest tandf julia> f(1) & t(2) 1 2 false julia> t(1) | t(2) 1 2 true ``` 与 `if`, `elseif` 或者三元运算符中的条件表达式相同,`&&` 或者 `||` 的操作数必须是布尔值(`true` 或者 `false`)。在链式嵌套的条件表达式中, 除最后一项外,使用非布尔值会导致错误: ```jldoctest julia> 1 && true ERROR: TypeError: non-boolean (Int64) used in boolean context ``` 但在链的末尾允许使用任意类型的表达式,此表达式会根据前面的条件被执行并返回: ```jldoctest julia> true && (x = (1, 2, 3)) (1, 2, 3) julia> false && (x = (1, 2, 3)) false ``` ## [重复执行:循环](@id man-loops) 有两个用于重复执行表达式的组件:`while` 循环和 `for` 循环。下面是一个 `while` 循环的例子: ```jldoctest julia> i = 1; julia> while i <= 5 println(i) global i += 1 end 1 2 3 4 5 ``` `while` 循环会执行条件表达式(例子中为 `i <= 5`),只要它为 `true`,就一直执行`while` 循环的主体部分。当 `while` 循环第一次执行时,如果条件表达式为 `false`,那么主体代码就一次也不会被执行。 `for` 循环使得常见的重复执行代码写起来更容易。 像之前 `while` 循环中用到的向上和向下计数是可以用 `for` 循环更简明地表达: ```jldoctest julia> for i = 1:5 println(i) end 1 2 3 4 5 ``` 这里的 `1:5` 是一个范围对象,代表数字 1, 2, 3, 4, 5 的序列。`for` 循环在这些值之中迭代,对每一个变量 `i` 进行赋值。`for` 循环与之前 `while` 循环的一个非常重要区别是作用域,即变量的可见性。如果变量 `i` 没有在另一个作用域里引入,在 `for` 循环内,它就只在 `for` 循环内部可见,在外部和后面均不可见。你需要一个新的交互式会话实例或者一个新的变量名来测试这个特性: ```jldoctest julia> for j = 1:5 println(j) end 1 2 3 4 5 julia> j ERROR: UndefVarError: j not defined ``` 参见[变量作用域](@ref scope-of-variables)中对变量作用域的详细解释以及它在 Julia 中是如何工作的。 一般来说,`for` 循环组件可以用于迭代任一个容器。在这种情况下,相比 `=`,另外的(但完全相同)关键字 `in` 或者 `∈` 则更常用,因为它使得代码更清晰: ```jldoctest julia> for i in [1,4,0] println(i) end 1 4 0 julia> for s ∈ ["foo","bar","baz"] println(s) end foo bar baz ``` 在手册后面的章节中会介绍和讨论各种不同的迭代容器(比如,[多维数组](@ref man-multi-dim-arrays))。 为了方便,我们可能会在测试条件不成立之前终止一个 `while` 循环,或者在访问到迭代对象的结尾之前停止一个 `for` 循环,这可以用关键字 `break` 来完成: ```jldoctest julia> i = 1; julia> while true println(i) if i >= 5 break end global i += 1 end 1 2 3 4 5 julia> for j = 1:1000 println(j) if j >= 5 break end end 1 2 3 4 5 ``` 没有关键字 `break` 的话,上面的 `while` 循环永远不会自己结束,而 `for` 循环会迭代到 1000,这些循环都可以使用 `break` 来提前结束。 在某些场景下,需要直接结束此次迭代,并立刻进入下次迭代,`continue` 关键字可以用来完成此功能: ```jldoctest julia> for i = 1:10 if i % 3 != 0 continue end println(i) end 3 6 9 ``` 这是一个有点做作的例子,因为我们可以通过否定这个条件,把 `println` 调用放到 `if` 代码块里来更简洁的实现同样的功能。在实际应用中,在 `continue` 后面还会有更多的代码要运行,并且调用 `continue` 的地方可能会有多个。 多个嵌套的 `for` 循环可以合并到一个外部循环,可以用来创建其迭代对象的笛卡尔积: ```jldoctest julia> for i = 1:2, j = 3:4 println((i, j)) end (1, 3) (1, 4) (2, 3) (2, 4) ``` 有了这个语法,迭代变量依然可以正常使用循环变量来进行索引,例如 `for i = 1:n, j = 1:i` 是合法的,但是在一个循环里面使用 `break` 语句则会跳出整个嵌套循环,不仅仅是内层循环。每次内层循环运行的时候,变量(`i` 和 `j`)会被赋值为他们当前的迭代变量值。所以对 `i` 的赋值对于接下来的迭代是不可见的: ```jldoctest julia> for i = 1:2, j = 3:4 println((i, j)) i = 0 end (1, 3) (1, 4) (2, 3) (2, 4) ``` 如果这个例子给每个变量一个关键字 `for` 来重写,那么输出会不一样:第二个和第四个变量包含 `0`。 可以使用 [`zip`](@ref) 在单个 `for` 循环中同时迭代多个容器: ```jldoctest julia> for (j, k) in zip([1 2 3], [4 5 6 7]) println((j,k)) end (1, 4) (2, 5) (3, 6) ``` 使用 [`zip`](@ref) 将创建一个迭代器,它是一个包含传递给它的容器的子迭代器的元组。 `zip` 迭代器将按顺序迭代所有子迭代器,在 `for` 循环的第 ``i`` 次迭代中选择每个子迭代器的第 ``i`` 个元素。 一旦任何子迭代器用完,`for` 循环就会停止。 ## 异常处理 当一个意外条件发生时,一个函数可能无法向调用者返回一个合理的值。在这种情况下,最好让意外条件终止程序并打印出调试的错误信息,或者根据程序员预先提供的异常处理代码来采取恰当的措施。 ### 内置的 `Exception` 当一个意外的情况发生时,会抛出 `Exception`。下面列出的内置 `Exception` 都会中断正常的控制流程。 | `Exception` | |:----------------------------- | | [`ArgumentError`](@ref) | | [`BoundsError`](@ref) | | [`CompositeException`](@ref) | | [`DimensionMismatch`](@ref) | | [`DivideError`](@ref) | | [`DomainError`](@ref) | | [`EOFError`](@ref) | | [`ErrorException`](@ref) | | [`InexactError`](@ref) | | [`InitError`](@ref) | | [`InterruptException`](@ref) | | `InvalidStateException` | | [`KeyError`](@ref) | | [`LoadError`](@ref) | | [`OutOfMemoryError`](@ref) | | [`ReadOnlyMemoryError`](@ref) | | [`RemoteException`](@ref) | | [`MethodError`](@ref) | | [`OverflowError`](@ref) | | [`Meta.ParseError`](@ref) | | [`SystemError`](@ref) | | [`TypeError`](@ref) | | [`UndefRefError`](@ref) | | [`UndefVarError`](@ref) | | [`StringIndexError`](@ref) | 例如,当输入参数为负实数时,[`sqrt`](@ref) 函数会抛出一个 [`DomainError`](@ref) : ```jldoctest 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: [...] ``` 你可能需要根据下面的方式来定义你自己的异常: ```jldoctest julia> struct MyCustomException <: Exception end ``` ### [`throw`](@ref) 函数 我们可以用 [`throw`](@ref) 显式地创建异常。例如,若一个函数只对非负数有定义,当输入参数是负数的时候,可以用 [`throw`](@ref) 抛出一个 [`DomainError`](@ref)。 ```jldoctest; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> f(x) = x>=0 ? exp(-x) : throw(DomainError(x, "argument must be nonnegative")) f (generic function with 1 method) julia> f(1) 0.36787944117144233 julia> f(-1) ERROR: DomainError with -1: argument must be nonnegative Stacktrace: [1] f(::Int64) at ./none:1 ``` 注意 [`DomainError`](@ref) 后面不接括号的话不是一个异常,而是一个异常类型。我们需要调用它来获得一个 `Exception` 对象: ```jldoctest julia> typeof(DomainError(nothing)) <: Exception true julia> typeof(DomainError) <: Exception false ``` 另外,一些异常类型会接受一个或多个参数来进行错误报告: ```jldoctest julia> throw(UndefVarError(:x)) ERROR: UndefVarError: x not defined ``` 我们可以仿照 [`UndefVarError`](@ref) 的写法,用自定义异常类型来轻松实现这个机制: ```jldoctest julia> struct MyUndefVarError <: Exception var::Symbol end julia> Base.showerror(io::IO, e::MyUndefVarError) = print(io, e.var, " not defined") ``` !!! note 错误信息的第一个单词最好用小写。例如: `size(A) == size(B) || throw(DimensionMismatch("size of A not equal to size of B"))` 就比 `size(A) == size(B) || throw(DimensionMismatch("Size of A not equal to size of B"))`. 更好。 但是,有时保留大写首字母是有意义的,例如函数的参数就是大写字母时: `size(A,1) == size(B,2) || throw(DimensionMismatch("A has first dimension..."))`. ### 错误 我们可以用 [`error`](@ref) 函数生成一个 [`ErrorException`](@ref) 来中断正常的控制流程。 假设我们希望在计算负数的平方根时让程序立即停止执行。为了实现它,我们可以定义一个挑剔的 [`sqrt`](@ref) 函数,当它的参数是负数时,产生一个错误: ```jldoctest fussy_sqrt; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> fussy_sqrt(x) = x >= 0 ? sqrt(x) : error("negative x not allowed") fussy_sqrt (generic function with 1 method) julia> fussy_sqrt(2) 1.4142135623730951 julia> fussy_sqrt(-1) ERROR: negative x not allowed Stacktrace: [1] error at ./error.jl:33 [inlined] [2] fussy_sqrt(::Int64) at ./none:1 [3] top-level scope ``` 如果另一个函数调用 `fussy_sqrt` 和一个负数, 它会立马返回, 在交互会话中显示错误信息,而不会继续执行调用的函数: ```jldoctest fussy_sqrt; filter = r"Stacktrace:(\n \[[0-9]+\].*)*" julia> function verbose_fussy_sqrt(x) println("before fussy_sqrt") r = fussy_sqrt(x) println("after fussy_sqrt") return r end verbose_fussy_sqrt (generic function with 1 method) julia> verbose_fussy_sqrt(2) before fussy_sqrt after fussy_sqrt 1.4142135623730951 julia> verbose_fussy_sqrt(-1) before fussy_sqrt ERROR: negative x not allowed Stacktrace: [1] error at ./error.jl:33 [inlined] [2] fussy_sqrt at ./none:1 [inlined] [3] verbose_fussy_sqrt(::Int64) at ./none:3 [4] top-level scope ``` ### `try/catch` 语句 通过 `try / catch` 语句,可以测试 Exception 并 优雅处理可能会破坏应用程序的事情。 例如, 在下面的代码中,平方根函数会引发异常。 通过 在其周围放置 `try / catch` 块可以缓解。 您可以选择如何 处理此异常,无论是记录它,返回占位符值还是 就像下面仅打印一句话。 要注意的是 在决定如何处理异常时,使用`try / catch` 块 比使用条件分支处理要慢得多。 以下是使用` try / catch` 块处理异常的更多示例: ```jldoctest julia> try sqrt("ten") catch e println("You should have entered a numeric value") end You should have entered a numeric value ``` `try/catch` 语句允许保存 `Exception` 到一个变量中。在下面这个做作的例子中,如果 `x` 是可索引的,则计算 `x` 的第二项的平方根,否则就假设 `x` 是一个实数,并返回它的平方根: ```jldoctest julia> sqrt_second(x) = try sqrt(x[2]) catch y if isa(y, DomainError) sqrt(complex(x[2], 0)) elseif isa(y, BoundsError) sqrt(x) end end sqrt_second (generic function with 1 method) julia> sqrt_second([1 4]) 2.0 julia> sqrt_second([1 -4]) 0.0 + 2.0im julia> sqrt_second(9) 3.0 julia> sqrt_second(-9) ERROR: DomainError with -9.0: sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)). Stacktrace: [...] ``` 注意 `catch` 后面的字符会被一直认为是异常的名字,所以在写 `try/catch` 单行表达式时,需要特别小心。下面的代码**不会**在错误的情况下返回 `x` 的值: ```julia try bad() catch x end ``` 正确的做法是在 `catch` 后添加一个分号或者直接换行: ```julia try bad() catch; x end try bad() catch x end ``` `try/catch` 结构的强大之处在于能够立即将深度嵌套的计算展开到调用函数堆栈中的更高级别。 在某些情况下,没有发生错误,但需要能够展开堆栈并将值传递到更高级别。 Julia 提供了 [`rethrow`](@ref)、[`backtrace`](@ref)、[`catch_backtrace`](@ref) 和 [`current_exceptions`](@ref) 函数来进行更高级的错误处理。 ### `finally` 子句 在进行状态改变或者使用类似文件的资源的编程时,经常需要在代码结束的时候进行必要的清理工作(比如关闭文件)。由于异常会使得部分代码块在正常结束之前退出,所以可能会让上述工作变得复杂。`finally` 关键字提供了一种方式,无论代码块是如何退出的,都能够让代码块在退出时运行某段代码。 这里是一个确保一个打开的文件被关闭的例子: ```julia f = open("file") try # operate on file f finally close(f) end ``` 当控制流离开 `try` 代码块(例如,遇到 `return`,或者正常结束),`close(f)` 就会被执行。如果 `try` 代码块由于异常退出,这个异常会继续传递。`catch` 代码块可以和 `try` 还有 `finally` 配合使用。这时 `finally` 代码块会在 `catch` 处理错误之后才运行。 ## [ Tasks 任务(或协程)](@id man-tasks) `Task` 是一种允许计算以更灵活的方式被中断或者恢复的流程控制特性。 我们提及它只是为了说明的完整性;详细的介绍参见:[异步编程](@ref man-asynchronous)。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
8012
# [类型转换和类型提升](@id conversion-and-promotion) Julia 有一个提升系统,可以将数学运算符的参数提升为通用类型,如在前面章节中提到的[整数和浮点数](@ref)、[数学运算和初等函数](@ref)、[类型](@ref man-types)和[方法](@ref)。在本节中,我们将解释类型提升系统如何工作,以及如何将其扩展到新的类型,并将其应用于除内置数学运算符之外的其他函数。传统上,编程语言在参数的类型提升上分为两大阵营: * **内置数学类型和运算符的自动类型提升。**大多数语言中,内置数值类型,当作为带有中缀语法的算术运算符的操作数时,例如 `+`、`-`、`*` 和 `/` 将自动提升为通用类型,以产生预期的结果。举例来说,C、Java、Perl 和 Python,都将 `1 + 1.5` 的和作为浮点值 `2.5`,即使 `+` 的一个操作数是整数。这些系统非常方便且设计得足够精细,以至于它对于程序员来讲通常是不可见的:在编写这样的表达式时,几乎没有人有意识地想到这种类型提升,但编译器和解释器必须在相加前执行转换,因为整数和浮点值无法按原样相加。因此,这种自动类型转换的复杂规则不可避免地是这些语言的规范和实现的一部分。 * **没有自动类型提升。**这个阵营包括 Ada 和 ML——非常「严格的」 静态类型语言。在这些语言中,每个类型转换都必须由程序员明确指定。因此,示例表达式 `1 + 1.5` 在 Ada 和 ML 中都会导致编译错误。相反地,必须编写 `real(1) + 1.5`,来在执行加法前将整数 `1` 显式转换为浮点值。然而,处处都显式转换是如此地不方便,以至于连 Ada 也有一定程度的自动类型转换:整数字面量被类型提升为预期的整数类型,浮点字面量同样被类型提升为适当的浮点类型。 在某种意义上,Julia 属于「无自动类型提升」类别:数学操作符只是具有特殊语法的函数,函数的参数永远不会自动转换。然而,人们可能会发现数学运算能应用于各种混合的参数类型,但这只是多态的多重分派的极端情况——这是 Julia 的分派和类型系统特别适合处理的情况。数学操作数的「自动」类型提升只是作为一个特殊的应用出现:Julia 带有预定义的数学运算符的 catch-all 分派规则,其在某些操作数类型的组合没有特定实现时调用。这些 catch-all 分派规则首先使用用户可定义的类型提升规则将所有操作数提升到一个通用的类型,然后针对结果值(现在已属于相同类型)调用相关运算符的特定实现。用户定义的类型可简单地加入这个类型提升系统,这需要先定义与其它类型进行相互类型转换的方法,接着提供一些类型提升规则来定义与其它类型混合时应该提升到什么类型。 ## 类型转换 获取某种类型 `T` 的值的标准方法是调用该类型的构造函数 `T(x)`。但是,有些情况下,在程序员没有明确要求时,仍将值从一种类型转换为另一种类型是很方便的。其中一个例子是将值赋给一个数组:假设 `A` 是个 `Vector{Float64}`,表达式 `A[1] = 2` 执行时应该自动将 `2` 从 `Int` 转换为 `Float`,并将结果存储在该数组中。这通过 [`convert`](@ref) 函数完成。 `convert` 函数通常接受两个参数:第一个是类型对象,第二个是需要转换为该类型的值。返回的是已转换后的值。理解这个函数最简单的办法就是尝试: ```jldoctest julia> x = 12 12 julia> typeof(x) Int64 julia> xu = convert(UInt8, x) 0x0c julia> typeof(xu) UInt8 julia> xf = convert(AbstractFloat, x) 12.0 julia> typeof(xf) Float64 julia> a = Any[1 2 3; 4 5 6] 2×3 Matrix{Any}: 1 2 3 4 5 6 julia> convert(Array{Float64}, a) 2×3 Matrix{Float64}: 1.0 2.0 3.0 4.0 5.0 6.0 ``` 类型转换并不总是可行的,有时 `convert` 函数并不知道该如何执行所请求的类型转换就会抛出 [`MethodError`](@ref) 错误。例如下例: ```jldoctest julia> convert(AbstractFloat, "foo") ERROR: MethodError: Cannot `convert` an object of type String to an object of type AbstractFloat [...] ``` 一些语言考虑将解析字符串为数字或格式化数字为字符串来进行转换(许多动态语言甚至会自动执行转换),但 Julia 不会:尽管某些字符串可以解析为数字,但大多数字符串都不是有效的数字表示形式,只有非常有限的子集才是。因此,在 Julia 中,必须使用专用的 [`parse`](@ref) 函数来执行此操作,这使其更加明确。 ### 什么时候使用 `convert` 函数? 构造以下语言结构时需要调用 `convert` 函数: * 对一个数组赋值会转换为数组元素的类型。 * 对一个对象的字段赋值会转换为已声明的字段类型。 * 使用 [`new`](@ref) 构造对象会转换为该对象已声明的字段类型。 * 对已声明类型的变量赋值(例如 `local x::T`)会转换为该类型。 * 已声明返回类型的函数会转换其返回值为该类型。 * 把值传递给 [`ccall`](@ref) 会将其转换为相应参数的类型。 ### 类型转换与构造 注意到 `convert(T, x)` 的行为似乎与 `T(x)` 几乎相同,它的确通常是这样。但是,有一个关键的语义差别:因为 `convert` 能被隐式调用,所以它的方法仅限于被认为是「安全」或「意料之内」的情况。`convert` 只会在表示事物的相同基本种类的类型之间进行转换(例如,不同的数字表示和不同的字符串编码)。它通常也是无损的;将值转换为其它类型并再次转换回去应该产生完全相同的值。 这是四种一般的构造函数与 `convert` 不同的情况: #### 与其参数类型无关的类型的构造函数 一些构造函数没有体现「转换」的概念。例如,`Timer(2)` 创建一个时长 2 秒的定时器,它实际上并不是从整数到定时器的「转换」。 #### 可变的集合 如果 `x` 类型已经为 `T`,`convert(T, x)` 应该返回原本的 `x`。相反地,如果 `T` 是一个可变的集合类型,那么 `T(x)` 应该总是创建一个新的集合(从 `x` 复制元素)。 #### 封装器类型 对于某些「封装」其它值的类型,构造函数可能会将其参数封装在一个新对象中,即使它已经是所请求的类型。例如,用 `Some(x)` 表示封装了一个 `x` 值(在上下文中,其结果可能是一个 `Some` 或 `nothing`)。但是,`x` 本身可能是对象 `Some(y)`,在这种情况下,结果为 `Some(Some(y))`,封装了两层。然而,`convert(Some, x)` 只会返回 `x`,因为它已经是 `Some` 的实例了。 #### 不返回自身类型的实例的构造函数 在*极少见*的情况下,构造函数 `T(x)` 返回一个类型不为 `T` 的对象是有意义的。如果封装器类型是它自身的反转(例如 `Flip(Flip(x)) === x`),或者在重构库时为了支持某个旧的调用语法以实现向后兼容,则可能发生这种情况。但是,`convert(T, x)` 应该总是返回一个类型为 `T` 的值。 ### 定义新的类型转换 在定义新类型时,最初创建它的所有方法都应定义为构造函数。如果隐式类型转换很明显是有用的,并且某些构造函数满足上面的「安全」标准,那么可以考虑添加 `convert` 方法。这些方法通常非常简单,因为它们只需要调用适当的构造函数。此类定义可能会像这样: ```julia convert(::Type{MyType}, x) = MyType(x) ``` 这个方法的第一个参数的类型是[`Type{MyType}`](@ref man-typet-type),它的唯一实例是`MyType`。 因此,仅当第一个参数是类型值`MyType`时才会调用此方法。注意第一个参数使用的语法:在`::`符号之前省略参数名称,只给出类型。 这是 Julia 中指定类型但不需要通过名称引用其值的函数参数的语法。 某些抽象类型的所有实例默认都被认为是「足够相似的」,在 Julia Base 中也提供了通用的 `convert` 定义。例如,这个定义声明通过调用单参数构造函数将任何 `Number` 类型 `convert` 为其它任何 `Number` 类型是有效的: ```julia convert(::Type{T}, x::Number) where {T<:Number} = T(x) ``` 这意味着新的 `Number` 类型只需要定义构造函数,因为此定义将为它们处理 `convert`。在参数已经是所请求的类型的情况下,用恒同变换来处理 `convert`。 ```julia convert(::Type{T}, x::T) where {T<:Number} = x ``` `AbstractString`、[`AbstractArray`](@ref) 和 [`AbstractDict`](@ref) 也存在类似的定义。 ## 类型提升 类型提升是指将一组混合类型的值转换为单个通用类型。尽管不是绝对必要的,但一般暗示被转换的值的通用类型可以忠实地表示所有原始值。此意义下,术语「类型提升」是合适的,因为值被转换为「更大」的类型——即能用一个通用类型表示所有输入值的类型。但重要的是,不要将它与面向对象(结构)超类或 Julia 的抽象超类型混淆:类型提升与类型层次结构无关,而与备选的表示之间的转换有关。例如,尽管每个 [`Int32`](@ref) 值可以表示为 [`Float64`](@ref) 值,但 `Int32` 不是 `Float64` 的子类型。 在 Julia 中,类型提升到一个通用的「更大」类型的操作是通过 [`promote`](@ref) 函数执行的,该函数接受任意数量的参数,并返回由相同数量的值组成的元组,值会被转换为一个通用类型,或在无法类型提升时抛出异常。类型提升的最常见用途是将数字参数转换为通用类型: ```jldoctest julia> promote(1, 2.5) (1.0, 2.5) julia> promote(1, 2.5, 3) (1.0, 2.5, 3.0) julia> promote(2, 3//4) (2//1, 3//4) julia> promote(1, 2.5, 3, 3//4) (1.0, 2.5, 3.0, 0.75) julia> promote(1.5, im) (1.5 + 0.0im, 0.0 + 1.0im) julia> promote(1 + 2im, 3//4) (1//1 + 2//1*im, 3//4 + 0//1*im) ``` 浮点值被提升为最大的浮点参数类型。整数值会被提升为本机机器字大小或最大的整数参数类型中较大的一个。整数和浮点值的混合会被提升为一个足以包含所有值的浮点类型。与有理数混合的整数会被提升有理数。与浮点数混合的有理数会被提升为浮点数。与实数值混合的复数值会被提升为合适类型的复数值。 这就是使用类型提升的全部内容。剩下的只是聪明的应用,最典型的「聪明」应用是数值操作(如 `+`、`-`、`*` 和 `/`)的 catch-all 方法的定义。以下是在 [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl) 中给出的几个 catch-all 方法的定义: ```julia +(x::Number, y::Number) = +(promote(x,y)...) -(x::Number, y::Number) = -(promote(x,y)...) *(x::Number, y::Number) = *(promote(x,y)...) /(x::Number, y::Number) = /(promote(x,y)...) ``` 这些方法的定义表明,如果没有更特殊的规则来加、减、乘及除一对数值,则将这些值提升为通用类型并再试一次。这就是它的全部内容:在其它任何地方都不需要为数值操作担心到通用数值类型的类型提升——它会自动进行。许多算术和数学函数的 catch-all 类型提升方法的定义在 [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl) 中,但除此之外,Julia Base 中几乎不再需要调用 `promote`。`promote` 最常用于外部构造方法中,为了更方便,可允许使用混合类型的构造函数调用委托给一个内部构造函数,并将字段提升为适当的通用类型。例如,回想一下,[`rational.jl`](https://github.com/JuliaLang/julia/blob/master/base/rational.jl) 提供了以下外部构造方法: ```julia Rational(n::Integer, d::Integer) = Rational(promote(n,d)...) ``` 这允许像下面这样的调用正常工作: ```jldoctest julia> x = Rational(Int8(15),Int32(-5)) -3//1 julia> typeof(x) Rational{Int32} ``` 对于大多数用户定义的类型,最好要求程序员明确地向构造函数提供期待的类型,但有时,尤其是对于数值问题,自动进行类型提升会很方便。 ### 定义类型提升规则 虽然原则上可以直接为 `promote` 函数定义方法,但这需要为参数类型的所有可能排列下许多冗余的定义。相反地,`promote` 的行为是根据名为 [`promote_rule`](@ref) 的辅助函数定义的,该辅助函数可以为其提供方法。`promote_rule` 函数接受一对类型对象并返回另一个类型对象,这样参数类型的实例会被提升为被返回的类型。 因此,通过定义规则: ```julia promote_rule(::Type{Float64}, ::Type{Float32}) = Float64 ``` 声明当同时类型提升 64 位和 32 位浮点值时,它们应该被类型提升为 64 位浮点数。但是,提升类型不需要是参数类型之一;例如,在 Julia Base 中有以下类型提升规则: ```julia promote_rule(::Type{BigInt}, ::Type{Float64}) = BigFloat promote_rule(::Type{BigInt}, ::Type{Int8}) = BigInt ``` 在后一种情况下,输出类型是 [`BigInt`](@ref),因为 `BigInt` 是唯一一个足以容纳任意精度整数运算结果的类型。还要注意,不需要同时定义 `promote_rule(::Type{A}, ::Type{B})` 和 `promote_rule(::Type{B}, ::Type{A})`——对称性隐含在类型提升过程中使用 `promote_rule` 的方式。 以 `promote_rule` 函数为基础定义了 [`promote_type`](@ref) 函数,在给定任意数量的类型对象时,它返回这些值作为 `promote` 的参数应被提升的通用类型。因此,如果想知道在没有实际值情况下,具有确定类型的一些值会被类型提升为什么类型,可以使用 `promote_type`: ```jldoctest julia> promote_type(Int8, Int64) Int64 ``` 在内部,`promote_type` 在 `promote` 中用于确定参数值应被转换为什么类型以便进行类型提升。但是,它本身可能是有用的。好奇的读者可以阅读 [`promotion.jl`](https://github.com/JuliaLang/julia/blob/master/base/promotion.jl),该文件用大概 35 行定义了完整的类型提升规则。 ### 案例研究:有理数的类型提升 最后,我们来完成关于 Julia 的有理数类型的案例研究,该案例通过以下类型提升规则相对复杂地使用了类型提升机制: ```julia promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)} promote_rule(::Type{Rational{T}}, ::Type{Rational{S}}) where {T<:Integer,S<:Integer} = Rational{promote_type(T,S)} promote_rule(::Type{Rational{T}}, ::Type{S}) where {T<:Integer,S<:AbstractFloat} = promote_type(T,S) ``` 第一条规则说,使用其它整数类型类型提升有理数类型会得到个有理数类型,其分子/分母类型是使用其它整数类型提升该有理数分子/分母类型的结果。第二条规则将相同的逻辑应用于两种不同的有理数类型,它们进行类型提升会得到有理数类型,其分子/分母类型是它们各自的分子/分母类型进行提升的结果。第三个也是最后一个规则规定,使用浮点数类型提升有理数类型与使用该浮点数类型提升其分子/分母类型会产生相同的类型。 这一小部分的类型提升规则,连同该类型的构造函数和数字的默认 `convert` 方法,便足以使有理数与 Julia 的其它数值类型——整数、浮点数和复数——完全自然地互操作。通过以相同的方式提供类型转换方法和类型提升规则,任何用户定义的数值类型都可像 Julia 的预定义数值类型一样自然地进行互操作。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
35844
# 多进程和分布式计算 分布式内存并行计算的实现由模块 [`Distributed`](@ref man-distributed) 作为 Julia 附带的标准库的一部分提供。 大多数现代计算机都拥有不止一个 CPU,而且多台计算机可以组织在一起形成一个集群。借助多个 CPU 的计算能力,许多计算过程能够更快地完成,这其中影响性能的两个主要因素分别是:CPU 自身的速度以及它们访问内存的速度。显然,在一个集群中,一个 CPU 访问同一个节点的 RAM 速度是最快的,不过令人吃惊的是,在一台典型的多核笔记本电脑上,由于访问主存和[缓存](https://www.akkadia.org/drepper/cpumemory.pdf)的速度存在差别,类似的现象也会存在。因此,一个良好的多进程环境应该能够管理好某一片内存区域“所属”的CPU。Julia提供的多进程环境是基于消息传递来实现的,可以做到同时让程序在多个进程的不同内存区域中运行。 Julia 的消息传递实现不同于其他环境,例如 MPI[^1]。 Julia 中的通信通常是“单方面的”,这意味着程序员只需在双进程操作中显式管理一个进程。 此外,这些操作通常看起来不像“消息发送”和“消息接收”,而是类似于更高级别的操作,例如调用用户函数。 Julia 中的分布式编程基于两个基本概念:**远程引用**(*remote references*)和**远程调用**(*remote calls*)。远程引用是一个对象,任意一个进程可以通过它访问存储在某个特定进程上的对象。远程调用指是某个进程发起的执行函数的请求,该函数会在另一个(也可能是同一个)进程中执行。 远程引用有两种形式:[`Future`](@ref Distributed.Future) 和 [`RemoteChannel`](@ref)。 远程调用返回 [`Future`](@ref Distributed.Future) 作为其结果。 远程调用立即返回;当远程调用发生在其他地方后,发出调用的进程继续执行下一个操作。你可以通过在返回的 [`Future`](@ref Distributed.Future) 上调用 [`wait`](@ref) 来等待远程调用完成,并且可以使用 [`fetch `](@ref)。 对于 [`RemoteChannel`](@ref) 而言,它可以被反复写入。例如,多个进程可以通过引用同一个远程 `Channel` 来协调相互之间的操作。 每个进程都有一个关联的标识符。 提供交互式 Julia 提示符的进程的 `id` 总是等于 1。默认情况下用于并行操作的进程被称为“workers”。 当只有一个进程时,进程 1 被认为是一个worker。 否则,workers 被认为是进程 1 之外的所有进程。因此,需要添加 2 个或更多进程才能从 [`pmap`](@ref) 等并行处理方法中获益。 如果你只想在主进程中做其他事情,同时在工作进程上运行长时间的计算,那么添加单个进程是有益的。 让我们开始尝试。 以 `julia -p n` 开始,在本地机器上提供 `n` 个工作进程。 通常,`n` 等于机器上的 CPU 线程(逻辑核心)的数量是有意义的。 请注意,`-p` 参数隐式加载模块 [`Distributed`](@ref man-distributed)。 ```julia $ julia -p 2 julia> r = remotecall(rand, 2, 2, 2) Future(2, 1, 4, nothing) julia> s = @spawnat 2 1 .+ fetch(r) Future(2, 1, 5, nothing) julia> fetch(s) 2×2 Array{Float64,2}: 1.18526 1.50912 1.16296 1.60607 ``` [`remotecall`](@ref) 的第一个参数是想要调用的函数,第二个参数是执行函数的进程 `id`,其余的参数会喂给将要被调用的函数。在 Julia 中进行并行编程时,一般不需要显示地指明具体在哪个进程上执行,不过 [`remotecall`](@ref) 是一个相对底层的接口用来提供细粒度的管理。 可以看到,第一行代码请求进程2构建一个随机矩阵,第二行代码对该矩阵执行加一操作。每次执行的结果存在对应的 Future 中,即 `r` 和 `s`。这里 [`@spawnat`](@ref) 宏会在第一个参数所指定的进程中执行后面第二个参数中的表达式。 有时候,你可能会希望立即获取远程计算的结果,比如,在接下来的操作中就需要读取远程调用的结果,这时候你可以使用 [`remotecall_fetch`](@ref) 函数,其效果相当于 `fetch(remotecall(...))`,不过更高效些。 ```julia-repl julia> remotecall_fetch(r-> fetch(r)[1, 1], 2, r) 0.18526337335308085 ``` 这将获取 worker 2 上的数组并返回第一个值。 请注意,在这种情况下,`fetch` 不会移动任何数据,因为它是在拥有该数组的 worker 上执行的。 还可以这样写: ```julia-repl julia> remotecall_fetch(getindex, 2, r, 1, 1) 0.10824216411304866 ``` 回忆下,这里 [`getindex(r,1,1)`](@ref) [相当于](@ref man-array-indexing) `r[1,1]`,因此,上面的调用相当于获取 `r` 的第一个元素。 为方便起见,可以将符号 `:any` 传递给 [`@spawnat`](@ref),它会为你选择执行操作的位置: ```julia-repl julia> r = @spawnat :any rand(2,2) Future(2, 1, 4, nothing) julia> s = @spawnat :any 1 .+ fetch(r) Future(3, 1, 5, nothing) julia> fetch(s) 2×2 Array{Float64,2}: 1.38854 1.9098 1.20939 1.57158 ``` 请注意,我们使用了 `1 .+ fetch(r)` 而不是 `1 .+ r`。 这是因为我们不知道代码将在哪里运行,因此通常可能需要一个 [`fetch`](@ref) 将 `r` 移动到执行添加的进程。 在这种情况下,[`@spawnat`](@ref) 足够聪明,可以在拥有 `r` 的进程上执行计算,因此 [`fetch`](@ref) 将是一个空操作(没有工作被完成)。 (值得注意的是, [`@spawnat`](@ref) 不是内置的,而是在 Julia 中定义的 [宏](@ref man-macros)。你也可以自己定义此类构造。) 需要记住的重要一点是,一旦 fetch,[`Future`](@ref Distributed.Future) 将在本地缓存其值。 进一步的 [`fetch`](@ref) 调用不需要网络跃点。 一旦所有引用 [`Future`](@ref Distributed.Future) 都已获取,远程存储的值将被删除。 [`@async`](@ref) 类似于 [`@spawnat`](@ref),但只在本地进程上运行任务。我们使用它为每个进程创建一个“feeder”任务。每个任务选择需要计算的下一个索引,然后等待其进程完成,然后重复直到我们用完索引。请注意,feeder任务直到主任务到达 [`@sync`](@ref) 块的末尾才开始执行,此时它放弃控制并等待所有本地任务完成,然后从主任务返回功能。对于 v0.7 及更高版本,feeder 任务能够通过 `nextidx` 共享状态,因为它们都运行在同一个进程上。即使`Tasks` 是协作调度的,在某些上下文中可能仍然需要锁定,例如在 [asynchronous I/O](@ref faq-async-io) 中。这意味着上下文切换只发生在明确定义的点:在这种情况下,当 [`remotecall_fetch`](@ref) 被调用时。这是当前的实现状态,它可能会在未来的 Julia 版本中发生变化,因为它旨在使在 M个 `Process` 上运行最多 N 个 `Tasks` 成为可能,也就是 [M:N Threading](https://en.wikipedia.org/wiki/Thread_(computing)#Models)。然后,需要为 `nextidx` 提供锁获取/释放模型,因为让多个进程同时读写一个资源是不安全的。 ## [访问代码以及加载库](@id code-availability) 对于想要并行执行的代码,需要所有对所有线程都可见。例如,在 Julia 命令行中输入以下命令: ```julia-repl julia> function rand2(dims...) return 2*rand(dims...) end julia> rand2(2,2) 2×2 Array{Float64,2}: 0.153756 0.368514 1.15119 0.918912 julia> fetch(@spawnat :any rand2(2,2)) ERROR: RemoteException(2, CapturedException(UndefVarError(Symbol("#rand2")) Stacktrace: [...] ``` 进程1知道函数 `rand2` 的存在,但进程2并不知道。 大多数情况下,你会从文件或者库中加载代码,在此过程中你可以灵活地控制哪个进程加载哪部分代码。假设有这样一个文件,`DummyModule.jl`,其代码如下: ```julia module DummyModule export MyType, f mutable struct MyType a::Int end f(x) = x^2+1 println("loaded") end ``` 为了在所有进程中引用 `MyType`,`DummyModule.jl` 需要在每个进程中载入。单独执行 `include("DummyModule.jl")` 只会在一个线程中将其载入。为了让每个线程都载入它,可以用 [`@everywhere`](@ref) 宏来实现(启动 Julia 的时候,执行 `julia -p 2`)。 ```julia-repl julia> @everywhere include("DummyModule.jl") loaded From worker 3: loaded From worker 2: loaded ``` 像往常一样,这不会将 `DummyModule` 引入任何进程的作用域,这需要 [`using`](@ref) 或 [`import`](@ref)。 此外,当 `DummyModule` 被带入一个进程的作用域时,它不在任何其他进程中: ```julia-repl julia> using .DummyModule julia> MyType(7) MyType(7) julia> fetch(@spawnat 2 MyType(7)) ERROR: On worker 2: UndefVarError: MyType not defined ⋮ julia> fetch(@spawnat 2 DummyModule.MyType(7)) MyType(7) ``` 不过,我们仍然可以在已经包含(include)过 `DummyModule` 的进程中,发送 `MyType` 类型的实例,尽管此时该进程的命名空间中并没有 `MyType` 变量: ```julia-repl julia> put!(RemoteChannel(2), MyType(7)) RemoteChannel{Channel{Any}}(2, 1, 13) ``` 文件代码还可以在启动的时候,通过 `-L` 参数指定,从而提前在多个进程中载入,然后通过一个 driver.jl 文件控制执行逻辑: ``` julia -p <n> -L file1.jl -L file2.jl driver.jl ``` 上面执行 `driver.jl` 的进程 id 为1,就跟提供交互式命令行的 Julia 进程一样。 最后,如果`DummyModule.jl`不是一个独立的文件,而是一个包,那么`using DummyModule`将在所有进程上_加载_ `DummyModule.jl`,但只在调用[`using`](@ref)的进程上将其纳入作用域。 ## 启动和管理 worker 进程 Julia 自带两种集群管理模式: * 本地集群,前面通过启动时指定 `-p` 参数就是这种模式 * 跨机器的集群,通过 `--machine-file` 指定。这种模式采用没有密码的 `ssh` 登陆并对应的机器上(与 host 相同的路径下)启动 Julia 的 worker 进程。每个机器定义都采用 `[count*][user@]host[:port] [bind_addr[:port]]` 的形式。 `user` 默认为当前用户,`port` 为标准 ssh 端口。`count` 是在节点上生成的 worker 数量,默认为 1。可选的 `bind-to bind_addr[:port]` 指定其他 worker 应该用来连接到这个 worker 的 IP 地址和端口。 [`addprocs`](@ref), [`rmprocs`](@ref), [`workers`](@ref) 这些函数可以分别用来对集群中的进程进行增加,删除和修改。 ```julia-repl julia> using Distributed julia> addprocs(2) 2-element Array{Int64,1}: 2 3 ``` 模块 [`Distributed`](@ref man-distributed) 必须在调用 [`addprocs`](@ref) 之前显式加载到主进程上。 它在工作进程上自动可用。 请注意,worker 不会运行 `~/.julia/config/startup.jl` 启动脚本,也不会将其全局状态(例如全局变量、新方法定义和加载的模块)与任何其他正在运行的进程同步 。你可以使用 `addprocs(exeflags="--project")` 来初始化具有特定环境的 worker,然后使用 `@everywhere using <modulename>` 或 `@everywhere include("file.jl")`。 其它类型的集群可以通过自己写一个 `ClusterManager` 来实现,下面 [集群管理器](@ref) 部分会介绍。 ## 数据转移 分布式程序的性能瓶颈主要是由发送消息和数据转移造成的,减少发送消息和转移数据的数量对于获取高性能和可扩展性至关重要,因此,深入了解 Julia 分布式程序是如何转移数据的非常有必要。 [`fetch`](@ref) 可以被认为是一个显式的数据转移操作,因为它直接要求将一个对象移动到本地机器。 [`@spawnat`](@ref)(以及一些相关的结构体)也移动数据,但这并不明显,因此可以称为隐式数据转移操作。 考虑这两种构造和平方一个随机矩阵的方法: 方法一: ```julia-repl julia> A = rand(1000,1000); julia> Bref = @spawnat :any A^2; [...] julia> fetch(Bref); ``` 方法二: ```julia-repl julia> Bref = @spawnat :any rand(1000,1000)^2; [...] julia> fetch(Bref); ``` 这种差异看起来微不足道,但实际上由于 [`@spawnat`](@ref) 的行为而非常显着。 在第一种方法中,在本地构造一个随机矩阵,然后将其发送到另一个进程进行平方。 在第二种方法中,随机矩阵在另一个进程中被构造和平方。 因此,第二种方法发送的数据比第一种方法少得多。 在这个简单示例中,这两种方法很容易区分和选择。 然而,在一个真正的程序设计数据转移可能需要更多的思考和一些测量。 例如,如果第一个进程需要矩阵`A`,那么第一种方法可能更好。 或者,如果计算 `A` 很昂贵并且只有当前进程拥有它,那么将它移到另一个进程可能是不可避免的。 或者,如果当前进程在 [`@spawnat`](@ref) 和 `fetch(Bref)` 之间几乎没有什么关系,最好完全消除并行性。 或者想象一下 `rand(1000,1000)` 被更昂贵的操作取代。 那么为这一步添加另一个 [`@spawnat`](@ref) 语句可能是有意义的。 ## 全局变量 通过 [`@spawnat`](@ref) 远程执行的表达式,或使用 [`remotecall`](@ref) 为远程执行指定的闭包可能会引用全局变量。 与其他模块中的全局绑定相比,模块 `Main` 下的全局绑定的处理方式略有不同。 考虑以下代码片段: ```julia-repl A = rand(10,10) remotecall_fetch(()->sum(A), 2) ``` 在这种情况下,[`sum`](@ref) 必须在远程进程中定义。请注意,`A` 是在本地工作区中定义的全局变量。 worker 2 在 `Main` 下没有名为 `A` 的变量。 将闭包 `()->sum(A)` 传送到 worker 2 的行为导致 `Main.A` 被定义在 2 上。即使在调用 [`remotecall_fetch`](@ref) 返回之后, `Main.A` 仍然存在于 worker 2 上。带有嵌入式全局引用的远程调用(仅在`Main` 模块下)以如下的方式管理全局变量: - 在全局调用中引用的全局绑定会在将要执行该调用的 worker 中被创建。 - 全局常量仍然在远端结点定义为常量。 - 全局绑定会在下一次远程调用中引用到的时候,当其值发生改变时,再次发送给目标 worker。此外,集群并不会所有结点的全局绑定。例如: ```julia A = rand(10,10) remotecall_fetch(()->sum(A), 2) # worker 2 A = rand(10,10) remotecall_fetch(()->sum(A), 3) # worker 3 A = nothing ``` 可以看到,`A` 作为全局变量在 worker 2中有定义,而 `B` 是一个局部变量,因而最后在 worker 2 中并没有 `B` 的绑定。 执行以上代码之后,worker 2 和 worker 3中的 `Main.A` 的值是不同的,同时,节点1上的值则为 `nothing`。 也许你也注意到了,在 master 主节点上被赋值为 `nothing` 之后,全局变量的内存会被回收,但在 worker 节点上的全局变量并没有被回收掉。执行 [`clear`](@ref) 可以手动将远端结点上的特定全局变量置为 `nothing`,然后对应的内存会被周期性的垃圾回收机制回收。 因此,在远程调用中,需要非常小心地引用全局变量。事实上,应当尽量避免引用全局变量,如果必须引用,那么可以考虑用`let`代码块将全局变量局部化: ```julia-repl julia> A = rand(10,10); julia> remotecall_fetch(()->A, 2); julia> B = rand(10,10); julia> let B = B remotecall_fetch(()->B, 2) end; julia> @fetchfrom 2 InteractiveUtils.varinfo() name size summary ––––––––– ––––––––– –––––––––––––––––––––– A 800 bytes 10×10 Array{Float64,2} Base Module Core Module Main Module ``` 可以看到,`A` 作为全局变量在 worker 2中有定义,而 `B` 是一个局部变量,因而最后在 worker 2 中并没有 `B` 的绑定。 ## 并行的Map和Loop 幸运的是,许多有用的并行计算不需要数据转移。 一个常见的例子是蒙特卡罗模拟,其中多个进程可以同时处理独立的模拟试验。 我们可以使用 [`@spawnat`](@ref) 在两个进程上抛硬币。 首先,在 `count_heads.jl` 中编写以下函数: ```julia function count_heads(n) c::Int = 0 for i = 1:n c += rand(Bool) end c end ``` 函数 `count_heads` 只是简单地将 `n` 个随机 0-1 值累加,下面在两个机器上进行试验,并将结果叠加: ```julia-repl julia> @everywhere include_string(Main, $(read("count_heads.jl", String)), "count_heads.jl") julia> a = @spawnat :any count_heads(100000000) Future(2, 1, 6, nothing) julia> b = @spawnat :any count_heads(100000000) Future(3, 1, 7, nothing) julia> fetch(a)+fetch(b) 100001564 ``` 上面的例子展示了一种非常常见而且有用的并行编程模式,在一些进程中执行多次独立的迭代,然后将它们的结果通过某个函数合并到一起,这个合并操作通常称作**聚合**(*reduction*),也就是一般意义上的**张量降维**(tensor-rank-reducing),比如将一个向量降维成一个数,或者是将一个 tensor 降维到某一行或者某一列等。在代码中,通常具有 `x = f(x, v[i])` 这种形式,其中 `x` 是一个叠加器,`f` 是一个聚合函数,而 `v[i]` 则是将要被聚合的值。一般来说,`f` 要求满足结合律,这样不管执行的顺序如何,都不会影响计算结果。 请注意,我们可以将这种`count_heads` 模式推广。 我们使用了两个显式的 [`@spawnat`](@ref) 语句,将并行性限制为两个进程。 要在任意数量的进程上运行,我们可以使用 *并行for循环*,在分布式内存中运行,可以在 Julia 中使用 [`@distributed`](@ref) 编写,如下所示: ```julia nheads = @distributed (+) for i = 1:200000000 Int(rand(Bool)) end ``` 上面的写法将多次迭代分配到了不同的线程,然后通过一个聚合函数(这里是 `(+)`)合并计算结果,其中,每次迭代的结果作为 `for` 循环中的表达式的结果,最后整个循环的结果聚合后得到最终的结果。 注意,尽管这里 for 循环看起来跟串行的 for 循环差不多,实际表现完全不同。这里的迭代并没有特定的执行顺序,而且由于所有的迭代都在不同的进程中进行,其中变量的写入对全局来说不可见。所有并行的 for 循环中的变量都会复制并广播到每个进程。 比如,下面这段代码并不会像你想要的那样执行: ```julia a = zeros(100000) @distributed for i = 1:100000 a[i] = i end ``` 这段代码并不会把 `a` 的所有元素初始化,因为每个进程都会有一份 `a` 的拷贝,因此类似的 for 循环一定要避免。幸运的是,[共享数组](@ref man-shared-arrays) 可以用来突破这种限制: ```julia using SharedArrays a = SharedArray{Float64}(10) @distributed for i = 1:10 a[i] = i end ``` 当然,对于 for 循环外面的变量来说,如果是只读的话,使用起来完全没问题: ```julia a = randn(1000) @distributed (+) for i = 1:100000 f(a[rand(1:end)]) end ``` 这里每次迭代都会从共享给每个进程的向量 `a` 中随机选一个样本,然后用来计算 `f`。 如你所见,如果不需要,可以省略归约运算符。 在这种情况下,循环异步执行,即它在所有可用的 worker 上产生独立的任务,并立即返回一个 [`Future`](@ref Distributed.Future) 数组,而无需等待完成。 调用者可以稍后通过调用 [`fetch`](@ref) 来等待 [`Future`](@ref Distributed.Future) 完成,或者通过添加前缀 [`@sync`](@ref),比如 `@sync @distributed for`,来等待循环结束。 在一些不需要聚合函数的情况下,我们可能只是像对某个范围内的整数应用一个函数(或者,更一般地,某个序列中的所有元素),这种操作称作**并行的 map**,在 Julia 中有一个对应的函数 [`pmap`](@ref)。例如,可以像下面这样计算一些随机大矩阵的奇异值: ```julia-repl julia> M = Matrix{Float64}[rand(1000,1000) for i = 1:10]; julia> pmap(svdvals, M); ``` Julia 中的 [`pmap`](@ref) 是被设计用来处理一些计算量比较复杂的函数的并行化的。与之对比的是,`@distributed for` 是用来处理一些每次迭代计算都很轻量的计算,比如简单地对两个数求和。[`pmap`](@ref) 和 `@distributed for` 都只会用到 worker 的进程。对于 `@distributed for` 而言,最后的聚合计算由发起者的进程完成。 ## 远程引用和 AbstractChannel 远程引用通常指某种 `AbstractChannel` 的实现。 `AbstractChannel`(如`Channel`)的具体实现,需要实现 [`put!`](@ref), [`take!`](@ref), [`fetch`](@ref) , [`isready`](@ref) 和 [`wait`](@ref)。 [`Future`](@ref Distributed.Future) 所引用的远程对象存储在`Channel{Any}(1)` 中,即大小为 1 的、能够容纳 `Any` 类型对象的 `Channel` 。 [`RemoteChannel`](@ref) 可以被反复写入,可以指向任意大小和类型的 channel(或者是任意 `AbstractChannel` 的实现)。 `RemoteChannel(f::Function, pid)()` 构造器可以构造一些引用,而这些引用指向的 channel 可以容纳多个某种具体类型的数据。其中 `f` 是将要在 `pid` 上执行的函数,其返回值必须是 `AbstractChannel` 类型。 例如,`RemoteChannel(()->Channel{Int}(10), pid)` 会创建一个 channel,其类型是 `Int`,容量是 10,这个 channel 存在于 `pid` 进程中。 针对 [`RemoteChannel`](@ref) 的 [`put!`](@ref), [`take!`](@ref), [`fetch`](@ref), [`isready`](@ref) 和 [`wait`](@ref) 方法会被重定向到其底层存储着 channel 的进程。 因此,[`RemoteChannel`](@ref) 可以用来引用用户自定义的 `AbstractChannel` 对象。在 [Examples repository](https://github.com/JuliaAttic/Examples) 中的 `dictchannel.jl` 文件中有一个简单的例子,其中使用了一个字典用于远端存储。 ## Channel 和 RemoteChannel * 一个 [`Channel`](@ref) 仅对局部的进程可见,worker 2 无法直接访问 worker 3 上的 `Channel`,反之亦如此。不过 [`RemoteChannel`](@ref) 可以跨 worker 获取和写入数据。 * [`RemoteChannel`](@ref) 可以看作是对 `Channel` 的封装。 * [`RemoteChannel`](@ref) 的 `pid` 就是其封装的 channel 所在的进程 id。 * 任意拥有 [`RemoteChannel`](@ref) 引用的进程都可以对其进行读写,数据会自动发送到 [`RemoteChannel`](@ref) 底层 channel 的进程(或从中获取数据) * 序列化 `Channel` 会将其中的所有数据也都序列化,因此反序列化的时候也就可以得到一个原始数据的拷贝。 * 不过,对 [`RemoteChannel`](@ref) 的序列化则只会序列化其底层指向的 channel 的 id,因此反序列化之后得到的对象仍然会指向之前存储的对象。 如上的通道示例可以修改为进程间通信,如下所示 首先,起 4 个 worker 进程处理同一个 remote channel `jobs`,其中的每个 job 都有一个对应的 `job_id`,然后每个 task 读取一个 `job_id`,然后模拟随机等待一段时间,然后往存储结果的 `RemoteChannel` 中写入一个 Tuple 对象,其中包含 `job_id` 和等待的时间。最后将结果打印出来。 ```julia-repl julia> addprocs(4); # add worker processes julia> const jobs = RemoteChannel(()->Channel{Int}(32)); julia> const results = RemoteChannel(()->Channel{Tuple}(32)); julia> @everywhere function do_work(jobs, results) # define work function everywhere while true job_id = take!(jobs) exec_time = rand() sleep(exec_time) # simulates elapsed time doing actual work put!(results, (job_id, exec_time, myid())) end end julia> function make_jobs(n) for i in 1:n put!(jobs, i) end end; julia> n = 12; julia> errormonitor(@async make_jobs(n)); # feed the jobs channel with "n" jobs julia> for p in workers() # start tasks on the workers to process requests in parallel remote_do(do_work, p, jobs, results) end julia> @elapsed while n > 0 # print out results job_id, exec_time, where = take!(results) println("$job_id finished in $(round(exec_time; digits=2)) seconds on worker $where") global n = n - 1 end 1 finished in 0.18 seconds on worker 4 2 finished in 0.26 seconds on worker 5 6 finished in 0.12 seconds on worker 4 7 finished in 0.18 seconds on worker 4 5 finished in 0.35 seconds on worker 5 4 finished in 0.68 seconds on worker 2 3 finished in 0.73 seconds on worker 3 11 finished in 0.01 seconds on worker 3 12 finished in 0.02 seconds on worker 3 9 finished in 0.26 seconds on worker 5 8 finished in 0.57 seconds on worker 4 10 finished in 0.58 seconds on worker 2 0.055971741 ``` ### 远程调用和分布式垃圾回收 远程引用所指向的对象可以在其所有引用都被集群删除之后被释放掉。 存储值的节点会跟踪哪些 worker 引用了它。 每次将 [`RemoteChannel`](@ref) 或(未获取的)[`Future`](@ref Distributed.Future) 序列化为 worker 时,都会通知引用指向的节点。 并且每次在本地对 [`RemoteChannel`](@ref) 或(未获取的)[`Future`](@ref Distributed.Future) 进行垃圾回收时,都会再次通知拥有该值的节点。 这是在内部集群感知序列化程序中实现的。 远程引用仅在正在运行的集群的上下文中有效。 不支持对常规`IO`对象的引用进行序列化和反序列化。 上面说到的**通知**都是通过发送"跟踪"信息来实现的,当一个引用被序列化的时候,就会发送"添加引用"的信息,而一个引用被本地的垃圾回收器回收的时候,就会发送一个"删除引用"的信息。 由于 [`Future`](@ref Distributed.Future) 是一次性写入并在本地缓存,因此 [`fetch`](@ref)ing 一个 [`Future`](@ref Distributed.Future) 的行为也会更新拥有该值的节点上的引用跟踪信息。 一旦指向某个值的引用都被删除了,对应的节点会将其释放。 使用 [`Future`](@ref Distributed.Future),将已获取的[`Future`](@ref Distributed.Future)序列化到其他节点也会发送该值,因为此时原始远程存储可能已收集该值了。 此外需要注意的是,本地的垃圾回收到底发生在什么时候取决于具体对象的大小以及当时系统的内存压力。 在远程引用的情况下,本地引用对象的大小非常小,而存储在远程节点上的值可能非常大。 由于可能不会立即收集本地对象,因此在 [`RemoteChannel`](@ref) 的本地实例或未获取的 [`Future`](@ref Distributed.Future) 上显式调用 [`finalize`](@ref) 是一个好习惯 。 由于在 [`Future`](@ref Distributed.Future) 上调用 [`fetch`](@ref) 也会从远程存储中删除其引用,因此在获取的 [`Future`](@ref Distributed.Future) 上不需要这样做。 显式调用 [`finalize`](@ref) 会导致立即向远程节点发送消息以继续并删除其对该值的引用。 一旦执行了 finalize 之后,引用就不可用了。 ## 本地调用 数据必须复制到远程节点以供执行。 远程调用和数据存储到不同节点上的 [`RemoteChannel`](@ref) / [`Future`](@ref Distributed.Future) 时都是这种情况。 正如预期的那样,这会在远程节点上生成序列化对象的副本。 但是,当目的节点是本地节点时,即调用进程id与远程节点id相同,则作为本地调用执行。 它通常(并非总是)在不同的 Task 中执行 - 但没有数据的序列化/反序列化。 因此,该调用引用了与传递相同的对象实例 - 没有创建副本。 这种行为在下面突出显示: ```julia-repl julia> using Distributed; julia> rc = RemoteChannel(()->Channel(3)); # RemoteChannel created on local node julia> v = [0]; julia> for i in 1:3 v[1] = i # Reusing `v` put!(rc, v) end; julia> result = [take!(rc) for _ in 1:3]; julia> println(result); Array{Int64,1}[[3], [3], [3]] julia> println("Num Unique objects : ", length(unique(map(objectid, result)))); Num Unique objects : 1 julia> addprocs(1); julia> rc = RemoteChannel(()->Channel(3), workers()[1]); # RemoteChannel created on remote node julia> v = [0]; julia> for i in 1:3 v[1] = i put!(rc, v) end; julia> result = [take!(rc) for _ in 1:3]; julia> println(result); Array{Int64,1}[[1], [2], [3]] julia> println("Num Unique objects : ", length(unique(map(objectid, result)))); Num Unique objects : 3 ``` 可以看出,本地拥有的 [`RemoteChannel`](@ref) 上的 [`put!`](@ref) 在调用之间修改了相同的对象 `v` 会导致存储相同的单个对象实例。 与当拥有 `rc` 的节点是不同节点时创建的 `v` 副本相反。 需要注意的是,这通常不是问题。 只有当对象既存储在本地又在调用后被修改时,才需要考虑这一点。 在这种情况下,存储对象的 `deepcopy` 可能是合适的。 对于本地节点上的远程调用也是如此,如下例所示: ```julia-repl julia> using Distributed; addprocs(1); julia> v = [0]; julia> v2 = remotecall_fetch(x->(x[1] = 1; x), myid(), v); # Executed on local node julia> println("v=$v, v2=$v2, ", v === v2); v=[1], v2=[1], true julia> v = [0]; julia> v2 = remotecall_fetch(x->(x[1] = 1; x), workers()[1], v); # Executed on remote node julia> println("v=$v, v2=$v2, ", v === v2); v=[0], v2=[1], false ``` 再次可以看出,对本地节点的远程调用就像直接调用一样。调用修改作为参数传递的本地对象。 在远程调用中,它对参数的副本进行操作。 重复一遍,一般来说这不是问题。 如果本地节点也被用作计算节点,并且在调用后使用的参数,则需要考虑此行为,并且如果需要,必须将参数的深拷贝传递给在本地节点上唤起的调用。 对远程节点的调用将始终对参数的副本进行操作。 ## [共享数组](@id man-shared-arrays) 共享数组使用系统共享内存将数组映射到多个进程上,尽管和 [`DArray`](https://github.com/JuliaParallel/DistributedArrays.jl) 有点像,但其实际表现有很大不同。在 [`DArray`](https://github.com/JuliaParallel/DistributedArrays.jl) 中,每个进程可以访问数据中的一块,但任意两个进程都不能共享同一块数据,而对于 [`SharedArray`](@ref),每个进程都可以访问整个数组。如果你想在一台机器上,让一大块数据能够被多个进程访问到,那么 [`SharedArray`](@ref) 是个不错的选择。 共享数组由 `SharedArray` 提供,必须在所有相关的 worker 中都显式地加载。 对 [`SharedArray`](@ref) 索引(访问和复制)操作就跟普通的数组一样,由于底层的内存对本地的进程是可见的,索引的效率很高,因此大多数单进程上的算法对 [`SharedArray`](@ref) 来说都是适用的,除非某些算法必须使用 [`Array`](@ref) 类型(此时可以通过调用 [`sdata`](@ref) 来获取 [`SharedArray`](@ref) 数组)。对于其它类型的 `AbstractArray` 类型数组来说,[`sdata`](@ref) 仅仅会返回数组本身,因此,可以放心地使用 [`sdata`](@ref) 对任意类型的 `Array` 进行操作。 共享数组可以通过以下形式构造: ```julia SharedArray{T,N}(dims::NTuple; init=false, pids=Int[]) ``` 它在由 `pids` 指定的进程中创建了一个位类型为 `T` 和形状为 `dims` 的 `N` 维共享数组。 与分布式数组不同,共享数组只能从由`pids` 命名参数指定的那些参与 worker 访问(如果创建过程在同一主机上,也是如此)。 请注意,SharedArray 中仅支持 [`isbits`](@ref) 元素。 如果提供了一个类型为 `initfn(S::SharedArray)` 的 `init` 函数,那么所有相关的 worker 都会调用它。你可以让每个 worker 都在共享数组不同的地方执行 `init` 函数,从而实现并行初始化。 下面是个例子: ```julia-repl julia> using Distributed julia> addprocs(3) 3-element Array{Int64,1}: 2 3 4 julia> @everywhere using SharedArrays julia> S = SharedArray{Int,2}((3,4), init = S -> S[localindices(S)] = repeat([myid()], length(localindices(S)))) 3×4 SharedArray{Int64,2}: 2 2 3 4 2 3 3 4 2 3 4 4 julia> S[3,2] = 7 7 julia> S 3×4 SharedArray{Int64,2}: 2 2 3 4 2 3 3 4 2 7 4 4 ``` [`SharedArrays.localindices`](@ref) 提供了一个以为的切片,可以很方便地用来将 task 分配到各个进程上。当然你可以按你想要的方式做区分: ```julia-repl julia> S = SharedArray{Int,2}((3,4), init = S -> S[indexpids(S):length(procs(S)):length(S)] = repeat([myid()], length( indexpids(S):length(procs(S)):length(S)))) 3×4 SharedArray{Int64,2}: 2 2 2 2 3 3 3 3 4 4 4 4 ``` 由于所有的进程都能够访问底层的数据,因此一定要小心避免出现冲突: ```julia @sync begin for p in procs(S) @async begin remotecall_wait(fill!, p, S, p) end end end ``` 上面的代码会导致不确定的结果,因为每个进程都将**整个**数组赋值为其 `pid`,从而导致最后一个执行完成的进程会保留其 `pid`。 考虑更复杂的一种情况: ```julia q[i,j,t+1] = q[i,j,t] + u[i,j,t] ``` 这个例子中,如果首先将任务用按照一维的索引作区分,那么就会出问题:如果 `q[i,j,t]` 位于分配给某个 worker 的最后一个位置,而 `q[i,j,t+1]` 位于下一个 worker 的开始位置,那么后面这个 worker 开始计算的时候,可能 `q[i,j,t]` 还没有准备好,这时候,更好的做法是,手动分区,比如可以定义一个函数,按照 `(irange,jrange)` 给每个 worker 分配任务。 ```julia-repl julia> @everywhere function myrange(q::SharedArray) idx = indexpids(q) if idx == 0 # This worker is not assigned a piece return 1:0, 1:0 end nchunks = length(procs(q)) splits = [round(Int, s) for s in range(0, stop=size(q,2), length=nchunks+1)] 1:size(q,1), splits[idx]+1:splits[idx+1] end ``` 然后定义计算内核: ```julia-repl julia> @everywhere function advection_chunk!(q, u, irange, jrange, trange) @show (irange, jrange, trange) # display so we can see what's happening for t in trange, j in jrange, i in irange q[i,j,t+1] = q[i,j,t] + u[i,j,t] end q end ``` 然后定义一个 wrapper: ```julia-repl julia> @everywhere advection_shared_chunk!(q, u) = advection_chunk!(q, u, myrange(q)..., 1:size(q,3)-1) ``` 接下来,比较三个不同的版本,第一个是单进程版本: ```julia-repl julia> advection_serial!(q, u) = advection_chunk!(q, u, 1:size(q,1), 1:size(q,2), 1:size(q,3)-1); ``` 然后是使用 [`@distributed`](@ref): ```julia-repl julia> function advection_parallel!(q, u) for t = 1:size(q,3)-1 @sync @distributed for j = 1:size(q,2) for i = 1:size(q,1) q[i,j,t+1]= q[i,j,t] + u[i,j,t] end end end q end; ``` 最后是使用分区: ```julia-repl julia> function advection_shared!(q, u) @sync begin for p in procs(q) @async remotecall_wait(advection_shared_chunk!, p, q, u) end end q end; ``` 如果创建好了 `SharedArray` 之后,计算这些函数的执行时间,那么可以得到以下结果(用 `julia -p 4` 启动): ```julia-repl julia> q = SharedArray{Float64,3}((500,500,500)); julia> u = SharedArray{Float64,3}((500,500,500)); ``` 先执行一次以便 JIT 编译,然后用 [`@time`](@ref) 宏测试其第二次执行的时间: ```julia-repl julia> @time advection_serial!(q, u); (irange,jrange,trange) = (1:500,1:500,1:499) 830.220 milliseconds (216 allocations: 13820 bytes) julia> @time advection_parallel!(q, u); 2.495 seconds (3999 k allocations: 289 MB, 2.09% gc time) julia> @time advection_shared!(q,u); From worker 2: (irange,jrange,trange) = (1:500,1:125,1:499) From worker 4: (irange,jrange,trange) = (1:500,251:375,1:499) From worker 3: (irange,jrange,trange) = (1:500,126:250,1:499) From worker 5: (irange,jrange,trange) = (1:500,376:500,1:499) 238.119 milliseconds (2264 allocations: 169 KB) ``` 这里 `advection_shared!` 最大的优势在于,最小程度地降低了 woker 之间的通信,从而让每个 worker 能针对被分配的部分持续地计算一段时间。 ### 共享数组与分布式垃圾回收 和远程引用一样,共享数组也依赖于创建节点上的垃圾回收来释放所有参与的 worker 上的引用。因此,创建大量生命周期比较短的数组,并尽可能快地显式 finilize 这些对象,代码会更高效,这样与之对用的内存和文件句柄都会更快地释放。 ## 集群管理器 Julia 通过集群管理器实现对多个进程(所构成的逻辑上的集群)的启动,管理以及网络通信。一个 `ClusterManager` 负责: * 在一个集群环境中启动 worker 进程 * 管理每个 worker 生命周期内的事件 * (可选),提供数据传输 一个 Julia 集群由以下特点: * 初始进程,称为 `master`,其 `id` 为 1 * 只有 master 进程可以增加或删除 worker 进程 * 所有进程之间都可以直接通信 worker 之间的连接(用的是内置的 TCP/IP 传输)按照以下方式进行: * master 进程对一个 `ClusterManager` 对象调用 [`addprocs`](@ref) * [`addprocs`](@ref) 调用对应的 [`launch`](@ref) 方法,然后在对应的机器上启动相应数量的 worker 进程 * 每个 worker 监听一个端口,然后将其 host 和 port 信息传给 [`stdout`](@ref) * 集群管理器捕获 [`stdout`](@ref) 中每个 worker 的信息,并提供给 master 进程 * master 进程解析信息并与相应的 worker 建立 TCP/IP 连接 * 每个 worker 都会被通知集群中的其它 worker * 每个 worker 与 `id` 小于自己的 worker 连接 * 这样,一个网络就建立了,从而,每个 worker 都可以与其它 worker 建立连接 尽管默认的传输层使用的是 [`TCPSocket`](@ref),对于一个自定义的集群管理器来说,完全可以使用其它传输方式。 Julia 提供了两种内置的集群管理器: * `LocalManager`,调用 [`addprocs()`](@ref) 或 [`addprocs(np::Integer)`](@ref) 时会用到。 * `SSHManager`,调用 [`addprocs(hostnames::Array)`](@ref) 时,传递一个 hostnames 的列表。 `LocalManager` 用来在同一个 host 上启动多个 worker,从而利用多核/多处理器硬件。 因此,一个最小的集群管理器需要: * 是一个 `ClusterManager` 抽象类的一个子类 * 实现 [`launch`](@ref) 接口,用来启动新的 worker * 实现 [`manage`](@ref),在一个 worker 的生命周期中多次被调用(例如,发送中断信号) [`addprocs(manager::FooManager)`](@ref addprocs) 需要 `FooManager` 实现: ```julia function launch(manager::FooManager, params::Dict, launched::Array, c::Condition) [...] end function manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol) [...] end ``` 作为一个例子,我们来看下 `LocalManager` 是怎么实现的: ```julia struct LocalManager <: ClusterManager np::Integer end function launch(manager::LocalManager, params::Dict, launched::Array, c::Condition) [...] end function manage(manager::LocalManager, id::Integer, config::WorkerConfig, op::Symbol) [...] end ``` [`launch`](@ref) 方法接收以下参数: * `manager::ClusterManager`: 调用 [`addprocs`](@ref) 时所用到的集群管理器 * `params::Dict`: 所有的关键字参数都会传递到 [`addprocs`](@ref) 中 * `launched::Array`: 用来存储一个或多个 `WorkerConfig` * `c::Condition`: 在 workers 启动后被通知的条件变量 [`launch`](@ref) 会在一个异步的task中调用,该 task 结束之后,意味着所有请求的 worker 都已经启动好了。因此,[`launch`](@ref) 函数**必须**在所有 worker 启动之后,尽快退出。 新启动的 worker 之间采用的是多对多的连接方式。在命令行中指定参数 `--worker[=<cookie>]` 会让所有启动的进程把自己当作 worker,然后通过 TCP/IP 构建连接。 集群中所有的 worker 默认使用同一个 master 的 [cookie](@ref man-cluster-cookie)。如果 cookie 没有指定,(比如没有通过 `--worker` 指定),那么 worker 会尝试从它的标准输入中读取。`LocalManager` 和 `SSHManager` 都是通过标准输入来将 cookie 传递给新启动的 worker。 默认情况下,一个 worker 会监听从 [`getipaddr()`](@ref) 函数返回的地址上的一个开放端口。若要指定监听的地址,可以通过额外的参数 `--bind-to bind_addr[:port]` 指定,这对于多 host 的情况来说很方便。 对于非 TCP/IP 传输,可以选择 MPI 作为一种实现,此时一定**不要**指定 `--worker` 参数,另外,新启动的 worker 必须调用 `init_worker(cookie)` 之后再使用并行的结构体。 对于每个已经启动的 worker,[`launch`](@ref) 方法必须往 `launched` 中添加一个 `WorkerConfig` 对象(相应的值已经初始化)。 ```julia mutable struct WorkerConfig # Common fields relevant to all cluster managers io::Union{IO, Nothing} host::Union{AbstractString, Nothing} port::Union{Integer, Nothing} # Used when launching additional workers at a host count::Union{Int, Symbol, Nothing} exename::Union{AbstractString, Cmd, Nothing} exeflags::Union{Cmd, Nothing} # External cluster managers can use this to store information at a per-worker level # Can be a dict if multiple fields need to be stored. userdata::Any # SSHManager / SSH tunnel connections to workers tunnel::Union{Bool, Nothing} bind_addr::Union{AbstractString, Nothing} sshflags::Union{Cmd, Nothing} max_parallel::Union{Integer, Nothing} # Used by Local/SSH managers connect_at::Any [...] end ``` `WorkerConfig` 中的大多数字段都是内置的集群管理器会用到,对于自定义的管理器,通常只需要指定 `io` 或 `host`/`port`: * 如果指定了 `io`,那么就会用来读取 host/port 信息。每个 worker 会在启动时打印地址和端口,这样 worker 就可以自由监听可用的端口,而不必手动配置 worker 的端口。 * 如果 `io` 没有指定,那么 `host` 和 `port` 就会用来连接。 * `count`,`exename` 和 `exeflags` 用于从一个 worker 上启动额外的 worker。例如,一个集群管理器可能对每个节点都只启动一个 worker,然后再用它来启动额外的 worker。 * `count` 可以是一个整数 `n`,用来指定启动 `n` 个 worker * `count` 还可以是 `:auto`,用来启动跟那台机器上 CPU 个数(逻辑上的核的个数)相同的 worker * `exename` 是 `julia` 可执行文件的全路径 * `exeflags` 应该设置成传递给将要启动的 worker 命令行参数 * `tunnel`, `bind_addr`, `sshflags` 和 `max_parallel` 会在从 worker 与 master 进程建立 ssh 隧道时用到 * `userdata` 用来提供给自定义集群管理器存储自己的 worker 相关的信息 `manage(manager::FooManager, id::Integer, config::WorkerConfig, op::Symbol)` 会在一个 worker 生命周期中的不同时刻被调用,其中 op 的值可能是: * `:register`/`:deregister`,从 Julia 的 worker 池子中添加/删除一个 worker * `:interrupt`,当 `interrupt(workers)` 被调用是,此时,`ClusterManager` 应该给相应的 worker 发送终端信号 * `:finalize`,用于清理操作。 ### 自定义集群管理器的传输方式 将默认的 TCP/IP 多对多 socket 连接替换成一个自定义的传输层需要做很多工作。每个 Julia 进程都有与其连接的 worker 数量相同的通信 task。例如,在一个有 32 个进程的多对多集群中: * 每个进程都有31个通信task * 每个 task 在一个**消息处理循环**中从一个远端 worker 读取所有的输入信息 * 每个消息处理循环等待一个 `IO` 对象(比如,在默认实现中是一个 [`TCPSocket`](@ref)),然后读取整个信息,处理,等待下一个 * 发送消息则可以直接在任意 Julia task 中完成,而不只是通信 task,同样,也是通过相应的 `IO` 对象 要替换默认的传输方式,需要新的实现能够在远程 worker 之间建立连接,同时提供一个可以用来被消息处理循环等待的 `IO` 对象。集群管理器的回调函数需要实现如下函数: ```julia connect(manager::FooManager, pid::Integer, config::WorkerConfig) kill(manager::FooManager, pid::Int, config::WorkerConfig) ``` 默认的实现(使用的是 TCP/IP socket)是 `connect(manager::ClusterManager, pid::Integer, config::WorkerConfig)`。 `connect` 需要返回一对 `IO` 对象,一个用于从 `pid` worker 读取数据,另一个用于往 `pid` 写数据。自定义的集群管理器可以用内存中的 `BUfferStream` 作为一个管道将自定义的(很可能是非 `IO` 的)传输与 Julia 内置的并行基础设施衔接起来。 `BufferStream` 是一个内存中的 [`IOBuffer`](@ref),其表现很像 `IO`,就是一个**流**(stream),可以异步地处理。 在 [Examples repository](https://github.com/JuliaAttic/Examples) 的 `clustermanager/0mq` 目录中,包含一个使用 ZeroMQ 连接 Julia worker 的例子,用的是星型拓补结构。需要注意的是:Julia 的进程仍然是**逻辑上**相互连接的,任意 worker 都可以与其它 worker 直接相连而无需感知到 0MQ 作为传输层的存在。 在使用自定义传输的时候: * Julia 的 workers 必须**不能**通过 `--worker` 启动。如果启动的时候使用了 `--worker`,那么新启动的 worker 会默认使用基于 TCP/IP socket 的实现 * 对于每个 worker 逻辑上的输入连接,必须调用 `Base.process_messages(rd::IO, wr::IO)()`,这会创建一个新的 task 来处理 worker 消息的读写 * `init_worker(cookie, manager::FooManager)` 必须作为 worker 进程初始化的一部分呢被调用 * `WorkerConfig `中的 `connect_at::Any` 字段可以被集群管理器在调用 [`launch`](@ref) 的时候设置,该字段的值会发送到所有的 [`connect`](@ref) 回调中。通常,其中包含的是**如何连接到**一个 worker 的信息。例如,在 TCP/IP socket 传输中,用这个字段存储 `(host, port)` 来声明如何连接到一个 worker。 `kill(manager, pid, config)` 用来从一个集群中删除一个 worker,在 master 进程中,对应的 `IO` 对象必须通过对应的实现来关闭,从而保证正确地释放资源。默认的实现简单地对指定的远端 worker 执行 `exit()` 即可。 在例子目录中,`clustermanager/simple` 展示了一个简单地实现,使用的是 UNIX 下的 socket。 ### LocalManager 和 SSHManager 的网络要求 Julia 集群设计的时候,默认是在一个安全的环境中执行,比如本地的笔记本,部门的集群,甚至是云端。这部分将介绍 `LocalManager` 和 `SSHManager` 的网络安全要点: * master 进程不监听任何端口,它只负责向外连接 worker * 每个 worker 都只绑定一个本地的接口,同时监听一个操作系统分配的临时端口。 * `addprocs(N)` 使用的 `LocalManager`,默认只会绑定到回环接口(loopback interface),这就意味着,之后在远程主机上(恶意)启动的 worker 无法连接到集群中,在执行 `addprocs(4)` 之后,又跟一个 `addprocs(["remote_host"])` 会失败。有些用户可能希望创建一个集群同时管理本地系统和几个远端系统,这可以通过在绑定 `LocalManager` 到外部网络接口的时候,指定一个 `restrict` 参数:`addprocs(4; restrict=false)` * `addprocs(list_of_remote_hosts)` 使用的 `SSHManager` 会通过 SSH 启动远程机上的 worker。 默认 SSH 只会用来启动 Julia 的 worker。随后的 master-worker 和 worker-worker 连接使用的是普通的、未加密的 TCP/IP 通信。 远程机必须开启免密登陆。 额外的 SSH 标记或认证信息会通过关键字参数 `sshflags` 指定。 * `addprocs(list_of_remote_hosts; tunnel=true, sshflags=<ssh keys and other flags>)` 在我们希望给 master-worker 也使用 SSH 连接的时候很有用。 一个典型的场景是本地的笔记本 运行 Julia ERPL (做为 master)和云上的其他机器,比如 Amazon EC2,构成集群。 这时候远程机器只要开启 22 端口就可以,然后要有 SSH 客户端 通过公约基础设施(PKI)认证过。授权信息可以通过 `sshflags` 生效,比如 ```sshflags=`-i <keyfile>` ```。 在一个所有节点联通的拓扑网中(默认情况下是这样的),所有的 worker 节点都通过普通 TCP socket 通信互相连接。 这样集群的安全策略就必须允许 worker 节点间 通过操作系统分配的临时端口范围自由连接。 所有 worker-worker 间(都是 SSH)的安全和加密或者信息的加密 都可以通过自定义 `ClusterManager` 完成。 * 如果将 `multiplex=true` 指定为 [`addprocs`](@ref) 的选项,则 SSH 多路复用用于在 master 和 worker 之间创建隧道。 如果你自己配置了 SSH 多路复用并且已经建立了连接,则无论 `multiplex` 选项如何,都会使用 SSH 多路复用。 如果启用了多路复用,则使用现有连接(ssh 中的 `-O forward` 选项)设置转发。 如果你的服务器需要密码验证,那么这就很有用了; 你可以通过在 [`addprocs`](@ref) 之前登录服务器来避免在 Julia 中进行身份验证。 除非使用现有的多路复用连接,否则在会话期间控制套接字将位于 `~/.ssh/julia-%r@%h:%p`。 请注意,如果你在一个节点上创建多个进程并启用多路复用,带宽可能会受到限制,因为在这种情况下,进程共享一个多路复用 TCP 连接。 ### [集群 Cookie](@id man-cluster-cookie) 集群上所有的进程都共享同一个 cookie,默认是 master 进程随机生成的字符串。 * [`cluster_cookie()`](@ref) 返回 cookie,而 `cluster_cookie(cookie)()` 设置并返回新的 cookie。 * 所有的连接都进行双向认证,从而保证只有 master 启动的 worker 才能相互连接。 * cookie 可以在 worker 启动的时候,通过参数 `--worker=<cookie>` 指定,如果参数 `--worker` 没有指定 cookie,那么 worker 会从它的标准输入中 ([`stdin`](@ref)) 读取, `stdin` 会在 cookie 获取之后立即关闭。 * `ClusterManager` 可以通过 [`cluster_cookie()`](@ref) 从 master 中过去 cookie,不适用默认 TCP/IP 传输的集群管理器(即没有指定 `--worker`)必须用于 master 相同的 cookie 调用 `init_worker(cookie, manager)`。 注意,在对安全性要求很高的环境中,可以通过自定义 `ClusterManager` 实现。例如,cookie 可以提前共享,然后不必再启动参数中指定。 ## 指定网络拓补结构(实验性功能) 传递给 [`addprocs`](@ref) 的关键字参数 `topology` 用于指定 workers 必须如何相互连接: * `:all_to_all`,默认的,所有 worker 之间相互都连接 * `:master_worker`,只有主进程,即 `pid` 为 1 的进程能够与 worker 建立连接 * `:custom`: 集群管理器的 `launch` 方法通过 `WorkerConfig` 中的 `ident` 和 `connect_idents` 指定连接的拓补结构。一个 worker 通过集群管理器提供的 `ident` 来连接到所有 `connect_idents` 指定的 worker。 关键字参数 `lazy=true|false` 只会影响 `topology` 选项中的 `:all_to_all`。如果是 `true`,那么集群启动的时候 master 会连接所有的 worker,然后 worker 之间的特定连接会在初次唤醒的是建立连接,这有利于降低集群初始化的时候对资源的分配。`lazy` 的默认值是 `true`。 目前,在没有建立连接的两个 worker 之间传递消息会出错,目前该行为是实验性的,未来的版本中可能会改变。 ## 一些值得关注的外部库 除了 Julia 自带的并行机制之外,还有许多外部的库值得一提。例如 [MPI.jl](https://github.com/JuliaParallel/MPI.jl) 提供了一个 `MPI` 协议的 Julia 的封装,或者是在 [共享数组](@ref) 提到的 [DistributedArrays.jl](https://github.com/JuliaParallel/Distributedarrays.jl),此外尤其值得一提的是 Julia 的 GPU 编程生态,其包括: 1. 底层(C内核)的 [OpenCL.jl](https://github.com/JuliaGPU/OpenCL.jl) 和 [CUDAdrv.jl](https://github.com/JuliaGPU/CUDAdrv.jl),分别提供了 OpenCL 和 CUDA 的封装。 2. 底层(Julia 内核)的接口,如 [CUDAnative.jl](https://github.com/JuliaGPU/CUDAnative.jl),提供了 Julia 原生的 CUDA 实现。 3. 高层的特定抽象,如 [CuArrays.jl](https://github.com/JuliaGPU/CuArrays.jl) 和 [CLArrays.jl](https://github.com/JuliaGPU/CLArrays.jl)。 4. 高层的库,如 [ArrayFire.jl](https://github.com/JuliaComputing/ArrayFire.jl) 和 [GPUArrays.jl](https://github.com/JuliaGPU/GPUArrays.jl)。 下面的例子将介绍如何用 `DistributedArrays.jl` 和 `CuArrays.jl` 通过 `distribute()` 和 `CuArray()` 将数组分配到多个进程。 记住在载入 `DistributedArrays.jl` 时,需要用 [`@everywhere`](@ref) 将其载入到多个进程中。 ```julia-repl $ ./julia -p 4 julia> addprocs() julia> @everywhere using DistributedArrays julia> using CuArrays julia> B = ones(10_000) ./ 2; julia> A = ones(10_000) .* π; julia> C = 2 .* A ./ B; julia> all(C .≈ 4*π) true julia> typeof(C) Array{Float64,1} julia> dB = distribute(B); julia> dA = distribute(A); julia> dC = 2 .* dA ./ dB; julia> all(dC .≈ 4*π) true julia> typeof(dC) DistributedArrays.DArray{Float64,1,Array{Float64,1}} julia> cuB = CuArray(B); julia> cuA = CuArray(A); julia> cuC = 2 .* cuA ./ cuB; julia> all(cuC .≈ 4*π); true julia> typeof(cuC) CuArray{Float64,1} ``` 请记住,CUDAnative.jl[^2] 目前不支持某些 Julia 功能,尤其是像 `sin` 这样的一些函数需要替换为 `CUDAnative.sin`(cc:@maleadt)。 下面的例子中,通过 `DistributedArrays.jl` 和 `CuArrays.jl` 将一个数组分配到多个进程,然后调用一个函数。 ```julia function power_method(M, v) for i in 1:100 v = M*v v /= norm(v) end return v, norm(M*v) / norm(v) # or (M*v) ./ v end ``` `power_method` 重复创建一个新的向量然后对其归一化,这里并没有在函数中指定类型信息,来看看是否对前面提到的类型适用: ```julia-repl julia> M = [2. 1; 1 1]; julia> v = rand(2) 2-element Array{Float64,1}: 0.40395 0.445877 julia> power_method(M,v) ([0.850651, 0.525731], 2.618033988749895) julia> cuM = CuArray(M); julia> cuv = CuArray(v); julia> curesult = power_method(cuM, cuv); julia> typeof(curesult) CuArray{Float64,1} julia> dM = distribute(M); julia> dv = distribute(v); julia> dC = power_method(dM, dv); julia> typeof(dC) Tuple{DistributedArrays.DArray{Float64,1,Array{Float64,1}},Float64} ``` 最后,我们来看看 `MPI.jl`,这个库时 Julia 对 MPI 协议的封装。一一介绍其中的每个函数太累赘了,这里领会其实现协议的方法就够了。 考虑下面这个简单的脚本,它做的只是调用每个子进程,然后初始化其 rank,然后在 master 访问时,对 rank 求和。 ```julia import MPI MPI.Init() comm = MPI.COMM_WORLD MPI.Barrier(comm) root = 0 r = MPI.Comm_rank(comm) sr = MPI.Reduce(r, MPI.SUM, root, comm) if(MPI.Comm_rank(comm) == root) @printf("sum of ranks: %s\n", sr) end MPI.Finalize() ``` ``` mpirun -np 4 ./julia example.jl ``` [^1]: In this context, MPI refers to the MPI-1 standard. Beginning with MPI-2, the MPI standards committee introduced a new set of communication mechanisms, collectively referred to as Remote Memory Access (RMA). The motivation for adding rma to the MPI standard was to facilitate one-sided communication patterns. For additional information on the latest MPI standard, see <https://mpi-forum.org/docs>. [^2]: [Julia GPU man pages](http://juliagpu.github.io/CUDAnative.jl/stable/man/usage.html#Julia-support-1)
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
10093
# [文档](@id man-documentation) Julia允许开发者和用户,使用其内置的文档系统更加便捷地为函数、类型以及其他对象编写文档。   基础语法很简单:紧接在对象(函数,宏,类型和实例)之前的字符串都会被认为是对应对象的文档(称作 *docstrings*)。 注意不要在 docstring 和文档对象之间有空行或者注释。 这里有个基础的例子: ```julia "Tell whether there are too foo items in the array." foo(xs::Array) = ... ``` 文档会被翻译成 [Markdown](https://en.wikipedia.org/wiki/Markdown),所以你可以 使用缩进和代码块来分隔代码示例和文本。从技术上来说,任何对象 都可以作为 metadata 与任何其他对象关联;Markdown 是默认的,但是可以创建 其它字符串宏并传递给 `@doc` 宏来使用其他格式。 !!! note Markdown 支持由 `Markdown` 标准库实现,有关支持语法的完整列表,请参阅其[文档](@ref markdown_stdlib)。 这里是一个更加复杂的例子,但仍然使用 Markdown: ````julia """ bar(x[, y]) Compute the Bar index between `x` and `y`. If `y` is unspecified, compute the Bar index between all pairs of columns of `x`. # Examples ```julia-repl julia> bar([1, 2], [1, 2]) 1 ``` """ function bar(x, y) ... ```` 如上例所示,我们推荐在写文档时遵守一些简单约定: 1. 始终在文档顶部显示函数的签名并带有四空格缩进,以便能够显示成 Julia 代码。 这和在 Julia 代码中的签名是一样的(比如 `mean(x::AbstractArray)`),或是简化版。可选参数应该尽可能与默认值一同显示(例如 `f(x, y=1)`),这与实际的 Julia 语法一致。没有默认值的可选参数应该放在括号中(例如 `f(x[, y])` 和 `f(x[, y[, z]])`)。可选的解决方法是使用多行:一个没有可选参数,其他的拥有可选参数(或者多个可选参数)。这个解决方案也可以用作给某个函数的多个方法来写文档。当一个函数接收到多个关键字参数,只在签名中包含占位符 `<keyword arguments>`(例如 `f(x; <keyword arguments>)`),并在 `# Arguments` 章节给出完整列表(参照下列第 4 点)。 2. 在简化的签名块后请包含一个描述函数能做什么或者对象代表什么的单行句。如果需要的话,在一个空行之后,在第二段提供更详细的信息。 撰写函数的文档时,单行语句应使用祈使结构(比如「Do this」、「Return that」)而非第三人称(不要写「Returns the length...」)。并且应以句号结尾。如果函数的意义不能简单地总结,更好的方法是分成分开的组合句(虽然这不应被看做是对于每种情况下的绝对要求)。 3. 不要自我重复。 因为签名给出了函数名,所以没有必要用「The function `bar`...」开始文档:直接说要点。类似地,如果签名指定了参数的类型,在描述中提到这些是多余的。 4. 只在确实必要时提供参数列表。 对于简单函数,直接在函数目的的描述中提到参数的作用常常更加清楚。参数列表只会重复再其他地方提供过的信息。但是,对于拥有多个参数的(特别是含有关键字参数的)复杂函数来说,提供一个参数列表是个好主意。在这种情况下,请在函数的一般描述之后、标题 `# Arguments` 之下插入参数列表,并在每个参数前加个着重号 `-`。参数列表应该提到参数的类型和默认值(如果有): ```julia """ ... # Arguments - `n::Integer`: the number of elements to compute. - `dim::Integer=1`: the dimensions along which to perform the computation. ... """ ``` 5. 给相关函数提供提示。 有时会存在具有功能相联系的函数。为了更易于发现相关函数,请在段落 `See also:` 中为其提供一个小列表。 ``` See also [`bar!`](@ref), [`baz`](@ref), [`baaz`](@ref). ``` 6. 请在 `# Examples` 中包含一些代码例子。 例子应尽可能按照 *doctest* 来写。*doctest* 是一个栅栏分隔开的代码块(请参阅[代码块](@ref Code-blocks)),其以 ````` ```jldoctest````` 开头并包含任意数量的提示符 `julia>` 以及用来模拟 Julia REPL 的输入和预期输出。 !!! note Doctest 由 [`Documenter.jl`](https://github.com/JuliaDocs/Documenter.jl) 支持。有关更详细的文档,请参阅 Documenter 的[手册](https://juliadocs.github.io/Documenter.jl/)。 例如在下面的 docstring 中定义了变量 `a`,预期的输出,跟在 Julia REPL 中打印的一样,出现在后面。 ````julia """ Some nice documentation here. # Examples ```jldoctest julia> a = [1 2; 3 4] 2×2 Array{Int64,2}: 1 2 3 4 ``` """ ```` !!! warning Calling `rand` and other RNG-related functions should be avoided in doctests since they will not produce consistent outputs during different Julia sessions. If you would like to show some random number generation related functionality, one option is to explicitly construct and seed your own RNG object (see [`Random`](@ref Random-Numbers)) and pass it to the functions you are doctesting. Operating system word size ([`Int32`](@ref) or [`Int64`](@ref)) as well as path separator differences (`/` or `\`) will also affect the reproducibility of some doctests. Note that whitespace in your doctest is significant! The doctest will fail if you misalign the output of pretty-printing an array, for example. 你可以运行 `make -C doc doctest=true` 来运行在 Julia 手册和 API 文档中的 doctests,这样可以确保你的例子都能正常运行。 为了表示输出结果被截断了,你应该在校验应该停止的一行写上 `[...]`。这个在当 doctest 显示有个异常被抛出时隐藏堆栈跟踪时很有用(堆栈跟踪包含对 julia 代码的行的非永久引用),例如: ````julia ```jldoctest julia> div(1, 0) ERROR: DivideError: integer division error [...] ``` ```` 那些不能进行测试的例子应该写在以 ````` ```julia````` 开头的栅栏分隔的代码块中,以便在生成的文档中正确地高亮显示。 !!! tip 例子应尽可能**独立**和**可运行**以便读者可以在不需要引入任何依赖的情况下对它们进行实验。 7. 使用倒引号来标识代码和方程。 Julia 标识符和代码摘录应该出现在倒引号 ``` ` ``` 之间来使其能高亮显示。LaTeX 语法下的方程应该插入到双倒引号 ``` `` ``` 之间。请使用 Unicode 字符而非 LaTeX 转义序列,比如 ``` ``α = 1`` ``` 而非 ``` ``\\alpha = 1`` ```。 8. 请将起始和结束的`"""`符号单独成行。 也就是说,请写: ```julia """ ... ... """ f(x, y) = ... ``` 而非: ```julia """... ...""" f(x, y) = ... ``` 这将让 docstring 的起始和结束位置更加清楚。 9. 请在代码中遵守单行长度限制。 Docstring 是使用与代码相同的工具编辑的。所以应运用同样的约定。 建议一行 92 个字符后换行。 6. 请在 `# Implementation` 章节中提供自定义类型如何实现该函数的信息。这些实现细节是针对开发者而非用户的,解释了例如哪些函数应该被重写、哪些函数自动使用恰当的回退函数等信息,最好与描述函数的主体描述分开。 5. 对于长文档字符串,可以考虑使用 `# Extended help` 头拆分文档。典型的帮助模式将只显示标题上方的内容;你可以通过添加一个 `?` 在表达的开头来查看完整的文档(即 `??foo` 而不是 `?foo`)。 ## 访问文档 文档可以在REPL中访问,也可以在 [IJulia](https://github.com/JuliaLang/IJulia.jl) 中通过键入`?`紧接函数或者宏的名字并按下`Enter`访问。例如, ```julia ?cos ?@time ?r"" ``` 会分别为相应的函数,宏或者字符显示文档。在 [Juno](http://junolab.org) 中,使用 `Ctrl-J, Ctrl-D` 会为光标处的对象显示文档。 ## 函数与方法 在Julia中函数可能有多种实现,被称为方法。虽然通用函数 一般只有一个目的,Julia允许在必要时可以对方法独立写文档。 通常,应该只有最通用的方法才有文档,或者甚至只是函数本身 (也就是在`function bar end`之前没有任何方法的对象)。特定方法应该 只因为其行为与其他通用方法有所区别才写文档。在任何情况下都不应 重复其他地方有的信息。例如 ```julia """ *(x, y, z...) Multiplication operator. `x * y * z *...` calls this function with multiple arguments, i.e. `*(x, y, z...)`. """ function *(x, y, z...) # ... [implementation sold separately] ... end """ *(x::AbstractString, y::AbstractString, z::AbstractString...) When applied to strings, concatenates them. """ function *(x::AbstractString, y::AbstractString, z::AbstractString...) # ... [insert secret sauce here] ... end help?> * search: * .* *(x, y, z...) Multiplication operator. x * y * z *... calls this function with multiple arguments, i.e. *(x,y,z...). *(x::AbstractString, y::AbstractString, z::AbstractString...) When applied to strings, concatenates them. ``` 当从通用函数里抽取文档时,每个方法的元数据会用函数`catdoc`拼接,其当然可以被自定义类型重写。 ## 进阶用法 `@doc` 宏将它的第一个参数与它的第二个参数关联在各个模块的名为 `META` 的字典中。 为了让写文档更加简单,语法分析器对宏名`@doc`特殊对待:如果`@doc`的调用只有一个参数,但是在下一行出现了另外一个表达式,那么这个表达式就会追加为宏的参数。所以接下来的语法会被分析成`@doc`的2个参数的调用: ```julia @doc raw""" ... """ f(x) = x ``` 这就让使用任意对象(这里指的是原始字符串 `raw""`)作为 docstring 变得简单。 当`@doc`宏(或者`doc`函数)用作抽取文档时,他会在所有的`META`字典寻找与对象相关的元数据并且返回。返回的对象(例如一些Markdown内容)会默认智能地显示。这个设计也让以编程方法使用文档系统变得容易;例如,在一个函数的不同版本中重用文档: ```julia @doc "..." foo! @doc (@doc foo!) foo ``` 或者与Julia的元编程功能一起使用: ```julia for (f, op) in ((:add, :+), (:subtract, :-), (:multiply, :*), (:divide, :/)) @eval begin $f(a,b) = $op(a,b) end end @doc "`add(a,b)` adds `a` and `b` together" add @doc "`subtract(a,b)` subtracts `b` from `a`" subtract ``` 写在非顶级块,比如`begin`, `if`, `for`, 和 `let`,中的文档会根据块的评估情况加入文档系统中,例如: ```julia if condition() "..." f(x) = x end ``` 会被加到`f(x)`的文档中,当`condition()`是`true`的时候。注意即使`f(x)`在块的末尾离开了作用域,他的文档还会保留。 可以利用元编程来帮助创建文档。当在文档字符串中使用字符串插值时,需要使用额外的 `$` 例如:`$($name)` ```julia for func in (:day, :dayofmonth) name = string(func) @eval begin @doc """ $($name)(dt::TimeType) -> Int64 The day of month of a `Date` or `DateTime` as an `Int64`. """ $func(dt::Dates.TimeType) end end ``` ### 动态写文档 有些时候类型的实例的合适的文档并非只取决于类型本身,也取决于实例的值。在这些情况下,你可以添加一个方法给自定义类型的`Docs.getdoc`函数,返回基于每个实例的文档。例如, ```julia struct MyType value::Int end Docs.getdoc(t::MyType) = "Documentation for MyType with value $(t.value)" x = MyType(1) y = MyType(2) ``` `?x` 将显示“Documentation for MyType with value 1”,而`?y` 将显示“Documentation for MyType with value 2”。 ## 语法指南 本指南提供了如何将文档附加到所有可能的 Julia 语法构造的全面概述。 在下述例子中`"..."`用来表示任意的docstring。 ### `$` 与 `\` 字符 `$` 和 `\` 字符仍然被解析为字符串插值或转义序列的开始字符。 `raw""` 字符串宏和 `@doc` 宏可以用来避免对它们进行转义。 当文档字符串包含 LaTeX 或 Julia 源代码,且示例中包含插值时,这是很方便的: ````julia @doc raw""" ```math \LaTeX ``` """ function f end ```` ### 函数与方法 ```julia "..." function f end "..." f ``` 把 docstring `"..."` 添加给了函数 `f`。首选的语法是第一种,虽然两者是等价的。 ```julia "..." f(x) = x "..." function f(x) x end "..." f(x) ``` 把 docstring `"..."` 添加给了方法 `f(::Any)`。 ```julia "..." f(x, y = 1) = x + y ``` 把 docstring `"..."` 添加给了两个方法,分别为 `f(::Any)` 和 `f(::Any, ::Any)`。 ### 宏 ```julia "..." macro m(x) end ``` 把 docstring `"..."` 添加给了宏 `@m(::Any)` 的定义。 ```julia "..." :(@m) ``` 把 docstring `"..."` 添加给了名为 `@m` 的宏。 ### 类型 ``` "..." abstract type T1 end "..." mutable struct T2 ... end "..." struct T3 ... end ``` 把 docstring `"..."` 添加给了类型 `T1`、`T2` 和 `T3`。 ```julia "..." struct T "x" x "y" y end ``` 把 docstring `"..."` 添加给了类型 `T`,`"x"` 添加给字段 `T.x`,`"y"` 添加给字段 `T.y`。也可以运用于`mutable struct` 类型。 ### 模块 ```julia "..." module M end module M "..." M end ``` 把 docstring `"..."` 添加给了模块 `M`。首选的语法是在模块之前添加 docstring,虽然两者是等价的。 ```julia "..." baremodule M # ... end baremodule M import Base: @doc "..." f(x) = x end ``` 通过在表达式上方放置一个 docstring 来记录 `baremodule` 会自动将 `@doc` 导入到模块中。 当没有记录模块表达式时,必须手动完成这些导入。 ### 全局变量 ```julia "..." const a = 1 "..." b = 2 "..." global c = 3 ``` 把docstring`"..."`添加给了`绑定` `a`,`b`和`c`。 `绑定`是用来在`模块`中存储对于特定`符号`的引用而非存储被引用的值本身。 !!! note 当一个 `const` 定义只是用作定义另外一个定义的别名时,比如函数 `div` 和其在 `Base` 中的别名 `÷`,并不要为别名写文档,转而去为实际的函数写文档。 如果别名写了文档而实际定义没有,那么文档系统(`?` 模式)在寻找实际定义的文档时将不会返回别名的对应文档。 比如你应该写 ```julia "..." f(x) = x + 1 const alias = f ``` 而非 ```julia f(x) = x + 1 "..." const alias = f ``` ```julia "..." sym ``` 把 docstring `"..."` 添加给值 `sym`。但是应首选在 `sym` 的定义处写文档。 ### 多重对象 ```julia "..." a, b ``` 把docstring `"..."` 添加给`a`和`b`,两个都应该是可以写文档的表达式。这个语法等价于 ```julia "..." a "..." b ``` 这种方法可以给任意数量的表达式写文档。当两个函数相关,比如非变版本`f`和可变版本`f!`,这个语法是有用的。 ### 宏生成代码 ```julia "..." @m expression ``` 把docstring `"..."` 添加给通过展开 `@m expression` 生成的表达式。 这就允许由 `@inline`、`@noinline`、`@generated` 或者任意其他宏装饰的表达式,能和没有装饰的表达式以同样的方式写文档。 宏作者应该注意到只有只生成单个表达式的宏才会自动支持docstring。如果宏返回的是含有多个子表达式的块,需要写文档的子表达式应该使用宏 [`@__doc__`](@ref Core.@__doc__) 标记。 [`@enum`](@ref) 宏使用了 `@__doc__` 来允许给 `Enum` 写文档。它的做法可以作为如何正确使用 `@__doc__` 的范例。 ```@docs Core.@__doc__ ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
12878
# 嵌入 Julia 正如我们在 [调用 C 和 Fortran 代码](@ref) 中看到的, Julia 有着简单高效的方法来调用 C 编写的函数。但有时恰恰相反,我们需要在 C 中调用 Julia 的函数。这可以将 Julia 代码集成到一个更大的 C/C++ 项目而无需在 C/C++ 中重写所有内容。Julia 有一个 C API 来实现这一目标。几乎所有编程语言都能以某种方式来调用 C 语言的函数,因此 Julia 的 C API 也就能够进行更多语言的桥接。(例如在 Python 或是 C# 中调用 Julia ). ## 高级别嵌入 __Note__: 本节包含可运行在类 Unix 系统上的、使用 C 编写的嵌入式 Julia 代码。Windows 平台请参阅下一节。 我们从一个简单的 C 程序开始初始化 Julia 并调用一些 Julia 代码: ```c #include <julia.h> JULIA_DEFINE_FAST_TLS // only define this once, in an executable (not in a shared library) if you want fast code. int main(int argc, char *argv[]) { /* required: setup the Julia context */ jl_init(); /* run Julia commands */ jl_eval_string("print(sqrt(2.0))"); /* strongly recommended: notify Julia that the program is about to terminate. this allows Julia time to cleanup pending write requests and run all finalizers */ jl_atexit_hook(0); return 0; } ``` 为构建这个程序,你必须将 Julia 头文件的路径放入 include 路径并链接 `libjulia` 。例如 Julia 被安装到 `$JULIA_DIR`,则可以用 `gcc` 来编译上面的测试程序 `test.c`: ``` gcc -o test -fPIC -I$JULIA_DIR/include/julia -L$JULIA_DIR/lib -Wl,-rpath,$JULIA_DIR/lib test.c -ljulia ``` 或者,查看 `test/embedding/` 文件夹中 Julia 源代码树中的 `embedding.c` 程序。 文件 `cli/loader_exe.c` 程序是另一个简单的例子,说明如何在链接 `libjulia` 时设置 `jl_options` 选项。 在调用任何其他 Julia C 函数之前第一件必须要做的事是初始化 Julia,通过调用 `jl_init` 尝试自动确定 Julia 的安装位置来实现。如果需要自定义位置或指定要加载的系统映像,请改用 `jl_init_with_image`。 测试程序中的第二个语句通过调用 `jl_eval_string` 来执行 Julia 语句。 在程序结束之前,强烈建议调用 `jl_atexit_hook`。上面的示例程序在 `main` 返回之前进行了调用。 !!! note 现在,动态链接 `libjulia` 的共享库需要传递选项 `RTLD_GLOBAL` 。比如在 Python 中像这样调用: ``` >>> julia=CDLL('./libjulia.dylib',RTLD_GLOBAL) >>> julia.jl_init.argtypes = [] >>> julia.jl_init() 250593296 ``` !!! note 如果 Julia 程序需要访问 主可执行文件 中的符号,那么除了下面描述的由 `julia-config.jl` 生成的标记之外,可能还需要在 Linux 上的编译时添加 `-Wl,--export-dynamic` 链接器标志。编译共享库时则不必要。 ### 使用 julia-config 自动确定构建参数 `julia-config.jl` 创建脚本是为了帮助确定使用嵌入的 Julia 程序所需的构建参数。此脚本使用由其调用的特定 Julia 分发的构建参数和系统配置来导出嵌入程序的必要编译器标志以与该分发交互。此脚本位于 Julia 的 share 目录中。 #### 例子 ```c #include <julia.h> int main(int argc, char *argv[]) { jl_init(); (void)jl_eval_string("println(sqrt(2.0))"); jl_atexit_hook(0); return 0; } ``` #### 在命令行中 命令行脚本简单用法:假设 `julia-config.jl` 位于 `/usr/local/julia/share/julia`,它可以直接在命令行上调用,并采用 3 个标志的任意组合: ``` /usr/local/julia/share/julia/julia-config.jl Usage: julia-config [--cflags|--ldflags|--ldlibs] ``` 如果上面的示例源代码保存为文件 `embed_example.c`,则以下命令将其编译为 Linux 和 Windows 上运行的程序(MSYS2 环境),或者如果在 OS/X 上,则用 `clang` 替换 `gcc`。: ``` /usr/local/julia/share/julia/julia-config.jl --cflags --ldflags --ldlibs | xargs gcc embed_example.c ``` #### 在 Makefiles 中使用 但通常来说,嵌入的项目会比上面更复杂,因此一般会提供 makefile 支持。由于使用了 **shell** 宏扩展,我们就假设用 GNU make 。 另外,尽管很多时候 `julia-config.jl` 会在目录 `/usr/local` 中出现多次,不过也未必如此,但 Julia 也定位 `julia-config.jl`,并且可以使用 makefile 来利用它。上面的示例程序使用 Makefile 来扩展。: ```makefiles JL_SHARE = $(shell julia -e 'print(joinpath(Sys.BINDIR, Base.DATAROOTDIR, "julia"))') CFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags) CXXFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags) LDFLAGS += $(shell $(JL_SHARE)/julia-config.jl --ldflags) LDLIBS += $(shell $(JL_SHARE)/julia-config.jl --ldlibs) all: embed_example ``` 现在构建的命令就只需要简简单单的`make`了。 ## 在 Windows 使用 Visual Studio 进行高级别嵌入 如果尚未设置`JULIA_DIR`环境变量,请在启动 Visual Studio 之前使用系统面板添加它。JULIA_DIR 下的`bin` 文件夹应该在系统路径上。 我们首先打开 Visual Studio 并创建一个新的控制台应用程序项目。 在`stdafx.h`头文件的末尾添加以下几行: ```c #include <julia.h> ``` 然后,将项目中的 main() 函数替换为以下代码: ```c int main(int argc, char *argv[]) { /* required: setup the Julia context */ jl_init(); /* run Julia commands */ jl_eval_string("print(sqrt(2.0))"); /* strongly recommended: notify Julia that the program is about to terminate. this allows Julia time to cleanup pending write requests and run all finalizers */ jl_atexit_hook(0); return 0; } ``` 下一步是设置项目以查找 Julia 包含的文件和库。 了解 Julia 安装的是 32 位还是 64 位非常重要。 在继续之前删除与 Julia 安装不对应的任何平台配置。 使用项目属性对话框,转到`C/C++` | `General` 并将 `$(JULIA_DIR)\include\julia\` 添加到 Additional Include Directories 属性。 然后,转到`Linker` | `General` 部分并将 `$(JULIA_DIR)\lib` 添加到 Additional Library Directories 属性。最后,在`Linker`| `Input`下,将`libjulia.dll.a;libopenlibm.dll.a;`添加到库列表中。 到这里,该项目应该成功构建和运行。 ## 转换类型 真正的应用程序不仅仅要执行表达式,还要返回表达式的值给宿主程序。`jl_eval_string` 返回 一个 `jl_value_t*`,它是指向堆分配的 Julia 对象的指针。存储像 [`Float64`](@ref) 这些简单数据类型叫做 `装箱`,然后提取存储的基础类型数据叫 `拆箱`。我们改进的示例程序在 Julia 中计算 2 的平方根,并在 C 中读取回结果,如下所示: ```c jl_value_t *ret = jl_eval_string("sqrt(2.0)"); if (jl_typeis(ret, jl_float64_type)) { double ret_unboxed = jl_unbox_float64(ret); printf("sqrt(2.0) in C: %e \n", ret_unboxed); } else { printf("ERROR: unexpected return type from sqrt(::Float64)\n"); } ``` 为了检查 `ret` 是否为特定的 Julia 类型,我们可以使用 `jl_isa`,`jl_typeis` 或 `jl_is_...` 函数。通过输入 `typeof(sqrt(2.0))`到 Julia shell,我们可以看到返回类型是 [`Float64`](@ref)(在C中是 `double` 类型)。要将装箱的 Julia 值转换为 C 的double,上面的代码片段使用了 `jl_unbox_float64`函数。 相应的, 用 `jl_box_...` 函数是另一种转换的方式。 ```c jl_value_t *a = jl_box_float64(3.0); jl_value_t *b = jl_box_float32(3.0f); jl_value_t *c = jl_box_int32(3); ``` 正如我们将在下面看到的那样,装箱需要在调用 Julia 函数时使用特定参数。 ## 调用 Julia 函数 虽然 `jl_eval_string` 允许 C 获取 Julia 表达式的结果,但它不允许将在 C 中计算的参数传递给 Julia。因此需要使用 `jl_call` 来直接调用Julia函数: ```c jl_function_t *func = jl_get_function(jl_base_module, "sqrt"); jl_value_t *argument = jl_box_float64(2.0); jl_value_t *ret = jl_call1(func, argument); ``` 在第一步中,通过调用 `jl_get_function` 检索出 Julia 函数 `sqrt` 的句柄(handle)。 传递给 `jl_get_function` 的第一个参数是 指向 定义`sqrt`所在的 `Base` 模块 的指针。 然后,double 值通过 `jl_box_float64` 被装箱。 最后,使用 `jl_call1` 调用该函数。也有 `jl_call0`,`jl_call2`和`jl_call3` 函数,方便地处理不同数量的参数。 要传递更多参数,使用 `jl_call`: ```c jl_value_t *jl_call(jl_function_t *f, jl_value_t **args, int32_t nargs) ``` 它的第二个参数 `args` 是 `jl_value_t*` 类型的数组,`nargs` 是参数的个数 ## 内存管理 正如我们所见,Julia 对象在 C 中表示为指针。这就出现了 谁来负责释放这些对象的问题。 通常,Julia 对象由垃圾收集器(GC)释放,但 GC 不会自动就懂我们正C中保留对Julia值的引用。这意味着 GC 会在你的掌控之外释放对象,从而使指针无效。 GC 只能在分配 Julia 对象时运行。 像 `jl_box_float64` 这样的调用执行分配,分配可能发生在运行 Julia 代码的任何时候。 然而,在 `jl_...` 调用之间使用指针通常是安全的。 但是为了确保值可以在 `jl_...` 调用后留存下来,我们必须告诉 Julia 我们仍然持有对 Julia [root](https://www.cs.purdue.edu/homes/hosking/690M/p611-fenichel.pdf) 的引用,这个过程称为“GC rooting”。把一个值”扎根“将确保垃圾收集器不会意外地将此值识别为未使用并释放该值的内存。 这可以使用 `JL_GC_PUSH` 宏来完成: ```c jl_value_t *ret = jl_eval_string("sqrt(2.0)"); JL_GC_PUSH1(&ret); // Do something with ret JL_GC_POP(); ``` `JL_GC_POP` 调用会释放之前的 `JL_GC_PUSH` 建立的引用。 请注意,`JL_GC_PUSH` 将引用存储在 C 堆栈上,因此在退出作用域之前,它必须与一个 `JL_GC_POP` 精确配对。 也就是说,在函数返回之前,或者流程控制以其他方式离开调用了`JL_GC_PUSH` 的块。 可以使用 `JL_GC_PUSH2`、`JL_GC_PUSH3`、`JL_GC_PUSH4`、`JL_GC_PUSH5` 和 `JL_GC_PUSH6` 宏一次推送多个 Julia 值。 要推送一个 Julia 数组,可以使用 `JL_GC_PUSHARGS` 宏,其用法如下: ```c jl_value_t **args; JL_GC_PUSHARGS(args, 2); // args can now hold 2 `jl_value_t*` objects args[0] = some_value; args[1] = some_other_value; // Do something with args (e.g. call jl_... functions) JL_GC_POP(); ``` 每个作用域必须只有一次对 `JL_GC_PUSH*` 的调用。 因此,如果不能通过一次调用`JL_GC_PUSH*` 一次推送所有变量,或者如果要推送的变量超过 6 个并且使用参数数组不是一种选择,那么可以使用内部块: ```c jl_value_t *ret1 = jl_eval_string("sqrt(2.0)"); JL_GC_PUSH1(&ret1); jl_value_t *ret2 = 0; { jl_function_t *func = jl_get_function(jl_base_module, "exp"); ret2 = jl_call1(func, ret1); JL_GC_PUSH1(&ret2); // Do something with ret2. JL_GC_POP(); // This pops ret2. } JL_GC_POP(); // This pops ret1. ``` 如果需要在函数(或块作用域)之间保存指向变量的指针,则不能使用 `JL_GC_PUSH*`。 在这种情况下,有必要在 Julia 全局作用域内创建并保留对变量的引用。 实现这一点的一种简单方法是使用一个全局的`IdDict`来保存引用,避免 GC 释放。 但是,此方法仅适用于可变类型。 ```c // This functions shall be executed only once, during the initialization. jl_value_t* refs = jl_eval_string("refs = IdDict()"); jl_function_t* setindex = jl_get_function(jl_base_module, "setindex!"); ... // `var` is the variable we want to protect between function calls. jl_value_t* var = 0; ... // `var` is a `Vector{Float64}`, which is mutable. var = jl_eval_string("[sqrt(2.0); sqrt(4.0); sqrt(6.0)]"); // To protect `var`, add its reference to `refs`. jl_call3(setindex, refs, var, var); ``` 如果变量是不可变的,则需要将其包装在等效的可变容器中,或者最好在将其推送到`IdDict`之前包装在`RefValue{Any}`中。 在这种方法中,容器必须通过 C 代码创建或填充,例如使用函数`jl_new_struct`。 如果容器是由`jl_call*` 创建的,那么你将需要重新加载要在 C 代码中使用的指针。 ```c // This functions shall be executed only once, during the initialization. jl_value_t* refs = jl_eval_string("refs = IdDict()"); jl_function_t* setindex = jl_get_function(jl_base_module, "setindex!"); jl_datatype_t* reft = (jl_datatype_t*)jl_eval_string("Base.RefValue{Any}"); ... // `var` is the variable we want to protect between function calls. jl_value_t* var = 0; ... // `var` is a `Float64`, which is immutable. var = jl_eval_string("sqrt(2.0)"); // Protect `var` until we add its reference to `refs`. JL_GC_PUSH1(&var); // Wrap `var` in `RefValue{Any}` and push to `refs` to protect it. jl_value_t* rvar = jl_new_struct(reft, var); JL_GC_POP(); jl_call3(setindex, refs, rvar, rvar); ``` GC 可以通过使用函数`delete!` 从`refs` 中删除对变量的引用来释放变量,前提是没有其它对该变量的引用保留在任何地方: ```c jl_function_t* delete = jl_get_function(jl_base_module, "delete!"); jl_call2(delete, refs, rvar); ``` 作为非常简单情况的替代方案,可以只创建一个类型为`Vector{Any}`的全局容器,并在必要时从中获取元素,甚至可以使用以下方法为每个指针创建一个全局变量 ```c jl_set_global(jl_main_module, jl_symbol("var"), var); ``` ### 更新 GC 管理对象的字段 垃圾回收器的运行假设它知道每个年老代对象都指向一个年轻代对象。 任何时候一个指针被更新打破了这个假设,它必须用`jl_gc_wb`(写屏障)函数向回收器发出信号,如下所示: ```c jl_value_t *parent = some_old_value, *child = some_young_value; ((some_specific_type*)parent)->field = child; jl_gc_wb(parent, child); ``` 通常情况下不可能在运行时预测 值是否是旧的,因此 写屏障 必须被插入在所有显式存储之后。一个需要注意的例外是如果 `parent` 对象刚分配,垃圾收集之后并不执行。请记住大多数 `jl_...` 函数有时候都会执行垃圾收集。 直接更新数据时,对于指针数组来说 写屏障 也是必需的 例如: ```c jl_array_t *some_array = ...; // e.g. a Vector{Any} void **data = (void**)jl_array_data(some_array); jl_value_t *some_value = ...; data[0] = some_value; jl_gc_wb(some_array, some_value); ``` ### 控制垃圾收集器 有一些函数能够控制GC。在正常使用情况下这些不是必要的。 | 函数 | 描述 | |:-------------------- |:-------------------------------------------- | | `jl_gc_collect()` | 强制执行 GC | | `jl_gc_enable(0)` | 禁用 GC, 返回前一个状态作为 int 类型 | | `jl_gc_enable(1)` | 启用 GC, 返回前一个状态作为 int 类型 | | `jl_gc_is_enabled()` | 返回当前状态作为 int 类型 | ## 使用数组 Julia 和 C 可以不通过复制而共享数组数据。下面一个例子将展示它是如何工作的。 Julia数组用数据类型 `jl_array_t *` 表示。基本上,`jl_array_t` 是一个包含以下内容的结构: * 关于数据类型的信息 * 指向数据块的指针 * 关于数组长度的信息 为了让事情比较简单,我们从一维数组开始,创建一个存有 10 个 FLoat64 类型的数组如下所示: ```c jl_value_t* array_type = jl_apply_array_type((jl_value_t*)jl_float64_type, 1); jl_array_t* x = jl_alloc_array_1d(array_type, 10); ``` 或者,如果您已经分配了数组,则可以生成一个简易的包装器来包裹其数据: ```c double *existingArray = (double*)malloc(sizeof(double)*10); jl_array_t *x = jl_ptr_to_array_1d(array_type, existingArray, 10, 0); ``` 最后一个参数是一个布尔值,表示 Julia 是否应该获取数据的所有权。 如果这个参数 不为零,当数组不再被引用时,GC 会在数据的指针上调用 `free` 。 为了访问 x 的数据,我们可以使用 `jl_array_data`: ```c double *xData = (double*)jl_array_data(x); ``` 现在我们可以填充这个数组: ```c for(size_t i=0; i<jl_array_len(x); i++) xData[i] = i; ``` 现在让我们调用一个对 `x` 就地操作的 Julia 函数: ```c jl_function_t *func = jl_get_function(jl_base_module, "reverse!"); jl_call1(func, (jl_value_t*)x); ``` 通过打印数组,可以验证 `x` 的元素现在是否已被逆置 (reversed)。 ### 获取返回的数组 如果 Julia 函数返回一个数组,`jl_eval_string` 和 `jl_call` 的返回值可以被强制转换为`jl_array_t *`: ```c jl_function_t *func = jl_get_function(jl_base_module, "reverse"); jl_array_t *y = (jl_array_t*)jl_call1(func, (jl_value_t*)x); ``` 现在使用 `jl_array_data` 可以像前面一样访问 `y` 的内容。一如既往地,一定要在使用数组的时候确保 持有使用数组的引用。 ### 多维数组 Julia的多维数组以 列序优先 存储在内存中。这是一些 创建一个2D数组并访问其属性 的代码: ```c // Create 2D array of float64 type jl_value_t *array_type = jl_apply_array_type(jl_float64_type, 2); jl_array_t *x = jl_alloc_array_2d(array_type, 10, 5); // Get array pointer double *p = (double*)jl_array_data(x); // Get number of dimensions int ndims = jl_array_ndims(x); // Get the size of the i-th dim size_t size0 = jl_array_dim(x,0); size_t size1 = jl_array_dim(x,1); // Fill array with data for(size_t i=0; i<size1; i++) for(size_t j=0; j<size0; j++) p[j + size0*i] = i + j; ``` 请注意,虽然 Julia 的数组使用基于 1 的索引,但C API 中使用基于 0 的索引(例如 在调用`jl_array_dim`)以便用C代码的习惯来阅读。 ## 异常 Julia 代码可以抛出异常。比如: ```c jl_eval_string("this_function_does_not_exist()"); ``` 这个调用似乎什么都没做。但可以检查异常是否抛出: ```c if (jl_exception_occurred()) printf("%s \n", jl_typeof_str(jl_exception_occurred())); ``` 如果您使用 支持异常的语言的 Julia C API(例如Python,C#,C ++),使用 检查是否有异常的函数 将每个调用 包装到 `libjulia` 中是有意义的,然后异常在宿主语言中重新抛出。 ### 抛出 Julia 异常 在编写 Julia 可调用函数时,可能需要验证参数 并抛出异常表示错误。 典型的类型检查像这样: ```c if (!jl_typeis(val, jl_float64_type)) { jl_type_error(function_name, (jl_value_t*)jl_float64_type, val); } ``` 可以使用以下函数 引发一般异常: ```c void jl_error(const char *str); void jl_errorf(const char *fmt, ...); ``` `jl_error`采用 C 字符串,而 `jl_errorf` 像 `printf` 一样调用: ```c jl_errorf("argument x = %d is too large", x); ``` 在这个例子中假定 `x` 是一个整数值。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
7590
# 环境变量 Julia 可以配置许多环境变量,一种常见的方式是直接配置操作系统环境变量,另一种更便携的方式是在 Julia 中配置。假设你要将环境变量 `JULIA_EDITOR` 设置为 `vim`,可以直接在 REPL 中输入 `ENV["JULIA_EDITOR"] = "vim"`(请根据具体情况对此进行修改),也可以将其添加到用户主目录中的配置文件 `~/.julia/config/startup.jl`,这样做会使其永久生效。环境变量的当前值是通过执行 `ENV["JULIA_EDITOR"]` 来确定的。 Julia 使用的环境变量通常以 `JULIA` 开头。如果调用 [`InteractiveUtils.versioninfo`](@ref) 时使用关键字参数 `verbose = true`,那么输出结果将列出与 Julia 相关的已定义环境变量,即包括那些名称中包含 `JULIA` 的环境变量。 !!! note 某些变量需要在 Julia 启动之前设置,比如 `JULIA_NUM_THREADS` 和 `JULIA_PROJECT`,因为在启动过程中将这些变量添加到 `~/.julia/config/startup.jl` 中为时已晚。在 Bash 中,环境变量可以手动设置,这可通过在 Julia 启动前运行诸如 `export JULIA_NUM_THREADS=4` 的命令,亦可通过向 `~/.bashrc` 或 `~/.bash_profile` 添加相同命令来在 Bash 每次启动时设置该变量。 ## 文件位置 ### `JULIA_BINDIR` 包含 Julia 可执行文件的目录的绝对路径,它会设置全局变量 [`Sys.BINDIR`](@ref)。`$JULIA_BINDIR` 如果没有设置,那么 Julia 会在运行时确定 `Sys.BINDIR` 的值。 在默认情况下,可执行文件是指: ``` $JULIA_BINDIR/julia $JULIA_BINDIR/julia-debug ``` 全局变量 `Base.DATAROOTDIR` 是一个从 `Sys.BINDIR` 到 Julia 数据目录的相对路径。 ``` $JULIA_BINDIR/$DATAROOTDIR/julia/base ``` 上述路径是 Julia 最初搜索源文件的路径(通过 `Base.find_source_file()`)。 同样,全局变量 `Base.SYSCONFDIR` 是一个到配置文件目录的相对路径。在默认情况下,Julia 会在下列文件中搜索 `startup.jl` 文件(通过 `Base.load_julia_startup()`) ``` $JULIA_BINDIR/$SYSCONFDIR/julia/startup.jl $JULIA_BINDIR/../etc/julia/startup.jl ``` 例如,在 Linux 下安装的 Julia 可执行文件位于 `/bin/julia`,`DATAROOTDIR` 为 `../share`,`SYSCONFDIR` 为 `../etc`,`JULIA_BINDIR` 会被设置为 `/bin`,会有一个源文件搜索路径: ``` /share/julia/base ``` 和一个全局配置文件搜索路径: ``` /etc/julia/startup.jl ``` ### `JULIA_PROJECT` 指示哪个项目应该是初始活动项目的目录路径。 设置这个环境变量和指定`--project`启动选项效果一样,但是`--project`优先级更高。 如果变量设置为 `@.`,那么 Julia 会尝试从当前目录及其父目录中查找包含 `Project.toml` 或 `JuliaProject.toml` 文件的项目目录。 另请参阅有关 [代码加载](@ref code-loading) 的章节。 !!! note `JULIA_PROJECT` 必须在启动 julia 前定义;于 `startup.jl` 中定义它对于启动的过程为时已晚。 ### `JULIA_LOAD_PATH` `JULIA_LOAD_PATH` 环境变量用于补充全局的 Julia 变量 [`LOAD_PATH`](@ref) ,该变量可用于确定通过 `import` 和 `using` 可以加载哪些包(请参阅 [Code Loading](@ref code-loading))。 与 shell 使用的 `PATH` 变量不同, 在 `JULIA_LOAD_PATH` 中的空条目将会在填充 `LOAD_PATH` 时被扩展为 `LOAD_PATH` 的默认值 `["@", "@v#.#", "@stdlib"]` 。这样,无论 `JULIA_LOAD_PATH` 是否已被设置,均可以使用 shell 脚本轻松地在加载路径前面或后面添加值。例如要将 `/foo/bar` 添加到 `LOAD_PATH` 之前,只需要使用下列脚本: ```sh export JULIA_LOAD_PATH="/foo/bar:$JULIA_LOAD_PATH" ``` 如果已经设置了 `JULIA_LOAD_PATH` 环境变量,那么 `/foo/bar` 将被添加在原有值之前。另一方面,如果 `JULIA_LOAD_PATH` 尚未设置,那么它会被设置为 `/foo/bar:` ,而这将使用 `LOAD_PATH` 的值扩展为 `["/foo/bar", "@", "@v#.#", "@stdlib"]` 。如果 `JULIA_LOAD_PATH` 被设置为空字符串,那么它将被扩展为一个空的 `LOAD_PATH` 数组。换句话说,这个空字符串数组将被认为是零元素的数组,而非是一个空字符串单元素的数组。使用这样的加载行为是为了可以通过环境变量设置空的加载路径。如果你需要使用默认的加载路径,请不要设置这一环境变量,如果它必须有值,那么可将其设置为字符串 `:` 。 !!! note 在 Windows 上,路径元素由 `;` 字符分隔,就像 Windows 上的大多数路径列表一样。 将上一段中的 `:` 替换为 `;`。 ### `JULIA_DEPOT_PATH` `JULIA_DEPOT_PATH` 环境变量用于填充全局的 Julia 变量 [`DEPOT_PATH`](@ref) ,该变量用于控制包管理器以及 Juila 代码加载机制在何处查找包注册表、已安装的包、命名环境、克隆的存储库、缓存的预编译包映像、配置文件和 REPL 历史记录文件的默认位置。 与 shell 使用的 `PATH` 变量不同,但与 `JULIA_LOAD_PATH` 类似, 在 `JULIA_DEPOT_PATH` 中的空条目将会被扩展为 `DEPOT_PATH` 的默认值。这样,无论 `JULIA_DEPOT_PATH` 是否已被设置,均可以使用 shell 脚本轻松地在仓库路径前面或后面添加值。例如要将 `/foo/bar` 添加到 `DEPOT_PATH` 之前,只需要使用下列脚本: ```sh export JULIA_DEPOT_PATH="/foo/bar:$JULIA_DEPOT_PATH" ``` 如果已经设置了 `JULIA_DEPOT_PATH` 环境变量,那么 `/foo/bar` 将被添加在原有值之前。另一方面,如果 `JULIA_DEPOT_PATH` 尚未设置,那么它会被设置为 `/foo/bar:` ,而这将使 `/foo/bar` 被添加到默认仓库路径之前。如果 `JULIA_DEPOT_PATH` 被设置为空字符串,那么它将扩展为一个空的 `DEPOT_PATH` 数组。换句话说,这个空字符串数组将被认为是零元素的数组,而非是一个空字符串单元素的数组。使用这样的加载行为是为了可以通过环境变量设置空的仓库路径。如果你需要使用默认的仓库路径,请不要设置这一环境变量,如果它必须有值,那么可将其设置为字符串 `:` 。 !!! note 在 Windows 上,路径元素由 `;` 字符分隔,就像 Windows 上的大多数路径列表一样。 将上一段中的 `:` 替换为 `;`。 ### `JULIA_HISTORY` REPL 历史文件中 `REPL.find_hist_file()` 的绝对路径。如果没有设置 `$JULIA_HISTORY`,那么 `REPL.find_hist_file()` 默认为 ``` $(DEPOT_PATH[1])/logs/repl_history.jl ``` ### `JULIA_PKG_SERVER` 由`Pkg.jl` 使用,用于下载软件包和更新注册表。默认情况下,`Pkg` 使用 `https://pkg.julialang.org` 来获取 Julia 包。你可以使用此环境变量来选择不同的服务器。 此外,你可以禁用 PkgServer 协议的使用,并通过设置直接从它们的主机(GitHub、GitLab 等)访问包: ``` export JULIA_PKG_SERVER="" ``` ## 外部应用 ### `JULIA_SHELL` Julia 用来执行外部命令的 shell 的绝对路径(通过 `Base.repl_cmd()`)。默认为环境变量 `$SHELL`,如果 `$SHELL` 未设置,则为 `/bin/sh`。 !!! note 在 Windows 上,此环境变量将被忽略,并且外部命令会直接被执行。 ### `JULIA_EDITOR` `InteractiveUtils.editor()` 的返回值--编辑器,例如,[`InteractiveUtils.edit`](@ref),会启动偏好编辑器,比如 `vim`。 `$JULIA_EDITOR` 优先于 `$VISUAL`,而后者优先于 `$EDITOR`。如果这些环境变量都没有设置,那么在 Windows 和 OS X 上会设置为 `open`,或者 `/etc/alternatives/editor`(如果存在的话),否则为 `emacs`。 ## 并行 ### `JULIA_CPU_THREADS` 改写全局变量 [`Base.Sys.CPU_THREADS`](@ref),逻辑 CPU 核心数。 ### `JULIA_WORKER_TIMEOUT` 一个 [`Float64`](@ref) 值,用来确定 `Distributed.worker_timeout()` 的值(默认:`60.0`)。此函数提供 worker 进程在死亡之前等待 master 进程建立连接的秒数。 ### [`JULIA_NUM_THREADS`](@id JULIA_NUM_THREADS) 一个无符号 64 位整数 (`uint64_t`),用于设置 Julia 可用的最大线程数。 如果`$JULIA_NUM_THREADS` 不为正数或未设置,或者无法通过系统调用确定CPU 线程数,则将线程数设置为`1`。 如果`$JULIA_NUM_THREADS` 设置为`auto`,则线程数将设置为CPU线程数。 !!! note `JULIA_NUM_THREADS` 必须在启动 julia 之前定义; 启动过程中在`startup.jl` 中定义它是不能奏效的。 !!! compat "Julia 1.5" 在 Julia 1.5 和更高版本中,也可在启动时使用 `-t`/`--threads` 命令行参数指定线程数。 !!! compat "Julia 1.7" `$JULIA_NUM_THREADS` 的 `auto` 值需要 Julia 1.7 或更高版本。 ### `JULIA_THREAD_SLEEP_THRESHOLD` 如果被设置为字符串,并且以大小写敏感的子字符串 `"infinite"` 开头,那么自旋线程从不睡眠。否则,`$JULIA_THREAD_SLEEP_THRESHOLD` 被解释为一个无符号 64 位整数(`uint64_t`),并且提供以纳秒为单位的自旋线程睡眠的时间量。 ### `JULIA_EXCLUSIVE` 如果设置为 `0` 以外的任何值,那么 Julia 的线程策略与在专用计算机上一致:主线程在 proc 0 上且线程间是关联的。否则,Julia 让操作系统处理线程策略。 ## REPL 格式化输出 决定 REPL 应当如何格式化输出的环境变量。通常,这些变量应当被设置为 [ANSI 终端转义序列](http://ascii-table.com/ansi-escape-sequences.php)。Julia 提供了具有相同功能的高级接口;请参阅 [Julia REPL](@ref) 章节。 ### `JULIA_ERROR_COLOR` `Base.error_color()`(默认值:亮红,`"\033[91m"`),errors 在终端中的格式。 ### `JULIA_WARN_COLOR` `Base.warn_color()`(默认值:黄,`"\033[93m"`),warnings 在终端中的格式。 ### `JULIA_INFO_COLOR` `Base.info_color()`(默认值:青,`"\033[36m"`),info 在终端中的格式。 ### `JULIA_INPUT_COLOR` `Base.input_color()`(默认值:标准,`"\033[0m"`),在终端中,输入应有的格式。 ### `JULIA_ANSWER_COLOR` `Base.answer_color()`(默认值:标准,`"\033[0m"`),在终端中,输出应有的格式。 ## 调试和性能分析 ### `JULIA_DEBUG` 为文件或模块启动调试日志记录,请参阅 [日志](@ref Logging) 了解更多信息。 ### `JULIA_GC_ALLOC_POOL`, `JULIA_GC_ALLOC_OTHER`, `JULIA_GC_ALLOC_PRINT` 这些环境变量取值为字符串,可以以字符 `‘r’` 开头,后接一个由三个带符号 64 位整数(`int64_t`)组成的、以冒号分割的列表的插值字符串。这个整数的三元组 `a:b:c` 代表算术序列 `a`, `a + b`, `a + 2*b`, ... `c`。 * 如果是第 `n` 次调用 `jl_gc_pool_alloc()`,并且 `n` 属于 `$JULIA_GC_ALLOC_POOL` 代表的算术序列, 那么垃圾回收是强制的。 * 如果是第 `n` 次调用 `maybe_collect()`,并且 `n` 属于 `$JULIA_GC_ALLOC_OTHER` 代表的算术序列,那么垃圾 回收是强制的。 * 如果是第 `n` 次调用 `jl_gc_alloc()`,并且 `n` 属于 `$JULIA_GC_ALLOC_PRINT` 代表的算术序列,那么 调用 `jl_gc_pool_alloc()` 和 `maybe_collect()` 的次数会 被打印。 如果这些环境变量的值以字符 `‘r'` 开头,那么垃圾回收事件间的间隔是随机的。 !!! note 这些环境变量生效要求 Julia 在编译时带有垃圾收集调试支持(也就是,在构建配置中将 `WITH_GC_DEBUG_ENV` 设置为 `1`)。 ### `JULIA_GC_NO_GENERATIONAL` 如果设置为 `0` 以外的任何值,那么 Julia 的垃圾收集器将从不执行「快速扫描」内存。 !!! note 此环境变量生效要求 Julia 在编译时带有垃圾收集调试支持(也就是,在构建配置中将 `WITH_GC_DEBUG_ENV` 设置为 `1`)。 ### `JULIA_GC_WAIT_FOR_DEBUGGER` 如果设置为 `0` 以外的任何值,Julia 的垃圾收集器每当出现严重错误时将等待调试器连接而不是中止。 !!! note 此环境变量生效要求 Julia 在编译时带有垃圾收集调试支持(也就是,在构建配置中将 `WITH_GC_DEBUG_ENV` 设置为 `1`)。 ### `ENABLE_JITPROFILING` 如果设置为 `0` 以外的任何值,那么编译器将为即时(JIT)性能分析创建并注册一个事件监听器。 !!! note 此环境变量仅在使用 JIT 性能分析支持编译 Julia 时有效,使用如下之一: * Intel's [VTune™ Amplifier](https://software.intel.com/en-us/vtune)(`USE_INTEL_JITEVENTS` 在配置中设置为`1`), 或 * [OProfile](http://oprofile.sourceforge.net/news/)(`USE_OPROFILE_JITEVENTS` 在配置中设置为`1`)。 * [Perf](https://perf.wiki.kernel.org) (`USE_PERF_JITEVENTS` 在构建配置中设置为 `1`)。 默认情况下启用此集成。 ### `ENABLE_GDBLISTENER` 如果设置为除`0`之外的任何内容,则在发布版本上启用 Julia 代码的 GDB 注册。 在 Julia 的调试版本中,这始终处于启用状态。 推荐与 `-g 2` 一起使用。 ### `JULIA_LLVM_ARGS` 传递给 LLVM 后端的参数。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
23835
# 常见问题 ## 概述 ### Julia 的名字来源于某人或某事物吗? 不。 ### 为什么不把 Matlab/Python/R 或者其他语言的代码编译为 Julia 呢? 由于大多数人对其他动态语言的语法很熟悉,而且已经在这些动态语言中编写了很多代码,人们也许会问:为什么我们不直接设计以Julia为后端的Matlab或是Python前端(也就是把其他代码“转译”到Julia)?这样既能获得Julia的高性能,也能避免程序员花费精力来学一门新的语言。这是一个简单的解决方案,不是吗? 总的来说,我们这样做是因为 **Julia 编译器没有什么特别之处**:我们使用的是普通的编译器(LLVM),这里面没有什么其他语言开发者所不知道的“独家秘方”。诚然,Julia编译器在许多地方比其他动态语言的编译器更简单(比如 PyPy 和 LuaJIT)。Julia 的性能优势几乎完全来自其前端:它的语义学使得 [高质量的 Julia 程序](@ref man-performance-tips) 能够给予编译器更多的机会来产生高效的代码和内存结构。如果你尝试将 Matlab 或 Python 代码编译为 Julia,我们的编译器会被其语义学限制而不能产生相对现有编译器更好的代码(甚至更差)。语义学的关键角色也正是一些现存的 Python 编译器(像 Numba 和 Pythran)仅仅尝试优化语言的一小部分(比如 Numpy 的矢量与标量运算)的原因,而这些部分已经至少在相同的语义学上与我们做的一样好。致力于这些项目的人员难以置信得聪明并且已经取得了令人惊叹的成就,但为被解释而设计的语言加装编译器是十分困难的。 Julia 的优势在于好的性能不止被限制在一小部分的内置类型与操作,用户能够写出使用任意自定义类型的高级泛型代码,同时也能保证很高的运行与内存效率。在如 Python 一般的语言中,类型没有给编译器提供太多的信息来达成这样的目的,当你试图像使用 Julia 前端一样使用这些语言时,你会遇到困难。 出于类似的原因,自动翻译为 Julia 的代码一般来说会是可读性差、缓慢且违反习惯的代码。这些代码不是从其他语言迁移到 Julia 的好的起点。 另一方面,语言**可迁移性**是极其有用的:我们会在一些时候想要将其他语言的高质量代码迁移到 Julia 中(也可能相反)。这一工作的最佳实践不是翻译器,而是使用简单的跨语言调用。我们对此有许多工作,从内置的 `ccall` (来调用 C 和 Fortran 模块)到[JuliaInterop](https://github.com/JuliaInterop) 包来链接 Julia 和 Python、Matlab、C++ 以及更多语言。 ## [公共 API](@id man-api) ### Julia 如何定义其公共 API? 对于 `julia` 版本的 [SemVer](https://semver.org/),唯一稳定的接口是 Julia 的 `Base` 和 [文档](https://docs.julialang.org/) 中的标准库接口中且未标记为不稳定(例如,实验性的和内部性的)的部分。 如果函数、类型和常量未包含在文档中,则它们不是公共 API 的一部分,_即使它们具有文档_。 ### 有一个有用的非官方的函数/类型/常量。我可以使用它吗? 如果您使用非公共 API,更新 Julia 可能会使你的代码失效。 如果代码是自洽的,最好将其复制到你的项目中。 如果你想依赖一个复杂的非公共 API,尤其是从稳定的包中使用它时,最好打开发起 [issue](https://github.com/JuliaLang/julia/issues) 或 [pull request](https://github.com/JuliaLang/julia/pulls) 开始讨论将其转换为公共 API。 尽管你可以在下游自己开发一个包来封装这个内部实现,并且屏蔽不同的 `Julia` 版本差异,但我们并不鼓励这样做。 ### 文档不够准确。 我可以依赖现有的行为吗? 请发起一个 [issue](https://github.com/JuliaLang/julia/issues) 或 [pull request](https://github.com/JuliaLang/julia/pulls) 开始讨论将现有行为转换为公共 API。 ## 会话和 REPL ### 如何从内存中删除某个对象? Julia 没有类似于 MATLAB 的 `clear` 函数,某个名称一旦定义在 Julia 的会话中(准确地说,在 `Main` 模块中),它就会一直存在下去。 如果关心内存使用情况,你可以用消耗较少内存的对象替换原对象。 例如,如果 `A` 是一个你不再需要的千兆字节大小的数组,你可以使用 `A = nothing` 来释放内存。 下次垃圾收集器运行时会释放内存; 您可以使用 [`GC.gc()`](@ref Base.GC.gc) 强制执行此操作。 此外,尝试使用 `A` 可能会导致错误,因为大多数方法都没有在类型 `Nothing` 上定义。 ### 如何在会话中修改某个类型的声明? 也许你定义了某个类型,后来发现需要向其中增加一个新的域。如果在 REPL 中尝试这样做,会得到一个错误: ``` ERROR: invalid redefinition of constant MyType ``` 模块 `Main` 中的类型不能重新定义。 尽管这在开发新代码时会造成不便,但是这个问题仍然有一个不错的解决办法:可以用重新定义的模块替换原有的模块,把所有新代码封装在一个模块里,这样就能重新定义类型和常量了。虽说不能将类型名称导入到 `Main` 模块中再去重新定义,但是可以用模块名来改变作用范围。换言之,开发时的工作流可能类似这样: ```julia include("mynewcode.jl") # this defines a module MyModule obj1 = MyModule.ObjConstructor(a, b) obj2 = MyModule.somefunction(obj1) # Got an error. Change something in "mynewcode.jl" include("mynewcode.jl") # reload the module obj1 = MyModule.ObjConstructor(a, b) # old objects are no longer valid, must reconstruct obj2 = MyModule.somefunction(obj1) # this time it worked! obj3 = MyModule.someotherfunction(obj2, c) ... ``` ## [脚本](@id man-scripting) ### 该如何检查当前文件是否正在以主脚本运行? 当一个文件通过使用 `julia file.jl` 来当做主脚本运行时,有人也希望激活另外的功能例如命令行参数操作。确定文件是以这个方式运行的一个方法是检查 `abspath(PROGRAM_FILE) == @__FILE__` 是不是 `true`。 ### [怎样在脚本中捕获 CTRL-C ?](@id catch-ctrl-c) 通过 `julia file.jl` 方式运行的 Julia 脚本,在你尝试按 CTRL-C (SIGINT) 中止它时,并不会抛出 [`InterruptException`](@ref)。如果希望在脚本终止之后运行一些代码,请使用 [`atexit`](@ref),注意:脚本的中止不一定是由 CTRL-C 导致的。 另外你也可以通过 `julia -e 'include(popfirst!(ARGS))' file.jl` 命令运行脚本,然后可以通过 [`try`](@ref) 捕获 `InterruptException`。 ### 怎样通过 `#!/usr/bin/env` 传递参数给 `julia`? 通过类似 `#!/usr/bin/env julia --startup-file=no` 的方式,使用 shebang 传递选项给 Julia 的方法,可能在像 Linux 这样的平台上无法正常工作。这是因为各平台上 shebang 的参数解析是平台相关的,并且尚未标准化。 在类 Unix 的环境中,可以通过以 `bash` 脚本作为可执行脚本的开头,并使用 `exec` 代替给 `julia` 传递选项的过程,来可靠的为 `julia` 传递选项。 ```julia #!/bin/bash #= exec julia --color=yes --startup-file=no "${BASH_SOURCE[0]}" "$@" =# @show ARGS # put any Julia code here ``` 在以上例子中,位于 `#=` 和 `=#` 之间的代码可以当作一个 `bash` 脚本。 因为这些代码放在 Julia 的多行注释中,所以 Julia 会忽略它们。 在 `=#` 之后的 Julia 代码会被 `bash` 忽略,J因为当文件解析到 `exec` 语句时会停止解析,开始执行命令。 !!! note 为了在脚本中捕获 [catch CTRL-C](@ref catch-ctrl-c) ,我们可以使用 ```julia #!/bin/bash #= exec julia --color=yes --startup-file=no -e 'include(popfirst!(ARGS))' \ "${BASH_SOURCE[0]}" "$@" =# @show ARGS # put any Julia code here ``` instead. Note that with this strategy [`PROGRAM_FILE`](@ref) will not be set. ## 函数 ### 向函数传递了参数 `x`,在函数中做了修改,但是在函数外变量 `x` 的值还是没有变。为什么? 假设函数被如此调用: ```jldoctest julia> x = 10 10 julia> function change_value!(y) y = 17 end change_value! (generic function with 1 method) julia> change_value!(x) 17 julia> x # x is unchanged! 10 ``` 在 Julia 中,通过将 `x` 作为参数传递给函数,不能改变变量 `x` 的绑定。在上例中,调用 `change_value!(x)` 时,`y` 是一个新建变量,初始时与 `x` 的值绑定,即 `10`。然后 `y` 与常量 `17` 重新绑定,此时变量外作用域中的 `x` 并没有变动。 假设 `x` 被绑定至 `Array` 类型 (也有可能是其他 *可变* 的类型)。在函数中,你无法将 `x` 与 Array *解绑*,但是你可以改变其内容。 ```jldoctest julia> x = [1,2,3] 3-element Vector{Int64}: 1 2 3 julia> function change_array!(A) A[1] = 5 end change_array! (generic function with 1 method) julia> change_array!(x) 5 julia> x 3-element Vector{Int64}: 5 2 3 ``` 这里我们新建了一个函数 `chang_array!`,它把 `5` 赋值给传入的数组(在调用处与 `x` 绑定,在函数中与 `A` 绑定)的第一个元素。注意,在函数调用之后,`x` 依旧与同一个数组绑定,但是数组的内容变化了:变量 `A` 和 `x` 是不同的绑定,引用同一个可变的 `Array` 对象。 ### 函数内部能否使用 `using` 或 `import`? 不可以,不能在函数内部使用 `using` 或 `import` 语句。如果你希望导入一个模块,但只在特定的一个或一组函数中使用它的符号,有以下两种方式: 1. 使用 `import`: ```julia import Foo function bar(...) # ... refer to Foo symbols via Foo.baz ... end ``` 这会加载 `Foo` 模块,同时定义一个变量 `Foo` 引用该模块,但并不会 将其他任何符号从该模块中导入当前的命名空间。 `Foo` 等符号可以由限定的名称 `Foo.bar` 等引用。 2. 将函数封装到模块中: ```julia module Bar export bar using Foo function bar(...) # ... refer to Foo.baz as simply baz .... end end using Bar ``` 这会从 `Foo` 中导入所有符号,但仅限于 `Bar` 模块内。 ### 运算符 `...` 有何作用? #### `...` 运算符的两个用法:slurping 和 splatting 很多 Julia 的新手会对运算符 `...` 的用法感到困惑。让 `...` 用法如此困惑的部分原因是根据上下文它有两种不同的含义。 #### `...` 在函数定义中将多个参数组合成一个参数 在函数定义的上下文中,`...`运算符用来将多个不同的参数组合成单个参数。`...`运算符的这种将多个不同参数组合成单个参数的用法称为slurping: ```jldoctest julia> function printargs(args...) println(typeof(args)) for (i, arg) in enumerate(args) println("Arg #$i = $arg") end end printargs (generic function with 1 method) julia> printargs(1, 2, 3) Tuple{Int64, Int64, Int64} Arg #1 = 1 Arg #2 = 2 Arg #3 = 3 ``` 如果Julia是一个使用ASCII字符更加自由的语言的话,slurping运算符可能会写作`<-...`而非`...`。 #### `...`在函数调用中将一个参数分解成多个不同参数 与在定义函数时表示将多个不同参数组合成一个参数的`...`运算符用法相对,当用在函数调用的上下文中`...`运算符也用来将单个的函数参数分成多个不同的参数。`...`函数的这个用法叫做splatting: ```jldoctest julia> function threeargs(a, b, c) println("a = $a::$(typeof(a))") println("b = $b::$(typeof(b))") println("c = $c::$(typeof(c))") end threeargs (generic function with 1 method) julia> x = [1, 2, 3] 3-element Vector{Int64}: 1 2 3 julia> threeargs(x...) a = 1::Int64 b = 2::Int64 c = 3::Int64 ``` 如果Julia是一个使用ASCII字符更加自由的语言的话,splatting运算符可能会写作`...->`而非`...`。 ### 赋值语句的返回值是什么? `=`运算符始终返回右侧的值,所以: ```jldoctest julia> function threeint() x::Int = 3.0 x # returns variable x end threeint (generic function with 1 method) julia> function threefloat() x::Int = 3.0 # returns 3.0 end threefloat (generic function with 1 method) julia> threeint() 3 julia> threefloat() 3.0 ``` 相似地: ```jldoctest julia> function twothreetup() x, y = [2, 3] # assigns 2 to x and 3 to y x, y # returns a tuple end twothreetup (generic function with 1 method) julia> function twothreearr() x, y = [2, 3] # returns an array end twothreearr (generic function with 1 method) julia> twothreetup() (2, 3) julia> twothreearr() 2-element Vector{Int64}: 2 3 ``` ## 类型,类型声明和构造函数 ### [何谓“类型稳定”?](@id man-type-stability) 这意味着输出的类型可以由输入的类型预测出来。特别地,这意味着输出的类型不会因输入的*值*的不同而变化。以下代码*不是*类型稳定的: ```jldoctest julia> function unstable(flag::Bool) if flag return 1 else return 1.0 end end unstable (generic function with 1 method) ``` 根据参数值的不同,该函数可能返回 `Int` 或 [`Float64`](@ref)。由于 Julia 无法在编译期预测该函数的返回值类型,任何使用该函数的计算都需要考虑这两种可能的返回类型,这样难以生成高效的机器码。 ### [为何 Julia 对某个看似合理的操作返回 `DomainError`?](@id faq-domain-errors) 某些运算在数学上有意义,但会产生错误: ```jldoctest julia> sqrt(-2.0) ERROR: DomainError with -2.0: sqrt will only return a complex result if called with a complex argument. Try sqrt(Complex(x)). Stacktrace: [...] ``` 这一行为是为了保证类型稳定而带来的不便。对于 [`sqrt`](@ref),许多用户会希望 `sqrt(2.0)` 产生一个实数,如果得到了复数 `1.4142135623730951 + 0.0im` 则会不高兴。也可以编写 [`sqrt`](@ref) 函数,只有当传递一个负数时才切换到复值输出,但结果将不是[类型稳定](@ref man-type-stability)的,而且 [`sqrt`](@ref) 函数的性能会很差。 在这样那样的情况下,若你想得到希望的结果,你可以选择一个*输入类型*,它可以使根据你的想法接受一个*输出类型*,从而结果可以这样表示: ```jldoctest julia> sqrt(-2.0+0im) 0.0 + 1.4142135623730951im ``` ### 怎样限制或计算类型参数? [参数类型](@ref Parametric-Types) 的参数可以包含类型或比特值,并且类型本身选择如何使用这些参数。例如,`Array{Float64, 2}` 由类型 `Float64` 参数化以表示其元素类型,并通过整数值 `2` 来表示其维度数。在定义自己的参数类型时,可以使用子类型约束来声明某个参数必须是某个抽象类型的子类型 ([`<:`](@ref)) 或以前的类型参数。但是,没有专用的语法来声明参数必须是给定类型的_值_ — 也就是说,例如,你不能在`struct`定义中直接声明一个维度参数 [`isa`](@ref) `Int`。同样,你不能对类型参数进行计算(包括简单的加法或减法)。相反,这些类型的约束和关系可以通过在类型的 [构造函数](@ref man-constructors) 中计算和强制执行的附加类型参数来表达。 例如,考虑 ```julia struct ConstrainedType{T,N,N+1} # NOTE: INVALID SYNTAX A::Array{T,N} B::Array{T,N+1} end ``` 其中,用户希望强制第三个类型参数始终是第二个参数加一。 这可以使用显式类型参数来实现,该参数由 [内部构造函数方法](@ref man-inner-constructor-methods)(可以与其他检查结合使用)进行检查: ```julia struct ConstrainedType{T,N,M} A::Array{T,N} B::Array{T,M} function ConstrainedType(A::Array{T,N}, B::Array{T,M}) where {T,N,M} N + 1 == M || throw(ArgumentError("second argument should have one more axis" )) new{T,N,M}(A, B) end end ``` 这种检查通常是*无成本的*,因为编译器可以省略对有效具体类型的检查。 如果还计算了第二个参数,则提供执行此计算的 [外部构造函数方法](@ref man-outer-constructor-methods) 可能更好: ```julia ConstrainedType(A) = ConstrainedType(A, compute_B(A)) ``` ### [为什么Julia使用机器算法进行整数运算?](@id faq-integer-arithmetic) Julia使用机器算法进行整数计算。这意味着`Int`的范围是有界的,值在范围的两端循环,也就是说整数的加法,减法和乘法会出现上溢或者下溢,导致出现某些从开始就令人不安的结果: ```jldoctest julia> x = typemax(Int) 9223372036854775807 julia> y = x+1 -9223372036854775808 julia> z = -y -9223372036854775808 julia> 2*z 0 ``` 无疑,这与数学上的整数的行为很不一样,并且你会想对于高阶编程语言来说把这个暴露给用户难称完美。然而,对于效率优先和透明度优先的数值计算来说,其他的备选方案可谓更糟。 一个备选方案是去检查每个整数运算是否溢出,如果溢出则将结果提升到更大的整数类型比如[`Int128`](@ref)或者[`BigInt`](@ref)。 不幸的是,这会给所有的整数操作(比如让循环计数器自增)带来巨大的额外开销 — 这需要生成代码去在算法指令后进行运行溢出检测,并生成分支去处理潜在的溢出。更糟糕的是,这会让涉及整数的所有运算变得类型不稳定。如同上面提到的,对于高效生成高效的代码[类型稳定很重要](@ref man-type-stability)。如果不指望整数运算的结果是整数,就无法想C和Fortran编译器一样生成快速简单的代码。 这个方法有个变体可以避免类型不稳定的出现,这个变体是将类型`Int`和[`BigInt`](@ref)合并成单个混合整数类型,当结果不再满足机器整数的大小时会内部自动切换表示。虽然表面上在Julia代码层面解决了类型不稳定,但是这个只是通过将所有的困难硬塞给实现混合整数类型的C代码而掩盖了这个问题。这个方法*可能*有用,甚至在很多情况下速度很快,但是它有很多缺点。一个缺点是整数和整数数组的内存上的表示不再与C、Fortran和其他使用原生机器整数的怨言所使用的自然表示一样。所以,为了与那些语言协作,我们无论如何最终都需要引入原生整数类型。任何整数的无界表示都不会占用固定的比特数,所以无法使用固定大小的槽来内联地存储在数组中 — 大的整数值通常需要单独的堆分配的存储。并且无论使用的混合整数实现多么智能,总会存在性能陷阱 — 无法预期的性能下降的情况。复杂的表示,与C和Fortran协作能力的缺乏,无法在不使用另外的堆存储的情况下表示整数数组,和无法预测的性能特性让即使是最智能化的混合整数实现对于高性能数值计算来说也是个很差的选择。 除了使用混合整数和提升到BigInt,另一个备选方案是使用饱和整数算法,此时最大整数值加一个数时值保持不变,最小整数值减一个数时也是同样的。这就是Matlab™的做法: ``` >> int64(9223372036854775807) ans = 9223372036854775807 >> int64(9223372036854775807) + 1 ans = 9223372036854775807 >> int64(-9223372036854775808) ans = -9223372036854775808 >> int64(-9223372036854775808) - 1 ans = -9223372036854775808 ``` 乍一看,这个似乎足够合理,因为9223372036854775807比-9223372036854775808更接近于9223372036854775808并且整数还是以固定大小的自然方式表示的,这与C和Fortran相兼容。但是饱和整数算法是很有问题的。首先最明显的问题是这并不是机器整数算法的工作方式,所以实现饱和整数算法需要生成指令,在每个机器整数运算后检查上溢或者下溢并正确地讲这些结果用[`typemin(Int)`](@ref)或者[`typemax(Int)`](@ref)取代。单单这个就将整数运算从单语句的快速的指令扩展成六个指令,还可能包括分支。哎呦喂~~但是还有更糟的 — 饱和整数算法并不满足结合律。考虑下列的Matlab计算: ``` >> n = int64(2)^62 4611686018427387904 >> n + (n - 1) 9223372036854775807 >> (n + n) - 1 9223372036854775806 ``` 这就让写很多基础整数算法变得困难因为很多常用技术都是基于有溢出的机器加法*是*满足结合律这一事实的。考虑一下在Julia中求整数值`lo`和`hi`之间的中点值,使用表达式`(lo + hi) >>> 1`: ```jldoctest julia> n = 2^62 4611686018427387904 julia> (n + 2n) >>> 1 6917529027641081856 ``` 看到了吗?没有任何问题。那就是2^62和2^63之间的正确地中点值,虽然`n + 2n`的值是 -4611686018427387904。现在使用Matlab试一下: ``` >> (n + 2*n)/2 ans = 4611686018427387904 ``` 哎呦喂。在Matlab中添加`>>>`运算符没有任何作用,因为在将`n`与`2n`相加时已经破坏了能计算出正确地中点值的必要信息,已经出现饱和。 没有结合性不但对于不能依靠像这样的技术的程序员是不幸的,并且让几乎所有的希望优化整数算法的编译器铩羽而归。例如,因为Julia中的整数使用平常的机器整数算法,LLVM就可以自由地激进地优化像`f(k) = 5k-1`这样的简单地小函数。这个函数的机器码如下所示: ```julia-repl julia> code_native(f, Tuple{Int}) .text Filename: none pushq %rbp movq %rsp, %rbp Source line: 1 leaq -1(%rdi,%rdi,4), %rax popq %rbp retq nopl (%rax,%rax) ``` 这个函数的实际函数体只是一个简单地`leap`指令,可以立马计算整数乘法与加法。当`f`内联在其他函数中的时候这个更加有益: ```julia-repl julia> function g(k, n) for i = 1:n k = f(k) end return k end g (generic function with 1 methods) julia> code_native(g, Tuple{Int,Int}) .text Filename: none pushq %rbp movq %rsp, %rbp Source line: 2 testq %rsi, %rsi jle L26 nopl (%rax) Source line: 3 L16: leaq -1(%rdi,%rdi,4), %rdi Source line: 2 decq %rsi jne L16 Source line: 5 L26: movq %rdi, %rax popq %rbp retq nop ``` 因为`f`的调用内联化,循环体就只是简单地`leap`指令。接着,考虑一下如果循环迭代的次数固定的时候会发生什么: ```julia-repl julia> function g(k) for i = 1:10 k = f(k) end return k end g (generic function with 2 methods) julia> code_native(g,(Int,)) .text Filename: none pushq %rbp movq %rsp, %rbp Source line: 3 imulq $9765625, %rdi, %rax # imm = 0x9502F9 addq $-2441406, %rax # imm = 0xFFDABF42 Source line: 5 popq %rbp retq nopw %cs:(%rax,%rax) ``` 因为编译器知道整数加法和乘法是满足结合律的并且乘法可以在加法上使用分配律 — 两者在饱和算法中都不成立 — 所以编译器就可以把整个循环优化到只有一个乘法和一个加法。饱和算法完全无法使用这种优化,因为在每个循环迭代中结合律和分配律都会失效导致不同的失效位置会得到不同的结果。编译器可以展开循环,但是不能代数上将多个操作简化到更少的等效操作。 让整数算术沉默地溢出的最合理替代方法是在任何地方进行检查算术,在加法、减法和乘法溢出时引发错误,产生不正确的值。 在这篇[博文](https://danluu.com/integer-overflow/)中,Dan Luu 对此进行了分析,并发现这种方法在理论上应该具有的微不足道的成本,但由于编译器(LLVM 和 GCC)没有优雅地围绕添加的溢出检查进行优化,它最终会产生大量成本。 如果这在未来有所改善,我们可以考虑在 Julia 中默认使用检查整数算法,但现在,我们必须忍受可能会溢出这一现状。 同时,可以通过使用[SaferIntegers.jl](https://github.com/JeffreySarnoff/SaferIntegers.jl)等外部库来实现溢出安全的整数运算。 请注意,如前所述,使用这些库会显着增加使用已检查整数类型的代码的执行时间。 但是,对于有限的使用,这远比将其用于所有整数运算时的问题要小得多。你可以在 [此处](https://github.com/JuliaLang/julia/issues/855) 中关注讨论的状态。 ### 在远程执行中`UndefVarError`的可能原因有哪些? 如同这个错误表述的,远程结点上的`UndefVarError`的直接原因是变量名的绑定并不存在。让我们探索一下一些可能的原因。 ```julia-repl julia> module Foo foo() = remotecall_fetch(x->x, 2, "Hello") end julia> Foo.foo() ERROR: On worker 2: UndefVarError: Foo not defined Stacktrace: [...] ``` 闭包`x->x`中有`Foo`的引用,因为`Foo`在节点2上不存在,所以`UndefVarError`被扔出。 在模块中而非`Main`中的全局变量不会在远程节点上按值序列化。只传递了一个引用。新建全局绑定的函数(除了`Main`中)可能会导致之后扔出`UndefVarError`。 ```julia-repl julia> @everywhere module Foo function foo() global gvar = "Hello" remotecall_fetch(()->gvar, 2) end end julia> Foo.foo() ERROR: On worker 2: UndefVarError: gvar not defined Stacktrace: [...] ``` 在上面的例子中,`@everywhere module Foo`在所有节点上定义了`Foo`。但是调用`Foo.foo()`在本地节点上新建了新的全局绑定`gvar`,但是节点2中并没有找到这个绑定,这会导致`UndefVarError`错误。 注意着并不适用于在模块`Main`下新建的全局变量。模块`Main`下的全局变量会被序列化并且在远程节点的`Main`下新建新的绑定。 ```julia-repl julia> gvar_self = "Node1" "Node1" julia> remotecall_fetch(()->gvar_self, 2) "Node1" julia> remotecall_fetch(varinfo, 2) name size summary ––––––––– –––––––– ––––––– Base Module Core Module Main Module gvar_self 13 bytes String ``` 这并不适用于`函数`或者`结构体`声明。但是绑定到全局变量的匿名函数被序列化,如下例所示。 ```julia-repl julia> bar() = 1 bar (generic function with 1 method) julia> remotecall_fetch(bar, 2) ERROR: On worker 2: UndefVarError: #bar not defined [...] julia> anon_bar = ()->1 (::#21) (generic function with 1 method) julia> remotecall_fetch(anon_bar, 2) 1 ``` ## “method not matched”故障排除:参数类型不变性和`MethodError` ### 为什么声明 `foo(bar::Vector{Real}) = 42` 然后调用 `foo([1])` 不起作用? 如果你尝试了,结果就会看到`MethodError`: ```jldoctest julia> foo(x::Vector{Real}) = 42 foo (generic function with 1 method) julia> foo([1]) ERROR: MethodError: no method matching foo(::Vector{Int64}) Closest candidates are: foo(!Matched::Vector{Real}) at none:1 ``` 这是因为 `Vector{Real}` 不是 `Vector{Int}` 的超类型! 您可以使用类似 `foo(bar::Vector{T}) where {T<:Real}`(或缩写 `foo(bar::Vector{<:Real})` 如果静态参数函数体中不需要`T`)。`T` 是一个通配符:首先指定它必须是 Real 的子类型,然后指定函数采用具有该类型元素的 Vector 。 同样的问题适用于任何复合类型`Comp`,而不仅仅是`Vector`。 如果`Comp` 有一个声明为`Y` 类型的参数,那么另一个带有`X<:Y` 类型参数的类型`Comp2` 不是`Comp` 的子类型。 这是类型不变性(相比之下,元组在其参数中是类型协变的)。 有关这些的更多解释,请参阅 [参数复合类型](@ref man-parametric-composite-types)。 ### 为什么 Julia 使用 `*` 进行字符串拼接?而不是使用 `+` 或其他符号? 使用 `+` 的[主要依据](@ref man-concatenation)是:字符串拼接是不可交换的操作,而 `+` 通常是一个具有可交换性的操作符。Julia 社区也意识到其他语言使用了不同的操作符,一些用户也可能不熟悉 `*` 包含的特定代数性值。 注意:你也可以用 `string(...)` 来拼接字符串和其他能转换成字符串的值; 类似的 `repeat` 函数可以用于替代用于重复字符串的 `^` 操作符。 [字符串插值语法](@ref string-interpolation)在构造字符串时也很常用。 ## 包和模块 ### "using"和"import"的区别是什么? 只有一个区别,并且在表面上(语法层面)这个区别看来很小。`using`和`import`的区别是使用`using`时你需要写`function Foo.bar(..`来用一个新方法来扩展模块Foo的函数bar,但是使用`import Foo.bar`时,你只需要写`function bar(...`,会自动扩展模块Foo的函数bar。 这个区别足够重要以至于提供不同的语法的原因是你不希望意外地扩展一个你根本不知道其存在的函数,因为这很容易造成bug。对于使用像字符串后者整数这样的常用类型的方法最有可能出现这个问题,因为你和其他模块都可能定义了方法来处理这样的常用类型。如果你使用`import`,你会用你自己的新实现覆盖别的函数的`bar(s::AbstractString)`实现,这会导致做的事情天差地别(并且破坏模块Foo中其他的依赖于调用bar的函数的所有/大部分的将来的使用)。 ## 空值与缺失值 ### [在Julia中"null","空"或者"缺失"是怎么工作的?](@id faq-nothing) 不像其它很多语言(例如 C 和 Java),Julia 对象默认不能为"null"。当一个引用(变量,对象域,或者数组元素)没有被初始化,访问它会立即扔出一个错误。这种情况可以使用函数 [`isdefined`](@ref) 或者 [`isassigned`](@ref Base.isassigned) 检测到。 一些函数只为了其副作用使用,并不需要返回一个值。在这些情况下,约定的是返回 `nothing` 这个值,这只是 `Nothing` 类型的一个单例对象。这是一个没有域的一般类型;除了这个约定之外没有任何特殊点,REPL 不会为它打印任何东西。有些语言结构不会有值,也产生 `nothing`,例如 `if false; end`。 对于类型`T`的值`x`只会有时存在的情况,`Union{T,Nothing}`类型可以用作函数参数,对象域和数组元素的类型,与其他语言中的[`Nullable`, `Option` or `Maybe`](https://en.wikipedia.org/wiki/Nullable_type)相等。如果值本身可以是`nothing`(显然当`T`是`Any`时),`Union{Some{T}, Nothing}`类型更加准确因为`x == nothing`表示值的缺失,`x == Some(nothing)`表示与`nothing`相等的值的存在。[`something`](@ref)函数允许使用默认值的展开的`Some`对象,而非`nothing`参数。注意在使用`Union{T,Nothing}`参数或者域时编译器能够生成高效的代码。 在统计环境下表示缺失的数据(R 中的 `NA` 或者 SQL 中的 `NULL`)请使用 [`missing`](@ref) 对象。请参照[`缺失值`](@ref missing)章节来获取详细信息。 在某些语言中,空元组 (`()`) 被认为是"没有“的规范形式。但是,在 julia 中,最好将其视为恰好包含零个值的常规元组。 空(或者"底层")类型,写作`Union{}`(空的union类型)是没有值和子类型(除了自己)的类型。通常你没有必要用这个类型。 ## 内存 ### 为什么当`x`和`y`都是数组时`x += y`还会申请内存? 在 Julia 中,`x += y` 在语法分析中会用 `x = x + y` 代替。对于数组,结果就是它会申请一个新数组来存储结果,而非把结果存在 `x` 同一位置的内存上。 这个行为可能会让一些人吃惊,但是这个结果是经过深思熟虑的。主要原因是Julia中的不可变对象,这些对象一旦新建就不能改变他们的值。实际上,数字是不可变对象,语句`x = 5; x += 1`不会改变`5`的意义,改变的是与`x`绑定的值。对于不可变对象,改变其值的唯一方法是重新赋值。 为了稍微详细一点,考虑下列的函数: ```julia function power_by_squaring(x, n::Int) ispow2(n) || error("此实现只适用于2的幂") while n >= 2 x *= x n >>= 1 end x end ``` 在`x = 5; y = power_by_squaring(x, 4)`调用后,你可以得到期望的结果`x == 5 && y == 625`。然而,现在假设当`*=`与矩阵一起使用时会改变左边的值,这会有两个问题: * 对于普通的方阵,`A = A*B` 不能在没有临时存储的情况下实现:`A[1,1]` 会被计算并且在被右边使用完之前存储在左边。 * 假设你愿意申请一个计算的临时存储(这会消除 `*=`就地计算的大部分要点);如果你利用了`x`的可变性, 这个函数会对于可变和不可变的输入有不同的行为。特别地, 对于不可变的`x`,在调用后(通常)你会得到`y != x`,而对可变的`x`,你会有`y == x`。 因为支持范用计算被认为比能使用其他方法完成的潜在的性能优化(比如使用显式循环)更加重要,所以像`+=`和`*=`运算符以绑定新值的方式工作。 ## [异步 IO 与并发同步写入](@id faq-async-io) ### 为什么对于同一个流的并发写入会导致相互混合的输出? 虽然流式 I/O 的 API 是同步的,底层的实现是完全异步的。 思考一下下面的输出: ```jldoctest julia> @sync for i in 1:3 @async write(stdout, string(i), " Foo ", " Bar ") end 123 Foo Foo Foo Bar Bar Bar ``` 这是因为,虽然`write`调用是同步的,每个参数的写入在等待那一部分I/O完成时会生成其他的Tasks。 `print`和`println`在调用中会"锁定"该流。因此把上例中的`write`改成`println`会导致: ```jldoctest julia> @sync for i in 1:3 @async println(stdout, string(i), " Foo ", " Bar ") end 1 Foo Bar 2 Foo Bar 3 Foo Bar ``` 你可以使用`ReentrantLock`来锁定你的写入,就像这样: ```jldoctest julia> l = ReentrantLock(); julia> @sync for i in 1:3 @async begin lock(l) try write(stdout, string(i), " Foo ", " Bar ") finally unlock(l) end end end 1 Foo Bar 2 Foo Bar 3 Foo Bar ``` ## 数组 ### 零维数组和标量之间的有什么差别? 零维数组是`Array{T,0}`形式的数组,它与标量的行为相似,但是有很多重要的不同。这值得一提,因为这是使用数组的范用定义来解释也符合逻辑的特殊情况,虽然最开始看起来有些非直觉。下面一行定义了一个零维数组: ``` julia> A = zeros() 0-dimensional Array{Float64,0}: 0.0 ``` 在这个例子中,`A`是一个含有一个元素的可变容器,这个元素可以通过`A[] = 1.0`来设置,通过`A[]`来读取。所有的零维数组都有同样的大小(`size(A) == ()`)和长度(`length(A) == 1`)。特别地,零维数组不是空数组。如果你觉得这个非直觉,这里有些想法可以帮助理解Julia的这个定义。 * 类比的话,零维数组是"点",向量是"线"而矩阵 是"面"。就像线没有面积一样(但是也能代表事物的一个集合), 点没有长度和任意一个维度(但是也能表示一个事物)。 * 我们定义`prod(())`为1,一个数组中的所有的元素个数是 大小的乘积。零维数组的大小为`()`,所以 它的长度为`1`。 * 零维数组没有任何你可以索引的维度——它们仅仅是`A[]`。我们可以给它们应用同样的"尾一"规则就像对其它维度数组那样,比如`A[1]`,`A[1,1]`,等;参见[Omitted and extra indices](@ref). 理解它与普通的标量之间的区别也很重要。标量不是一个可变的容器(尽管它们是可迭代的,可以定义像`length`,`getindex`这样的东西,*例如*`1[] == 1`)。特别地,如果`x = 0.0`是以一个标量来定义,尝试通过`x[] = 1.0`来改变它的值会报错。标量`x`能够通过`fill(x)`转化成包含它的零维数组,并且相对地,一个零维数组`a`可以通过`a[]`转化成其包含的标量。另外一个区别是标量可以参与到线性代数运算中,比如`2 * rand(2,2)`,但是零维数组的相似操作`fill(2) * rand(2,2)`会报错。 ### 为什么我的Julia的线性代数操作测试与其他的语言不同。 你可能找到一些简单的线性代数测试,比如, ```julia using BenchmarkTools A = randn(1000, 1000) B = randn(1000, 1000) @btime $A \ $B @btime $A * $B ``` 也许和其他语言不同比如Matlab或R。 由于像这样的操作都非常直接地从相关的BLAS函数调用,这样做的原因是, 1. 在每种语言中使用的BLAS库 2. 并发线程的数量 Julia 编译并使用自己的 OpenBLAS 副本,当前线程数上限为 8(或内核数)。 修改 OpenBLAS 设置或使用不同的 BLAS 库编译 Julia,例如 [Intel MKL](https://software.intel.com/en-us/mkl),可能会提高性能。 你可以使用 [MKL.jl](https://github.com/JuliaComputing/MKL.jl),这是一个使 Julia 的线性代数使用英特尔 MKL BLAS 和 LAPACK 而不是 OpenBLAS 的包,或搜索论坛以获取有关如何使用的建议。 请注意,英特尔 MKL 不能与 Julia 捆绑在一起,因为它不是开源的。 ## 计算集群 ### 我该如何管理分布式文件系统的预编译缓存? 在高性能计算 (HPC) 设施中使用 `julia` 时,同时调用 _n_ 个 `julia` 进程最多会创建 _n_ 个预编译缓存文件的临时副本。 如果这是一个问题(缓慢和/或小型分布式文件系统),你可以: 1. 使用 `julia`的 `--compiled-modules=no` 标志来关掉预编译。 2. 使用 `pushfirst!(DEPOT_PATH, private_path)` 配置一个私有的可写仓库 在这里`private_path`是一个路径单独地到这个`julia`进程 也可以通过设置环境变量 `JULIA_DEPOT_PATH` 到 `$private_path:$HOME/.julia`. 3. 在scratch里创建到 `~/.julia/compiled`的符号链接。 ## Julia 版本发布 ### 你希望使用稳定的、长期支持的或是每日构建版本的Julia? Julia 的稳定版是最新发布的 Julia 版本,这是大多数人想要运行的版本。 它具有最新的功能,包括改进的性能。 Julia 的稳定版本根据 [SemVer](https://semver.org/) 版本化为 v1.x.y。 在作为候选版本进行几周的测试后,大约每 4-5 个月就会发布一个与新稳定版本相对应的新 Julia 次要版本。 与 LTS 版本不同,在 Julia 的另一个稳定版本发布后,稳定版本通常不会收到错误修正。 但是,始终可以升级到下一个稳定版本,因为 Julia v1.x 的每个版本都将继续运行为早期版本编写的代码。 如果正在寻找非常稳定的代码库,你可能更喜欢 Julia 的 LTS(长期支持)版本。 Julia 当前的 LTS 版本根据 SemVer 版本为 v1.0.x; 此分支将继续接收错误修复,直到选择新的 LTS 分支,此时 v1.0.x 系列将不再收到常规错误修复,建议除最保守的用户之外的所有用户升级到新的 LTS 版本系列。作为软件包开发人员,你可能更喜欢针对 LTS 版本进行开发,以最大限度地增加可以使用你的软件包的用户数量。 根据 SemVer,为 v1.0 编写的代码将继续适用于所有未来的 LTS 和稳定版本。 一般来说,即使针对 LTS,也可以在最新的 Stable 版本中开发和运行代码,以利用改进的性能; 只要避免使用新功能(例如添加的库函数或新方法)。 如果您想利用该语言的最新更新,您可能更喜欢 Julia 的每日构建版本,并且不介意今天可用的版本是否偶尔无法正常工作。 顾名思义,每日构建版本的发布大约每晚发布一次(取决于构建基础设施的稳定性)。 一般来说,每日构建的发布是相当安全的——你的代码不会着火。 然而,它们可能出现偶尔的版本倒退和问题,直到更彻底的预发布测试才会发现。 你可能希望针对每日构建版本进行测试,以确保在发布之前捕获影响你的用例的版本倒退。 最后,您也可以考虑为自己从源代码构建 Julia。 此选项主要适用于那些熟悉命令行或对学习感兴趣的人。 如果你是这样的人,你可能也有兴趣阅读我们的 [贡献指南](https://github.com/JuliaLang/julia/blob/master/CONTRIBUTING.md)。 可以在[https://julialang.org/downloads/](https://julialang.org/downloads/)的下载页面上找到每种下载类型的链接。 请注意,并非所有版本的Julia都适用于所有平台。 ### 更新我的 Julia 版本后,如何转移已安装软件包的列表? julia 的每个次要版本都有自己的默认 [环境](https://docs.julialang.org/en/v1/manual/code-loading/#Environments-1)。 因此,在安装新的 Julia 次要版本时,默认情况下你使用先前次要版本添加的包将不可用。 给定 julia 版本的环境由文件`Project.toml`和`Manifest.toml`定义,文件夹中的文件与`.julia/environments/`中的版本号匹配,例如`.julia/environments/v1.3`。 如果你安装了一个新的 Julia 次要版本,比如 `1.4`,并且想要在它的默认环境中使用与以前版本(例如 `1.3`)相同的包,你可以从`1.3` 文件夹复制文件 `Project.toml` 的内容到`1.4`。然后,在新的 Julia 版本的会话中,输入`]` 键进入“包管理模式”,并运行命令 [`instantiate`](https://julialang.github.io/Pkg.jl/v1/api/#Pkg.instantiate)。 此操作将从复制的文件中解析一组与目标 Julia 版本兼容的可行包,并在合适时安装或更新它们。 如果你不仅要重现软件包,还要重现在以前的 Julia 版本中使用的版本,您还应该在运行 Pkg 命令 `instantiate` 之前复制 `Manifest.toml` 文件。 但是,请注意,包可能定义了兼容性约束,这些约束可能会受到更改 Julia 版本的影响,因此你在`1.3`中拥有的确切版本集可能不适用于`1.4`。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
18648
# [函数](@id man-functions) 在 Julia 里,函数是将参数值组成的元组映射到返回值的一个对象。Julia 的函数不是纯粹的数学函数,因为这些函数可以改变程序的全局状态并且可能受其影响。在Julia中定义函数的基本语法是: ```jldoctest julia> function f(x,y) x + y end f (generic function with 1 method) ``` 这个函数接收两个参数 `x` 和 `y` 并返回最后一个表达式的值,这里是 `x + y`。 在 Julia 中定义函数还有第二种更简洁的语法。上述的传统函数声明语法等效于以下紧凑性的“赋值形式”: ```jldoctest fofxy julia> f(x,y) = x + y f (generic function with 1 method) ``` 尽管函数可以是复合表达式 (见 [复合表达式](@ref man-compound-expressions)),但在赋值形式下,函数体必须是一个一行的表达式。简短的函数定义在 Julia 中是很常见的。非常惯用的短函数语法大大减少了打字和视觉方面的干扰。 使用传统的括号语法调用函数: ```jldoctest fofxy julia> f(2,3) 5 ``` 没有括号时,表达式 `f` 指的是函数对象,可以像任何值一样被传递: ```jldoctest fofxy julia> g = f; julia> g(2,3) 5 ``` 和变量名一样,Unicode 字符也可以用作函数名: ```jldoctest julia> ∑(x,y) = x + y ∑ (generic function with 1 method) julia> ∑(2, 3) 5 ``` ## 参数传递行为 Julia 函数参数遵循有时称为 “pass-by-sharing” 的约定,这意味着变量在被传递给函数时其值并不会被复制。函数参数本身充当新的变量绑定(指向变量值的新地址),它们所指向的值与所传递变量的值完全相同。调用者可以看到对函数内可变值(如数组)的修改。这与 Scheme,大多数 Lisps,Python,Ruby 和 Perl 以及其他动态语言中的行为相同。 ## 参数类型声明 您可以通过将 `::TypeName` 附加到参数名称来声明函数参数的类型,就像 Julia 中的 [类型声明](@ref Type-Declarations) 一样。 例如,以下函数递归计算 [斐波那契数列](https://en.wikipedia.org/wiki/Fibonacci_number): ``` fib(n::Integer) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2) ``` 并且 `::Integer` 规范意味着它只有在 `n` 是 [抽象](@ref man-abstract-types) `Integer` 类型的子类型时才可调用。 参数类型声明**通常对性能没有影响**:无论声明什么参数类型(如果有),Julia 都会为实际参数类型编译函数的特例版本。 例如,调用 `fib(1)` 将触发专门为 `Int` 参数优化的特例化的`fib` 的编译,它会在 `fib(7)` 或 `fib(15)` 调用时重新使用。 (参数类型声明不触发额外的编译器特化的情况很少;请参阅:[注意 Julia 何时不触发特例化](@ref Be-aware-of-when-Julia-avoids-specializing)。)在 Julia 中声明参数类型的最常见原因是: * **派发:** 如 [方法](@ref) 中所述,对于不同的参数类型,你可以有不同版本(“方法”)的函数,在这种情况下,参数类型用于确定调用哪个版本的函数。例如,你可以使用 [Binet 公式](https://en.wikipedia.org/wiki/Fibonacci_number#Binet's_formula) 实现一个完全不同的算法 `fib(x::Number) = ...`,该算法扩展为了非整数值,适用于任何 `Number` 类型。 * **正确性:** 如果函数只为某些参数类型返回正确的结果,则类型声明会很有用。例如,如果我们省略参数类型并写成 `fib(n) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2)`,然后`fib(1.5)`会默默地给我们无意义的答案`1.0`。 * **清晰性:** 类型声明可以作为一种关于预期参数的文档形式。 但是,**过分限制参数类型是常见的错误**,这会不必要地限制函数的适用性,并防止它在未预料到的情况下被重用。例如,上面的 `fib(n::Integer)` 函数同样适用于 `Int` 参数(机器整数)和 `BigInt` 任意精度整数(参见 [BigFloats 和 BigInts](@ref BigFloats-and-BigInts)),这样十分有效,因为斐波那契数以指数方式快速增长,并且会迅速溢出任何固定精度类型,如 `Int`(参见 [溢出行为](@ref))。但是,如果我们将函数声明为 `fib(n::Int)`,那么 `BigInt` 的应用就会被阻止。通常,应该对参数使用最通用的适用抽象类型,并且**如有不确定,就省略参数类型**。如果有必要,你可以随时添加参数类型规范,并且不会因为省略它们而牺牲性能或功能。 ## `return` 关键字 函数返回的值是最后计算的表达式的值,默认情况下,它是函数定义主体中的最后一个表达式。在上一小节的示例函数 `f` 中,返回值是表达式的 `x + y` 值。与在 C 语言和大多数其他命令式或函数式语言中一样,`return` 关键字会让函数立即返回,从而提供返回值的表达式: ```julia function g(x,y) return x * y x + y end ``` 由于函数定义可以输入到交互式会话中,因此可以很容易的比较这些定义: ```jldoctest julia> f(x,y) = x + y f (generic function with 1 method) julia> function g(x,y) return x * y x + y end g (generic function with 1 method) julia> f(2,3) 5 julia> g(2,3) 6 ``` 当然,在一个单纯的线性执行的函数体内,例如 `g`,使用 `return` 是没有意义的,因为表达式 `x + y` 永远不会被执行到,我们可以简单地把 `x * y` 写为最后一个表达式从而省略掉 `return`。 然而在使用其他控制流程的函数体内,`return` 却是有用的。 例如,在计算两条边长分别为 `x` 和 `y` 的三角形的斜边长度时可以避免溢出: ```jldoctest julia> function hypot(x,y) x = abs(x) y = abs(y) if x > y r = y/x return x*sqrt(1+r*r) end if y == 0 return zero(x) end r = x/y return y*sqrt(1+r*r) end hypot (generic function with 1 method) julia> hypot(3, 4) 5.0 ``` 这个函数有三个可能的返回处,返回三个不同表达式的值,具体取决于 `x` 和 `y` 的值。 最后一行的 `return` 可以省略,因为它是最后一个表达式。 ### 返回类型 也可以使用 `::` 运算符在函数声明中指定返回类型。 这可以将返回值转换为指定的类型。 ```jldoctest julia> function g(x, y)::Int8 return x * y end; julia> typeof(g(1, 2)) Int8 ``` 这个函数将忽略 `x` 和 `y` 的类型,返回 `Int8` 类型的值。有关返回类型的更多信息,请参见[类型声明](@ref Type-Declarations)。 返回类型声明在 Julia 中**很少使用**:通常,你应该编写“类型稳定”的函数,Julia 的编译器可以在其中自动推断返回类型。更多信息请参阅 [性能提示](@ref man-performance-tips) 一章。 ### 返回 nothing 对于不需要任何返回值的函数(只用来产生副作用的函数), Julia 中的写法为返回值[`nothing`](@ref): ```julia function printx(x) println("x = $x") return nothing end ``` 这在某种意义上是一个“惯例”,在 Julia 中 `nothing` 不是一个关键字,而是 `Nothing` 类型的一个单例(singleton)。 也许你已经注意到 `printx` 函数有点不自然,因为 `println` 实际上已经会返回 `nothing`,所以 `return` 语句是多余的。 有两种比 `return nothing` 更短的写法:一种是直接写 `return` 这会隐式的返回 `nothing`。 另一种是在函数的会后一行写上 `nothing`,因为函数会隐式的返回最后一个表达式的值。 三种写法使用哪一种取决于代码风格的偏好。 ## 操作符也是函数 在 Julia中,大多数操作符只不过是支持特殊语法的函数( `&&` 和`||` 等具有特殊评估语义的操作符除外,他们不能是函数,因为[短路求值](@ref)要求在计算整个表达式的值之前不计算每个操作数)。因此,您也可以使用带括号的参数列表来使用它们,就和任何其他函数一样: ```jldoctest julia> 1 + 2 + 3 6 julia> +(1,2,3) 6 ``` 中缀表达式和函数形式完全等价。—— 事实上,前一种形式会被编译器转换为函数调用。这也意味着你可以对操作符,例如 [`+`](@ref) 和 [`*`](@ref) ,进行赋值和传参,就像其它函数传参一样。 ```jldoctest julia> f = +; julia> f(1,2,3) 6 ``` 然而,函数以`f`命名时不再支持中缀表达式。 ## 具有特殊名称的操作符 有一些特殊的表达式对应的函数调用没有显示的函数名称,它们是: | 表达式 | 函数调用 | |:----------------- |:----------------------- | | `[A B C ...]` | [`hcat`](@ref) | | `[A; B; C; ...]` | [`vcat`](@ref) | | `[A B; C D; ...]` | [`hvcat`](@ref) | | `A'` | [`adjoint`](@ref) | | `A[i]` | [`getindex`](@ref) | | `A[i] = x` | [`setindex!`](@ref) | | `A.n` | [`getproperty`](@ref Base.getproperty) | | `A.n = x` | [`setproperty!`](@ref Base.setproperty!) | ## [匿名函数](@id man-anonymous-functions) 函数在Julia里是[一等公民](https://en.wikipedia.org/wiki/First-class_citizen):可以指定给变量,并使用标准函数调用语法通过被指定的变量调用。函数可以用作参数,也可以当作返回值。函数也可以不带函数名称地匿名创建,使用语法如下: ```jldoctest julia> x -> x^2 + 2x - 1 #1 (generic function with 1 method) julia> function (x) x^2 + 2x - 1 end #3 (generic function with 1 method) ``` 这样就创建了一个接受一个参数 `x` 并返回当前值的多项式 `x^2+2x-1` 的函数。注意结果是个泛型函数,但是带了编译器生成的连续编号的名字。 匿名函数最主要的用法是传递给接收函数作为参数的函数。一个经典的例子是 [`map`](@ref) ,为数组的每个元素应用一次函数,然后返回一个包含结果值的新数组: ```jldoctest julia> map(round, [1.2, 3.5, 1.7]) 3-element Vector{Float64}: 1.0 4.0 2.0 ``` 如果做为第一个参数传递给 [`map`](@ref) 的转换函数已经存在,那直接使用函数名称是没问题的。但是通常要使用的函数还没有定义好,这样使用匿名函数就更加方便: ```jldoctest julia> map(x -> x^2 + 2x - 1, [1, 3, -1]) 3-element Vector{Int64}: 2 14 -2 ``` 接受多个参数的匿名函数写法可以使用语法 `(x,y,z)->2x+y-z`,而无参匿名函数写作 `()->3` 。无参函数的这种写法看起来可能有些奇怪,不过它对于延迟计算很有必要。这种用法会把代码块包进一个无参函数中,后续把它当做 `f` 调用。 例如,考虑对 [`get`](@ref) 的调用: ```julia get(dict, key) do # default value calculated here time() end ``` 上面的代码等效于使用包含代码的匿名函数调用`get`。 被包围在do和end之间,如下所示 ```julia get(()->time(), dict, key) ``` 这里对 [`time`](@ref) 的调用,被包裹了它的一个无参数的匿名函数延迟了。该匿名函数只当 `dict` 缺少被请求的键时,才被调用。 ## 元组 Julia 有一个和函数参数与返回值密切相关的内置数据结构叫做元组(*tuple*)。 一个元组是一个固定长度的容器,可以容纳任何值,但不可以被修改(是*immutable*的)。 元组通过圆括号和逗号来构造,其内容可以通过索引来访问: ```jldoctest julia> (1, 1+1) (1, 2) julia> (1,) (1,) julia> x = (0.0, "hello", 6*7) (0.0, "hello", 42) julia> x[2] "hello" ``` 注意,长度为1的元组必须使用逗号 `(1,)`,而 `(1)` 只是一个带括号的值。`()` 表示空元组(长度为0)。 ## 具名元组 元组的元素可以有名字,这时候就有了*具名元组*: ```jldoctest julia> x = (a=2, b=1+2) (a = 2, b = 3) julia> x[1] 2 julia> x.a 2 ``` 具名元组和元组十分类似,区别在于除了一般的下标语法(`x[1]`),还可以使用点运算符语法(`x.a`)通过元素的名字来访问它的元素。 ## [解构赋值和多返回值](@id destructuring-assignment) 逗号分隔的变量列表(可选地用括号括起来)可以出现在赋值的左侧:右侧的值通过迭代并依次分配给每个变量来_解构_: ```jldoctest julia> (a,b,c) = 1:3 1:3 julia> b 2 ``` 右边的值应该是一个至少与左边的变量数量一样长的迭代器(参见[迭代接口](@ref man-interface-iteration))(迭代器的任何多余元素会被忽略)。 可用于通过返回元组或其他可迭代值从函数返回多个值。例如,以下函数返回两个值: ```jldoctest foofunc julia> function foo(a,b) a+b, a*b end foo (generic function with 1 method) ``` 如果你在交互式会话中调用它且不把返回值赋值给任何变量,你会看到返回的元组: ```jldoctest foofunc julia> foo(2,3) (5, 6) ``` 解构赋值将每个值提取到一个变量中: ```jldoctest foofunc julia> x, y = foo(2,3) (5, 6) julia> x 5 julia> y 6 ``` 另一个常见用途是交换变量: ```jldoctest foofunc julia> y, x = x, y (5, 6) julia> x 6 julia> y 5 ``` 如果只需要迭代器元素的一个子集,一个常见的惯例是将忽略的元素分配给一个只包含下划线 `_` 的变量(这是一个无效的变量名,请参阅 [合法的变量名](@ref man -allowed-variable-names)): ```jldoctest julia> _, _, _, d = 1:10 1:10 julia> d 4 ``` 其他有效的左侧表达式可以用作赋值列表的元素,它们将调用 [`setindex!`](@ref) 或 [`setproperty!`](@ref),或者递归地解构迭代器的各个元素: ```jldoctest julia> X = zeros(3); julia> X[1], (a,b) = (1, (2, 3)) (1, (2, 3)) julia> X 3-element Vector{Float64}: 1.0 0.0 0.0 julia> a 2 julia> b 3 ``` !!! compat "Julia 1.6" 带 `...` 的赋值需要 Julia 1.6 如果赋值列表中的最后一个符号后缀为 `...`(称为 _slurping_),那么它将被分配给右侧迭代器剩余元素的集合或其惰性迭代器: ```jldoctest julia> a, b... = "hello" "hello" julia> a 'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase) julia> b "ello" julia> a, b... = Iterators.map(abs2, 1:4) Base.Generator{UnitRange{Int64}, typeof(abs2)}(abs2, 1:4) julia> a 1 julia> b Base.Iterators.Rest{Base.Generator{UnitRange{Int64}, typeof(abs2)}, Int64}(Base.Generator{UnitRange{Int64}, typeof(abs2)}(abs2, 1:4), 1) ``` 有关特定迭代器的精确处理和自定义的详细信息,请参阅 [`Base.rest`](@ref)。 ## 参数解构 析构特性也可以被用在函数参数中。 如果一个函数的参数被写成了元组形式 (如 `(x, y)`) 而不是简单的符号,那么一个赋值运算 `(x, y) = argument` 将会被默认插入: ```julia julia> minmax(x, y) = (y < x) ? (y, x) : (x, y) julia> gap((min, max)) = max - min julia> gap(minmax(10, 2)) 8 ``` 注意在定义函数 `gap` 时额外的括号。 没有它们,`gap` 函数将会是一个双参数函数,这个例子也会无法正常运行。 对于匿名函数,解构单个元组需要一个额外的逗号: ``` julia> map(((x,y),) -> x + y, [(1,2), (3,4)]) 2-element Array{Int64,1}: 3 7 ``` ## 变参函数 定义有任意个参数的函数会带来很多便利。这类函数通常被称为“变参”函数,即“参数数量可变”的简称。你可以通过在最后一个参数后增加省略号来定义一个变参函数: ```jldoctest barfunc julia> bar(a,b,x...) = (a,b,x) bar (generic function with 1 method) ``` 变量 `a` 和 `b` 和以前一样被绑定给前两个参数,后面的参数整个做为迭代集合被绑定到变量 `x` 上 : ```jldoctest barfunc julia> bar(1,2) (1, 2, ()) julia> bar(1,2,3) (1, 2, (3,)) julia> bar(1, 2, 3, 4) (1, 2, (3, 4)) julia> bar(1,2,3,4,5,6) (1, 2, (3, 4, 5, 6)) ``` 在所有这些情况下,`x` 被绑定到传递给 `bar` 的尾随值的元组。 也可以限制可以传递给函数的参数的数量,这部分内容稍后在 [参数化约束的可变参数方法](@ref) 中讨论。 另一方面,将可迭代集中包含的值拆解为单独的参数进行函数调用通常很方便。 要实现这一点,需要在函数调用中额外使用 `...` 而不仅仅只是变量: ```jldoctest barfunc julia> x = (3, 4) (3, 4) julia> bar(1,2,x...) (1, 2, (3, 4)) ``` 在这个情况下一组值会被精确切片成一个可变参数调用,这里参数的数量是可变的。但是并不需要成为这种情况: ```jldoctest barfunc julia> x = (2, 3, 4) (2, 3, 4) julia> bar(1,x...) (1, 2, (3, 4)) julia> x = (1, 2, 3, 4) (1, 2, 3, 4) julia> bar(x...) (1, 2, (3, 4)) ``` 进一步,拆解给函数调用中的可迭代对象不需要是个元组: ```jldoctest barfunc julia> x = [3,4] 2-element Vector{Int64}: 3 4 julia> bar(1,2,x...) (1, 2, (3, 4)) julia> x = [1,2,3,4] 4-element Vector{Int64}: 1 2 3 4 julia> bar(x...) (1, 2, (3, 4)) ``` 此外,参数被放入的函数不一定是可变参数函数(尽管经常是): ```jldoctest julia> baz(a,b) = a + b; julia> args = [1,2] 2-element Vector{Int64}: 1 2 julia> baz(args...) 3 julia> args = [1,2,3] 3-element Vector{Int64}: 1 2 3 julia> baz(args...) ERROR: MethodError: no method matching baz(::Int64, ::Int64, ::Int64) Closest candidates are: baz(::Any, ::Any) at none:1 ``` 正如你所见,如果要拆解的容器(比如元组或数组)元素数量不匹配就会报错,和直接给多个参数报错一样。 ## 可选参数 在很多情况下,函数参数有合理的默认值,因此也许不需要显式地传递。例如,`Dates` 模块中的 [`Date(y, [m, d])`](@ref) 函数对于给定的年(year)`y`、月(mouth)`m`、日(data)`d` 构造了 `Date` 类型。但是,`m` 和 `d` 参数都是可选的,默认值都是 `1`。这行为可以简述为: ```julia function Date(y::Int64, m::Int64=1, d::Int64=1) err = validargs(Date, y, m, d) err === nothing || throw(err) return Date(UTD(totaldays(y, m, d))) end ``` 注意,这个定义调用了 `Date` 函数的另一个方法,该方法带有一个 `UTInstant{Day}` 类型的参数。 通过此定义,函数调用时可以带有一个、两个或三个参数,并且在只有一个或两个参数被指定时后,自动传递 `1` 为未指定参数值: ```jldoctest julia> using Dates julia> Date(2000, 12, 12) 2000-12-12 julia> Date(2000, 12) 2000-12-01 julia> Date(2000) 2000-01-01 ``` 可选参数实际上只是一种方便的语法,用于编写多种具有不同数量参数的方法定义(请参阅 [可选参数和关键字的参数的注意事项](@ref))。这可通过调用 `methods` 函数来检查我们的 `Date` 函数示例。 ## 关键字参数 某些函数需要大量参数,或者具有大量行为。记住如何调用这样的函数可能很困难。关键字参数允许通过名称而不是仅通过位置来识别参数,使得这些复杂接口易于使用和扩展。 例如,考虑绘制一条线的函数 `plot`。这个函数可能有很多选项,用来控制线条的样式、宽度、颜色等。如果它接受关键字参数,一个可行的调用可能看起来像 `plot(x, y, width=2)`,这里我们仅指定线的宽度。请注意,这样做有两个目的。调用更可读,因为我们能以其意义标记参数。也使得大量参数的任意子集都能以任意次序传递。 具有关键字参数的函数在签名中使用分号定义: ```julia function plot(x, y; style="solid", width=1, color="black") ### end ``` 在函数调用时,分号是可选的:可以调用 `plot(x, y, width=2)` 或 `plot(x, y; width=2)`,但前者的风格更为常见。显式的分号只有在传递可变参数或下文中描述的需计算的关键字时是必要的。 关键字参数的默认值只在必需时求值(当相应的关键字参数没有被传入),并且按从左到右的顺序求值,因为默认值的表达式可能会参照先前的关键字参数。 关键字参数的类型可以通过如下的方式显式指定: ```julia function f(;x::Int=1) ### end ``` 关键字参数也可以在变参函数中使用: ```julia function plot(x...; style="solid") ### end ``` 附加的关键字参数可用 `...` 收集,正如在变参函数中: ```julia function f(x; y=0, kwargs...) ### end ``` 在 `f` 中,`kwargs` 将是一个在命名元组上的不可变键值迭代器。 具名元组(以及带有`Symbol`键的字典)可以在调用中使用分号作为关键字参数传递,例如 `f(x, z=1; kwargs...)`。 如果一个关键字参数在方法定义中未指定默认值,那么它就是*必需的*:如果调用者没有为其赋值,那么将会抛出一个 [`UndefKeywordError`](@ref) 异常: ```julia function f(x; y) ### end f(3, y=5) # ok, y is assigned f(3) # throws UndefKeywordError(:y) ``` 在分号后也可传递 `key => value` 表达式。例如,`plot(x, y; :width => 2)` 等价于 `plot(x, y, width=2)`。当关键字名称需要在运行时被计算时,这就很实用了。 当分号后出现裸标识符或点表达式时,标识符或字段名称隐含关键字参数名称。 例如`plot(x, y; width)` 等价于`plot(x, y; width=width)`,`plot(x, y; options.width)` 等价于`plot(x, y; width=options.width)`。 可选参数的性质使得可以多次指定同一参数的值。例如,在调用 `plot(x, y; options..., width=2)` 的过程中,`options` 结构也能包含一个 `width` 的值。在这种情况下,最右边的值优先级最高;在此例中,`width` 的值可以确定是 `2`。但是,显式地多次指定同一参数的值是不允许的,例如 `plot(x, y, width=2, width=3)`,这会导致语法错误。 ## 默认值作用域的计算 当计算可选和关键字参数的默认值表达式时,只有*先前*的参数才在作用域内。例如,给出以下定义: ```julia function f(x, a=b, b=1) ### end ``` `a=b` 中的 `b` 指的是外部作用域内的 `b`,而不是后续参数中的 `b`。 ## [函数参数中的 Do 结构](@id Do-Block-Syntax-for-Function-Arguments) 把函数作为参数传递给其他函数是一种强大的技术,但它的语法并不总是很方便。当函数参数占据多行时,这样的调用便特别难以编写。例如,考虑在具有多种情况的函数上调用 [`map`](@ref): ```julia map(x->begin if x < 0 && iseven(x) return 0 elseif x == 0 return 1 else return x end end, [A, B, C]) ``` Julia 提供了一个保留字 `do`,用于更清楚地重写此代码: ```julia map([A, B, C]) do x if x < 0 && iseven(x) return 0 elseif x == 0 return 1 else return x end end ``` `do x` 语法创建一个带有参数 `x` 的匿名函数,并将其作为第一个参数传递给 [`map`](@ref)。 类似地,`do a,b` 将创建一个有两个参数的匿名函数。 请注意,`do (a,b)` 将创建一个单参数匿名函数,其参数是一个要解构的元组。 一个简单的 `do` 会声明接下来是一个形式为 `() -> ...` 的匿名函数。 这些参数如何初始化取决于「外部」函数;在这里,[`map`](@ref) 将会依次将 `x` 设置为 `A`、`B`、`C`,再分别调用调用匿名函数,正如在 `map(func, [A, B, C])` 语法中所发生的。 这种语法使得更容易使用函数来有效地扩展语言,因为调用看起来就像普通代码块。有许多可能的用法与 [`map`](@ref) 完全不同,比如管理系统状态。例如,有一个版本的 [`open`](@ref) 可以通过运行代码来确保已经打开的文件最终会被关闭: ```julia open("outfile", "w") do io write(io, data) end ``` 这是通过以下定义实现的: ```julia function open(f::Function, args...) io = open(args...) try f(io) finally close(io) end end ``` 在这里,[`open`](@ref) 首先打开要写入的文件,接着将结果输出流传递给你在 `do ... end` 代码快中定义的匿名函数。在你的函数退出后,[`open`](@ref) 将确保流被正确关闭,无论你的函数是正常退出还是抛出了一个异常(`try/finally` 结构会在 [流程控制](@ref) 中描述)。 使用 `do` 代码块语法时,查阅文档或实现有助于了解用户函数的参数是如何初始化的。 类似于其他的内部函数, `do` 代码块也可以“捕获”上一个作用域的变量。例如,上一个 `open...do` 的例子中变量 `data` 是从外部作用域捕获的。捕获变量可能会给性能优化带来挑战,详见 [性能建议](@ref man-performance-captured)。 ## 函数的复合与链式调用 Julia中的多个函数可以用函数复合或管道连接(链式调用)组合起来。 函数的复合指的是把多个函数绑定到一起,然后作用于最先调用那个函数的参数。 你可以使用函数复合运算符 (`∘`) 来组合函数,这样一来 `(f ∘ g)(args...)` 就等价于 `f(g(args...))`. 你可以在REPL和合理配置的编辑器中用 `\circ<tab>` 输入函数复合运算符。 例如, `sqrt` 和 `+` 可以用下面这种方式组合: ```jldoctest julia> (sqrt ∘ +)(3, 6) 3.0 ``` 这个语句先把数字相加,再对结果求平方根。 下一个例子组合了三个函数并把新函数作用到一个字符串组成的数组上: ```jldoctest julia> map(first ∘ reverse ∘ uppercase, split("you can compose functions like this")) 6-element Vector{Char}: 'U': ASCII/Unicode U+0055 (category Lu: Letter, uppercase) 'N': ASCII/Unicode U+004E (category Lu: Letter, uppercase) 'E': ASCII/Unicode U+0045 (category Lu: Letter, uppercase) 'S': ASCII/Unicode U+0053 (category Lu: Letter, uppercase) 'E': ASCII/Unicode U+0045 (category Lu: Letter, uppercase) 'S': ASCII/Unicode U+0053 (category Lu: Letter, uppercase) ``` 函数的链式调用(有时也称“使用管道”把数据送到一系列函数中去)指的是把一个函数作用到前一个函数的输出上: ```jldoctest julia> 1:10 |> sum |> sqrt 7.416198487095663 ``` 在这里, `sum` 函数求出的和被传递到 `sqrt` 函数作为参数。等价的函数复合写法是: ```jldoctest julia> (sqrt ∘ sum)(1:10) 7.416198487095663 ``` 管道运算符还可以和广播一起使用(`.|>`),这提供了一个有用的链式调用/管道+向量化运算的组合语法(接下来将描述)。 ```jldoctest julia> ["a", "list", "of", "strings"] .|> [uppercase, reverse, titlecase, length] 4-element Vector{Any}: "A" "tsil" "Of" 7 ``` ## [向量化函数的点语法](@id man-vectorized) 在科学计算语言中,通常会有函数的「向量化」版本,它简单地将给定函数 `f(x)` 作用于数组 `A` 的每个元素,接着通过 `f(A)` 生成一个新数组。这种语法便于数据处理,但在其它语言中,向量化通常也是性能所需要的:如果循环很慢,函数的「向量化」版本可以调用由低级语言编写的、快速的库代码。在 Julia 中,向量化函数*不*是性能所必需的,实际上编写自己的循环通常也是有益的(请参阅 [Performance Tips](@ref man-performance-tips)),但它们仍然很方便。因此,*任何* Julia 函数 `f` 能够以元素方式作用于任何数组(或者其它集合),这通过语法 `f.(A)` 实现。例如,`sin` 可以作用于向量 `A` 中的所有元素,如下所示: ```jldoctest julia> A = [1.0, 2.0, 3.0] 3-element Vector{Float64}: 1.0 2.0 3.0 julia> sin.(A) 3-element Vector{Float64}: 0.8414709848078965 0.9092974268256817 0.1411200080598672 ``` 当然,你如果为 `f` 编写了一个专门的「向量化」方法,例如通过 `f(A::AbstractArray) = map(f, A)`,可以省略点号,这和 `f.(A)` 一样高效。但这种方法要求你事先决定要进行向量化的函数。 更一般地,`f.(args...)` 实际上等价于 `broadcast(f, args...)`,它允许你操作多个数组(甚至是不同形状的),或是数组和标量的混合(请参阅 [Broadcasting](@ref))。例如,如果有 `f(x,y) = 3x + 4y`,那么 `f.(pi,A)` 将为 `A` 中的每个 `a` 返回一个由 `f(pi,a)` 组成的新数组,而 `f.(vector1,vector2)` 将为每个索引 `i` 返回一个由 `f(vector1[i],vector2[i])` 组成的新向量(如果向量具有不同的长度则会抛出异常)。 ```jldoctest julia> f(x,y) = 3x + 4y; julia> A = [1.0, 2.0, 3.0]; julia> B = [4.0, 5.0, 6.0]; julia> f.(pi, A) 3-element Vector{Float64}: 13.42477796076938 17.42477796076938 21.42477796076938 julia> f.(A, B) 3-element Vector{Float64}: 19.0 26.0 33.0 ``` 此外,*嵌套的* `f.(args...)` 调用会被*融合*到一个 `broadcast` 循环中。例如,`sin.(cos.(X))` 等价于 `broadcast(x -> sin(cos(x)), X)`,类似于 `[sin(cos(x)) for x in X]`:在 `X` 上只有一个循环,并且只为结果分配了一个数组。[ 相反,在典型的「向量化」语言中,`sin(cos(X))` 首先会为 `tmp=cos(X)` 分配第一个临时数组,然后在单独的循环中计算 `sin(tmp)`,再分配第二个数组。] 这种循环融合不是可能发生也可能不发生的编译器优化,只要遇到了嵌套的 `f.(args...)` 调用,它就是一个*语法保证*。技术上,一旦遇到「非点」函数调用,融合就会停止;例如,在 `sin.(sort(cos.(X)))` 中,由于插入的 `sort` 函数,`sin` 和 `cos` 无法被合并。 最后,最大效率通常在向量化操作的输出数组被*预分配*时实现,这样重复调用就不会一次又一次地为结果分配新数组(请参阅 [输出预分配](@ref))。一个方便的语法是 `X .= ...`,它等价于 `broadcast!(identity, X, ...)`,除了上面提到的,`broadcast!` 循环可与任何嵌套的「点」调用融合。例如,`X .= sin.(Y)` 等价于 `broadcast!(sin, X, Y)`,用 `sin.(Y)` in-place 覆盖 `X`。如果左边是数组索引表达式,例如 `X[2:end] .= sin.(Y)`,那就将 `broadcast!` 转换在一个 `view` 上,例如 `broadcast!(sin, view(X, 2:lastindex(X)), Y)`,这样左侧就被 in-place 更新了。 由于在表达式中为许多操作和函数调用添加点可能很乏味并导致难以阅读的代码,宏 [`@.`](@ref @__dot__) 用于将表达式中的*每个*函数调用、操作和赋值转换为「点」版本。 ```jldoctest julia> Y = [1.0, 2.0, 3.0, 4.0]; julia> X = similar(Y); # pre-allocate output array julia> @. X = sin(cos(Y)) # equivalent to X .= sin.(cos.(Y)) 4-element Vector{Float64}: 0.5143952585235492 -0.4042391538522658 -0.8360218615377305 -0.6080830096407656 ``` 像 `.+` 这样的二元(或一元)运算符使用相同的机制进行管理:它们等价于 `broadcast` 调用且可与其它嵌套的「点」调用融合。`X .+= Y` 等等价于 `X .= X .+ Y`,结果为一个融合的 in-place 赋值;另见 [dot operators](@ref man-dot-operators)。 您也可以使用 [`|>`](@ref) 将点操作与函数链组合在一起,如本例所示: ```jldoctest julia> [1:5;] .|> [x->x^2, inv, x->2*x, -, isodd] 5-element Vector{Real}: 1 0.5 6 -4 true ``` ## 更多阅读 我们应该在这里提到,这远不是定义函数的完整图景。Julia 拥有一个复杂的类型系统并且允许对参数类型进行多重分派。这里给出的示例都没有为它们的参数提供任何类型注释,意味着它们可以作用于任何类型的参数。类型系统在[类型](@ref man-types)中描述,而[方法](@ref)则描述了根据运行时参数类型上的多重分派所选择的方法定义函数。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2820
# [入门](@id man-getting-started) 无论是使用预编译好的二进制程序,还是自己从源码编译,安装 Julia 都是一件很简单的事情。 请按照 [https://julialang.org/downloads/](https://julialang.org/downloads/) 的提示来下载并安装 Julia。 如果你是从下面的某一种语言切换到 Julia 的话,那么你应该首先阅读与这些语言有显著差异的那一部分 [MATLAB](@ref Noteworthy-differences-from-MATLAB), [R](@ref Noteworthy-differences-from-R), [Python](@ref Noteworthy-differences-from-Python), [C/C++](@ref Noteworthy-differences-from-C/C) or [Common Lisp](@ref Noteworthy-differences-from-Common-Lisp). 这将帮助你避免一些常见的编程陷阱,因为 Julia 在许多微妙的方面与这些语言不同。 启动一个交互式会话(也叫 REPL)是学习和尝试 Julia 最简单的方法。双击 Julia 的可执行文件或是从命令行运行 `julia` 就可以启动: ```@eval io = IOBuffer() Base.banner(io) banner = String(take!(io)) import Markdown Markdown.parse("```\n\$ julia\n\n$(banner)\njulia> 1 + 2\n3\n\njulia> ans\n3\n```") ``` 输入 `CTRL-D`(同时按 `Ctrl` 键和 `d` 键)或 `exit()` 便可以退出交互式会话。在交互式模式中,`julia` 会显示一条横幅并提示用户输入。一旦用户输入了一段完整的代码(表达式),例如 `1 + 2`,然后按回车,交互式会话就会执行这段代码,并将结果显示出来。如果输入的代码以分号结尾,那么结果将不会显示出来。然而不管结果显示与否,变量 `ans` 总会存储上一次执行代码的结果,需要注意的是,变量 `ans` 只在交互式会话中才有。 在交互式会话中,要运行写在源文件 `file.jl` 中的代码,只需输入 `include("file.jl")`。 如果想以非交互的方式执行文件中的代码,可以把文件名作为 `julia` 命令的第一个参数: ``` $ julia script.jl arg1 arg2... ``` 如这个例子所示,`julia` 后跟着的命令行参数会被作为程序 `script.jl` 的命令行参数。这些参数使用全局常量 `ARGS` 来传递,脚本自身的名字会以全局变量 `PROGRAM_FILE` 传入。注意当脚本以命令行里的 `-e` 选项输入时,`ARGS` 也会被设定(详见此页末尾列表)但是 `PROGRAM_FILE` 会是空的。例如,要把一个脚本的输入参数显示出来,你可以: ``` $ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar foo bar ``` 或者你可以把代码写到一个脚本文件中再执行它: ``` $ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl $ julia script.jl foo bar script.jl foo bar ``` 可以使用 `--` 分隔符来将传给脚本文件的参数和 Julia 本身的命令行参数区分开: ``` $ julia --color=yes -O -- script.jl arg1 arg2.. ``` 有关编写 Julia 脚本的更多信息,请参阅 [脚本](@ref man-scripting)。 使用选项 `-p` 或者 `--machine-file` 可以在并行模式下启动 Julia。 `-p n` 会启动额外的 `n` 个 worker,使用 `--machine-file file` 会为 `file` 文件中的每一行启动一个 worker。 定义在 `file` 中的机器必须能够通过一个不需要密码的 `ssh` 登陆访问到,且 Julia 的安装位置需要和当前主机相同。 定义机器的格式为 `[count*][user@]host[:port] [bind_addr[:port]]`。 `user` 默认值是当前用户; `port` 默认值是标准 ssh 端口; `count` 是在这个节点上的 worker 的数量,默认是 1; 可选的 `bind-to bind_addr[:port]` 指定了其它 worker 访问当前 worker 应当使用的 IP 地址与端口。 要让 Julia 每次启动都自动执行一些代码,你可以把它们放在 `~/.julia/config/startup.jl` 中: ``` $ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl $ julia Greetings! 你好! 안녕하세요? ... ``` 在你第一次运行 Julia 后,你应该多了一个 `~/.julia` 文件夹。 你还可以新建 `~/.julia/config` 文件夹和 `~/.julia/config/startup.jl` 文件来配置 Julia。 和 `perl` 和 `ruby` 程序类似,还有很多种运行 Julia 代码的方式,运行代码时也有很多选项: ``` julia [switches] -- [programfile] [args...] ``` 详细的命令选项可以在这里找到 [Command-line Options](@ref command-line-options). ## 资源 除了本手册以外,官方网站还提供了一个有用的**[学习资源列表](https://julialang.org/learning/)**来帮助新用户学习 Julia。 如果已经对 Julia 有所了解,你可以先看 [Performance Tips](@ref man-performance-tips) 和 [Workflow Tips](@ref man-workflow-tips)。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
682
# 处理操作系统差异 当编写跨平台的应用或库时,通常需要考虑到操作系统之间的差异。变量 `Sys.KERNEL` 可以用于这些场合。在 `Sys` 模块中有一些函数将会使这些事情更加简单:`isunix`、 `islinux`、`isapple`、`isbsd`、`isfreebsd` 以及 `iswindows`。这些函数可以按如下方式使用: ```julia if Sys.iswindows() windows_specific_thing(a) end ``` 注意,`islinux`、`isapple` 和 `isfreebsd` 是 `isunix` 完全互斥的子集。另外,有一个宏 `@static` 可以使用这些函数有条件地隐藏无效代码,如以下示例所示。 简单例子: ``` ccall((@static Sys.iswindows() ? :_fopen : :fopen), ...) ``` 复杂例子: ```julia @static if Sys.islinux() linux_specific_thing(a) else generic_thing(a) end ``` 在链式嵌套的条件表达式中(包括 `if`/`elseif`/`end`),`@static` 必须在每一层都调用(括号是可选的,但是为了可读性,建议添加)。 ```julia @static Sys.iswindows() ? :a : (@static Sys.isapple() ? :b : :c) ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
5919
```@eval io = IOBuffer() release = isempty(VERSION.prerelease) v = "$(VERSION.major).$(VERSION.minor)" !release && (v = v*"-$(first(VERSION.prerelease))") print(io, """ # Julia $(v) Documentation Welcome to the documentation for Julia $(v). """) if !release print(io,""" !!! warning "Work in progress!" This documentation is for an unreleased, in-development, version of Julia. """) end import Markdown Markdown.parse(String(take!(io))) ``` 请阅读 [release notes](NEWS.md) 以了解自上次发行以来发生了什么变化。 ```@eval release = isempty(VERSION.prerelease) file = release ? "julia-$(VERSION).pdf" : "julia-$(VERSION.major).$(VERSION.minor).$(VERSION.patch)-$(first(VERSION.prerelease)).pdf" url = "https://raw.githubusercontent.com/JuliaLang/docs.julialang.org/assets/$(file)" import Markdown Markdown.parse(""" !!! note The documentation is also available in PDF format: [$file]($url). """) ``` ### [简介](@id man-introduction) 科学计算对性能一直有着最高的需求,但目前各领域的专家却大量使用较慢的动态语言来开展他们的日常工作。 偏爱动态语言有很多很好的理由,因此我们不会舍弃动态的特性。 幸运的是,现代编程语言设计与编译器技术可以大大消除性能折衷(trade-off),并提供有足够生产力的单一环境进行原型设计,而且能高效地部署性能密集型应用程序。 Julia 语言在这其中扮演了这样一个角色:它是一门灵活的动态语言,适合用于科学计算和数值计算,并且性能可与传统的静态类型语言媲美。 由于 Julia 的编译器和其它语言比如 Python 或 R 的解释器有所不同,一开始你可能发现 Julia 的性能并不是很突出。 如果你觉得速度有点慢,我们强烈建议在尝试其他功能前,先读一读文档中的[提高性能的窍门](@ref man-performance-tips)部分。 一旦你理解了 Julia 的运作方式后,写出和 C 一样快的代码就是小菜一碟。 Julia features optional typing, multiple dispatch, and good performance, achieved using type inference and [just-in-time (JIT) compilation](https://en.wikipedia.org/wiki/Just-in-time_compilation), implemented using [LLVM](https://en.wikipedia.org/wiki/Low_Level_Virtual_Machine). It is multi-paradigm, combining features of imperative, functional, and object-oriented programming. Julia provides ease and expressiveness for high-level numerical computing, in the same way as languages such as R, MATLAB, and Python, but also supports general programming. To achieve this, Julia builds upon the lineage of mathematical programming languages, but also borrows much from popular dynamic languages, including [Lisp](https://en.wikipedia.org/wiki/Lisp_(programming_language)), [Perl](https://en.wikipedia.org/wiki/Perl_(programming_language)), [Python](https://en.wikipedia.org/wiki/Python_(programming_language)), [Lua](https://en.wikipedia.org/wiki/Lua_(programming_language)), and [Ruby](https://en.wikipedia.org/wiki/Ruby_(programming_language)). Julia 与传统动态语言最重要的区别是: * The core language imposes very little; Julia Base and the standard library are written in Julia itself, including primitive operations like integer arithmetic * A rich language of types for constructing and describing objects, that can also optionally be used to make type declarations * The ability to define function behavior across many combinations of argument types via [multiple dispatch](https://en.wikipedia.org/wiki/Multiple_dispatch) * Automatic generation of efficient, specialized code for different argument types * Good performance, approaching that of statically-compiled languages like C Although one sometimes speaks of dynamic languages as being "typeless", they are definitely not: every object, whether primitive or user-defined, has a type. The lack of type declarations in most dynamic languages, however, means that one cannot instruct the compiler about the types of values, and often cannot explicitly talk about types at all. In static languages, on the other hand, while one can -- and usually must -- annotate types for the compiler, types exist only at compile time and cannot be manipulated or expressed at run time. In Julia, types are themselves run-time objects, and can also be used to convey information to the compiler. While the casual programmer need not explicitly use types or multiple dispatch, they are the core unifying features of Julia: functions are defined on different combinations of argument types, and applied by dispatching to the most specific matching definition. This model is a good fit for mathematical programming, where it is unnatural for the first argument to "own" an operation as in traditional object-oriented dispatch. Operators are just functions with special notation -- to extend addition to new user-defined data types, you define new methods for the `+` function. Existing code then seamlessly applies to the new data types. Partly because of run-time type inference (augmented by optional type annotations), and partly because of a strong focus on performance from the inception of the project, Julia's computational efficiency exceeds that of other dynamic languages, and even rivals that of statically-compiled languages. For large scale numerical problems, speed always has been, continues to be, and probably always will be crucial: the amount of data being processed has easily kept pace with Moore's Law over the past decades. Julia aims to create an unprecedented combination of ease-of-use, power, and efficiency in a single language. In addition to the above, some advantages of Julia over comparable systems include: * Free and open source ([MIT licensed](https://github.com/JuliaLang/julia/blob/master/LICENSE.md)) * User-defined types are as fast and compact as built-ins * No need to vectorize code for performance; devectorized code is fast * Designed for parallelism and distributed computation * Lightweight "green" threading ([coroutines](https://en.wikipedia.org/wiki/Coroutine)) * Unobtrusive yet powerful type system * Elegant and extensible conversions and promotions for numeric and other types * Efficient support for [Unicode](https://en.wikipedia.org/wiki/Unicode), including but not limited to [UTF-8](https://en.wikipedia.org/wiki/UTF-8) * Call C functions directly (no wrappers or special APIs needed) * Powerful shell-like capabilities for managing other processes * Lisp-like macros and other metaprogramming facilities
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
15229
# 整数和浮点数 整数和浮点值是算术和计算的基础。这些数值的内置表示被称作原始数值类型(numeric primitive),且整数和浮点数在代码中作为立即数时称作数值字面量(numeric literal)。例如,`1` 是个整型字面量,`1.0` 是个浮点型字面量,它们在内存中作为对象的二进制表示就是原始数值类型。 Julia 提供了很丰富的原始数值类型,并基于它们定义了一整套算术操作,还提供按位运算符以及一些标准数学函数。这些函数能够直接映射到现代计算机原生支持的数值类型及运算上,因此 Julia 可以充分地利用运算资源。此外,Julia 还为[任意精度算术](@ref)提供了软件支持,对于无法使用原生硬件表示的数值类型,Julia 也能够高效地处理其数值运算。当然,这需要相对的牺牲一些性能。 以下是 Julia 的原始数值类型: * **整数类型:** | 类型 | 带符号? | 比特数 | 最小值 | 最大值 | |:----------------- |:------- |:-------------- |:-------------- |:------------- | | [`Int8`](@ref) | ✓ | 8 | -2^7 | 2^7 - 1 | | [`UInt8`](@ref) |   | 8 | 0 | 2^8 - 1 | | [`Int16`](@ref) | ✓ | 16 | -2^15 | 2^15 - 1 | | [`UInt16`](@ref) |   | 16 | 0 | 2^16 - 1 | | [`Int32`](@ref) | ✓ | 32 | -2^31 | 2^31 - 1 | | [`UInt32`](@ref) |   | 32 | 0 | 2^32 - 1 | | [`Int64`](@ref) | ✓ | 64 | -2^63 | 2^63 - 1 | | [`UInt64`](@ref) |   | 64 | 0 | 2^64 - 1 | | [`Int128`](@ref) | ✓ | 128 | -2^127 | 2^127 - 1 | | [`UInt128`](@ref) |   | 128 | 0 | 2^128 - 1 | | [`Bool`](@ref) | N/A | 8 | `false` (0) | `true` (1) | * **浮点类型:** | 类型 | 精度 | 比特数 | |:----------------- |:------------------------------------------------------------------------------ |:-------------- | | [`Float16`](@ref) | [半精度](https://en.wikipedia.org/wiki/Half-precision_floating-point_format) | 16 | | [`Float32`](@ref) | [单精度](https://en.wikipedia.org/wiki/Single_precision_floating-point_format) | 32 | | [`Float64`](@ref) | [双精度](https://en.wikipedia.org/wiki/Double_precision_floating-point_format) | 64 | 此外,对[复数和有理数](@ref)的完整支持是在这些原始数据类型之上建立起来的。多亏了 Julia 有一个很灵活的、用户可扩展的[类型提升系统](@ref conversion-and-promotion),所有的数值类型都无需显式转换就可以很自然地相互进行运算。 ## 整数 整数字面量以标准形式表示: ```jldoctest julia> 1 1 julia> 1234 1234 ``` 整型字面量的默认类型取决于目标系统是 32 位还是 64 位架构: ```julia-repl # 32 位系统: julia> typeof(1) Int32 # 64 位系统: julia> typeof(1) Int64 ``` Julia 的内置变量 [`Sys.WORD_SIZE`](@ref) 表明了目标系统是 32 位还是 64 位架构: ```julia-repl # 32 位系统: julia> Sys.WORD_SIZE 32 # 64 位系统: julia> Sys.WORD_SIZE 64 ``` Julia 也定义了 `Int` 与 `UInt` 类型,它们分别是系统有符号和无符号的原生整数类型的别名。 ```julia-repl # 32 位系统: julia> Int Int32 julia> UInt UInt32 # 64 位系统: julia> Int Int64 julia> UInt UInt64 ``` 那些超过 32 位表示范围的大整数,如果能用 64 位表示,那么无论是什么系统都会用 64 位表示: ```jldoctest # 32 位或 64 位系统: julia> typeof(3000000000) Int64 ``` 无符号整数会通过 `0x` 前缀以及十六进制数 `0-9a-f` 来输入和输出(输入也可以使用大写的 `A-F`)。无符号值的位数取决于十六进制数字使用的数量: ```jldoctest julia> x = 0x1 0x01 julia> typeof(x) UInt8 julia> x = 0x123 0x0123 julia> typeof(x) UInt16 julia> x = 0x1234567 0x01234567 julia> typeof(x) UInt32 julia> x = 0x123456789abcdef 0x0123456789abcdef julia> typeof(x) UInt64 julia> x = 0x11112222333344445555666677778888 0x11112222333344445555666677778888 julia> typeof(x) UInt128 ``` 采用这种做法是因为,当人们使用无符号十六进制字面量表示整数值的时候,通常会用它们来表示一个固定的数值字节序列,而不仅仅是个整数值。 二进制和八进制字面量也是支持的: ```jldoctest julia> x = 0b10 0x02 julia> typeof(x) UInt8 julia> x = 0o010 0x08 julia> typeof(x) UInt8 julia> x = 0x00000000000000001111222233334444 0x00000000000000001111222233334444 julia> typeof(x) UInt128 ``` 二进制、八进制和十六进制的字面量都会产生无符号的整数类型。当字面量不是开头全是 0 时,它们二进制数据项的位数会是最少需要的位数。当开头都是 `0` 时,位数取决于一个字面量需要的最少位数,这里的字面量指的是一个有着同样长度但开头都为 `1` 的数。这样用户就可以控制位数了。那些无法使用 `UInt128` 类型存储下的值无法写成这样的字面量。 二进制、八进制和十六进制的字面量前面加一个负号 `-`,这样可以产生一个和原字面量有着同样位数而值为原数的补码的数(二补数): ```jldoctest julia> -0x2 0xfe julia> -0x0002 0xfffe ``` 整型等原始数值类型的最小和最大可表示的值可用 [`typemin`](@ref) 和 [`typemax`](@ref) 函数得到: ```jldoctest julia> (typemin(Int32), typemax(Int32)) (-2147483648, 2147483647) julia> for T in [Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128] println("$(lpad(T,7)): [$(typemin(T)),$(typemax(T))]") end Int8: [-128,127] Int16: [-32768,32767] Int32: [-2147483648,2147483647] Int64: [-9223372036854775808,9223372036854775807] Int128: [-170141183460469231731687303715884105728,170141183460469231731687303715884105727] UInt8: [0,255] UInt16: [0,65535] UInt32: [0,4294967295] UInt64: [0,18446744073709551615] UInt128: [0,340282366920938463463374607431768211455] ``` [`typemin`](@ref) 和 [`typemax`](@ref) 返回的值的类型总与所给参数的类型相同。(上面的表达式用了一些目前还没有介绍的功能,包括 [for 循环](@ref man-loops)、[字符串](@ref man-strings)和[字符串插值](@ref string-interpolation),但这对于已有一些编程经验的用户应该是很容易理解的。) ### 溢出行为 在 Julia 里,超出一个类型可表示的最大值会导致环绕 (wraparound) 行为: ```jldoctest julia> x = typemax(Int64) 9223372036854775807 julia> x + 1 -9223372036854775808 julia> x + 1 == typemin(Int64) true ``` 因此,Julia 的整数算术实际上是[模算数](https://en.wikipedia.org/wiki/Modular_arithmetic)的一种形式,它反映了现代计算机实现底层算术的特点。在可能有溢出产生的程序中,对最值边界出现循环进行显式检查是必要的。否则,推荐使用[任意精度算术](@ref Arbitrary-Precision-Arithmetic)中的 [`BigInt`](@ref) 类型作为替代。 下面是溢出行为的一个例子以及如何解决溢出: ```jldoctest julia> 10^19 -8446744073709551616 julia> big(10)^19 10000000000000000000 ``` ### 除法错误 `div` 函数的整数除法有两种异常情况:除以零,以及使用 -1 去除最小的负数([`typemin`](@ref))。 这两种情况都会抛出一个 [`DivideError`](@ref) 错误。 `rem` 取余函数和 `mod` 取模函数在除零时抛出 [`DivideError`](@ref) 错误。 ## 浮点数 浮点数字面量以标准格式表示,必要时可使用[E-表示法](https://en.wikipedia.org/wiki/Scientific_notation#E_notation)。 ```jldoctest julia> 1.0 1.0 julia> 1. 1.0 julia> 0.5 0.5 julia> .5 0.5 julia> -1.23 -1.23 julia> 1e10 1.0e10 julia> 2.5e-4 0.00025 ``` 上面的结果都是 [`Float64`](@ref) 类型的值。使用 `f` 替代 `e` 可以得到 [`Float32`](@ref) 类型的字面量: ```jldoctest julia> x = 0.5f0 0.5f0 julia> typeof(x) Float32 julia> 2.5f-4 0.00025f0 ``` 数值可以很容易地转换为 [`Float32`](@ref) 类型: ```jldoctest julia> x = Float32(-1.5) -1.5f0 julia> typeof(x) Float32 ``` 也存在十六进制的浮点数字面量,但只适用于 [`Float64`](@ref) 类型的值。一般使用 `p` 前缀及以 2 为底的指数来表示: ```jldoctest julia> 0x1p0 1.0 julia> 0x1.8p3 12.0 julia> x = 0x.4p-1 0.125 julia> typeof(x) Float64 ``` Julia 也支持半精度浮点数([`Float16`](@ref)),但它们是使用 [`Float32`](@ref) 进行软件模拟实现的。 ```jldoctest julia> sizeof(Float16(4.)) 2 julia> 2*Float16(4.) Float16(8.0) ``` 下划线 `_` 可用作数字分隔符: ```jldoctest julia> 10_000, 0.000_000_005, 0xdead_beef, 0b1011_0010 (10000, 5.0e-9, 0xdeadbeef, 0xb2) ``` ### 浮点数中的零 浮点数有[两种零](https://en.wikipedia.org/wiki/Signed_zero),正零和负零。它们相互相等但有着不同的二进制表示,可以使用 [`bitstring`](@ref) 函数来查看: ```jldoctest julia> 0.0 == -0.0 true julia> bitstring(0.0) "0000000000000000000000000000000000000000000000000000000000000000" julia> bitstring(-0.0) "1000000000000000000000000000000000000000000000000000000000000000" ``` ### 特殊的浮点值 有三种特定的标准浮点值不和实数轴上任何一点对应: | `Float16` | `Float32` | `Float64` | 名称 | 描述 | |:--------- |:--------- |:--------- |:----------------- |:--------------------------------------------------------------- | | `Inf16` | `Inf32` | `Inf` | 正无穷 | 一个大于所有有限浮点数的数 | | `-Inf16` | `-Inf32` | `-Inf` | 负无穷 | 一个小于所有有限浮点数的数 | | `NaN16` | `NaN32` | `NaN` | 不是数(Not a Number) | 一个不和任何浮点值(包括自己)相等(`==`)的值 | 对于这些非有限浮点值相互之间以及关于其它浮点值的顺序的更多讨论,请参见[数值比较](@ref)。根据 [IEEE 754 标准](https://en.wikipedia.org/wiki/IEEE_754-2008),这些浮点值是某些算术运算的结果: ```jldoctest julia> 1/Inf 0.0 julia> 1/0 Inf julia> -5/0 -Inf julia> 0.000001/0 Inf julia> 0/0 NaN julia> 500 + Inf Inf julia> 500 - Inf -Inf julia> Inf + Inf Inf julia> Inf - Inf NaN julia> Inf * Inf Inf julia> Inf / Inf NaN julia> 0 * Inf NaN julia> NaN == NaN false julia> NaN != NaN true julia> NaN < NaN false julia> NaN > NaN false ``` [`typemin`](@ref) 和 [`typemax`](@ref) 函数同样适用于浮点类型: ```jldoctest julia> (typemin(Float16),typemax(Float16)) (-Inf16, Inf16) julia> (typemin(Float32),typemax(Float32)) (-Inf32, Inf32) julia> (typemin(Float64),typemax(Float64)) (-Inf, Inf) ``` ### 机器精度 大多数实数都无法用浮点数准确地表示,因此有必要知道两个相邻可表示的浮点数间的距离。它通常被叫做[机器精度](https://en.wikipedia.org/wiki/Machine_epsilon)。 Julia 提供了 [`eps`](@ref) 函数,它可以给出 `1.0` 与下一个 Julia 能表示的浮点数之间的差值: ```jldoctest julia> eps(Float32) 1.1920929f-7 julia> eps(Float64) 2.220446049250313e-16 julia> eps() # 与 eps(Float64) 相同 2.220446049250313e-16 ``` 这些值分别是 [`Float32`](@ref) 中的 `2.0^-23` 和 [`Float64`](@ref) 中的 `2.0^-52`。[`eps`](@ref) 函数也可以接受一个浮点值作为参数,然后给出这个值与下一个可表示的浮点数值之间的绝对差。也就是说,`eps(x)` 产生一个和 `x` 类型相同的值,并且 `x + eps(x)` 恰好是比 `x` 更大的下一个可表示的浮点值: ```jldoctest julia> eps(1.0) 2.220446049250313e-16 julia> eps(1000.) 1.1368683772161603e-13 julia> eps(1e-27) 1.793662034335766e-43 julia> eps(0.0) 5.0e-324 ``` 两个相邻可表示的浮点数之间的距离并不是常数,数值越小,间距越小,数值越大,间距越大。换句话说,可表示的浮点数在实数轴上的零点附近最稠密,并沿着远离零点的方向以指数型的速度变得越来越稀疏。根据定义,`eps(1.0)` 与 `eps(Float64)` 相等,因为 `1.0` 是个 64 位浮点值。 Julia 也提供了 [`nextfloat`](@ref) 和 [`prevfloat`](@ref) 两个函数分别返回基于参数的下一个更大或更小的可表示的浮点数: ```jldoctest julia> x = 1.25f0 1.25f0 julia> nextfloat(x) 1.2500001f0 julia> prevfloat(x) 1.2499999f0 julia> bitstring(prevfloat(x)) "00111111100111111111111111111111" julia> bitstring(x) "00111111101000000000000000000000" julia> bitstring(nextfloat(x)) "00111111101000000000000000000001" ``` 这个例子体现了一般原则,即相邻可表示的浮点数也有着相邻的二进制整数表示。 ### 舍入模式 一个数如果没有精确的浮点表示,就必须被舍入到一个合适的可表示的值。然而,如果想的话,可以根据舍入模式改变舍入的方式,如 [IEEE 754 标准](https://en.wikipedia.org/wiki/IEEE_754-2008) 所述。 Julia 所使用的默认模式总是 [`RoundNearest`](@ref),指舍入到最接近的可表示的值,这个被舍入的值会使用尽量少的有效位数。 ### 背景知识与参考文献 浮点算术带来了很多微妙之处,它们可能对于那些不熟悉底层实现细节的用户会是很出人意料的。然而,这些微妙之处在大部分科学计算的书籍中以及以下的参考资料中都有详细介绍: * 浮点数算术的权威指南是 [IEEE 754-2008 标准](https://standards.ieee.org/standard/754-2008.html); 然而这篇标准在网上无法免费获得。 * 关于浮点数是如何表示的,想要一个简单而明白的介绍的话,可以看 John D. Cook 的[文章](https://www.johndcook.com/blog/2009/04/06/anatomy-of-a-floating-point-number/)以及他关于从这种表示与实数理想的抽象化的差别中产生的一些问题的[介绍](https://www.johndcook.com/blog/2009/04/06/numbers-are-a-leaky-abstraction/) * 同样推荐 Bruce Dawson 的[一系列关于浮点数的博客文章](https://randomascii.wordpress.com/2012/05/20/thats-not-normalthe-performance-of-odd-floats)。 * 想要一个对浮点数和使用浮点数计算时产生的数值精度问题的极好的、有深度的讨论,可以参见 David Goldberg 的文章 [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.22.6768&rep=rep1&type=pdf)。 * 更多延伸文档,包括浮点数的历史、基础理论、问题以及数值计算中很多其它主题的讨论,可以参见 [William Kahan](https://en.wikipedia.org/wiki/William_Kahan) 的[写作集](https://people.eecs.berkeley.edu/~wkahan/)。他以“浮点数之父”闻名。特别感兴趣的话可以看 [An Interview with the Old Man of Floating-Point](https://people.eecs.berkeley.edu/~wkahan/ieee754status/754story.html)。 ## [任意精度算术](@id Arbitrary-Precision-Arithmetic) 为了允许使用任意精度的整数与浮点数,Julia 分别包装了 [GNU Multiple Precision Arithmetic Library (GMP)](https://gmplib.org) 以及 [GNU MPFR Library](https://www.mpfr.org)。Julia 中的 [`BigInt`](@ref) 与 [`BigFloat`](@ref) 两种类型分别提供了任意精度的整数和浮点数。 可以使用构造函数从原始数据类型创建任意精度的整数和浮点数,或是使用[字符串字面量](@ref non-standard-string-literals) [`@big_str`](@ref)、[`parse`](@ref)函数从 `AbstractString` 类型来创建。当创建的整型字面量过大而无法被其它内置的整数类型表示时,也会被输入为 `BigInt` 类型。注意到 Julia 的`Base`中并没有无符号的任意精度的整型(`BigInt`在多数情况下已经够用了),(除十进制外)也可以使用十六进制、八进制、二进制的字面量。 得益于 Julia 的[类型提升和类型转换机制](@ref conversion-and-promotion),一旦被创建,它们就可以像其它数值类型一样参与算术运算。 ```jldoctest julia> BigInt(typemax(Int64)) + 1 9223372036854775808 julia> big"123456789012345678901234567890" + 1 123456789012345678901234567891 julia> parse(BigInt, "123456789012345678901234567890") + 1 123456789012345678901234567891 julia> string(big"2"^200, base=16) "100000000000000000000000000000000000000000000000000" julia> 0x100000000000000000000000000000000-1 == typemax(UInt128) true julia> 0x000000000000000000000000000000000 0 julia> typeof(ans) BigInt julia> big"1.23456789012345678901" 1.234567890123456789010000000000000000000000000000000000000000000000000000000004 julia> parse(BigFloat, "1.23456789012345678901") 1.234567890123456789010000000000000000000000000000000000000000000000000000000004 julia> BigFloat(2.0^66) / 3 2.459565876494606882133333333333333333333333333333333333333333333333333333333344e+19 julia> factorial(BigInt(40)) 815915283247897734345611269596115894272000000000 ``` 然而,上面的原始类型与 [`BigInt`](@ref)/[`BigFloat`](@ref) 之间的类型提升并不是自动的,需要明确地指定: ```jldoctest julia> x = typemin(Int64) -9223372036854775808 julia> x = x - 1 9223372036854775807 julia> typeof(x) Int64 julia> y = BigInt(typemin(Int64)) -9223372036854775808 julia> y = y - 1 -9223372036854775809 julia> typeof(y) BigInt ``` [`BigFloat`](@ref) 的默认精度(有效数字的位数)和舍入模式可以通过调用 [`setprecision`](@ref) 和 [`setrounding`](@ref) 来全局地改变,所有之后的计算都会根据这些改变进行。还有一种方法,可以使用同样的函数以及 `do`-block 来只在运行一个特定代码块时改变精度和舍入模式: ```jldoctest julia> setrounding(BigFloat, RoundUp) do BigFloat(1) + parse(BigFloat, "0.1") end 1.100000000000000000000000000000000000000000000000000000000000000000000000000003 julia> setrounding(BigFloat, RoundDown) do BigFloat(1) + parse(BigFloat, "0.1") end 1.099999999999999999999999999999999999999999999999999999999999999999999999999986 julia> setprecision(40) do BigFloat(1) + parse(BigFloat, "0.1") end 1.1000000000004 ``` ## [数值字面量系数](@id man-numeric-literal-coefficients) 为了让常见的数值公式和表达式更清楚,Julia 允许变量直接跟在一个数值字面量后,暗指乘法。这可以让写多项式变得很清楚: ```jldoctest numeric-coefficients julia> x = 3 3 julia> 2x^2 - 3x + 1 10 julia> 1.5x^2 - .5x + 1 13.0 ``` 也会让写指数函数变得更加优雅: ```jldoctest numeric-coefficients julia> 2^2x 64 ``` 数值字面量系数的优先级跟一元运算符相同,比如说取相反数。所以 `2^3x` 会被解析成 `2^(3x)`,而 `2x^3` 会被解析成 `2*(x^3)`。 数值字面量也能作为被括号表达式的系数: ```jldoctest numeric-coefficients julia> 2(x-1)^2 - 3(x-1) + 1 3 ``` !!! note 用于隐式乘法的数值字面量系数的优先级高于其它的二元运算符,例如乘法(`*`)和除法(`/`、`\` 以及 `//`)。这意味着,比如说,`1 / 2im` 等于 `-0.5im` 以及 `6 // 2(2+1)` 等于 `1 // 1`。 此外,括号表达式可以被用作变量的系数,暗指表达式与变量相乘: ```jldoctest numeric-coefficients julia> (x-1)x 6 ``` 但是,无论是把两个括号表达式并列,还是把变量放在括号表达式之前,都不会被用作暗指乘法: ```jldoctest numeric-coefficients julia> (x-1)(x+1) ERROR: MethodError: objects of type Int64 are not callable julia> x(x+1) ERROR: MethodError: objects of type Int64 are not callable ``` 这两种表达式都会被解释成函数调用:所有不是数值字面量的表达式,后面紧跟一个括号,就会被解释成使用括号内的值来调用函数(更多关于函数的信息请参见[函数](@ref))。因此,在这两种情况中,都会因为左边的值并不是函数而产生错误。 上述的语法糖显著地降低了在写普通数学公式时的视觉干扰。注意数值字面量系数和后面用来相乘的标识符或括号表达式之间不能有空格。 ### 语法冲突 并列的字面量系数语法可能和两种数值字面量语法产生冲突:十六进制、八进制、二进制整数字面量以及浮点字面量的工程表示法。下面是几种会产生语法冲突的情况: * 十六进制整数字面量 `0xff` 可能被解释成数值字面量 `0` 乘以变量 `xff`。类似的,像 `0o777` 或`0b01001010` 使用八进制或二进制表示法也会形成冲突。 * 浮点字面量表达式 `1e10` 可以被解释成数值字面量 `1` 乘以变量 `e10`,与之等价的 `E`-表示法也存在类似的情况。 * 32-bit 的浮点数字面量 `1.5f22` 被解释成数值字面量 `1.5` 乘以变量 `f22`。 在这些所有的情况中,歧义都优先解释为数值字面量: * `0x` /`0o`/`0b` 开头的表达式总是十六进制/八进制/二进制字面量。 * 数值开头跟着 `e` 和 `E` 的表达式总是浮点字面量。 * 数值开头跟着 `f` 的表达式总是 32-bit 浮点字面量。 由于历史原因 `E` 和 `e` 在数值字面量上是等价的,与之不同的是,`F` 只是一个行为和 `f` 不同的字母。因此开头为 `F` 的表达式将会被 解析为一个数值字面量乘以一个变量,例如 `1.5F22`等价于 `1.5 * F22`。 ## 零和一的字面量 Julia 提供了 0 和 1 的字面量函数,可以返回特定类型或所给变量的类型。 | 函数 | 描述 | |:----------------- |:------------------------------------------------ | | [`zero(x)`](@ref) | `x` 类型或变量 `x` 的类型的零字面量 | | [`one(x)`](@ref) | `x` 类型或变量 `x` 的类型的一字面量 | 这些函数在[数值比较](@ref)中可以用来避免不必要的[类型转换](@ref conversion-and-promotion)带来的开销。 例如: ```jldoctest julia> zero(Float32) 0.0f0 julia> zero(1.0) 0.0 julia> one(Int32) 1 julia> one(BigFloat) 1.0 ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
23982
# 接口 Julia 的很多能力和扩展性都来自于一些非正式的接口。通过为自定义的类型扩展一些特定的方法,自定义类型的对象不但获得那些方法的功能,而且也能够用于其它的基于那些行为而定义的通用方法中。 ## [迭代](@id man-interface-iteration) | 必需方法 |   | 简短描述 | |:------------------------------ |:---------------------- |:------------------------------------------------------------------------------------- | | `iterate(iter)` |   | 通常返回由第一项及其初始状态组成的元组,但如果为空,则返回 [`nothing`](@ref)  | | `iterate(iter, state)` |   | 通常返回由下一项及其状态组成的元组,或者在没有下一项存在时返回 `nothing`。 | | **重要可选方法** | **默认定义** | **简短描述** | | `IteratorSize(IterType)` | `HasLength()` | `HasLength()`,`HasShape{N}()`,`IsInfinite()` 或者 `SizeUnknown()` 中合适的一个 | | `IteratorEltype(IterType)` | `HasEltype()` | `EltypeUnknown()` 或 `HasEltype()` 中合适的一个 | | `eltype(IterType)` | `Any` | 由 `iterate()` 返回元组中第一项的类型。 | | `length(iter)` | (*未定义*) | 项数,如果已知 | | `size(iter, [dim])` | (*未定义*) | 在各个维度上项数,如果已知 | | 由 `IteratorSize(IterType)` 返回的值 | 必需方法 | |:------------------------------------------ |:------------------------------------------ | | `HasLength()` | [`length(iter)`](@ref) | | `HasShape{N}()` | `length(iter)` 和 `size(iter, [dim])` | | `IsInfinite()` | (*无*) | | `SizeUnknown()` | (*无*) | | 由 `IteratorEltype(IterType)` 返回的值 | 必需方法 | |:-------------------------------------------- |:------------------ | | `HasEltype()` | `eltype(IterType)` | | `EltypeUnknown()` | (*none*) | 顺序迭代由 [`iterate`](@ref) 函数实现。 Julia 的迭代器可以从对象外部跟踪迭代状态,而不是在迭代过程中改变对象本身。 迭代过程中的返回一个包含了当前迭代值及其状态的元组,或者在没有元素存在的情况下返回 `nothing`。 状态对象将在下一次迭代时传递回 iterate 函数,并且通常被认为是可迭代对象的私有实现细节。 任何定义了这个函数的对象都是可迭代的,并且可以被应用到[许多依赖迭代的函数上](@ref lib-collections-iteration) 。 也可以直接被应用到 [`for`](@ref) 循环中,因为根据语法: ```julia for item in iter # or "for item = iter" # body end ``` 以上代码被解释为: ```julia next = iterate(iter) while next !== nothing (item, state) = next # body next = iterate(iter, state) end ``` 举一个简单的例子:一组定长数据的平方数迭代序列: ```jldoctest squaretype julia> struct Squares count::Int end julia> Base.iterate(S::Squares, state=1) = state > S.count ? nothing : (state*state, state+1) ``` 仅仅定义了 [`iterate`](@ref) 函数的 `Squares` 类型就已经很强大了。 我们现在可以迭代所有的元素了: ```jldoctest squaretype julia> for item in Squares(7) println(item) end 1 4 9 16 25 36 49 ``` 我们可以利用许多内置方法来处理迭代,比如标准库 `Statistics` 中的 [`in`](@ref),[`mean`](@ref) 和 [`std`](@ref) 。 ```jldoctest squaretype julia> 25 in Squares(10) true julia> using Statistics julia> mean(Squares(100)) 3383.5 julia> std(Squares(100)) 3024.355854282583 ``` 我们可以扩展一些其它的方法,为 Julia 提供有关此可迭代集合的更多信息。我们知道 `Squares` 序列中的元素总是 `Int` 型的。通过扩展 [`eltype`](@ref) 方法,我们可以给 Julia 更多信息来帮助其在更复杂的方法中生成更具体的代码。我们同时也知道该序列中的元素数目,故同样地也可以扩展 [`length`](@ref): ```jldoctest squaretype julia> Base.eltype(::Type{Squares}) = Int # Note that this is defined for the type julia> Base.length(S::Squares) = S.count ``` 现在,当我们让 Julia 去 [`collect`](@ref) 所有元素到一个数组中时,Julia 可以预分配一个适当大小的 `Vector{Int}`,而不是朴素地 [`push!`](@ref) 每一个元素到 `Vector{Any}`: ```jldoctest squaretype julia> collect(Squares(4)) 4-element Vector{Int64}: 1 4 9 16 ``` 尽管大多时候我们都可以依赖一些通用的实现,但某些时候,如果我们知道一个更简单的算法,可以用其扩展具体方法。例如,计算平方和有公式,因此可以扩展出一个更高效的解法来替代通用方法: ```jldoctest squaretype julia> Base.sum(S::Squares) = (n = S.count; return n*(n+1)*(2n+1)÷6) julia> sum(Squares(1803)) 1955361914 ``` 这种模式在 Julia Base 中很常见,一些必须实现的方法构成了一个小的集合,从而定义出一个非正式的接口,用于实现一些更加炫酷的操作。某些应用场景中,一些类型有更高效的算法,故可以扩展出额外的专用方法。 能以*逆序*迭代集合也很有用,这可由 [`Iterators.reverse(iterator)`](@ref) 迭代实现。但是,为了实际支持逆序迭代,迭代器类型 `T` 需要为 `Iterators.Reverse{T}` 实现 `iterate`。(给定 `r::Iterators.Reverse{T}`,类型 `T` 的底层迭代器是 `r.itr`。)在我们的 `Squares` 示例中,我们可以实现 `Iterators.Reverse{Squares}` 方法: ```jldoctest squaretype julia> Base.iterate(rS::Iterators.Reverse{Squares}, state=rS.itr.count) = state < 1 ? nothing : (state*state, state-1) julia> collect(Iterators.reverse(Squares(4))) 4-element Vector{Int64}: 16 9 4 1 ``` ## Indexing | Methods to implement | Brief description | |:-------------------- |:-------------------------------- | | `getindex(X, i)` | `X[i]`, indexed element access | | `setindex!(X, v, i)` | `X[i] = v`, indexed assignment | | `firstindex(X)` | The first index, used in `X[begin]` | | `lastindex(X)` | The last index, used in `X[end]` | For the `Squares` iterable above, we can easily compute the `i`th element of the sequence by squaring it. We can expose this as an indexing expression `S[i]`. To opt into this behavior, `Squares` simply needs to define [`getindex`](@ref): ```jldoctest squaretype julia> function Base.getindex(S::Squares, i::Int) 1 <= i <= S.count || throw(BoundsError(S, i)) return i*i end julia> Squares(100)[23] 529 ``` 另外,为了支持语法 `S[begin]` 和 `S[end]`,我们必须定义 [`lastindex`](@ref) 来指定最后一个有效索引。建议也定义 [`firstindex`](@ref) 来指定第一个有效索引: ```jldoctest squaretype julia> Base.firstindex(S::Squares) = 1 julia> Base.lastindex(S::Squares) = length(S) julia> Squares(23)[end] 529 ``` 对多维的 `begin`/`end`索引,例如,像是 `a[3, begin, 7]`,你应该定义 `firstindex(a, dim)` 和 `lastindex(a, dim)`(它们默认各自在 `axes(a, dim)` 上调用 `first`和`last`) 注意,上面*只*定义了一个整数索引的 [`getindex`](@ref) 方法,用除一个整数之外的其它东西索引会抛出[`MethodError`](@ref),因为现在还没有匹配的方法。为了支持 `Int` 的范围或向量索引,必须另外写一个方法: ```jldoctest squaretype julia> Base.getindex(S::Squares, i::Number) = S[convert(Int, i)] julia> Base.getindex(S::Squares, I) = [S[i] for i in I] julia> Squares(10)[[3,4.,5]] 3-element Vector{Int64}: 9 16 25 ``` 虽然这开始支持更多[某些内置类型支持的索引操作](@ref man-array-indexing),但仍然有很多行为不支持。因为我们为 `Squares` 序列所添加的行为,它开始看起来越来越像向量。我们可以正式定义其为 [`AbstractArray`](@ref) 的子类型,而不是自己定义所有这些行为。 ## [抽象数组](@id man-interface-array) | 需要实现的方法 |   | 简短描述 | |:----------------------------------------------- |:-------------------------------------- |:------------------------------------------------------------------------------------- | | `size(A)` |   | 返回包含 `A` 各维度大小的元组 | | `getindex(A, i::Int)` |   | (若为 `IndexLinear`)线性标量索引 | | `getindex(A, I::Vararg{Int, N})` |   | (若为 `IndexCartesian`,其中 `N = ndims(A)`)N 维标量索引 | | `setindex!(A, v, i::Int)` |   | (若为 `IndexLinear`)线性索引元素赋值 | | `setindex!(A, v, I::Vararg{Int, N})` |   | (若为 `IndexCartesian`,其中 `N = ndims(A)`)N 维标量索引元素赋值 | | **可选方法** | **默认定义** | **简短描述** | | `IndexStyle(::Type)` | `IndexCartesian()` | 返回 `IndexLinear()` 或 `IndexCartesian()`。请参阅下文描述。 | | `getindex(A, I...)` | 基于标量 `getindex` 定义 | [多维非标量索引](@ref man-array-indexing) | | `setindex!(A, X, I...)` | 基于标量 `setindex!` 定义 | [多维非标量索引元素赋值](@ref man-array-indexing) | | `iterate` | 基于标量 `getindex` 定义 | Iteration | | `length(A)` | `prod(size(A))` | 元素数 | | `similar(A)` | `similar(A, eltype(A), size(A))` | 返回具有相同形状和元素类型的可变数组 | | `similar(A, ::Type{S})` | `similar(A, S, size(A))` | 返回具有相同形状和指定元素类型的可变数组 | | `similar(A, dims::Dims)` | `similar(A, eltype(A), dims)` | 返回具有相同元素类型和大小为 *dims* 的可变数组 | | `similar(A, ::Type{S}, dims::Dims)` | `Array{S}(undef, dims)` | 返回具有指定元素类型及大小的可变数组 | | **不遵循惯例的索引** | **默认定义** | **简短描述** | | `axes(A)` | `map(OneTo, size(A))` | 返回有效索引的 `AbstractUnitRange{<:Integer}` | | `similar(A, ::Type{S}, inds)` | `similar(A, S, Base.to_shape(inds))` | 返回使用特殊索引 `inds` 的可变数组(详见下文) | | `similar(T::Union{Type,Function}, inds)` | `T(Base.to_shape(inds))` | 返回类似于 `T` 的使用特殊索引 `inds` 的数组(详见下文) | 如果一个类型被定义为 `AbstractArray` 的子类型,那它就继承了一大堆丰富的行为,包括构建在单元素访问之上的迭代和多维索引。有关更多支持的方法,请参阅文档 [多维数组](@ref man-multi-dim-arrays) 及 [Julia Base](@ref lib-arrays)。 定义 `AbstractArray` 子类型的关键部分是 [`IndexStyle`](@ref)。由于索引是数组的重要部分且经常出现在 hot loops 中,使索引和索引赋值尽可能高效非常重要。数组数据结构通常以两种方式定义:要么仅使用一个索引(即线性索引)来最高效地访问其元素,要么实际上使用由各个维度确定的索引访问其元素。这两种方式被 Julia 标记为 `IndexLinear()` 和 `IndexCartesian()`。把线性索引转换为多重索引下标通常代价高昂,因此这提供了基于 traits 机制,以便能为所有矩阵类型提供高效的通用代码。 此区别决定了该类型必须定义的标量索引方法。`IndexLinear()` 很简单:只需定义 `getindex(A::ArrayType, i::Int)`。当数组后用多维索引集进行索引时,回退 `getindex(A::AbstractArray, I...)()` 高效地将该索引转换为线性索引,然后调用上述方法。另一方面,`IndexCartesian()` 数组需要为每个支持的、使用 `ndims(A)` 个 `Int` 索引的维度定义方法。例如,`SparseArrays` 标准库里的 [`SparseMatrixCSC`](@ref) 只支持二维,所以它只定义了 `getindex(A::SparseMatrixCSC, i::Int, j::Int)`。[`setindex!`](@ref) 也是如此。 回到上面的平方数序列,我们可以将它定义为 `AbstractArray{Int, 1}` 的子类型: ```jldoctest squarevectype julia> struct SquaresVector <: AbstractArray{Int, 1} count::Int end julia> Base.size(S::SquaresVector) = (S.count,) julia> Base.IndexStyle(::Type{<:SquaresVector}) = IndexLinear() julia> Base.getindex(S::SquaresVector, i::Int) = i*i ``` 请注意,指定 `AbstractArray` 的两个参数非常重要;第一个参数定义了 [`eltype`](@ref),第二个则定义了 [`ndims`](@ref)。该超类型和这三个方法就足以使 `SquaresVector` 变成一个可迭代、可索引且功能齐全的数组: ```jldoctest squarevectype julia> s = SquaresVector(4) 4-element SquaresVector: 1 4 9 16 julia> s[s .> 8] 2-element Vector{Int64}: 9 16 julia> s + s 4-element Vector{Int64}: 2 8 18 32 julia> sin.(s) 4-element Vector{Float64}: 0.8414709848078965 -0.7568024953079282 0.4121184852417566 -0.2879033166650653 ``` 作为一个更复杂的例子,让我们在 [`Dict`](@ref) 之上定义自己的玩具性质的 N 维稀疏数组类型。 ```jldoctest squarevectype julia> struct SparseArray{T,N} <: AbstractArray{T,N} data::Dict{NTuple{N,Int}, T} dims::NTuple{N,Int} end julia> SparseArray(::Type{T}, dims::Int...) where {T} = SparseArray(T, dims); julia> SparseArray(::Type{T}, dims::NTuple{N,Int}) where {T,N} = SparseArray{T,N}(Dict{NTuple{N,Int}, T}(), dims); julia> Base.size(A::SparseArray) = A.dims julia> Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where {T} = SparseArray(T, dims) julia> Base.getindex(A::SparseArray{T,N}, I::Vararg{Int,N}) where {T,N} = get(A.data, I, zero(T)) julia> Base.setindex!(A::SparseArray{T,N}, v, I::Vararg{Int,N}) where {T,N} = (A.data[I] = v) ``` 请注意,这是个 `IndexCartesian` 数组,因此我们必须在数组的维度上手动定义 [`getindex`](@ref) 和 [`setindex!`](@ref)。与 `SquaresVector` 不同,我们可以定义 [`setindex!`](@ref),这样便能更改数组: ```jldoctest squarevectype julia> A = SparseArray(Float64, 3, 3) 3×3 SparseArray{Float64, 2}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 julia> fill!(A, 2) 3×3 SparseArray{Float64, 2}: 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 2.0 julia> A[:] = 1:length(A); A 3×3 SparseArray{Float64, 2}: 1.0 4.0 7.0 2.0 5.0 8.0 3.0 6.0 9.0 ``` 索引 `AbstractArray` 的结果本身可以是数组(例如,在使用 `AbstractRange` 时)。`AbstractArray` 回退方法使用 [`similar`](@ref) 来分配具有适当大小和元素类型的 `Array`,该数组使用上述的基本索引方法填充。但是,在实现数组封装器时,你通常希望也封装结果: ```jldoctest squarevectype julia> A[1:2,:] 2×3 SparseArray{Float64, 2}: 1.0 4.0 7.0 2.0 5.0 8.0 ``` 在此例中,创建合适的封装数组通过定义 `Base.similar(A::SparseArray, ::Type{T}, dims::Dims) where T` 来实现。(请注意,虽然 `similar` 支持 1 参数和 2 参数形式,但在大多数情况下,你只需要专门定义 3 参数形式。)为此,`SparseArray` 是可变的(支持 `setindex!`)便很重要。为 `SparseArray` 定义 `similar`、`getindex` 和 `setindex!` 也使得该数组能够 [`copy`](@ref) 。 ```jldoctest squarevectype julia> copy(A) 3×3 SparseArray{Float64,2}: 1.0 4.0 7.0 2.0 5.0 8.0 3.0 6.0 9.0 ``` 除了上面的所有可迭代和可索引方法之外,这些类型还能相互交互,并使用在 Julia Base 中为 `AbstractArray` 定义的大多数方法: ```jldoctest squarevectype julia> A[SquaresVector(3)] 3-element SparseArray{Float64, 1}: 1.0 4.0 9.0 julia> sum(A) 45.0 ``` 如果要定义允许非传统索引(索引以 1 之外的数字开始)的数组类型,你应该专门指定 [`axes`](@ref)。你也应该专门指定 [`similar`](@ref),以便 `dims` 参数(通常是大小为 `Dims` 的元组)可以接收 `AbstractUnitRange` 对象,它也许是你自己设计的 range 类型 `Ind`。有关更多信息,请参阅[使用自定义索引的数组](@ref man-custom-indices)。 ## [等步长数组](@id man-interface-strided-arrays) | 实习方法 | | 简要描述 | |:----------------------------------------------- |:-------------------------------------- |:------------------------------------------------------------------------------------- | | `strides(A)` | | 返回每个维度中相邻元素之间的内存距离(以内存元素数量的形式)组成的元组。如果 `A` 是 `AbstractArray{T,0}`,这应该返回空元组。 | | `Base.unsafe_convert(::Type{Ptr{T}}, A)` | | 返回数组的本地内存地址 | | `Base.elsize(::Type{<:A})` | | 返回数组中连续元素的步长 | | **可选方法** | **默认定义** | **简要描述** | | `stride(A, i::Int)` | `strides(A)[i]` | 返回维度 i(译注:原文为 k)上相邻元素之间的内存距离(以内存元素数量的形式)。 | 等步长数组是 `AbstractArray` 的子类型,其条目以固定步长储存在内存中。如果数组的元素类型与 BLAS 兼容,则 strided 数组可以利用 BLAS 和 LAPACK 例程来实现更高效的线性代数例程。用户定义的 strided 数组的典型示例是把标准 `Array` 用附加结构进行封装的数组。 警告:如果底层存储实际上不是 strided,则不要实现这些方法,因为这可能导致错误的结果或段错误。 下面是一些示例,用来演示哪些数组类型是 strided 数组,哪些不是: ```julia 1:5 # not strided (there is no storage associated with this array.) Vector(1:5) # is strided with strides (1,) A = [1 5; 2 6; 3 7; 4 8] # is strided with strides (1,4) V = view(A, 1:2, :) # is strided with strides (1,4) V = view(A, 1:2:3, 1:2) # is strided with strides (2,4) V = view(A, [1,2,4], :) # is not strided, as the spacing between rows is not fixed. ``` ## [自定义广播](@id man-interfaces-broadcasting) | 需要实现的方法 | 简短描述 | |:-------------------- |:----------------- | | `Base.BroadcastStyle(::Type{SrcType}) = SrcStyle()` | `SrcType` 的广播行为 | | `Base.similar(bc::Broadcasted{DestStyle}, ::Type{ElType})` | 输出容器的分配 | | **可选方法** | | | | `Base.BroadcastStyle(::Style1, ::Style2) = Style12()` | 混合广播风格的优先级规则 | | `Base.axes(x)` | 用于广播的 `x` 的索引的声明(默认为 [`axes(x)`](@ref)) | | `Base.broadcastable(x)` | 将 `x` 转换为一个具有 `axes` 且支持索引的对象 | | **绕过默认机制** | | | `Base.copy(bc::Broadcasted{DestStyle})` | `broadcast` 的自定义实现 | | `Base.copyto!(dest, bc::Broadcasted{DestStyle})` | 专门针对 `DestStyle` 的自定义 `broadcast!` 实现 | | `Base.copyto!(dest::DestType, bc::Broadcasted{Nothing})` | 专门针对 `DestStyle` 的自定义 `broadcast!` 实现 | | `Base.Broadcast.broadcasted(f, args...)` | 覆盖融合表达式中的默认惰性行为 | | `Base.Broadcast.instantiate(bc::Broadcasted{DestStyle})` | 覆盖惰性广播的 axes 的计算 | [广播](@ref)可由 `broadcast` 或 `broadcast!` 的显式调用、或者像 `A .+ b` 或 `f.(x, y)` 这样的「点」操作隐式触发。任何具有 [`axes`](@ref) 且支持索引的对象都可作为参数参与广播,默认情况下,广播结果储存在 `Array` 中。这个基本框架可通过三个主要方式扩展: * 确保所有参数都支持广播 * 为给定参数集选择合适的输出数组 * 为给定参数集选择高效的实现 不是所有类型都支持 `axes` 和索引,但许多类型便于支持广播。[`Base.broadcastable`](@ref) 函数会在每个广播参数上调用,它能返回与广播参数不同的支持 `axes` 和索引的对象。默认情况下,对于所有 `AbstractArray` 和 `Number` 来说这是 identity 函数——因为它们已经支持 `axes` 和索引了。少数其它类型(包括但不限于类型本身、函数、像 [`missing`](@ref) 和 [`nothing`](@ref) 这样的特殊单态类型以及日期)为了能被广播,`Base.broadcastable` 会返回封装在 `Ref` 的参数来充当 0 维「标量」。自定义类型可以类似地指定 `Base.broadcastable` 来定义其形状,但是它们应当遵循 `collect(Base.broadcastable(x)) == collect(x)` 的约定。一个值得注意的例外是 `AbstractString`;字符串是个特例,为了能被广播其表现为标量,尽管它们是其字符的可迭代集合(详见 [字符串](@id man-strings))。 接下来的两个步骤(选择输出数组和实现)依赖于如何确定给定参数集的唯一解。广播必须接受其参数的所有不同类型,并把它们折叠到一个输出数组和实现。广播称此唯一解为“风格”。每个可广播对象都有自己的首选风格,并使用类似于类型提升的系统将这些风格组合成一个唯一解——“目标风格”。 ### 广播风格 抽象类型 `Base.BroadcastStyle` 派生了所有的广播风格。其在用作函数时有两种可能的形式,分别为一元形式(单参数)和二元形式。使用一元形式表明你打算实现特定的广播行为和/或输出类型,并且不希望依赖于默认的回退 [`Broadcast.DefaultArrayStyle`](@ref)。 为了覆盖这些默认值,你可以为对象自定义 `BroadcastStyle`: ```julia struct MyStyle <: Broadcast.BroadcastStyle end Base.BroadcastStyle(::Type{<:MyType}) = MyStyle() ``` 在某些情况下,无需定义 `MyStyle` 也许很方便,在这些情况下,你可以利用一个通用的广播封装器: - `Base.BroadcastStyle(::Type{<:MyType}) = Broadcast.Style{MyType}()` 可用于任意类型。 - 如果 `MyType` 是一个 `AbstractArray`,首选是 `Base.BroadcastStyle(::Type{<:MyType}) = Broadcast.ArrayStyle{MyType}()`。 - 对于只支持某个具体维度的 `AbstractArrays`,请创建 `Broadcast.AbstractArrayStyle{N}` 的子类型(请参阅下文)。 当你的广播操作涉及多个参数,各个广播风格将合并,来确定唯一一个 `DestStyle` 以控制输出容器的类型。有关更多详细信息,请参阅[下文](@ref writing-binary-broadcasting-rules)。 ### 选择合适的输出数组 每个广播操作都会计算广播风格以便支持派发和专门化。结果数组的实际分配由 `similar` 处理,其使用 Broadcasted 对象作为其第一个参数。 ```julia Base.similar(bc::Broadcasted{DestStyle}, ::Type{ElType}) ``` 回退定义是 ```julia similar(bc::Broadcasted{DefaultArrayStyle{N}}, ::Type{ElType}) where {N,ElType} = similar(Array{ElType}, axes(bc)) ``` 但是,如果需要,你可以专门化任何或所有这些参数。最后的参数 `bc` 是(还可能是融合的)广播操作的惰性表示,即 `Broadcasted` 对象。出于这些目的,该封装器中最重要的字段是 `f` 和 `args`,分别描述函数和参数列表。请注意,参数列表可以——并且经常——包含其它嵌套的 `Broadcasted` 封装器。 举个完整的例子,假设你创建了类型 `ArrayAndChar`,该类型存储一个数组和单个字符: ```jldoctest ArrayAndChar; output = false struct ArrayAndChar{T,N} <: AbstractArray{T,N} data::Array{T,N} char::Char end Base.size(A::ArrayAndChar) = size(A.data) Base.getindex(A::ArrayAndChar{T,N}, inds::Vararg{Int,N}) where {T,N} = A.data[inds...] Base.setindex!(A::ArrayAndChar{T,N}, val, inds::Vararg{Int,N}) where {T,N} = A.data[inds...] = val Base.showarg(io::IO, A::ArrayAndChar, toplevel) = print(io, typeof(A), " with char '", A.char, "'") # output ``` 你可能想要广播保留“元数据”`char`。为此,我们首先定义 ```jldoctest ArrayAndChar; output = false Base.BroadcastStyle(::Type{<:ArrayAndChar}) = Broadcast.ArrayStyle{ArrayAndChar}() # output ``` 这意味着我们还必须定义相应的 `similar` 方法: ```jldoctest ArrayAndChar; output = false function Base.similar(bc::Broadcast.Broadcasted{Broadcast.ArrayStyle{ArrayAndChar}}, ::Type{ElType}) where ElType # Scan the inputs for the ArrayAndChar: A = find_aac(bc) # Use the char field of A to create the output ArrayAndChar(similar(Array{ElType}, axes(bc)), A.char) end "`A = find_aac(As)` returns the first ArrayAndChar among the arguments." find_aac(bc::Base.Broadcast.Broadcasted) = find_aac(bc.args) find_aac(args::Tuple) = find_aac(find_aac(args[1]), Base.tail(args)) find_aac(x) = x find_aac(::Tuple{}) = nothing find_aac(a::ArrayAndChar, rest) = a find_aac(::Any, rest) = find_aac(rest) # output find_aac (generic function with 6 methods) ``` 在这些定义中,可以得到以下行为: ```jldoctest ArrayAndChar julia> a = ArrayAndChar([1 2; 3 4], 'x') 2×2 ArrayAndChar{Int64, 2} with char 'x': 1 2 3 4 julia> a .+ 1 2×2 ArrayAndChar{Int64, 2} with char 'x': 2 3 4 5 julia> a .+ [5,10] 2×2 ArrayAndChar{Int64, 2} with char 'x': 6 7 13 14 ``` ### [使用自定义实现扩展广播](@id extending-in-place-broadcast) 一般来说,广播操作由一个惰性 `Broadcasted` 容器表示,该容器保存要应用的函数及其参数。这些参数可能本身是嵌套得更深的 `Broadcasted` 容器,并一起形成了一个待求值的大型表达式树。嵌套的 `Broadcasted` 容器树可由隐式的点语法直接构造;例如,`5 .+ 2.*x` 由 `Broadcasted(+, 5, Broadcasted(*, 2, x))` 暂时表示。这对于用户是不可见的,因为它是通过调用 `copy` 立即实现的,但是此容器为自定义类型的作者提供了广播可扩展性的基础。然后,内置的广播机制将根据参数确定结果的类型和大小,为它分配内存,并最终通过默认的 `copyto!(::AbstractArray, ::Broadcasted)` 方法将 `Broadcasted` 对象复制到其中。内置的回退 `broadcast` 和 `broadcast!` 方法类似地构造操作的暂时 `Broadcasted` 表示,因此它们共享相同的代码路径。这便允许自定义的数组实现通过提供它们自己的专门化 `copyto!` 来定义和优化广播。这再次由计算后的广播风格确定。此广播风格在广播操作中非常重要,以至于它被存储为 `Broadcasted` 类型的第一个类型参数,且允许派发和专门化。 对于某些类型,跨越层层嵌套的广播的「融合」操作无法实现,或者无法更高效地逐步完成。在这种情况下,你可能需要或者想要求值 `x .* (x .+ 1)`,就好像该式已被编写成 `broadcast(*, x, broadcast(+, x, 1))`,其中内部广播操作会在处理外部广播操作前进行求值。这种直接的操作以有点间接的方式得到直接支持;Julia 不会直接构造 `Broadcasted` 对象,而会将 待融合的表达式 `x .* (x .+ 1)` 降低为 `Broadcast.broadcasted(*, x, Broadcast.broadcasted(+, x, 1))`。现在,默认情况下,`broadcasted` 只会调用 `Broadcasted` 构造函数来创建待融合表达式树的惰性表示,但是你可以选择为函数和参数的特定组合覆盖它。 举个例子,内置的 `AbstractRange` 对象使用此机制优化广播表达式的片段,这些表达式片段可以只根据 start、step 和 length(或 stop)直接进行求值,而无需计算每个元素。与所有其它机制一样,`broadcasted` 也会计算并暴露其参数的组合广播风格,所以你可以为广播风格、函数和参数的任意组合专门化 `broadcasted(::DestStyle, f, args...)`,而不是专门化 `broadcasted(f, args...)`。 例如,以下定义支持 range 的负运算: ```julia broadcasted(::DefaultArrayStyle{1}, ::typeof(-), r::OrdinalRange) = range(-first(r), step=-step(r), length=length(r)) ``` ### [扩展 in-place 广播](@id extending-in-place-broadcast) In-place 广播可通过定义合适的 `copyto!(dest, bc::Broadcasted)` 方法来支持。由于你可能想要专门化 `dest` 或 `bc` 的特定子类型,为了避免包之间的歧义,我们建议采用以下约定。 如果你想要专门化特定的广播风格 `DestStyle`,请为其定义一个方法 ```julia copyto!(dest, bc::Broadcasted{DestStyle}) ``` 你可选择使用此形式,如果使用,你还可以专门化 `dest` 的类型。 如果你想专门化目标类型 `DestType` 而不专门化 `DestStyle`,那么你应该定义一个带有以下签名的方法: ```julia copyto!(dest::DestType, bc::Broadcasted{Nothing}) ``` 这利用了 `copyto!` 的回退实现,它将该封装器转换为一个 `Broadcasted{Nothing}` 对象。因此,专门化 `DestType` 的方法优先级低于专门化 `DestStyle` 的方法。 同样,你可以使用 `copy(::Broadcasted)` 方法完全覆盖 out-of-place 广播。 #### 使用 `Broadcasted` 对象 当然,为了实现这样的 `copy` 或 `copyto!` 方法,你必须使用 `Broadcasted` 封装器来计算每个元素。这主要有两种方式: * `Broadcast.flatten` 将可能的嵌套操作重新计算为单个函数并平铺参数列表。你自己负责实现广播形状规则,但这在有限的情况下可能会有所帮助。 * 迭代 `axes(::Broadcasted)` 的 `CartesianIndices` 并使用所生成的 `CartesianIndex` 对象的索引来计算结果。 ### [编写二元广播规则](@id writing-binary-broadcasting-rules) 广播风格的优先级规则由二元 `BroadcastStyle` 调用定义: ```julia Base.BroadcastStyle(::Style1, ::Style2) = Style12() ``` 其中,`Style12` 是你要为输出所选择的 `BroadcastStyle`,所涉及的参数具有 `Style1` 及 `Style2`。例如, ```julia Base.BroadcastStyle(::Broadcast.Style{Tuple}, ::Broadcast.AbstractArrayStyle{0}) = Broadcast.Style{Tuple}() ``` 表示 `Tuple`「胜过」零维数组(输出容器将是元组)。值得注意的是,你不需要(也不应该)为此调用的两个参数顺序下定义;无论用户提供的以何种顺序提供参数,定义一个就够了。 对于 `AbstractArray` 类型,定义 `BroadcastStyle` 将取代回退选择 [`Broadcast.DefaultArrayStyle`](@ref)。`DefaultArrayStyle` 及其抽象超类型 `AbstractArrayStyle` 将维度存储为类型参数,以支持具有固定维度需求的特定数组类型。 由于以下方法,`DefaultArrayStyle`「输给」任何其它已定义的 `AbstractArrayStyle`: ```julia BroadcastStyle(a::AbstractArrayStyle{Any}, ::DefaultArrayStyle) = a BroadcastStyle(a::AbstractArrayStyle{N}, ::DefaultArrayStyle{N}) where N = a BroadcastStyle(a::AbstractArrayStyle{M}, ::DefaultArrayStyle{N}) where {M,N} = typeof(a)(Val(max(M, N))) ``` 除非你想要为两个或多个非 `DefaultArrayStyle` 的类型建立优先级,否则不需要编写二元 `BroadcastStyle` 规则。 如果你的数组类型确实有固定的维度需求,那么你应该定义一个 `AbstractArrayStyle` 的子类型。例如,稀疏数组的代码中有以下定义: ```julia struct SparseVecStyle <: Broadcast.AbstractArrayStyle{1} end struct SparseMatStyle <: Broadcast.AbstractArrayStyle{2} end Base.BroadcastStyle(::Type{<:SparseVector}) = SparseVecStyle() Base.BroadcastStyle(::Type{<:SparseMatrixCSC}) = SparseMatStyle() ``` 每当你定义一个 `AbstractArrayStyle` 的子类型,你还需要定义用于组合维度的规则,这通过为你的广播风格创建带有一个 `Val(N)` 参数的构造函数。例如: ```julia SparseVecStyle(::Val{0}) = SparseVecStyle() SparseVecStyle(::Val{1}) = SparseVecStyle() SparseVecStyle(::Val{2}) = SparseMatStyle() SparseVecStyle(::Val{N}) where N = Broadcast.DefaultArrayStyle{N}() ``` 这些规则表明 `SparseVecStyle` 与 0 维或 1 维数组的组合会产生另一个 `SparseVecStyle`,与 2 维数组的组合会产生 `SparseMatStyle`,而与维度更高的数组则回退到任意维密集矩阵的框架中。这些规则允许广播为产生一维或二维输出的操作保持其稀疏表示,但为任何其它维度生成 `Array`。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
17658
# 数学运算和初等函数 Julia 为它所有的基础数值类型,提供了整套的基础算术和位运算,也提供了一套高效、可移植的标准数学函数。 ## 算术运算符 以下[算术运算符](https://en.wikipedia.org/wiki/Arithmetic#Arithmetic_operations)支持所有的原始数值类型: | 表达式 | 名称 | 描述 | |:---------- |:-------------- |:----------------------------------------| | `+x` | 一元加法运算符 | 全等操作 | | `-x` | 一元减法运算符 | 将值变为其相反数 | | `x + y` | 二元加法运算符 | 执行加法 | | `x - y` | 二元减法运算符 | 执行减法 | | `x * y` | 乘法运算符 | 执行乘法 | | `x / y` | 除法运算符 | 执行除法 | | `x ÷ y` | 整除 | 取 x / y 的整数部分 | | `x \ y` | 反向除法 | 等价于 `y / x` | | `x ^ y` | 幂操作符 | `x` 的 `y` 次幂 | | `x % y` | 取余 | 等价于 `rem(x,y)` | 除了优先级比二元操作符高以外,直接放在标识符或括号前的数字,如 `2x` 或 `2(x+y)` 还会被视为乘法。详见[数值字面量系数](@ref man-numeric-literal-coefficients)。 Julia 的类型提升系统使得混合参数类型上的代数运算也能顺其自然的工作,请参考[类型提升系统](@ref conversion-and-promotion)来了解更多内容。 符号 ÷ 可以通过输入 `\div<tab>` 到 REPL 或 Julia IDE 的方式来打出. 更多信息参见 [Unicode 输入表](@ref Unicode-Input)。 这里是使用算术运算符的一些简单例子: ```jldoctest julia> 1 + 2 + 3 6 julia> 1 - 2 -1 julia> 3*2/12 0.5 ``` 习惯上我们会把优先运算的操作符紧邻操作数,比如 `-x + 2` 表示先要给 `x` 取反,然后再加 `2` 。 在乘法操作中,`false` 被视作 **零**。 ```jldoctest julia> NaN * false 0.0 julia> false * Inf 0.0 ``` 这在已知某些量为零时,可以避免 `NaN` 的传播。详细的动机参见:[Knuth (1992)](https://arxiv.org/abs/math/9205211)。 ## 布尔运算符 [`Bool`](@ref) 类型支持以下[布尔运算符](https://en.wikipedia.org/wiki/Boolean_algebra#Operations): | 表达式 | 名称 | |:---------- |:--------------------------------------------------------| | `!x` | 否定 | | `x && y` | [短路与](@ref man-conditional-evaluation) | | `x \|\| y` | [短路或](@ref man-conditional-evaluation) | 否定将 `true` 更改为 `false`,反之亦然。链接页面上解释了逻辑短路。 请注意,`Bool` 是一个整数类型,所有常用的类型提升规则和数字运算符仍然对它适用。 ## 位运算符 所有原始整数类型都支持以下[位运算符](https://en.wikipedia.org/wiki/Bitwise_operation#Bitwise_operators): | 表达式 | 名称 | |:---------- |:------------------------------------------------------------------------ | | `~x` | 按位取反 | | `x & y` | 按位与 | | `x \| y` | 按位或 | | `x ⊻ y` | 按位异或(逻辑异或) | | `x ⊼ y` | 按位与(非与) | | `x ⊽ y` | 按位或(非或) | | `x >>> y` | [逻辑右移](https://en.wikipedia.org/wiki/Logical_shift) | | `x >> y` | [算术右移](https://en.wikipedia.org/wiki/Arithmetic_shift) | | `x << y` | 逻辑/算术左移 | 以下是位运算符的一些示例: ```jldoctest julia> ~123 -124 julia> 123 & 234 106 julia> 123 | 234 251 julia> 123 ⊻ 234 145 julia> xor(123, 234) 145 julia> nand(123, 123) -124 julia> 123 ⊼ 123 -124 julia> nor(123, 124) -128 julia> 123 ⊽ 124 -128 julia> ~UInt32(123) 0xffffff84 julia> ~UInt8(123) 0x84 ``` ## 复合赋值运算符 每一个二元运算符和位运算符都可以给左操作数复合赋值:方法是把 `=` 直接放在二元运算符后面。比如,`x += 3` 等价于 `x = x + 3` 。 ```jldoctest julia> x = 1 1 julia> x += 3 4 julia> x 4 ``` 二元运算符和位运算符的复合赋值操作符有下面几种: ``` += -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<= ``` !!! note 复合赋值后会把变量重新绑定到左操作数上,所以变量的类型可能会改变。 ```jldoctest julia> x = 0x01; typeof(x) UInt8 julia> x *= 2 # 与 x = x * 2 相同 2 julia> typeof(x) Int64 ``` ## [向量化 “点” 运算符](@id man-dot-operators) Julia 中,**每个**二元运算符都有一个 “点” 运算符与之对应,例如 `^` 就有对应的 `.^` 存在。这个对应的 `.^` 被 Julia **自动地**定义为逐元素地执行 `^` 运算。比如 `[1,2,3] ^ 3` 是非法的,因为数学上没有给(长宽不一样的)数组的立方下过定义。但是 `[1,2,3] .^ 3` 在 Julia 里是合法的,它会逐元素地执行 `^` 运算(或称向量化运算),得到 `[1^3, 2^3, 3^3]`。类似地,`!` 或 `√` 这样的一元运算符,也都有一个对应的 `.√` 用于执行逐元素运算。 ```jldoctest julia> [1,2,3] .^ 3 3-element Vector{Int64}: 1 8 27 ``` 更确切地说,`a .^b` 被解析为 [“点运算” 调用](@ref man-vectorized) `(^).(a,b)`,这会执行 [广播](@ref Broadcasting) 操作:该操作能结合数组和标量、相同大小的数组(进行元素之间的运算),甚至不同形状的数组(例如行、列向量结合生成矩阵)。此外,就像所有向量化的点运算调用一样,这些点运算符是*融合*的。例如,在计算关于数组 `A` 的表达式 `2 .* A.^2 .+ sin.(A)`(或者等价地,使用[`@.`](@ref @__dot__) 宏,`@. 2A^2 + sin(A)`),Julia 只对 `A` 进行做*一次*循环,遍历 `A` 中的每个元素 `a` 并计算 `2a^2 + sin(a)`。特别的,类似 `f.(g.(x))` 的嵌套点运算调用也是融合的,并且“相邻的”二元运算符表达式 `x .+ 3 .* x.^2` 可以等价转换为嵌套 dot 调用:`(+).(x, (*).(3, (^).(x, 2)))`。 除了点运算符,我们还有逐点赋值运算符,类似 `a .+= b`(或者 `@. a += b`)会被解析成 `a .= a .+ b`,这里的 `.=` 是一个**融合**的 in-place 运算,更多信息请查看 [`dot` 文档](@ref man-vectorized))。 这个点语法,也能用在用户自定义的运算符上。例如,通过定义 `⊗(A,B) = kron(A,B)` 可以为 Kronecker 积([`kron`](@ref))提供一个方便的中缀语法 `A ⊗ B`,那么配合点语法 `[A,B] .⊗ [C,D]` 就等价于 `[A⊗C, B⊗D]`。 将点运算符用于数值字面量可能会导致歧义。例如,`1.+x` 到底是表示 `1. + x` 还是 `1 .+ x`?这会令人疑惑。因此不允许使用这种语法,遇到这种情况时,必须明确地用空格消除歧义。 ## 数值比较 标准的比较操作对所有原始数值类型有定义: | 操作符 | 名称 | |:---------------------------- |:------------------------ | | [`==`](@ref) | 相等 | | [`!=`](@ref), [`≠`](@ref !=) | 不等 | | [`<`](@ref) | 小于 | | [`<=`](@ref), [`≤`](@ref <=) | 小于等于 | | [`>`](@ref) | 大于 | | [`>=`](@ref), [`≥`](@ref >=) | 大于等于 | 下面是一些简单的例子: ```jldoctest julia> 1 == 1 true julia> 1 == 2 false julia> 1 != 2 true julia> 1 == 1.0 true julia> 1 < 2 true julia> 1.0 > 3 false julia> 1 >= 1.0 true julia> -1 <= 1 true julia> -1 <= -1 true julia> -1 <= -2 false julia> 3 < -0.5 false ``` 整数的比较方式是标准的按位比较,而浮点数的比较方式则遵循 [IEEE 754 标准](https://en.wikipedia.org/wiki/IEEE_754-2008)。 * 有限数的大小顺序,和我们所熟知的相同。 * `+0` 等于但不大于 `-0`. * `Inf` 等于自身,并且大于除了 `NaN` 外的所有数。 * `-Inf` 等于自身,并且小于除了 `NaN` 外的所有数。 * `NaN` 不等于、不小于且不大于任何数值,包括它自己。 `NaN` 不等于它自己这一点可能会令人感到惊奇,所以需要注意: ```jldoctest julia> NaN == NaN false julia> NaN != NaN true julia> NaN < NaN false julia> NaN > NaN false ``` 当你将 `NaN` 和 [数组](@ref man-multi-dim-arrays) 一起连用时,你就会感到头疼: ```jldoctest julia> [1 NaN] == [1 NaN] false ``` 为此,Julia 给这些特别的数提供了下面几个额外的测试函数。这些函数在某些情况下很有用处,比如在做 hash 比较时。 | 函数 | 测试是否满足如下性质 | |:----------------------- |:------------------------- | | [`isequal(x, y)`](@ref) | `x` 与 `y` 是完全相同的 | | [`isfinite(x)`](@ref) | `x` 是有限大的数字 | | [`isinf(x)`](@ref) | `x` 是(正/负)无穷大 | | [`isnan(x)`](@ref) | `x` 是 `NaN` | [`isequal`](@ref) 认为 `NaN` 之间是相等的: ```jldoctest julia> isequal(NaN, NaN) true julia> isequal([1 NaN], [1 NaN]) true julia> isequal(NaN, NaN32) true ``` `isequal` 也能用来区分带符号的零: ```jldoctest julia> -0.0 == 0.0 true julia> isequal(-0.0, 0.0) false ``` 有符号整数、无符号整数以及浮点数之间的混合类型比较是很棘手的。开发者费了很大精力来确保 Julia 在这个问题上做的是正确的。 对于其它类型,`isequal` 会默认调用 [`==`](@ref),所以如果你想给自己的类型定义相等,那么就只需要为 [`==`](@ref) 增加一个方法。如果你想定义一个你自己的相等函数,你可能需要定义一个对应的 [`hash`](@ref) 方法,用于确保 `isequal(x,y)` 隐含着 `hash(x) == hash(y)`。 ### 链式比较 与其他多数语言不同,就像 [notable exception of Python](https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Comparison_operators) 一样,Julia 允许链式比较: ```jldoctest julia> 1 < 2 <= 2 < 3 == 3 > 2 >= 1 == 1 < 3 != 5 true ``` 链式比较在写数值代码时特别方便,它使用 `&&` 运算符比较标量,数组则用 [`&`](@ref) 进行按元素比较。比如,`0 .< A .< 1` 会得到一个 boolean 数组,如果 `A` 的元素都在 0 和 1 之间则数组元素就都是 true。 注意链式比较的执行顺序: ```jldoctest julia> v(x) = (println(x); x) v (generic function with 1 method) julia> v(1) < v(2) <= v(3) 2 1 3 true julia> v(1) > v(2) <= v(3) 2 1 false ``` 中间的表达式只会计算一次,而如果写成 `v(1) < v(2) && v(2) <= v(3)` 是计算了两次的。然而,链式比较中的顺序是不确定的。强烈建议不要在表达式中使用有副作用(比如 printing)的函数。如果的确需要,请使用短路运算符 `&&`(请参考[短路求值](@ref))。 ### 初等函数 Julia 提供了强大的数学函数和运算符集合。这些数学运算定义在各种合理的数值上,包括整型、浮点数、分数和复数,只要这些定义有数学意义就行。 而且,和其它 Julia 函数一样,这些函数也能通过 [点语法](@ref man-vectorized) `f.(A)` 以“向量化”的方式作用于数组和其它集合上。 比如,`sin.(A)` 会计算 `A` 中每个元素的 sin 值。 ## 运算符的优先级与结合性 从高到低,Julia 运算符的优先级与结合性为: | 分类 | 运算符 | 结合性 | |:-------------- |:------------------------------------------------------------------------------------------------- |:-------------------------- | | 语法 | `.` followed by `::` | 左结合 | | 幂运算 | `^` | 右结合 | | 一元运算符 | `+ - √` | 右结合[^1] | | 移位运算 | `<< >> >>>` | 左结合 | | 除法 | `//` | 左结合 | | 乘法 | `* / % & \ ÷` | 左结合[^2] | | 加法 | `+ - \| ⊻` | 左结合[^2] | | 语法 | `: ..` | 左结合 | | 语法 | `\|>` | 左结合 | | 语法 | `<\|` | 右结合 | | 比较 | `> < >= <= == === != !== <:` | 无结合性 | | 流程控制 | `&&` followed by `\|\|` followed by `?` | 右结合 | | Pair 操作 | `=>` | 右结合 | | 赋值 | `= += -= *= /= //= \= ^= ÷= %= \|= &= ⊻= <<= >>= >>>=` | 右结合 | [^1]: 一元运算符 `+` 和 `-` 需要显式调用,即给它们的参数加上括号,以免和 `++` 等运算符混淆。其它一元运算符的混合使用都被解析为右结合的,比如 `√√-a` 解析为 `√(√(-a))`。 [^2]: The operators `+`, `++` and `*` are non-associative. `a + b + c` is parsed as `+(a, b, c)` not `+(+(a, b), c)`. However, the fallback methods for `+(a, b, c, d...)` and `*(a, b, c, d...)` both default to left-associative evaluation. 想查看 *每个* Julia 运算符的优先级,可以参考这个文件:[`src/julia-parser.scm`](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm)。注意到有一些运算符在 `Base` 模块中没有定义但是可能是在标准库、包或者用户代码中定义的。 你也可以通过内置函数 `Base.operator_precedence` 查看任何给定运算符的优先级数值,数值越大优先级越高: ```jldoctest julia> Base.operator_precedence(:+), Base.operator_precedence(:*), Base.operator_precedence(:.) (11, 12, 17) julia> Base.operator_precedence(:sin), Base.operator_precedence(:+=), Base.operator_precedence(:(=)) # (注意:等号前后必须有括号 `:(=)`) (0, 1, 1) ``` 另外,内置函数 `Base.operator_associativity` 可以返回运算符结合性的符号表示: ```jldoctest julia> Base.operator_associativity(:-), Base.operator_associativity(:+), Base.operator_associativity(:^) (:left, :none, :right) julia> Base.operator_associativity(:⊗), Base.operator_associativity(:sin), Base.operator_associativity(:→) (:left, :none, :right) ``` 注意诸如 `:sin` 这样的符号返回优先级 `0`,此值代表无效的运算符或非最低优先级运算符。类似地,它们的结合性被认为是 `:none`。 [数字字面量系数](@ref man-numeric-literal-coefficients),例如 `2x` 被视为比任何其他二元运算具有更高优先级的乘法,除了`^`,指数计算具有更高的优先级。 ```jldoctest julia> x = 3; 2x^2 18 julia> x = 3; 2^2x 64 ``` 并列解析就像一元运算符,它在指数周围具有相同的自然不对称性:`-x^y` 和 `2x^y `解析为 `-(x^y)` 和 `2(x^y)` 而 `x^-y` 和 `x^2y` 解析为`x^(-y)` 和 `x^(2y)`。 ## 数值转换 Julia 支持三种数值转换,它们在处理不精确转换上有所不同。 * `T(x)` 和 `convert(T,x)` 都会把 `x` 转换为 `T`类型。 * 如果 `T` 是浮点类型,转换的结果就是最近的可表示值, 可能会是正负无穷大。 * 如果 `T` 为整数类型,当 `x` 不能由 `T` 类型表示时,会抛出 `InexactError`。 * `x % T` 将整数 `x` 转换为整型 `T`,与 `x` 模 `2^n` 的结果一致,其中 `n` 是 `T` 的位数。换句话说,在二进制表示下被截掉了一部分。 * [舍入函数](@ref) 接收一个 `T` 类型的可选参数。比如,`round(Int,x)` 是 `Int(round(x))` 的简写版。 下面的例子展示了不同的形式 ```jldoctest julia> Int8(127) 127 julia> Int8(128) ERROR: InexactError: trunc(Int8, 128) Stacktrace: [...] julia> Int8(127.0) 127 julia> Int8(3.14) ERROR: InexactError: Int8(3.14) Stacktrace: [...] julia> Int8(128.0) ERROR: InexactError: Int8(128.0) Stacktrace: [...] julia> 127 % Int8 127 julia> 128 % Int8 -128 julia> round(Int8,127.4) 127 julia> round(Int8,127.6) ERROR: InexactError: trunc(Int8, 128.0) Stacktrace: [...] ``` 请参考[类型转换与类型提升](@ref conversion-and-promotion)一节来定义你自己的类型转换和提升规则。 ### 舍入函数 | 函数 | 描述 | 返回类型 | |:--------------------- |:-------------------------------- |:----------- | | [`round(x)`](@ref) | `x` 舍到最接近的整数 | `typeof(x)` | | [`round(T, x)`](@ref) | `x` 舍到最接近的整数 | `T` | | [`floor(x)`](@ref) | `x` 向 `-Inf` 舍入 | `typeof(x)` | | [`floor(T, x)`](@ref) | `x` 向 `-Inf` 舍入 | `T` | | [`ceil(x)`](@ref) | `x` 向 `+Inf` 方向取整 | `typeof(x)` | | [`ceil(T, x)`](@ref) | `x` 向 `+Inf` 方向取整 | `T` | | [`trunc(x)`](@ref) | `x` 向 0 取整 | `typeof(x)` | | [`trunc(T, x)`](@ref) | `x` 向 0 取整 | `T` | ### 除法函数 | 函数 | 描述 | |:------------------------- |:--------------------------------------------------------------------------------------------------------- | | [`div(x,y)`](@ref), `x÷y` | 截断除法;商向零近似 | | [`fld(x,y)`](@ref) | 向下取整除法;商向 `-Inf` 近似 | | [`cld(x,y)`](@ref) | 向上取整除法;商向 `+Inf` 近似 | | [`rem(x,y)`](@ref) | 取余;满足 `x == div(x,y)*y + rem(x,y)`;符号与 `x` 一致 | | [`mod(x,y)`](@ref) | 取模;满足 `x == fld(x,y)*y + mod(x,y)`;符号与 `y` 一致 | | [`mod1(x,y)`](@ref) | 偏移 1 的 `mod`;若 `y>0`,则返回 `r∈(0,y]`,若 `y<0`,则 `r∈[y,0)` 且满足 `mod(r, y) == mod(x, y)` | | [`mod2pi(x)`](@ref) | 对 2pi 取模;`0 <= mod2pi(x) < 2pi` | | [`divrem(x,y)`](@ref) | 返回 `(div(x,y),rem(x,y))` | | [`fldmod(x,y)`](@ref) | 返回 `(fld(x,y),mod(x,y))` | | [`gcd(x,y...)`](@ref) | `x`, `y`,... 的最大公约数 | | [`lcm(x,y...)`](@ref) | `x`, `y`,... 的最小公倍数 | ### 符号和绝对值函数 | 函数 | 描述 | |:----------------------- |:---------------------------------------------------------- | | [`abs(x)`](@ref) | `x` 的模 | | [`abs2(x)`](@ref) | `x` 的模的平方 | | [`sign(x)`](@ref) | 表示 `x` 的符号,返回 -1,0,或 +1 | | [`signbit(x)`](@ref) | 表示符号位是 true 或 false | | [`copysign(x,y)`](@ref) | 返回一个数,其值等于 `x` 的模,符号与 `y` 一致 | | [`flipsign(x,y)`](@ref) | 返回一个数,其值等于 `x` 的模,符号与 `x*y` 一致 | ### 幂、对数与平方根 | 函数 | 描述 | |:------------------------ |:-------------------------------------------------------------------------- | | [`sqrt(x)`](@ref), `√x` | `x` 的平方根 | | [`cbrt(x)`](@ref), `∛x` | `x` 的立方根 | | [`hypot(x,y)`](@ref) | 当直角边的长度为 `x` 和 `y`时,直角三角形斜边的长度 | | [`exp(x)`](@ref) | 自然指数函数在 `x` 处的值 | | [`expm1(x)`](@ref) | 当 `x` 接近 0 时的 `exp(x)-1` 的精确值 | | [`ldexp(x,n)`](@ref) | `x*2^n` 的高效算法,`n` 为整数 | | [`log(x)`](@ref) | `x` 的自然对数 | | [`log(b,x)`](@ref) | 以 `b` 为底 `x` 的对数 | | [`log2(x)`](@ref) | 以 2 为底 `x` 的对数 | | [`log10(x)`](@ref) | 以 10 为底 `x` 的对数 | | [`log1p(x)`](@ref) | 当 `x`接近 0 时的 `log(1+x)` 的精确值 | | [`exponent(x)`](@ref) | `x` 的二进制指数 | | [`significand(x)`](@ref) | 浮点数 `x` 的二进制有效数(也就是尾数) | 想大概了解一下为什么诸如 [`hypot`](@ref)、[`expm1`](@ref)和 [`log1p`](@ref) 函数是必要和有用的,可以看一下 John D. Cook 关于这些主题的两篇优秀博文:[expm1, log1p, erfc](https://www.johndcook.com/blog/2010/06/07/math-library-functions-that-seem-unnecessary/), 和 [hypot](https://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/)。 ### 三角和双曲函数 所有标准的三角和双曲函数也都已经定义了: ``` sin cos tan cot sec csc sinh cosh tanh coth sech csch asin acos atan acot asec acsc asinh acosh atanh acoth asech acsch sinc cosc ``` 所有这些函数都是单参数函数,不过 [`atan`](@ref) 也可以接收两个参数 来表示传统的 [`atan2`](https://en.wikipedia.org/wiki/Atan2) 函数。 另外,[`sinpi(x)`](@ref) 和 [`cospi(x)`](@ref) 分别用来对 [`sin(pi*x)`](@ref) 和 [`cos(pi*x)`](@ref) 进行更精确的计算。 要计算角度而非弧度的三角函数,以 `d` 做后缀。 比如,[`sind(x)`](@ref) 计算 `x` 的 sine 值,其中 `x` 是一个角度值。 下面是角度变量的三角函数完整列表: ``` sind cosd tand cotd secd cscd asind acosd atand acotd asecd acscd ``` ### 特殊函数 [SpecialFunctions.jl](https://github.com/JuliaMath/SpecialFunctions.jl) 提供了许多其他的特殊数学函数。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
27861
# [元编程](@id Metaprogramming) Lisp 留给 Julia 最大的遗产就是它的元编程支持。和 Lisp 一样,Julia 把自己的代码表示为语言中的数据结构。既然代码被表示为了可以在语言中创建和操作的对象,程序就可以变换和生成自己的代码。这允许在没有额外构建步骤的情况下生成复杂的代码,并且还允许在 [abstract syntax trees](https://en.wikipedia.org/wiki/Abstract_syntax_tree) 级别上运行的真正的 Lisp 风格的宏。与之相对的是预处理器“宏”系统,比如 C 和 C++ 中的,它们在解析和解释代码之前进行文本操作和变换。由于 Julia 中的所有数据类型和代码都被表示为 Julia 的 数据结构,强大的 [reflection](https://en.wikipedia.org/wiki/Reflection_omputer_%28cprogramming%29) 功能可用于探索程序的内部及其类型,就像任何其他数据一样。 ## 程序表示 每个 Julia 程序均以字符串开始: ```jldoctest prog julia> prog = "1 + 1" "1 + 1" ``` **接下来会发生什么?** 下一步是 [parse](https://en.wikipedia.org/wiki/Parsing#Computer_languages) 每个字符串到一个称为表达式的对象,由 Julia 的类型 [`Expr`](@ref) 表示: ```jldoctest prog julia> ex1 = Meta.parse(prog) :(1 + 1) julia> typeof(ex1) Expr ``` `Expr` 对象包含两个部分: * 一个标识表达式类型的 [`Symbol`](@ref)。 Symbol 就是一个 [interned string](https://en.wikipedia.org/wiki/String_interning) 标识符(下面会有更多讨论) ```jldoctest prog julia> ex1.head :call ``` * 表达式的参数,可能是符号、其他表达式或字面量: ```jldoctest prog julia> ex1.args 3-element Vector{Any}: :+ 1 1 ``` 表达式也可能直接用 [prefix notation](https://en.wikipedia.org/wiki/Polish_notation) 构造: ```jldoctest prog julia> ex2 = Expr(:call, :+, 1, 1) :(1 + 1) ``` 上面构造的两个表达式 – 一个通过解析构造一个通过直接构造 – 是等价的: ```jldoctest prog julia> ex1 == ex2 true ``` **这里的关键点是 Julia 的代码在内部表示为可以从语言本身访问的数据结构** 函数 [`dump`](@ref) 可以带有缩进和注释地显示 `Expr` 对象: ```jldoctest prog julia> dump(ex2) Expr head: Symbol call args: Array{Any}((3,)) 1: Symbol + 2: Int64 1 3: Int64 1 ``` `Expr` 对象也可以嵌套: ```jldoctest ex3 julia> ex3 = Meta.parse("(4 + 4) / 2") :((4 + 4) / 2) ``` 另外一个查看表达式的方法是使用 `Meta.show_sexpr`,它能显示给定 `Expr` 的 [S-expression](https://en.wikipedia.org/wiki/S-expression),对 Lisp 用户来说,这看着很熟悉。下面是一个示例,阐释了如何显示嵌套的 `Expr`: ```jldoctest ex3 julia> Meta.show_sexpr(ex3) (:call, :/, (:call, :+, 4, 4), 2) ``` ### 符号 字符 `:` 在 Julia 中有两个作用。第一种形式构造一个 [`Symbol`](@ref),这是作为表达式组成部分的一个 [interned string](https://en.wikipedia.org/wiki/String_interning): ```jldoctest julia> s = :foo :foo julia> typeof(s) Symbol ``` 构造函数 [`Symbol`](@ref) 接受任意数量的参数并通过把它们的字符串表示连在一起创建一个新的符号: ```jldoctest julia> :foo == Symbol("foo") true julia> Symbol("func",10) :func10 julia> Symbol(:var,'_',"sym") :var_sym ``` 注意,要使用 `:` 语法,符号的名称必须是有效的标识符。否则,必须使用 `Symbol(str)` 构造函数。 在表达式的上下文中,符号用来表示对变量的访问;当一个表达式被求值时,符号会被替换为这个符号在合适的 [scope](@ref scope-of-variables) 中所绑定的值。 有时需要在 `:` 的参数两边加上额外的括号,以避免在解析时出现歧义: ```jldoctest julia> :(:) :(:) julia> :(::) :(::) ``` ## 表达式与求值 ### 引用 `:` 的第二个语义是不显式调用 [`Expr`](@ref) 构造器来创建表达式对象。这被称为*引用*。`:` 后面跟着包围着单个 Julia 语句括号,可以基于被包围的代码生成一个 `Expr` 对象。下面是一个引用算数表达式的例子: ```jldoctest julia> ex = :(a+b*c+1) :(a + b * c + 1) julia> typeof(ex) Expr ``` (为了查看这个表达式的结构,可以试一试 `ex.head` 和 `ex.args`,或者使用 [`dump`](@ref) 同时查看 `ex.head` 和 `ex.args` 或者 [`Meta.@dump`](@ref)) 注意等价的表达式也可以使用 [`Meta.parse`](@ref) 或者直接用 `Expr` 构造: ```jldoctest julia> :(a + b*c + 1) == Meta.parse("a + b*c + 1") == Expr(:call, :+, :a, Expr(:call, :*, :b, :c), 1) true ``` 解析器提供的表达式通常只有符号、其它表达式和字面量值作为其参数,而由 Julia 代码构造的表达式能以非字面量形式的任意运行期值作为其参数。在此特例中,`+` 和 `a` 都是符号,`*(b,c)` 是子表达式,而 `1` 是 64 位带符号整数字面量。 引用多个表达式有第二种语法形式:在 `quote ... end` 中包含代码块。 ```jldoctest julia> ex = quote x = 1 y = 2 x + y end quote #= none:2 =# x = 1 #= none:3 =# y = 2 #= none:4 =# x + y end julia> typeof(ex) Expr ``` ### [插值](@id man-expression-interpolation) 使用值参数直接构造 [`Expr`](@ref) 对象虽然很强大,但与「通常的」 Julia 语法相比,`Expr` 构造函数可能让人觉得乏味。作为替代方法,Julia 允许将字面量或表达式插入到被引用的表达式中。表达式插值由前缀 `$` 表示。 在此示例中,插入了变量 `a` 的值: ```jldoctest interp1 julia> a = 1; julia> ex = :($a + b) :(1 + b) ``` 对未被引用的表达式进行插值是不支持的,这会导致编译期错误: ```jldoctest interp1 julia> $a + b ERROR: syntax: "$" expression outside quote ``` 在此示例中,元组 `(1,2,3)` 作为表达式插入到条件测试中: ```jldoctest interp1 julia> ex = :(a in $:((1,2,3)) ) :(a in (1, 2, 3)) ``` 在表达式插值中使用 `$` 是有意让人联想到[字符串插值](@ref string-interpolation)和[命令插值](@ref command-interpolation)。表达式插值使得复杂 Julia 表达式的程序化构造变得方便和易读。 ### Splatting 插值 请注意,`$` 插值语法只允许插入单个表达式到包含它的表达式中。有时,你手头有个由表达式组成的数组,需要它们都变成其所处表达式的参数,而这可通过 `$(xs...)` 语法做到。例如,下面的代码生成了一个函数调用,其参数数量通过编程确定: ```jldoctest interp1 julia> args = [:x, :y, :z]; julia> :(f(1, $(args...))) :(f(1, x, y, z)) ``` ### 嵌套引用 自然地,引用表达式可以包含在其它引用表达式中。插值在这些情形中的工作方式可能会有点难以理解。考虑这个例子: ```jldoctest interp1 julia> x = :(1 + 2); julia> e = quote quote $x end end quote #= none:1 =# $(Expr(:quote, quote #= none:1 =# $(Expr(:$, :x)) end)) end ``` Notice that the result contains `$x`, which means that `x` has not been evaluated yet. In other words, the `$` expression "belongs to" the inner quote expression, and so its argument is only evaluated when the inner quote expression is: ```jldoctest interp1 julia> eval(e) quote #= none:1 =# 1 + 2 end ``` 但是,外部 `quote` 表达式可以把值插入到内部引用表达式的 `$` 中去。这通过多个 `$` 实现: ```jldoctest interp1 julia> e = quote quote $$x end end quote #= none:1 =# $(Expr(:quote, quote #= none:1 =# $(Expr(:$, :(1 + 2))) end)) end ``` Notice that `(1 + 2)` now appears in the result instead of the symbol `x`. Evaluating this expression yields an interpolated `3`: ```jldoctest interp1 julia> eval(e) quote #= none:1 =# 3 end ``` 这种行为背后的直觉是每个 `$` 都将 `x` 求值一遍:一个 `$` 工作方式类似于 `eval(:x)`,其返回 `x` 的值,而两个 `$` 行为相当于 `eval(eval(:x))`。 ### [QuoteNode](@id man-quote-node) `quote` 形式在 AST 中通常表示为一个 head 为 `:quote` 的 [`Expr`](@ref) : ```jldoctest interp1 julia> dump(Meta.parse(":(1+2)")) Expr head: Symbol quote args: Array{Any}((1,)) 1: Expr head: Symbol call args: Array{Any}((3,)) 1: Symbol + 2: Int64 1 3: Int64 2 ``` 正如我们所看到的,这些表达式支持插值符号 `$`。但是,在某些情况下,需要在*不执行*插值的情况下引用代码。 这种引用还没有语法,但在内部表示为 `QuoteNode` 类型的对象: ```jldoctest interp1 julia> eval(Meta.quot(Expr(:$, :(1+2)))) 3 julia> eval(QuoteNode(Expr(:$, :(1+2)))) :($(Expr(:$, :(1 + 2)))) ``` 解析器为简单的引用项(如符号)生成 `QuoteNode`: ```jldoctest interp1 julia> dump(Meta.parse(":x")) QuoteNode value: Symbol x ``` `QuoteNode` 也可用于某些高级的元编程任务。 ### 表达式求值 给定一个表达式对象,可以使用 [`eval`](@ref) 使 Julia 在全局作用域内评估(执行)它: ```jldoctest interp1 julia> ex1 = :(1 + 2) :(1 + 2) julia> eval(ex1) 3 julia> ex = :(a + b) :(a + b) julia> eval(ex) ERROR: UndefVarError: b not defined [...] julia> a = 1; b = 2; julia> eval(ex) 3 ``` 每个[模块](@ref modules)有自己的 [`eval`](@ref) 函数,该函数在其全局作用域内对表达式求值。传给 [`eval`](@ref) 的表达式不止可以返回值——它们还能具有改变封闭模块的环境状态的副作用: ```jldoctest julia> ex = :(x = 1) :(x = 1) julia> x ERROR: UndefVarError: x not defined julia> eval(ex) 1 julia> x 1 ``` 这里,表达式对象的求值导致一个值被赋值给全局变量 `x`。 由于表达式只是 `Expr` 对象,而其可以通过编程方式构造然后对它求值,因此可以动态地生成任意代码,然后使用 [`eval`](@ref) 运行所生成的代码。这是个简单的例子: ```julia-repl julia> a = 1; julia> ex = Expr(:call, :+, a, :b) :(1 + b) julia> a = 0; b = 2; julia> eval(ex) 3 ``` `a` 的值被用于构造表达式 `ex`,该表达式将函数 `+` 作用于值 1 和变量 `b`。请注意 `a` 和 `b` 使用方式间的重要区别: * *变量* `a` 在表达式构造时的值在表达式中用作立即值。因此,在对表达式求值时,`a` 的值就无关紧要了:表达式中的值已经是 `1`,与 `a` 的值无关。 * 另一方面,因为在表达式构造时用的是符号 `:b`,所以变量 `b` 的值无关紧要——`:b` 只是一个符号,变量 `b` 甚至无需被定义。然而,在表达式求值时,符号 `:b` 的值通过寻找变量 `b` 的值来解析。 ### 关于表达式的函数 如上所述,Julia 能在其内部生成和操作 Julia 代码,这是个非常有用的功能。我们已经见过返回 [`Expr`](@ref) 对象的函数例子:[`parse`](@ref) 函数,它接受字符串形式的 Julia 代码并返回相应的 `Expr`。函数也可以接受一个或多个 `Expr` 对象作为参数,并返回另一个 `Expr`。这是个简单、提神的例子: ```jldoctest julia> function math_expr(op, op1, op2) expr = Expr(:call, op, op1, op2) return expr end math_expr (generic function with 1 method) julia> ex = math_expr(:+, 1, Expr(:call, :*, 4, 5)) :(1 + 4 * 5) julia> eval(ex) 21 ``` 作为另一个例子,这个函数将数值参数加倍,但不处理表达式: ```jldoctest julia> function make_expr2(op, opr1, opr2) opr1f, opr2f = map(x -> isa(x, Number) ? 2*x : x, (opr1, opr2)) retexpr = Expr(:call, op, opr1f, opr2f) return retexpr end make_expr2 (generic function with 1 method) julia> make_expr2(:+, 1, 2) :(2 + 4) julia> ex = make_expr2(:+, 1, Expr(:call, :*, 5, 8)) :(2 + 5 * 8) julia> eval(ex) 42 ``` ## [宏](@id man-macros) 宏提供了一种机制,可以将生成的代码包含在程序的最终主体中。 宏将一组参数映射到返回的 *表达式*,并且生成的表达式被直接编译,而不需要运行时 [`eval`](@ref) 调用。 宏参数可能包括表达式、字面量和符号。 ### 基础 这是一个非常简单的宏: ```jldoctest sayhello julia> macro sayhello() return :( println("Hello, world!") ) end @sayhello (macro with 1 method) ``` 宏在Julia的语法中有一个专门的字符 `@` (at-sign),紧接着是其使用`macro NAME ... end` 形式来声明的唯一的宏名。在这个例子中,编译器会把所有的`@sayhello` 替换成: ```julia :( println("Hello, world!") ) ``` 当 `@sayhello` 在REPL中被输入时,解释器立即执行,因此我们只会看到计算后的结果: ```jldoctest sayhello julia> @sayhello() Hello, world! ``` 现在,考虑一个稍微复杂一点的宏: ```jldoctest sayhello2 julia> macro sayhello(name) return :( println("Hello, ", $name) ) end @sayhello (macro with 1 method) ``` 这个宏接受一个参数`name`。当遇到`@sayhello`时,quoted 表达式会被*展开*并将参数中的值插入到最终的表达式中: ```jldoctest sayhello2 julia> @sayhello("human") Hello, human ``` 我们可以使用函数 [`macroexpand`](@ref) 查看引用的返回表达式(**重要提示:** 这是一个非常有用的调试宏的工具): ```julia-repl sayhello2 julia> ex = macroexpand(Main, :(@sayhello("human")) ) :(Main.println("Hello, ", "human")) julia> typeof(ex) Expr ``` 我们可以看到 `"human"` 字面量已被插入到表达式中了。 还有一个宏 [`@ macroexpand`](@ ref),它可能比 `macroexpand` 函数更方便: ```jldoctest sayhello2 julia> @macroexpand @sayhello "human" :(println("Hello, ", "human")) ``` ### 停:为什么需要宏? 我们已经在上一节中看到了一个函数 `f(::Expr...) -> Expr`。 其实[`macroexpand`](@ref)也是这样一个函数。 那么,为什么会要设计宏呢? 宏是必需的,因为它们在解析代码时执行,因此,宏允许程序员在运行完整程序*之前*生成定制代码的片段。 为了说明差异,请考虑以下示例: ```julia-repl whymacros julia> macro twostep(arg) println("I execute at parse time. The argument is: ", arg) return :(println("I execute at runtime. The argument is: ", $arg)) end @twostep (macro with 1 method) julia> ex = macroexpand(Main, :(@twostep :(1, 2, 3)) ); I execute at parse time. The argument is: :((1, 2, 3)) ``` 第一个 [`println`](@ref) 调用在调用 [`macroexpand`](@ref) 时执行。生成的表达式*只*包含第二个 `println`: ```julia-repl whymacros julia> typeof(ex) Expr julia> ex :(println("I execute at runtime. The argument is: ", $(Expr(:copyast, :($(QuoteNode(:((1, 2, 3))))))))) julia> eval(ex) I execute at runtime. The argument is: (1, 2, 3) ``` ### 宏的调用 宏的通常调用语法如下: ```julia @name expr1 expr2 ... @name(expr1, expr2, ...) ``` 请注意,在宏名称前的标志 `@`,且在第一种形式中参数表达式间没有逗号,而在第二种形式中 `@name` 后没有空格。这两种风格不应混淆。例如,下列语法不同于上述例子;它把元组 `(expr1, expr2, ...)` 作为参数传给宏: ```julia @name (expr1, expr2, ...) ``` 在数组字面量(或推导式)上调用宏的另一种方法是不使用括号直接并列两者。在这种情况下,数组将是唯一的传给宏的表达式。以下语法等价(且与 `@name [a b] * v` 不同): ```julia @name[a b] * v @name([a b]) * v ``` 在这着重强调,宏把它们的参数作为表达式、字面量或符号接收。浏览宏参数的一种方法是在宏的内部调用 [`show`](@ref) 函数: ```jldoctest julia> macro showarg(x) show(x) # ... remainder of macro, returning an expression end @showarg (macro with 1 method) julia> @showarg(a) :a julia> @showarg(1+1) :(1 + 1) julia> @showarg(println("Yo!")) :(println("Yo!")) ``` 除了给定的参数列表,每个宏都会传递名为 `__source__` 和 `__module__` 的额外参数。 参数 `__source__` 提供 `@` 符号在宏调用处的解析器位置的相关信息(以 `LineNumberNode` 对象的形式)。这使得宏能包含更好的错误诊断信息,其通常用于日志记录、字符串解析器宏和文档,比如,用于实现 [`@__LINE__`](@ref)、[`@__FILE__`](@ref) 和 [`@__DIR__`](@ref) 宏。 引用 `__source__.line` 和 `__source__.file` 即可访问位置信息: ```jldoctest julia> macro __LOCATION__(); return QuoteNode(__source__); end @__LOCATION__ (macro with 1 method) julia> dump( @__LOCATION__( )) LineNumberNode line: Int64 2 file: Symbol none ``` 参数 `__module__` 提供宏调用展开处的上下文相关信息(以 `Module` 对象的形式)。这允许宏查找上下文相关的信息,比如现有的绑定,或者将值作为附加参数插入到一个在当前模块中进行自我反射的运行时函数调用中。 ### 构建高级的宏 这是 Julia 的 [`@assert`](@ref) 宏的简化定义: ```jldoctest building julia> macro assert(ex) return :( $ex ? nothing : throw(AssertionError($(string(ex)))) ) end @assert (macro with 1 method) ``` 这个宏可以像这样使用: ```jldoctest building julia> @assert 1 == 1.0 julia> @assert 1 == 0 ERROR: AssertionError: 1 == 0 ``` 宏调用在解析时扩展为其返回结果,并替代已编写的语法。这相当于编写: ```julia 1 == 1.0 ? nothing : throw(AssertionError("1 == 1.0")) 1 == 0 ? nothing : throw(AssertionError("1 == 0")) ``` 也就是说,在第一个调用中,表达式 `:(1 == 1.0)` 拼接到测试条件槽中,而 `string(:(1 == 1.0))` 拼接到断言信息槽中。如此构造的表达式会被放置在发生 `@assert` 宏调用处的语法树。然后在执行时,如果测试表达式的计算结果为真,则返回 [`nothing`](@ref),但如果测试结果为假,则会引发错误,表明声明的表达式为假。请注意,将其编写为函数是不可能的,因为能获取的只有条件的*值*而无法在错误信息中显示计算出它的表达式。 在 Julia Base 中,`@assert` 的实际定义更复杂。它允许用户可选地制定自己的错误信息,而不仅仅是打印断言失败的表达式。与函数一样,具有可变数量的参数( [变参函数](@ref))可在最后一个参数后面用省略号指定: ```jldoctest assert2 julia> macro assert(ex, msgs...) msg_body = isempty(msgs) ? ex : msgs[1] msg = string(msg_body) return :($ex ? nothing : throw(AssertionError($msg))) end @assert (macro with 1 method) ``` 现在`@assert` 有两种操作模式,这取决于它接收到的参数数量!如果只有一个参数,`msgs` 捕获的表达式元组将为空,并且其行为与上面更简单的定义相同。 但是现在如果用户指定了第二个参数,它会打印在消息正文中而不是不相等的表达式中。你可以使用恰当命名的 [`@macroexpand`](@ref) 宏检查宏展开的结果: ```julia-repl assert2 julia> @macroexpand @assert a == b :(if Main.a == Main.b Main.nothing else Main.throw(Main.AssertionError("a == b")) end) julia> @macroexpand @assert a==b "a should equal b!" :(if Main.a == Main.b Main.nothing else Main.throw(Main.AssertionError("a should equal b!")) end) ``` 实际的 `@assert` 宏还处理了另一种情形:我们如果除了打印「a should equal b」外还想打印它们的值?有人也许会天真地尝试在自定义消息中使用字符串插值,例如,`@assert a==b "a ($a) should equal b ($b)!"`,但这不会像上面的宏一样按预期工作。你能想到为什么吗?回想一下[字符串插值](@ref string-interpolation),内插字符串会被重写为 [`string`](@ref) 的调用。比较: ```jldoctest julia> typeof(:("a should equal b")) String julia> typeof(:("a ($a) should equal b ($b)!")) Expr julia> dump(:("a ($a) should equal b ($b)!")) Expr head: Symbol string args: Array{Any}((5,)) 1: String "a (" 2: Symbol a 3: String ") should equal b (" 4: Symbol b 5: String ")!" ``` 所以,现在宏在 `msg_body` 中获得的不是单纯的字符串,其接收了一个完整的表达式,该表达式需进行求值才能按预期显示。这可作为 [`string`](@ref) 调用的参数直接拼接到返回的表达式中;有关完整实现,请参阅 [`error.jl`](https://github.com/JuliaLang/julia/blob/master/base/error.jl)。 `@assert` 宏充分利用拼接被引用的表达式,以便简化对宏内部表达式的操作。 ### 卫生宏 在更复杂的宏中会出现关于[卫生宏](https://en.wikipedia.org/wiki/Hygienic_macro) 的问题。简而言之,宏必须确保在其返回表达式中引入的变量不会意外地与其展开处周围代码中的现有变量相冲突。相反,作为参数传递给宏的表达式通常被*认为*在其周围代码的上下文中进行求值,与现有变量交互并修改之。另一个问题源于这样的事实:宏可以在不同于其定义所处模块的模块中调用。在这种情况下,我们需要确保所有全局变量都被解析到正确的模块中。Julia 比使用文本宏展开的语言(比如 C)具有更大的优势,因为它只需要考虑返回的表达式。所有其它变量(例如上面`@assert` 中的 `msg`)遵循[通常的作用域块规则](@ref scope-of-variables)。 为了演示这些问题,让我们来编写宏 `@time`,其以表达式为参数,记录当前时间,对表达式求值,再次记录当前时间,打印前后的时间差,然后以表达式的值作为其最终值。该宏可能看起来就像这样: ```julia macro time(ex) return quote local t0 = time_ns() local val = $ex local t1 = time_ns() println("elapsed time: ", (t1-t0)/1e9, " seconds") val end end ``` 在这里,我们希望 `t0`、`t1` 和 `val` 成为私有临时变量,并且我们希望 `time_ns` 引用 Julia Base 中的 [`time_ns`](@ref) 函数,而不是任何用户可能拥有的 `time_ns` 变量(同样适用于 `println`)。 想象一下,如果用户表达式 `ex` 还包含对名为 `t0` 的变量的赋值,或者定义了自己的 `time_ns` 变量,可能会出现什么问题。 程序可能会报错,或者进行未知的行为。 Julia 的宏展开器通过以下方式解决了这些问题。 首先,宏结果中的变量分为局部变量或全局变量。 如果变量被赋值(并且不是声明为全局的)、声明为局部、或用作函数参数名称,则该变量被视为局部变量。 否则,它被认为是全局的。 然后将局部变量重命名为唯一的(使用 [`gensym`](@ref) 函数,该函数生成新符号),并在宏定义环境中解析全局变量。 因此,上述两个问题都得到了处理; 宏的局部变量不会与任何用户变量冲突,并且 `time_ns` 和 `println` 将引用 Julia Base 定义。 然而,仍有另外的问题。考虑此宏的以下用法: ```julia module MyModule import Base.@time time_ns() = ... # compute something @time time_ns() end ``` 这里的用户表达式`ex` 是对`time_ns` 的调用,但与宏使用的`time_ns` 函数不同。 它清楚地指向`MyModule.time_ns`。 因此我们必须安排在宏调用环境中解析`ex`中的代码。 这是通过使用 [`esc`](@ref)“转义”表达式来完成的: ```julia macro time(ex) ... local val = $(esc(ex)) ... end ``` 以这种方式封装的表达式会被宏展开器单独保留,并将其简单地逐字粘贴到输出中。因此,它将在宏调用所处环境中解析。 这种转义机制可以在必要时用于「违反」卫生,以便于引入或操作用户变量。例如,以下宏在其调用所处环境中将 `x` 设置为零: ```jldoctest julia> macro zerox() return esc(:(x = 0)) end @zerox (macro with 1 method) julia> function foo() x = 1 @zerox return x # is zero end foo (generic function with 1 method) julia> foo() 0 ``` 应当明智地使用这种变量操作,但它偶尔会很方便。 获得正确的规则也许是个艰巨的挑战。在使用宏之前,你可以去考虑是否函数闭包便已足够。另一个有用的策略是将尽可能多的工作推迟到运行时。例如,许多宏只是将其参数封装为 `QuoteNode` 或类似的 [`Expr`](@ref)。这方面的例子有 `@task body`,它只返回 `schedule(Task(() -> $body))`, 和 `@eval expr`,它只返回 `eval(QuoteNode(expr))`。 为了演示,我们可以将上面的 `@time` 示例重新编写成: ```julia macro time(expr) return :(timeit(() -> $(esc(expr)))) end function timeit(f) t0 = time_ns() val = f() t1 = time_ns() println("elapsed time: ", (t1-t0)/1e9, " seconds") return val end ``` 但是,我们不这样做也是有充分理由的:将 `expr` 封装在新的作用域块(该匿名函数)中也会稍微改变该表达式的含义(其中任何变量的作用域),而我们想要 `@time` 使用时对其封装的代码影响最小。 ### 宏与派发 与 Julia 函数一样,宏也是泛型的。由于多重派发,这意味着宏也能有多个方法定义: ```jldoctest macromethods julia> macro m end @m (macro with 0 methods) julia> macro m(args...) println("$(length(args)) arguments") end @m (macro with 1 method) julia> macro m(x,y) println("Two arguments") end @m (macro with 2 methods) julia> @m "asd" 1 arguments julia> @m 1 2 Two arguments ``` 但是应该记住,宏派发基于传递给宏的 AST 的类型,而不是 AST 在运行时进行求值的类型: ```jldoctest macromethods julia> macro m(::Int) println("An Integer") end @m (macro with 3 methods) julia> @m 2 An Integer julia> x = 2 2 julia> @m x 1 arguments ``` ## 代码生成 当需要大量重复的样板代码时,为了避免冗余,通常以编程方式生成它。在大多数语言中,这需要一个额外的构建步骤以及生成重复代码的独立程序。在 Julia 中,表达式插值和 [`eval`](@ref) 允许在通常的程序执行过程中生成这些代码。例如,考虑下列自定义类型 ```jldoctest mynumber-codegen struct MyNumber x::Float64 end # output ``` 我们想为该类型添加一些方法。在下面的循环中,我们以编程的方式完成此工作: ```jldoctest mynumber-codegen for op = (:sin, :cos, :tan, :log, :exp) eval(quote Base.$op(a::MyNumber) = MyNumber($op(a.x)) end) end # output ``` 现在,我们对自定义类型调用这些函数: ```jldoctest mynumber-codegen julia> x = MyNumber(π) MyNumber(3.141592653589793) julia> sin(x) MyNumber(1.2246467991473532e-16) julia> cos(x) MyNumber(-1.0) ``` 在这种方法中,Julia 充当了自己的[预处理器](https://en.wikipedia.org/wiki/Preprocessor),并且允许从语言内部生成代码。使用 `:` 前缀的引用形式编写上述代码会使其更简洁: ```julia for op = (:sin, :cos, :tan, :log, :exp) eval(:(Base.$op(a::MyNumber) = MyNumber($op(a.x)))) end ``` 不管怎样,这种使用 `eval(quote(...))` 模式生成语言内部的代码很常见,为此,Julia 自带了一个宏来缩写该模式: ```julia for op = (:sin, :cos, :tan, :log, :exp) @eval Base.$op(a::MyNumber) = MyNumber($op(a.x)) end ``` [`@eval`](@ref) 重写此调用,使其与上面的较长版本完全等价。为了生成较长的代码块,可以把一个代码块作为表达式参数传给 [`@eval`](@ref): ```julia @eval begin # multiple lines end ``` ## [非标准字符串字面量](@id meta-non-standard-string-literals) 回想一下在[字符串](@ref non-standard-string-literals)的文档中,以标识符为前缀的字符串字面量被称为非标准字符串字面量,它们可以具有与未加前缀的字符串字面量不同的语义。例如: * `r"^\s*(?:#|$)"` 产生一个[正则表达式对象](@ref man-regex-literals)而不是一个字符串 * `b"DATA\xff\u2200"` 是一个[字节数组字面量](@ref man-byte-array-literals) ,表示`[68,65,84,65,255,226,136,128]`。 可能令人惊讶的是,这些行为并没有被硬编码到 Julia 的解释器或编译器中。相反,它们是由一个通用机制实现的自定义行为,且任何人都可以使用该机制:带前缀的字符串字面量被解析为特定名称的宏的调用。例如,正则表达式宏如下: ```julia macro r_str(p) Regex(p) end ``` 这便是全部代码。这个宏说的是字符串字面量 `r"^\s*(?:#|$)"` 的字面内容应该传给宏 `@r_str`,并且展开后的结果应当放在该字符串字面量出现处的语法树中。换句话说,表达式 `r"^\s*(?:#|$)"` 等价于直接把下列对象放进语法树中: ```julia Regex("^\\s*(?:#|\$)") ``` 字符串字面量形式不仅更短、更方便,也更高效:因为正则表达式需要编译,`Regex` 对象实际上是*在编译代码时*创建的,所以编译只发生一次,而不是每次执行代码时都再编译一次。请考虑如果正则表达式出现在循环中: ```julia for line = lines m = match(r"^\s*(?:#|$)", line) if m === nothing # non-comment else # comment end end ``` 因为正则表达式 `r"^\s*(?:#|$)"` 在这段代码解析时便已编译并被插入到语法树中,所以它只编译一次,而不是每次执行循环时都再编译一次。要在不使用宏的情况下实现此效果,必须像这样编写此循环: ```julia re = Regex("^\\s*(?:#|\$)") for line = lines m = match(re, line) if m === nothing # non-comment else # comment end end ``` 此外,如果编译器无法确定在所有循环中正则表达式对象都是常量,可能无法进行某些优化,使得此版本的效率依旧低于上面的更方便的字面量形式。当然,在某些情况下,非字面量形式更方便:如果需要向正则表达式中插入变量,就必须采用这种更冗长的方法;如果正则表达式模式本身是动态的,可能在每次循环迭代时发生变化,就必须在每次迭代中构造新的正则表达式对象。然而,在绝大多数用例中,正则表达式不是基于运行时的数据构造的。在大多数情况下,将正则表达式编写为编译期值的能力是无法估量的。 用户定义字符串文字的机制非常强大。不仅使用它实现了 Julia 的非标准字面量,而且还使用以下看起来无害的宏实现了命令行字面量语法(``` `echo "Hello, $person"` ```): ```julia macro cmd(str) :(cmd_gen($(shell_parse(str)[1]))) end ``` 当然,这个宏的定义中使用的函数隐藏了许多复杂性,但它们只是函数且完全用 Julia 编写。你可以阅读它们的源代码并精确地看到它们的行为——它们所做的一切就是构造要插入到你的程序的语法树的表达式对象。 与字符串字面量一样,命令行字面量也可以以标识符为前缀,以形成所谓的非标准命令行字面量。 这些命令行字面量被解析为对特殊命名的宏的调用。 例如,语法 ```custom`literal` ``` 被解析为 `@custom_cmd "literal"`。 Julia 本身不包含任何非标准的命令行字面量,但包可以使用这种语法。 除了不同的语法和 `_cmd` 后缀而不是 `_str` 后缀,非标准命令行字面量的行为与非标准字符串字面量完全一样。 如果两个模块提供了同名的非标准字符串或命令字面量,能使用模块名限定该字符串或命令字面量。例如,如果 `Foo` 和 `Bar` 提供了相同的字符串字面量 `@x_str`,那么可以编写 `Foo.x"literal"` 或 `Bar.x"literal"` 来消除两者的歧义。 以下是另一种定义宏的方式: ```julia macro foo_str(str, flag) # do stuff end ``` 可以使用如下语法来调用这个宏 ```julia foo"str"flag ``` 上述语法中 flag 的类型可以是一个`String`,在字符串字面量之后包含的内容。 ## 生成函数 有个非常特殊的宏叫 [`@generated`](@ref),它允许你定义所谓的*生成函数*。它们能根据其参数类型生成专用代码,与用多重派发所能实现的代码相比,其代码更灵活和/或少。虽然宏在解析时使用表达式且无法访问其输入值的类型,但是生成函数在参数类型已知时会被展开,但该函数尚未编译。 生成函数的声明不会执行某些计算或操作,而会返回一个被引用的表达式,接着该表达式构成参数类型所对应方法的主体。在调用生成函数时,其返回的表达式会被编译然后执行。为了提高效率,通常会缓存结果。为了能推断是否缓存结果,只能使用语言的受限子集。因此,生成函数提供了一个灵活的方式来将工作重运行时移到编译时,代价则是其构造能力受到更大的限制。 定义生成函数与普通函数有五个主要区别: 1. 使用 `@generated` 标注函数声明。这会向 AST 附加一些信息,让编译器知道这个函数是生成函数。 2. 在生成函数的主体中,你只能访问参数的*类型*,而不能访问其值,以及在生成函数的定义之前便已定义的任何函数。 3. 不应计算某些东西或执行某些操作,应返回一个*被引用的*表达式,它会在被求值时执行你想要的操作。 4. 生成函数只允许调用在生成函数定义之前定义的函数。(如果不遵循这一点,引用来自未来世界的函数可能会导致 `MethodErrors` ) 5. 生成函数不能*更改*或*观察*任何非常量的全局状态。(例如,其包括 IO、锁、非局部的字典或者使用 `hasmethod`)即它们只能读取全局常量,且没有任何副作用。换句话说,它们必须是纯函数。由于实现限制,这也意味着它们目前无法定义闭包或生成器。 举例子来说明这个是最简单的。我们可以将生成函数 `foo` 声明为 ```jldoctest generated julia> @generated function foo(x) Core.println(x) return :(x * x) end foo (generic function with 1 method) ``` 请注意,代码主体返回一个被引用的表达式,即 `:(x * x)`,而不仅仅是 `x * x` 的值。 从调用者的角度看,这与通常的函数等价;实际上,你无需知道你所调用的是通常的函数还是生成函数。让我们看看 `foo` 的行为: ```jldoctest generated julia> x = foo(2); # note: output is from println() statement in the body Int64 julia> x # now we print x 4 julia> y = foo("bar"); String julia> y "barbar" ``` 因此,我们知道在生成函数的主体中,`x` 是所传递参数的*类型*,并且,生成函数的返回值是其定义所返回的被引用的表达式的求值结果,在该表达式求值时 `x` 表示其*值*。 如果我们使用我们已经使用过的类型再次对 `foo` 求值会发生什么? ```jldoctest generated julia> foo(4) 16 ``` 请注意,这里并没有打印 [`Int64`](@ref)。我们可以看到对于特定的参数类型集来说,生成函数的主体只执行一次,且结果会被缓存。此后,对于此示例,生成函数首次调用返回的表达式被重新用作方法主体。但是,实际的缓存行为是由实现定义的性能优化,过于依赖此行为并不实际。 生成函数*可能*只生成一次函数,但也*可能*多次生成,或者看起来根本就没有生成过函数。因此,你应该*从不*编写有副作用的生成函数——因为副作用发生的时间和频率是不确定的。(对于宏来说也是如此——跟宏一样,在生成函数中使用 [`eval`](@ref) 也许意味着你正以错误的方式做某事。)但是,与宏不同,运行时系统无法正确处理对 [`eval`](@ref) 的调用,所以不允许这样做。 理解 `@generated` 函数与方法的重定义间如何相互作用也很重要。遵循正确的 `@generated` 函数不能观察任何可变状态或导致全局状态的任何更改的原则,我们看到以下行为。观察到,生成函数*不能*调用在生成函数本身的*定义*之前未定义的任何方法。 一开始 `f(x)` 有一个定义 ```jldoctest redefinition julia> f(x) = "original definition"; ``` 定义使用 `f(x)` 的其它操作: ```jldoctest redefinition julia> g(x) = f(x); julia> @generated gen1(x) = f(x); julia> @generated gen2(x) = :(f(x)); ``` 我们现在为 `f(x)` 添加几个新定义: ```jldoctest redefinition julia> f(x::Int) = "definition for Int"; julia> f(x::Type{Int}) = "definition for Type{Int}"; ``` 并比较这些结果的差异: ```jldoctest redefinition julia> f(1) "definition for Int" julia> g(1) "definition for Int" julia> gen1(1) "original definition" julia> gen2(1) "definition for Int" ``` 生成函数的每个方法都有自己的已定义函数视图: ```jldoctest redefinition julia> @generated gen1(x::Real) = f(x); julia> gen1(1) "definition for Type{Int}" ``` 上例中的生成函数 `foo` 能做的,通常的函数 `foo(x) = x * x` 也能做(除了在第一次调用时打印类型,并产生了更高的开销)。但是,生成函数的强大之处在于其能够根据传递给它的类型计算不同的被引用的表达式: ```jldoctest 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" ``` (当然,这个刻意的例子可以更简单地通过多重派发实现······) 滥用它会破坏运行时系统并导致未定义行为: ```jldoctest julia> @generated function baz(x) if rand() < .9 return :(x^2) else return :("boo!") end end baz (generic function with 1 method) ``` 由于生成函数的主体具有不确定性,其行为和*所有后续代码的行为*并未定义。 *不要复制这些例子!* 这些例子有助于说明生成函数定义和调用的工作方式;但是,*不要复制它们*,原因如下: * `foo` 函数有副作用(对 `Core.println` 的调用),并且未确切定义这些副作用发生的时间、频率和次数。 * `bar` 函数解决的问题可通过多重派发被更好地解决——定义 `bar(x) = x` 和 `bar(x::Integer) = x ^ 2` 会做同样的事,但它更简单和快捷。 * `baz` 函数是病态的 请注意,不应在生成函数中尝试的操作并无严格限制,且运行时系统现在只能检测一部分无效操作。还有许多操作只会破坏运行时系统而没有通知,通常以微妙的方式而非显然地与错误的定义相关联。因为函数生成器是在类型推导期间运行的,所以它必须遵守该代码的所有限制。 一些不应该尝试的操作包括: 1. 缓存本地指针。 2. 以任何方式与 `Core.Compiler` 的内容或方法交互。 3. 观察任何可变状态。 * 生成函数的类型推导可以在*任何*时候运行,包括你的代码正在尝试观察或更改此状态时。 4. 采用任何锁:你调用的 C 代码可以在内部使用锁(例如,调用 `malloc` 不会有问题,即使大多数实现在内部需要锁),但是不要试图在执行 Julia 代码时保持或请求任何锁。 5. 调用在生成函数的主体后定义的任何函数。对于增量加载的预编译模块,则放宽此条件,以允许调用模块中的任何函数。 那好,我们现在已经更好地理解了生成函数的工作方式,让我们使用它来构建一些更高级(和有效)的功能…… ### 一个高级的例子 Julia 的 base 库有个内部函数 `sub2ind`,用于根据一组 n 重线性索引计算 n 维数组的线性索引——换句话说,用于计算索引 `i`,其可用于使用 `A[i]` 来索引数组 `A`,而不是用 `A[x,y,z,...]`。一种可能的实现如下: ```jldoctest sub2ind julia> function sub2ind_loop(dims::NTuple{N}, I::Integer...) where N ind = I[N] - 1 for i = N-1:-1:1 ind = I[i]-1 + dims[i]*ind end return ind + 1 end sub2ind_loop (generic function with 1 method) julia> sub2ind_loop((3, 5), 1, 2) 4 ``` 用递归可以完成同样的事情: ```jldoctest julia> sub2ind_rec(dims::Tuple{}) = 1; julia> sub2ind_rec(dims::Tuple{}, i1::Integer, I::Integer...) = i1 == 1 ? sub2ind_rec(dims, I...) : throw(BoundsError()); julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer) = i1; julia> sub2ind_rec(dims::Tuple{Integer, Vararg{Integer}}, i1::Integer, I::Integer...) = i1 + dims[1] * (sub2ind_rec(Base.tail(dims), I...) - 1); julia> sub2ind_rec((3, 5), 1, 2) 4 ``` 这两种实现虽然不同,但本质上做同样的事情:在数组维度上的运行时循环,将每个维度上的偏移量收集到最后的索引中。 然而,循环所需的信息都已嵌入到参数的类型信息中。因此,我们可以利用生成函数将迭代移动到编译期;用编译器的说法,我们用生成函数手动展开循环。代码主体变得几乎相同,但我们不是计算线性索引,而是建立计算索引的*表达式*: ```jldoctest sub2ind_gen julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N ex = :(I[$N] - 1) for i = (N - 1):-1:1 ex = :(I[$i] - 1 + dims[$i] * $ex) end return :($ex + 1) end sub2ind_gen (generic function with 1 method) julia> sub2ind_gen((3, 5), 1, 2) 4 ``` **这会生成什么代码?** 找出所生成代码的一个简单方法是将生成函数的主体提取到另一个(通常的)函数中: ```jldoctest sub2ind_gen2 julia> @generated function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N return sub2ind_gen_impl(dims, I...) end sub2ind_gen (generic function with 1 method) julia> function sub2ind_gen_impl(dims::Type{T}, I...) where T <: NTuple{N,Any} where N length(I) == N || return :(error("partial indexing is unsupported")) ex = :(I[$N] - 1) for i = (N - 1):-1:1 ex = :(I[$i] - 1 + dims[$i] * $ex) end return :($ex + 1) end sub2ind_gen_impl (generic function with 1 method) ``` 我们现在可以执行 `sub2ind_gen_impl` 并检查它所返回的表达式: ```jldoctest sub2ind_gen2 julia> sub2ind_gen_impl(Tuple{Int,Int}, Int, Int) :(((I[1] - 1) + dims[1] * (I[2] - 1)) + 1) ``` 因此,这里使用的方法主体根本不包含循环——只有两个元组的索引、乘法和加法/减法。所有循环都是在编译期执行的,我们完全避免了在执行期间的循环。因此,我们只需对每个类型循环*一次*,在本例中每个 `N` 循环一次(除了在该函数被多次生成的边缘情况——请参阅上面的免责声明)。 ### 可选地生成函数 生成函数可以在运行时实现高效率,但需要编译时间成本:必须为具体的参数类型的每个组合生成新的函数体。通常,Julia 能够编译函数的「泛型」版本,其适用于任何参数,但对于生成函数,这是不可能的。这意味着大量使用生成函数的程序可能无法静态编译。 为了解决这个问题,语言提供用于编写生成函数的通常、非生成的替代实现的语法。应用于上面的 `sub2ind` 示例,它看起来像这样: ```julia function sub2ind_gen(dims::NTuple{N}, I::Integer...) where N if N != length(I) throw(ArgumentError("Number of dimensions must match number of indices.")) end if @generated ex = :(I[$N] - 1) for i = (N - 1):-1:1 ex = :(I[$i] - 1 + dims[$i] * $ex) end return :($ex + 1) else ind = I[N] - 1 for i = (N - 1):-1:1 ind = I[i] - 1 + dims[i]*ind end return ind + 1 end end ``` 在内部,这段代码创建了函数的两个实现:一个生成函数的实现,其使用 `if @generated` 中的第一个块,一个通常的函数的实现,其使用 `else` 块。在 `if @generated` 块的 `then` 部分中,代码与其它生成函数具有相同的语义:参数名称引用类型,且代码应返回表达式。可能会出现多个 `if @generated` 块,在这种情况下,生成函数的实现使用所有的 `then` 块,而替代实现使用所有的 `else` 块。 请注意,我们在函数顶部添加了错误检查。此代码对两个版本都是通用的,且是两个版本中的运行时代码(它将被引用并返回为生成函数版本中的表达式)。这意味着局部变量的值和类型在代码生成时不可用——用于代码生成的代码只能看到参数类型。 在这种定义方式中,代码生成功能本质上只是一种可选的优化。如果方便,编译器将使用它,否则可能选择使用通常的实现。这种方式是首选的,因为它允许编译器做出更多决策和以更多方式编译程序,还因为通常代码比由代码生成的代码更易读。但是,使用哪种实现取决于编译器实现细节,因此,两个实现的行为必须相同。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
23643
# 方法 我们回想一下,在[函数](@ref man-functions)中我们知道函数是这么一个对象,它把一组参数映射成一个返回值,或者当没有办法返回恰当的值时扔出一个异常。具有相同概念的函数或者运算,经常会根据参数类型的不同而进行有很大差异的实现:两个整数的加法与两个浮点数的加法是相当不一样的,整数与浮点数之间的加法也不一样。除了它们实现上的不同,这些运算都归在"加法"这么一个广义的概念之下,因此在 Julia 中这些行为都属于同一个对象:`+` 函数。 为了让对同样的概念使用许多不同的实现这件事更顺畅,函数没有必要马上全部都被定义,反而应该是一块一块地定义,为特定的参数类型和数量的组合提供指定的行为。对于一个函数的一个可能行为的定义叫做*方法*。直到这里,我们只展示了那些只定了一个方法的,对参数的所有类型都适用的函数。但是方法定义的特征是不仅能表明参数的数量,也能表明参数的类型,并且能提供多个方法定义。当一个函数被应用于特殊的一组参数时,能用于这一组参数的最特定的方法会被使用。所以,函数的全体行为是他的不同的方法定义的行为的组合。如果这个组合被设计得好,即使方法们的实现之间会很不一样,函数的外部行为也会显得无缝而自洽。 当一个函数被应用时执行方法的选择被称为 **分派**。Julia 允许分派过程基于给定的参数个数和所有参数的类型来选择调用函数的哪个方法。这与传统的面对对象的语言不一样,面对对象语言的分派只基于第一参数,经常有特殊的参数语法,并且有时是暗含而非显式写成一个参数。 [^1] 使用函数的所有参数,而非只用第一个,来决定调用哪个方法被称为[多重分派](https://en.wikipedia.org/wiki/Multiple_dispatch)。多重分派对于数学代码来说特别有用,人工地将运算视为对于其中一个参数的属于程度比其他所有的参数都强的这个概念对于数学代码是几乎没有意义的:`x + y` 中的加法运算对 `x` 的属于程度比对 `y` 更强?一个数学运算符的实现普遍基于它所有的参数的类型。即使跳出数学运算,多重分派是对于结构和组织程序来说也是一个强大而方便的范式。 [^1]: In C++ or Java, for example, in a method call like `obj.meth(arg1,arg2)`, the object obj "receives" the method call and is implicitly passed to the method via the `this` keyword, rather than as an explicit method argument. When the current `this` object is the receiver of a method call, it can be omitted altogether, writing just `meth(arg1,arg2)`, with `this` implied as the receiving object. !!! note 本章中的所有示例都假定是为*相同*模块中的函数定义模块。 如果你想给*另一个*模块中的函数添加方法,你必须`import`它或使用模块名称限定的名称。 请参阅有关 [命名空间管理](@ref namespace-management) 的部分。 ## 定义方法 直到这里,在我们的例子中,我们定义的函数只有一个不限制参数类型的方法。这种函数的行为就与传统动态类型语言中的函数一样。不过,我们已经在没有意识到的情况下已经使用了多重分派和方法:所有 Julia 标准函数和运算符,就像之前提到的 `+` 函数,都根据参数的类型和数量的不同组合而定义了大量方法。 当定义一个函数时,可以根据需要使用在[复合类型](@ref)中介绍的 `::` 类型断言运算符来限制参数类型, ```jldoctest fofxy julia> f(x::Float64, y::Float64) = 2x + y f (generic function with 1 method) ``` 这个函数只在 `x` 和 `y` 的类型都是 [`Float64`](@ref) 的情况下才会被调用: ```jldoctest fofxy julia> f(2.0, 3.0) 7.0 ``` 用其它任意的参数类型则会导致 [`MethodError`](@ref): ```jldoctest fofxy julia> f(2.0, 3) ERROR: MethodError: no method matching f(::Float64, ::Int64) Closest candidates are: f(::Float64, !Matched::Float64) at none:1 julia> f(Float32(2.0), 3.0) ERROR: MethodError: no method matching f(::Float32, ::Float64) Closest candidates are: f(!Matched::Float64, ::Float64) at none:1 julia> f(2.0, "3.0") ERROR: MethodError: no method matching f(::Float64, ::String) Closest candidates are: f(::Float64, !Matched::Float64) at none:1 julia> f("2.0", "3.0") ERROR: MethodError: no method matching f(::String, ::String) ``` 如同你所看到的,参数必须精确地是 [`Float64`](@ref) 类型。其它数字类型,比如整数或者 32 位浮点数值,都不会自动转化成 64 位浮点数,字符串也不会解析成数字。由于 `Float64` 是一个具体类型,且在 Julia 中具体类型无法拥有子类,所以这种定义方式只能适用于函数的输入类型精确地是 `Float64` 的情况,但一个常见的做法是用抽象类型来定义通用的方法: ```jldoctest fofxy julia> f(x::Number, y::Number) = 2x - y f (generic function with 2 methods) julia> f(2.0, 3) 1.0 ``` 用上面这种方式定义的方法可以接收任意一对 [`Number`](@ref) 的实例参数,且它们不需要是同一类型的,只要求都是数值。如何根据不同的类型来做相应的处理就可以委托给表达式 `2x - y` 中的代数运算。 为了定义一个有多个方法的函数,只需简单定义这个函数多次,使用不同的参数数量和类型。函数的第一个方法定义会建立这个函数对象,后续的方法定义会添加新的方法到存在的函数对象中去。当函数被应用时,最符合参数的数量和类型的特定方法会被执行。所以,上面的两个方法定义在一起定义了函数`f`对于所有的一对虚拟类型`Number`实例的行为 -- 但是针对一对[`Float64`](@ref)值有不同的行为。如果一个参数是64位浮点数而另一个不是,`f(Float64,Float64)`方法不会被调用,而一定使用更加通用的`f(Number,Number)`方法: ```jldoctest fofxy julia> f(2.0, 3.0) 7.0 julia> f(2, 3.0) 1.0 julia> f(2.0, 3) 1.0 julia> f(2, 3) 1 ``` `2x + y` 定义只用于第一个情况,`2x - y` 定义用于其他的情况。没有使用任何自动的函数参数的指派或者类型转换:Julia中的所有转换都不是 magic 的,都是完全显式的。然而[类型转换和类型提升](@ref conversion-and-promotion)显示了足够先进的技术的智能应用能够与 magic 不可分辨到什么程度。[^Clarke61] 对于非数字值,和比两个参数更多或者更少的情况,函数 `f` 并没有定义,应用会导致 [`MethodError`](@ref): ```jldoctest fofxy julia> f("foo", 3) ERROR: MethodError: no method matching f(::String, ::Int64) Closest candidates are: f(!Matched::Number, ::Number) at none:1 julia> f() ERROR: MethodError: no method matching f() Closest candidates are: f(!Matched::Float64, !Matched::Float64) at none:1 f(!Matched::Number, !Matched::Number) at none:1 ``` 可以简单地看到对于函数存在哪些方法,通过在交互式会话中键入函数对象本身: ```jldoctest fofxy julia> f f (generic function with 2 methods) ``` 这个输出展示了`f`有两个方法。为了找到这些方法的前面,使用[`methods`](@ref)函数: ```jldoctest fofxy julia> methods(f) # 2 methods for generic function "f": [1] f(x::Float64, y::Float64) in Main at none:1 [2] f(x::Number, y::Number) in Main at none:1 ``` 这表示`f`有两个方法,一个接受两个`Float64`参数一个接受两个`Number`类型的参数。它也显示了这些方法定义所在的文件和行数:因为这些方法是在REPL中定义的,我们得到了表面上的行数`none:1`. 没有`::`的类型声明,方法参数的类型默认为`Any`,这就意味着没有约束,因为Julia中的所有的值都是抽象类型`Any`的实例。所以,我们可以为`f`定义一个接受所有的方法,像这样: ```jldoctest fofxy julia> f(x,y) = println("Whoa there, Nelly.") f (generic function with 3 methods) julia> methods(f) # 3 methods for generic function "f": [1] f(x::Float64, y::Float64) in Main at none:1 [2] f(x::Number, y::Number) in Main at none:1 [3] f(x, y) in Main at none:1 julia> f("foo", 1) Whoa there, Nelly. ``` 这个接受所有参数类型的方法比其他的对一对参数值的其他任意可能的方法定义更不专用。所以他只会被没有其他方法定义应用的一对参数调用。 注意到第三个方法的签名中并没有指定参数`x`和`y`的类型。它是`f(x::Any, y::Any)`的简写。 尽管这看起来很简单,但对值类型的多重派发可能是 Julia 语言最强大和最核心的特性。 核心运算通常有几十种方法: ```julia-repl julia> methods(+) # 180 methods for generic function "+": [1] +(x::Bool, z::Complex{Bool}) in Base at complex.jl:227 [2] +(x::Bool, y::Bool) in Base at bool.jl:89 [3] +(x::Bool) in Base at bool.jl:86 [4] +(x::Bool, y::T) where T<:AbstractFloat in Base at bool.jl:96 [5] +(x::Bool, z::Complex) in Base at complex.jl:234 [6] +(a::Float16, b::Float16) in Base at float.jl:373 [7] +(x::Float32, y::Float32) in Base at float.jl:375 [8] +(x::Float64, y::Float64) in Base at float.jl:376 [9] +(z::Complex{Bool}, x::Bool) in Base at complex.jl:228 [10] +(z::Complex{Bool}, x::Real) in Base at complex.jl:242 [11] +(x::Char, y::Integer) in Base at char.jl:40 [12] +(c::BigInt, x::BigFloat) in Base.MPFR at mpfr.jl:307 [13] +(a::BigInt, b::BigInt, c::BigInt, d::BigInt, e::BigInt) in Base.GMP at gmp.jl:392 [14] +(a::BigInt, b::BigInt, c::BigInt, d::BigInt) in Base.GMP at gmp.jl:391 [15] +(a::BigInt, b::BigInt, c::BigInt) in Base.GMP at gmp.jl:390 [16] +(x::BigInt, y::BigInt) in Base.GMP at gmp.jl:361 [17] +(x::BigInt, c::Union{UInt16, UInt32, UInt64, UInt8}) in Base.GMP at gmp.jl:398 ... [180] +(a, b, c, xs...) in Base at operators.jl:424 ``` 多重分派和灵活的参数类型系统让Julia有能力抽象地表达高层级算法,而与实现细节解耦,也能生成高效而专用的代码来在运行中处理每个情况。 ## [方法歧义](@id man-ambiguities) 在一系列的函数方法定义时有可能没有单独的最专用的方法能适用于参数的某些组合: ```jldoctest gofxy julia> g(x::Float64, y) = 2x + y g (generic function with 1 method) julia> g(x, y::Float64) = x + 2y g (generic function with 2 methods) julia> g(2.0, 3) 7.0 julia> g(2, 3.0) 8.0 julia> g(2.0, 3.0) ERROR: MethodError: g(::Float64, ::Float64) is ambiguous. Candidates: g(x::Float64, y) in Main at none:1 g(x, y::Float64) in Main at none:1 Possible fix, define g(::Float64, ::Float64) ``` 这里`g(2.0,3.0)`的调用使用`g(Float64, Any)`和`g(Any, Float64)`都能处理,并且两个都不更加专用。在这样的情况下,Julia会扔出[`MethodError`](@ref)而非任意选择一个方法。你可以通过对交叉情况指定一个合适的方法来避免方法歧义: ```jldoctest gofxy julia> g(x::Float64, y::Float64) = 2x + 2y g (generic function with 3 methods) julia> g(2.0, 3) 7.0 julia> g(2, 3.0) 8.0 julia> g(2.0, 3.0) 10.0 ``` 建议先定义没有歧义的方法,因为不这样的话,歧义就会存在,即使是暂时性的,直到更加专用的方法被定义。 在更加复杂的情况下,解决方法歧义会会涉及到设计的某一个元素;这个主题将会在[下面](@ref man-method-design-ambiguities)进行进一步的探索。 ## 参数方法 方法定义可以视需要存在限定特征的类型参数: ```jldoctest same_typefunc julia> same_type(x::T, y::T) where {T} = true same_type (generic function with 1 method) julia> same_type(x,y) = false same_type (generic function with 2 methods) ``` 第一个方法应用于两个参数都是同一个具体类型时,不管类型是什么,而第二个方法接受一切,涉及其他所有情况。所以,总得来说,这个定义了一个布尔函数来检查两个参数是否是同样的类型: ```jldoctest same_typefunc julia> same_type(1, 2) true julia> same_type(1, 2.0) false julia> same_type(1.0, 2.0) true julia> same_type("foo", 2.0) false julia> same_type("foo", "bar") true julia> same_type(Int32(1), Int64(2)) false ``` 这样的定义对应着那些类型签名是 `UnionAll` 类型的方法(参见 [UnionAll 类型](@ref))。 在Julia中这种通过分派进行函数行为的定义是十分常见的,甚至是惯用的。方法类型参数并不局限于用作参数的类型:他们可以用在任意地方,只要值会在函数或者函数体的特征中。这里有个例子,例子中方法类型参数`T`用作方法特征中的参数类型`Vector{T}`的类型参数: ```jldoctest julia> myappend(v::Vector{T}, x::T) where {T} = [v..., x] myappend (generic function with 1 method) julia> myappend([1,2,3],4) 4-element Vector{Int64}: 1 2 3 4 julia> myappend([1,2,3],2.5) ERROR: MethodError: no method matching myappend(::Vector{Int64}, ::Float64) Closest candidates are: myappend(::Vector{T}, !Matched::T) where T at none:1 Stacktrace: [...] julia> myappend([1.0,2.0,3.0],4.0) 4-element Vector{Float64}: 1.0 2.0 3.0 4.0 julia> myappend([1.0,2.0,3.0],4) ERROR: MethodError: no method matching myappend(::Vector{Float64}, ::Int64) Closest candidates are: myappend(::Vector{T}, !Matched::T) where T at none:1 Stacktrace: [...] ``` 如你所看到的,追加的元素的类型必须匹配它追加到的向量的元素类型,否则会引起[`MethodError`](@ref)。在下面的例子中,方法类型参量`T`用作返回值: ```jldoctest julia> mytypeof(x::T) where {T} = T mytypeof (generic function with 1 method) julia> mytypeof(1) Int64 julia> mytypeof(1.0) Float64 ``` 就像你能在类型声明时通过类型参数对子类型进行约束一样(参见[参数类型](@ref)),你也可以约束方法的类型参数: ```jldoctest julia> same_type_numeric(x::T, y::T) where {T<:Number} = true same_type_numeric (generic function with 1 method) julia> same_type_numeric(x::Number, y::Number) = false same_type_numeric (generic function with 2 methods) julia> same_type_numeric(1, 2) true julia> same_type_numeric(1, 2.0) false julia> same_type_numeric(1.0, 2.0) true julia> same_type_numeric("foo", 2.0) ERROR: MethodError: no method matching same_type_numeric(::String, ::Float64) Closest candidates are: same_type_numeric(!Matched::T, ::T) where T<:Number at none:1 same_type_numeric(!Matched::Number, ::Number) at none:1 julia> same_type_numeric("foo", "bar") ERROR: MethodError: no method matching same_type_numeric(::String, ::String) julia> same_type_numeric(Int32(1), Int64(2)) false ``` `same_type_numeric`函数的行为与上面定义的`same_type`函数基本相似,但是它只对一对数定义。 参数方法允许与 `where` 表达式同样的语法用来写类型(参见 [UnionAll 类型](@ref))。如果只有一个参数,封闭的大括号(在 `where {T}` 中)可以省略,但是为了清楚起见推荐写上。多个参数可以使用逗号隔开,例如 `where {T, S <: Real}`,或者使用嵌套的 `where` 来写,例如 `where S<:Real where T`。 重定义方法 ------------------ 当重定义一个方法或者增加一个方法时,知道这个变化不会立即生效很重要。这是Julia能够静态推断和编译代码使其运行很快而没有惯常的JIT技巧和额外开销的关键。实际上,任意新的方法定义不会对当前运行环境可见,包括Tasks和线程(和所有的之前定义的`@generated`函数)。让我们通过一个例子说明这意味着什么: ```julia-repl julia> function tryeval() @eval newfun() = 1 newfun() end tryeval (generic function with 1 method) julia> tryeval() ERROR: MethodError: no method matching newfun() The applicable method may be too new: running in world age xxxx1, while current world is xxxx2. Closest candidates are: newfun() at none:1 (method too new to be called from this world context.) in tryeval() at none:1 ... julia> newfun() 1 ``` 在这个例子中看到`newfun`的新定义已经被创建,但是并不能立即调用。新的全局变量立即对`tryeval`函数可见,所以你可以写`return newfun`(没有小括号)。但是你,你的调用器,和他们调用的函数等等都不能调用这个新的方法定义! 但是这里有个例外:之后的*在 REPL 中*的 `newfun` 的调用会按照预期工作,能够见到并调用`newfun` 的新定义。 但是,之后的 `tryeval` 的调用将会继续看到 `newfun` 的定义,因为该定义*位于 REPL 的前一个语句中*并因此在之后的 `tryeval` 的调用之前。 你可以试试这个来让自己了解这是如何工作的。 这个行为的实现通过一个「world age 计数器」。这个单调递增的值会跟踪每个方法定义操作。此计数器允许用单个数字描述「对于给定运行时环境可见的方法定义集」,或者说「world age」。它还允许仅仅通过其序数值来比较在两个 world 中可用的方法。在上例中,我们看到(方法 `newfun` 所存在的)「current world」比局部于任务的「runtime world」大一,后者在 `tryeval` 开始执行时是固定的。 有时规避这个是必要的(例如,如果你在实现上面的REPL)。幸运的是这里有个简单地解决方法:使用[`Base.invokelatest`](@ref)调用函数: ```jldoctest julia> function tryeval2() @eval newfun2() = 2 Base.invokelatest(newfun2) end tryeval2 (generic function with 1 method) julia> tryeval2() 2 ``` 最后,让我们看一些这个规则生效的更复杂的例子。 定义一个函数`f(x)`,最开始有一个方法: ```jldoctest redefinemethod julia> f(x) = "original definition" f (generic function with 1 method) ``` 开始一些使用`f(x)`的运算: ```jldoctest redefinemethod julia> g(x) = f(x) g (generic function with 1 method) julia> t = @async f(wait()); yield(); ``` 现在我们给`f(x)`加上一些新的方法: ```jldoctest redefinemethod julia> f(x::Int) = "definition for Int" f (generic function with 2 methods) julia> f(x::Type{Int}) = "definition for Type{Int}" f (generic function with 3 methods) ``` 比较一下这些结果如何不同: ```jldoctest redefinemethod julia> f(1) "definition for Int" julia> g(1) "definition for Int" julia> fetch(schedule(t, 1)) "original definition" julia> t = @async f(wait()); yield(); julia> fetch(schedule(t, 1)) "definition for Int" ``` ## 使用参数方法设计样式 虽然复杂的分派逻辑对于性能或者可用性并不是必须的,但是有时这是表达某些算法的最好的方法。 这里有一些常见的设计样式,在以这个方法使用分派时有时会出现。 ### 从超类型中提取出类型参数 以下是一个正确的代码模板,用于返回具有明确定义的元素类型的 `AbstractArray` 的任意子类型的元素类型 `T`: ```julia abstract type AbstractArray{T, N} end eltype(::Type{<:AbstractArray{T}}) where {T} = T ``` 使用所谓的三角派发。 请注意,`UnionAll` 类型,对于示例`eltype(AbstractArray{T} where T <: Integer)`,与上述方法不符。 在这种情况下,`Base` 中 `eltype` 的实现为 `Any` 增加了一个回退方法。 一个常见的错误是试着使用内省来得到元素类型: ```julia eltype_wrong(::Type{A}) where {A<:AbstractArray} = A.parameters[1] ``` 但是创建一个这个方法会失败的情况不难: ```julia struct BitVector <: AbstractArray{Bool, 1}; end ``` 这里我们已经创建了一个没有参数的类型`BitVector`,但是元素类型已经完全指定了,`T`等于`Bool`! 另一个错误是尝试使用 `supertype` 沿着类型层次结构向上走: ```julia eltype_wrong(::Type{AbstractArray{T}}) where {T} = T eltype_wrong(::Type{AbstractArray{T, N}}) where {T, N} = T eltype_wrong(::Type{A}) where {A<:AbstractArray} = eltype_wrong(supertype(A)) ``` 虽然这适用于声明的类型,但对于不适用于没有超类型的类型: ```julia-repl julia> eltype_wrong(Union{AbstractArray{Int}, AbstractArray{Float64}}) ERROR: MethodError: no method matching supertype(::Type{Union{AbstractArray{Float64,N} where N, AbstractArray{Int64,N} where N}}) Closest candidates are: supertype(::DataType) at operators.jl:43 supertype(::UnionAll) at operators.jl:48 ``` ### 用不同的类型参数构建相似的类型 当构建通用代码时,通常需要创建一些类似对象,在类型的布局上有一些变化,这就也让类型参数的变化变得必要。 例如,你会有一些任意元素类型的抽象数组,想使用特定的元素类型来编写你基于它的计算。你必须实现为每个`AbstractArray{T}`的子类型实现方法,这些方法描述了如何计算类型转换。从一个子类型转化成拥有一个不同参数的另一个子类型的通用方法在这里不存在。(快速复习:你明白为什么吗?) `AbstractArray`的子类型典型情况下会实现两个方法来完成这个: 一个方法把输入输入转换成特定的`AbstractArray{T,N}`抽象类型的子类型;一个方法用特定的元素类型构建一个新的未初始化的数组。这些的样例实现可以在Julia Base里面找到。这里是一个基础的样例使用,保证`输入`与`输出`是同一种类型: ```julia input = convert(AbstractArray{Eltype}, input) output = similar(input, Eltype) ``` 作为这个的扩展,在算法需要输入数组的拷贝的情况下,[`convert`](@ref)使无法胜任的,因为返回值可能只是原始输入的别名。把[`similar`](@ref)(构建输出数组)和[`copyto!`](@ref)(用输入数据填满)结合起来是需要给出输入参数的可变拷贝的一个范用方法: ```julia copy_with_eltype(input, Eltype) = copyto!(similar(input, Eltype), input) ``` ### 迭代分派 为了分派一个多层的参数参量列表,将每一层分派分开到不同的函数中常常是最好的。这可能听起来跟单分派的方法相似,但是你会在下面见到,这个更加灵活。 例如,尝试按照数组的元素类型进行分派常常会引起歧义。相反地,常见的代码会首先按照容易类型分派,然后基于eltype递归到更加更加专用的方法。在大部分情况下,算法会很方便地就屈从与这个分层方法,在其他情况下,这种严苛的工作必须手动解决。这个分派分支能被观察到,例如在两个矩阵的加法的逻辑中: ```julia # 首先分派选择了逐元素相加的map算法。 +(a::Matrix, b::Matrix) = map(+, a, b) # 然后分派处理了每个元素然后选择了计算的 # 恰当的常见元素类型。 +(a, b) = +(promote(a, b)...) # 一旦元素有了相同类型,它们就可以相加。 # 例如,通过处理器暴露出的原始运算。 +(a::Float64, b::Float64) = Core.add(a, b) ``` ### 基于 Trait 的分派 对于上面的可迭代分派的一个自然扩展是给方法选择加一个内涵层,这个层允许按照那些与类型层级定义的集合相独立的类型的集合来分派。我们可以通过写出问题中的类型的一个`Union`来创建这个一个集合,但是这不能够扩展,因为`Union`类型在创建之后无法改变。但是这么一个可扩展的集合可以通过一个叫做["Holy-trait"](https://github.com/JuliaLang/julia/issues/2345#issuecomment-54537633)的一个设计样式来实现。 这个样式是通过定义一个范用函数来实现,这个函数为函数参数可能属于的每个trait集合都计算出不同的单例值(或者类型)。如果这个函数是单纯的,这与通常的分派对于性能没有任何影响。 上一部分中的示例掩盖了 [`map`](@ref) 和 [`promote`](@ref) 的实现细节,这两个都是依据trait来进行运算的。 在迭代矩阵时,例如在 `map` 的实现中,一个重要的问题是使用什么顺序遍历数据。 当 `AbstractArray` 子类型实现 [`Base.IndexStyle`](@ref) trait 时,`map` 等其他函数可以根据此信息进行派发以选择最佳算法(请参阅 [抽象数组接口](@ref man-interface-array))。这意味着每个子类型不需要实现`map`的自定义版本,因为通用定义+trait类将使系统能够选择最快的版本。 下面是 `map` 的一个简单实现,说明了基于 trait 的调度: ```julia map(f, a::AbstractArray, b::AbstractArray) = map(Base.IndexStyle(a, b), f, a, b) # generic implementation: map(::Base.IndexCartesian, f, a::AbstractArray, b::AbstractArray) = ... # linear-indexing implementation (faster) map(::Base.IndexLinear, f, a::AbstractArray, b::AbstractArray) = ... ``` 这个基于trait的方法也出现在[`promote`](@ref)机制中,被标量`+`使用。 它使用了[`promote_type`](@ref),这在知道两个计算对象的类型的情况下返回计算这个运算的最佳的常用类型。这就使得我们不用为每一对可能的类型参数实现每一个函数,而把问题简化为对于每个类型实现一个类型转换运算这样一个小很多的问题,还有一个优选的逐对的类型提升规则的表格。 ### 输出类型计算 基于trait的类型提升的讨论可以过渡到我们的下一个设计样式:为矩阵运算计算输出元素类型。 为了实现像加法这样的原始运算,我们使用[`promote_type`](@ref)函数来计算想要的输出类型。(像之前一样,我们在`+`调用中的`promote`调用中见到了这个工作)。 对于矩阵的更加复杂的函数,对于更加复杂的运算符序列来计算预期的返回类型是必要的。这经常按下列步骤进行: 1. 编写一个小函数`op`来表示算法核心中使用的运算的集合。 2. 使用`promote_op(op, argument_types...)`计算结果矩阵的元素类型`R`, 这里`argument_types`是通过应用到每个输入数组的`eltype`计算的。 3. 创建类似于`similar(R, dims)`的输出矩阵,这里`dims`是输出矩阵的预期维度数。 作为一个更加具体的例子,一个范用的方阵乘法的伪代码是: ```julia function matmul(a::AbstractMatrix, b::AbstractMatrix) op = (ai, bi) -> ai * bi + ai * bi ## this is insufficient because it assumes `one(eltype(a))` is constructable: # R = typeof(op(one(eltype(a)), one(eltype(b)))) ## this fails because it assumes `a[1]` exists and is representative of all elements of the array # R = typeof(op(a[1], b[1])) ## this is incorrect because it assumes that `+` calls `promote_type` ## but this is not true for some types, such as Bool: # R = promote_type(ai, bi) # this is wrong, since depending on the return value # of type-inference is very brittle (as well as not being optimizable): # R = Base.return_types(op, (eltype(a), eltype(b))) ## but, finally, this works: R = promote_op(op, eltype(a), eltype(b)) ## although sometimes it may give a larger type than desired ## it will always give a correct type output = similar(b, R, (size(a, 1), size(b, 2))) if size(a, 2) > 0 for j in 1:size(b, 2) for i in 1:size(a, 1) ## here we don't use `ab = zero(R)`, ## since `R` might be `Any` and `zero(Any)` is not defined ## we also must declare `ab::R` to make the type of `ab` constant in the loop, ## since it is possible that typeof(a * b) != typeof(a * b + a * b) == R ab::R = a[i, 1] * b[1, j] for k in 2:size(a, 2) ab += a[i, k] * b[k, j] end output[i, j] = ab end end end return output end ``` ### 分离转换和内核逻辑 能有效减少编译时间和测试复杂度的一个方法是将预期的类型和计算转换的逻辑隔离。这会让编译器将与大型内核的其他部分相独立的类型转换逻辑特别化并内联。 将更大的类型类转换成被算法实际支持的特定参数类是一个常见的设计样式: ```julia complexfunction(arg::Int) = ... complexfunction(arg::Any) = complexfunction(convert(Int, arg)) matmul(a::T, b::T) = ... matmul(a, b) = matmul(promote(a, b)...) ``` ## 参数化约束的可变参数方法 函数参数也可以用于约束应用于"可变参数"函数([变参函数](@ref))的参数的数量。`Vararg{T,N}` 可用于表明这么一个约束。举个例子: ```jldoctest julia> bar(a,b,x::Vararg{Any,2}) = (a,b,x) bar (generic function with 1 method) julia> bar(1,2,3) ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64) Closest candidates are: bar(::Any, ::Any, ::Any, !Matched::Any) at none:1 julia> bar(1,2,3,4) (1, 2, (3, 4)) julia> bar(1,2,3,4,5) ERROR: MethodError: no method matching bar(::Int64, ::Int64, ::Int64, ::Int64, ::Int64) Closest candidates are: bar(::Any, ::Any, ::Any, ::Any) at none:1 ``` 更加有用的是,用一个参数就约束可变参数的方法是可能的。例如: ```julia function getindex(A::AbstractArray{T,N}, indices::Vararg{Number,N}) where {T,N} ``` 只会在`indices`的个数与数组的维数相同时才会调用。 当只有提供的参数的类型需要被约束时,`Vararg{T}`可以写成`T...`。例如`f(x::Int...) = x`是`f(x::Vararg{Int}) = x`的简便写法。 ## 可选参数和关键字的参数的注意事项 与在[函数](@ref man-functions)中简要提到的一样,可选参数是使用多方法定义语法来实现的。例如,这个定义: ```julia f(a=1,b=2) = a+2b ``` 翻译成下列三个方法: ```julia f(a,b) = a+2b f(a) = f(a,2) f() = f(1,2) ``` 这就意味着调用`f()`等于调用`f(1,2)`。在这个情况下结果是`5`,因为`f(1,2)`使用的是上面`f`的第一个方法。但是,不总是需要是这种情况。如果你定义了第四个对于整数更加专用的方法: ```julia f(a::Int,b::Int) = a-2b ``` 此时`f()`和`f(1,2)`的结果都是`-3`。换句话说,可选参数只与函数捆绑,而不是函数的任意一个特定的方法。这个决定于使用的方法的可选参数的类型。当可选参数是用全局变量的形式定义时,可选参数的类型甚至会在运行时改变。 关键字参数与普通的位置参数的行为很不一样。特别地,他们不参与到方法分派中。方法只基于位置参数分派,在匹配得方法确定之后关键字参数才会被处理。 ## 类函数对象 方法与类型相关,所以可以通过给类型加方法使得任意一个Julia类型变得"可被调用"。(这个"可调用"的对象有时称为"函子"。) 例如,你可以定义一个类型,存储着多项式的系数,但是行为像是一个函数,可以为多项式求值: ```jldoctest polynomial julia> struct Polynomial{R} coeffs::Vector{R} end julia> function (p::Polynomial)(x) v = p.coeffs[end] for i = (length(p.coeffs)-1):-1:1 v = v*x + p.coeffs[i] end return v end julia> (p::Polynomial)() = p(5) ``` 注意函数是通过类型而非名字来指定的。如同普通函数一样这里有一个简洁的语法形式。在函数体内,`p`会指向被调用的对象。`Polynomial`会按如下方式使用: ```jldoctest polynomial julia> p = Polynomial([1,10,100]) Polynomial{Int64}([1, 10, 100]) julia> p(3) 931 julia> p() 2551 ``` 这个机制也是Julia中类型构造函数和闭包(指向其环境的内部函数)的工作原理。 ## 空泛型函数 有时引入一个没有添加方法的范用函数是有用的。这会用于分离实现与接口定义。这也可为了文档或者代码可读性。为了这个的语法是没有参数组的一个空`函数`块: ```julia function emptyfunc end ``` ## [方法设计与避免歧义](@id man-method-design-ambiguities) Julia的方法多态性是其最有力的特性之一,利用这个功能会带来设计上的挑战。特别地,在更加复杂的方法层级中出现[歧义](@ref man-ambiguities)不能说不常见。 在上面我们曾经指出我们可以像这样解决歧义 ```julia f(x, y::Int) = 1 f(x::Int, y) = 2 ``` 靠定义一个方法 ```julia f(x::Int, y::Int) = 3 ``` 这通常是正确的方案; 然而,在某些情况下,盲目地遵循这一建议可能会适得其反。 特别是,泛型函数的方法越多,产生歧义的可能性就越大。 当方法层次结构变得比这个简单的示例更复杂时,仔细考虑替代策略可能是值得的。 下面我们会讨论特别的一些挑战和解决这些挑战的一些可选方法。 ### 元组和N元组参数 `Tuple`(和`NTuple`)参数会带来特别的挑战。例如, ```julia f(x::NTuple{N,Int}) where {N} = 1 f(x::NTuple{N,Float64}) where {N} = 2 ``` 是有歧义的,因为存在`N == 0`的可能性:没有元素去确定`Int`还是`Float64`变体应该被调用。为了解决歧义,一个方法是为空元组定义方法: ```julia f(x::Tuple{}) = 3 ``` 作为一种选择,对于其中一个方法之外的所有的方法可以坚持元组中至少有一个元素: ```julia f(x::NTuple{N,Int}) where {N} = 1 # this is the fallback f(x::Tuple{Float64, Vararg{Float64}}) = 2 # this requires at least one Float64 ``` ### [正交化你的设计](@id man-methods-orthogonalize) 当你打算根据两个或更多的参数进行分派时,考虑一下,一个「包裹」函数是否会让设计简单一些。举个例子,与其编写多变量: ```julia f(x::A, y::A) = ... f(x::A, y::B) = ... f(x::B, y::A) = ... f(x::B, y::B) = ... ``` 不如考虑定义 ```julia f(x::A, y::A) = ... f(x, y) = f(g(x), g(y)) ``` 这里`g`把参数转变为类型`A`。这是更加普遍的[正交设计](https://en.wikipedia.org/wiki/Orthogonality_(programming))原理的一个特别特殊的例子,在正交设计中不同的概念被分配到不同的方法中去。这里`g`最可能需要一个fallback定义 ```julia g(x::A) = x ``` 一个相关的方案使用`promote`来把`x`和`y`变成常见的类型: ```julia f(x::T, y::T) where {T} = ... f(x, y) = f(promote(x, y)...) ``` 这个设计的一个隐患是:如果没有合适的把 `x` 和 `y` 转换到同样类型的类型提升方法,第二个方法就可能无限自递归然后引发堆溢出。 ### 一次只根据一个参数分派 如果你你需要根据多个参数进行分派,并且有太多的为了能定义所有可能的变量而存在的组合,而存在很多回退函数,你可以考虑引入"名字级联",这里(例如)你根据第一个参数分配然后调用一个内部的方法: ```julia f(x::A, y) = _fA(x, y) f(x::B, y) = _fB(x, y) ``` 接着内部方法`_fA`和`_fB`可以根据`y`进行分派,而不考虑有关`x`的歧义存在。 需要意识到这个方案至少有一个主要的缺点:在很多情况下,用户没有办法通过进一步定义你的输出函数`f`的具体行为来进一步定制`f`的行为。相反,他们需要去定义你的内部方法`_fA`和`_fB`的具体行为,这会模糊输出方法和内部方法之间的界线。 ### 抽象容器与元素类型 在可能的情况下要试图避免定义根据抽象容器的具体元素类型来分派的方法。举个例子, ```julia -(A::AbstractArray{T}, b::Date) where {T<:Date} ``` 会引起歧义,当定义了这个方法: ```julia -(A::MyArrayType{T}, b::T) where {T} ``` 最好的方法是不要定义这些方法中的*任何一个*。相反,使用范用方法`-(A::AbstractArray, b)`并确认这个方法是使用*分别*对于每个容器类型和元素类型都是适用的通用调用(像`similar`和`-`)实现的。这只是建议[正交化](@ref man-methods-orthogonalize)你的方法的一个更加复杂的变种而已。 当这个方法不可行时,这就值得与其他开发者开始讨论如果解决歧义;只是因为一个函数先定义并不总是意味着他不能改变或者被移除。作为最后一个手段,开发者可以定义"创可贴"方法 ```julia -(A::MyArrayType{T}, b::Date) where {T<:Date} = ... ``` 可以暴力解决歧义。 ### 与默认参数的复杂方法"级联" 如果你定义了提供默认的方法"级联",要小心去掉对应着潜在默认的任何参数。例如,假设你在写一个数字过滤算法,你有一个通过应用padding来出来信号的边的方法: ```julia function myfilter(A, kernel, ::Replicate) Apadded = replicate_edges(A, size(kernel)) myfilter(Apadded, kernel) # now perform the "real" computation end ``` 这会与提供默认padding的方法产生冲突: ```julia myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # replicate the edge by default ``` 这两个方法一起会生成无限的递归,`A`会不断变大。 更好的设计是像这样定义你的调用层级: ```julia struct NoPad end # indicate that no padding is desired, or that it's already applied myfilter(A, kernel) = myfilter(A, kernel, Replicate()) # default boundary conditions function myfilter(A, kernel, ::Replicate) Apadded = replicate_edges(A, size(kernel)) myfilter(Apadded, kernel, NoPad()) # indicate the new boundary conditions end # other padding methods go here function myfilter(A, kernel, ::NoPad) # Here's the "real" implementation of the core computation end ``` `NoPad` 被置于与其他 padding 类型一致的参数位置上,这保持了分派层级的良好组织,同时降低了歧义的可能性。而且,它扩展了「公开」的 `myfilter` 接口:想要显式控制 padding 的用户可以直接调用 `NoPad` 变量。 [^Clarke61]: Arthur C. Clarke, *Profiles of the Future* (1961): Clarke's Third Law.
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
7164
# [缺失值](@id missing) Julia 支持表示统计意义上的缺失值,即某个变量在观察中没有可用值,但在理论上存在有效值的情况。缺失值由 [`missing`](@ref) 对象表示,该对象是 [`Missing`](@ref) 类型的唯一实例。`missing` 等价于 [SQL 中的 `NULL`](https://en.wikipedia.org/wiki/NULL_(SQL)) 以及 [R 中的 `NA`](https://cran.r-project.org/doc/manuals/r-release/R-lang.html#NA-handling),并在大多数情况下表现得与它们一样。 ## 缺失值的传播 `missing` 值会自动在标准数学运算符和函数中*传播*。对于这类函数,其某个运算对象的值的不确定性会导致其结果的不确定性。在应用中,上述情形意味着若在数学操作中包括 `missing` 值,其结果也常常返回 `missing` 值。 ```jldoctest julia> missing + 1 missing julia> "a" * missing missing julia> abs(missing) missing ``` 由于`missing` 是 Julia 中的正常对象,此传播规则仅在可实现该对象的函数中应用。这可通过定义包含 `Missing` 类的实参的特定方法,或是简单地让函数可接受此类实参,并将该它们传入已具备传播规则的函数(如标准数学运算符)中实现。在包中定义新传播规则时,应考虑缺失值的传播是否具有实际意义,并在传播有意义时定义合适的方法。在某个不包含接受 `Missing` 类实参方法的函数中传递缺失值,则抛出 [`MethodError`](@ref)的报错,正如其它类型一样。 若希望函数不传播缺失值,可将其按照 [Missings.jl](https://github.com/JuliaData/Missings.jl) 库中的 `passmissing` 函数封装起来。例如,将 `f(x)` 封装为 `passmissing(f)(x)`。 ## 相等和比较运算符 标准相等和比较运算符遵循上面给出的传播规则:如果任何操作数是 `missing`,那么结果是 `missing`。这是一些例子 ```jldoctest julia> missing == 1 missing julia> missing == missing missing julia> missing < 1 missing julia> 2 >= missing missing ``` 特别要注意,`missing == missing` 返回 `missing`,所以 `==` 不能用于测试值是否为缺失值。要测试 `x` 是否为 `missing`,请用 [`ismissing(x)`](@ref)。 特殊的比较运算符 [`isequal`](@ref) 和 [`===`](@ref) 是传播规则的例外:它们总返回一个 `Bool` 值,即使存在 `missing` 值,并认为 `missing` 与 `missing` 相等且其与任何其它值不同。因此,它们可用于测试某个值是否为 `missing`。 ```jldoctest julia> missing === 1 false julia> isequal(missing, 1) false julia> missing === missing true julia> isequal(missing, missing) true ``` [`isless`](@ref) 运算符是另一个例外:`missing` 被认为比任何其它值大。此运算符被用于 [`sort`](@ref),因此 `missing` 值被放置在所有其它值之后。 ```jldoctest julia> isless(1, missing) true julia> isless(missing, Inf) false julia> isless(missing, missing) false ``` ## 逻辑运算符 逻辑(或布尔)运算符 [`|`](@ref)、[`&`](@ref) 和 [`xor`](@ref) 是另一种特殊情况,因为它们只有在逻辑上是必需的时传递 `missing` 值。对于这些运算符来说,结果是否不确定取决于具体操作,其遵循[*三值逻辑*](https://en.wikipedia.org/wiki/Three-valued_logic)的既定规则,这些规则也由 SQL 中的 `NULL` 以及 R 中的 `NA` 实现。这个抽象的定义实际上对应于一系列相对自然的行为,这最好通过具体的例子来解释。 让我们用逻辑「或」运算符 [`|`](@ref) 来说明这个原理。按照布尔逻辑的规则,如果其中一个操作数是 `true`,则另一个操作数对结果没影响,结果总是 `true`。 ```jldoctest julia> true | true true julia> true | false true julia> false | true true ``` 基于观察,我们可以得出结论,如果其中一个操作数是 `true` 而另一个是 `missing`,我们知道结果为 `true`,尽管另一个参数的实际值存在不确定性。如果我们能观察到第二个操作数的实际值,那么它只能是 `true` 或 `false`,在两种情况下结果都是 `true`。因此,在这种特殊情况下,值的缺失不会传播 ```jldoctest julia> true | missing true julia> missing | true true ``` 相反地,如果其中一个操作数是 `false`,结果可能是 `true` 或 `false`,这取决于另一个操作数的值。因此,如果一个操作数是 `missing`,那么结果也是 `missing`。 ```jldoctest julia> false | true true julia> true | false true julia> false | false false julia> false | missing missing julia> missing | false missing ``` 逻辑「且」运算符 [`&`](@ref) 的行为与 `|` 运算符相似,区别在于当其中一个操作数为 `false` 时,值的缺失不会传播。例如,当第一个操作数是 `false` 时 ```jldoctest julia> false & false false julia> false & true false julia> false & missing false ``` 另一方面,当其中一个操作数为 `true` 时,值的缺失会传播,例如,当第一个操作数是 `true` 时 ```jldoctest julia> true & true true julia> true & false false julia> true & missing missing ``` 最后,逻辑「异或」运算符 [`xor`](@ref) 总传播 `missing` 值,因为两个操作数都总是对结果产生影响。还要注意,否定运算符 [`!`](@ref) 在操作数是 `missing` 时返回 `missing`,这就像其它一元运算符。 ## 流程控制和短路运算符 流程控制操作符,包括 [`if`](@ref)、[`while`](@ref) 和[三元运算符](@ref man-conditional-evaluation) `x ? y : z`,不允许缺失值。这是因为如果我们能够观察实际值,它是 `true` 还是 `false` 是不确定的,这意味着我们不知道程序应该如何运行。一旦在以下上下文中遇到 `missing` 值,就会抛出 [`TypeError`](@ref) ```jldoctest julia> if missing println("here") end ERROR: TypeError: non-boolean (Missing) used in boolean context ``` 出于同样的原因,并与上面给出的逻辑运算符相反,短路布尔运算符 [`&&`](@ref) 和 [`||`](@ref) 在当前操作数的值决定下一个操作数是否求值时不允许 `missing` 值。例如 ```jldoctest julia> missing || false ERROR: TypeError: non-boolean (Missing) used in boolean context julia> missing && false ERROR: TypeError: non-boolean (Missing) used in boolean context julia> true && missing && false ERROR: TypeError: non-boolean (Missing) used in boolean context ``` 另一方面,如果无需 `missing` 值即可确定结果,则不会引发错误。代码在对 `missing` 操作数求值前短路,以及 `missing` 是最后一个操作数都是这种情况。 ```jldoctest julia> true && missing missing julia> false && missing false ``` ## 包含缺失值的数组 包含缺失值的数组的创建就像其它数组 ```jldoctest julia> [1, missing] 2-element Vector{Union{Missing, Int64}}: 1 missing ``` 如此示例所示,此类数组的元素类型为 `Union{Missing, T}`,其中 `T` 为非缺失值的类型。这简单地反映了以下事实:数组条目可以具有类型 `T`(此处为 `Int64`)或类型 `Missing`。此类数组使用高效的内存存储,其等价于一个 `Array{T}` 和一个 `Array{UInt8}` 的组合,前者保存实际值,后者表示条目类型(即它是 `Missing` 还是 `T`)。 允许缺失值的数组可以使用标准语法构造。使用 `Array{Union{Missing, T}}(missing, dims)` 来创建填充缺失值的数组: ```jldoctest julia> Array{Union{Missing, String}}(missing, 2, 3) 2×3 Matrix{Union{Missing, String}}: missing missing missing missing missing missing ``` !!! note 使用 `undef` 或 `similar` 目前可能会给出一个填充有 `missing` 的数组,但这不是获得这样一个数组的正确方法。 请使用如上所示的 `missing` 构造函数。 允许但不包含 `missing` 值的数组可使用 [`convert`](@ref) 转换回不允许缺失值的数组。如果该数组包含 `missing` 值,在类型转换时会抛出 `MethodError` ```jldoctest julia> x = Union{Missing, String}["a", "b"] 2-element Vector{Union{Missing, String}}: "a" "b" julia> convert(Array{String}, x) 2-element Vector{String}: "a" "b" julia> y = Union{Missing, String}[missing, "b"] 2-element Vector{Union{Missing, String}}: missing "b" julia> convert(Array{String}, y) ERROR: MethodError: Cannot `convert` an object of type Missing to an object of type String ``` ## 跳过缺失值 由于 `missing` 会随着标准数学运算符传播,归约函数会在调用的数组包含缺失值时返回 `missing` ```jldoctest julia> sum([1, missing]) missing ``` 在这种情况下,使用 [`skipmissing`](@ref) 即可跳过缺失值 ```jldoctest julia> sum(skipmissing([1, missing])) 1 ``` 此函数方便地返回一个可高效滤除 `missing` 值的迭代器。因此,它可应用于所有支持迭代器的函数 ```jldoctest skipmissing; setup = :(using Statistics) julia> x = skipmissing([3, missing, 2, 1]) skipmissing(Union{Missing, Int64}[3, missing, 2, 1]) julia> maximum(x) 3 julia> mean(x) 2.0 julia> mapreduce(sqrt, +, x) 4.146264369941973 ``` 通过在某数组中调用 `skipmissing` 生成的对象能以其在所属数组中的位置进行索引。对应缺失值的指标并不有效,若尝试使用之会丢出报错(它们在 `keys` 和 `eachindex` 中同样是被跳过的)。 ```jldoctest skipmissing julia> x[1] 3 julia> x[2] ERROR: MissingException: the value at index (2,) is missing [...] ``` 这允许对索引进行操作的函数与`skipmissing`结合使用。搜索和查找函数尤其如此,它们返回对`skipmissing` 函数返回的对象有效的索引,这些索引也是*在父数组中*匹配条目的索引。 ```jldoctest skipmissin julia> findall(==(1), x) 1-element Vector{Int64}: 4 julia> findfirst(!iszero, x) 1 julia> argmax(x) 1 ``` 使用 [`collect`](@ref) 提取非 `missing` 值并将它们存储在一个数组里 ```jldoctest skipmissing julia> collect(x) 3-element Vector{Int64}: 3 2 1 ``` ## 数组上的逻辑运算 上面描述的逻辑运算符的三值逻辑也适用于针对数组的函数。因此,使用 [`==`](@ref) 运算符的数组相等性测试中,若在未知 `missing` 条目实际值时无法确定结果,就返回 `missing`。在实际应用中意味着,在待比较数组中所有非缺失值都相等,且某个或全部数组包含缺失值(也许在不同位置)时会返回 `missing`。 ```jldoctest julia> [1, missing] == [2, missing] false julia> [1, missing] == [1, missing] missing julia> [1, 2, missing] == [1, missing, 2] missing ``` 对于单个值,[`isequal`](@ref) 会将 `missing` 值视为与其它 `missing` 值相等但与非缺失值不同。 ```jldoctest julia> isequal([1, missing], [1, missing]) true julia> isequal([1, 2, missing], [1, missing, 2]) false ``` 函数 [`any`](@ref) 和 [`all`](@ref) 遵循三值逻辑的规则,会在结果无法被确定时返回 `missing`。 ```jldoctest julia> all([true, missing]) missing julia> all([false, missing]) false julia> any([true, missing]) true julia> any([false, missing]) missing ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
11884
# [模块](@id modules) Julia 中的模块有助于将代码组织成连贯的部分。 它们在语法上以 `module Name ... end` 界定,并具有以下特点: 1. 模块是独立的命名空间,每个都引入了一个新的全局作用域。 这很有用,因为它允许对不同的函数或全局变量使用相同的名称而不会发生冲突,只要它们在不同的模块中即可。 2. 模块具有用于命名空间管理的工具:每个模块定义一组它`export`的名称,并且可以使用 `using` 和 `import` 从其他模块导入名称(我们将在下面解释这些)。 3. 模块可以预编译以加快加载速度,并包含用于运行时初始化的代码。 通常,在较大的 Julia 包中,你会看到模块的代码组织成文件,例如 ```julia module SomeModule # export, using, import statements are usually here; we discuss these below include("file1.jl") include("file2.jl") end ``` 文件和文件名大多与模块无关; 模块仅与模块表达式相关联。 每个模块可以有多个文件,每个文件可以有多个模块。 `include` 的行为就像在包含模块的全局作用域内执行源文件的内容一样。 在本章中,我们使用简短和简化的示例,因此我们不会使用`include`。 我们推荐不要缩进模块的主体,因为这通常会导致整个文件被缩进。 此外,通常使用 `UpperCamelCase` 作为模块名称(就像类型一样),并在适用时使用复数形式,特别是如果模块包含类似命名的标识符,以避免名称冲突。 例如, ```julia module FastThings struct FastThing ... end end ``` ## [命名空间管理](@id namespace-management) 命名空间管理是指语言提供的设施,用于使模块中的名称在其他模块中可用。 我们在下面详细讨论相关的概念和功能。 ### 合格的名称 全局作用域内的函数、变量和类型的名称,如`sin`、`ARGS`和`UnitRange`始终属于一个模块,称为*母模块*,例如,可以与[`parentmodule`](@ref)交互来找到该模块 ```jldoctest julia> parentmodule(UnitRange) Base ``` 也可以通过在它们的模块前面加上前缀来引用它们的父模块之外的这些名称,例如`Base.UnitRange`。 这称为*限定名称*。 父模块可以使用像`Base.Math.sin`这样的子模块链来访问,其中`Base.Math`被称为*模块路径*。 由于句法歧义,限定只包含符号的名称,例如运算符,需要插入冒号,例如 `Base.:+`。 少数运算符还需要括号,例如 `Base.:(==)`。 如果一个名称是限定的,那么它总是*可访问的*,在函数的情况下,它也可以通过使用限定的名称作为函数名称来添加方法。 在一个模块中,一个变量名可以通过将其声明 `global x` 不赋值而“保留”。 这可以防止在加载时间后初始化的全局变量的名称冲突。 语法`M.x = y` 不适用于在另一个模块中分配一个全局变量; 全局分配需要在模块本地进行操作。 ### 导出列表 名称(指函数、类型、全局变量和常量)可以通过 `export` 添加到模块的 *导出列表 *。 通常,它们位于或靠近模块定义的顶部,以便源代码的读者可以轻松找到它们,如 ```julia module NiceStuff export nice, DOG struct Dog end # singleton type, not exported const DOG = Dog() # named instance, exported nice(x) = "nice $x" # function, exported end ``` 但这只是一个风格建议——一个模块可以在任意位置有多个 `export` 语句。 导出构成 API(应用程序接口)一部分的名称是很常见的。 在上面的代码中,导出列表建议用户应该使用`nice`和`DOG`。 然而,由于限定名称总是使标识符可访问,这只是组织 API 的一个选项:与其他语言不同,Julia 没有真正隐藏模块内部的功能。 此外,某些模块根本不导出名称。 这通常是因为他们的 API 中使用常用词(例如`derivative`),这很容易与其他模块的导出列表发生冲突。 我们将在下面看到如何管理名称冲突。 ### 单独使用`using`和`import` 加载模块最常见的方式可能是`using ModuleName`。 这 [加载](@ref code-loading) 与 `ModuleName` 关联的代码,并引入 1. 模块名称 2. 和导出列表的元素到周围的全局命名空间中。 严格来说,声明 `using ModuleName` 意味着一个名为 `ModuleName` 的模块可用于根据需要解析名称。 当遇到当前模块中没有定义的全局变量时,系统会在`ModuleName`导出的变量中查找,找到就使用。 这意味着当前模块中该全局变量的所有使用都将解析为`ModuleName`中该变量的定义。 继续我们的例子, ```julia using NiceStuff ``` 将加载上面的代码,使 `NiceStuff`(模块名称)、`DOG` 和 `nice` 可用。 `Dog` 不在导出列表中,但如果名称被模块路径(这里只是模块名称)限定为 `NiceStuff.Dog`,则可以访问它。 重要的是,**导出列表只在`using ModuleName` 的形式下起作用**。 相反, ```julia import NiceStuff ``` *仅*将模块名称带入作用域。 用户需要使用 `NiceStuff.DOG`、`NiceStuff.Dog` 和 `NiceStuff.nice` 来访问其内容。 通常,当用户想要保持命名空间干净时,在上下文中使用 `import ModuleName`。 正如我们将在下一节中看到的,`import NiceStuff` 等同于 `using NiceStuff: NiceStuff`。 你可以用逗号分隔符来组合相同类型的多个`using`和`import`语句,例如: ```julia using LinearAlgebra, Statistics ``` ### 具有特定标识符的`using` 和 `import` ,并添加方法 当 `using ModuleName:` 或 `import ModuleName:` 后跟以逗号分隔的名称列表时,模块会被加载,但 *只有那些特定的名称才会被语句带入命名空间*。 例如, ```julia using NiceStuff: nice, DOG ``` 将导入名称`nice`和`DOG`。 重要的是,模块名称`NiceStuff` *不会*出现在命名空间中。 如果要使其可访问,则必须明确列出它,如 ```julia using NiceStuff: nice, DOG, NiceStuff ``` Julia有两种形式来表示似乎相同的内容,因为只有 `import ModuleName:f` 允许在 *没有模块路径*的情况下向 `f` 添加方法。也就是说,以下示例将给出一个错误: ```julia using NiceStuff: nice struct Cat end nice(::Cat) = "nice 😸" ``` 此错误可防止意外将方法添加到你仅打算使用的其他模块中的函数。 有两种方法可以解决这个问题。 你始终可以使用模块路径限定函数名称: ```julia using NiceStuff struct Cat end NiceStuff.nice(::Cat) = "nice 😸" ``` 或者,你可以`import`特定的函数名称: ```julia import NiceStuff: nice struct Cat end nice(::Cat) = "nice 😸" ``` 你选择哪一个取决于你的代码风格。第一种形式表明你正在向另一个模块中的函数添加一个方法(请记住,导入和方法定义可能在单独的文件中),而第二种形式较短,如果你定义了多个方法,这一点尤其方便。 一旦一个变量通过 `using` 或 `import` 引入,当前模块就不能创建同名的变量了。而且导入的变量是只读的,给全局变量赋值只能影响到由当前模块拥有的变量,否则会报错。 ### 用`as`来重命名 由`import` 或`using` 引入作用域的标识符可以用关键字`as` 重命名。 这对于解决名称冲突以及缩短名称很有用。 例如,`Base` 导出函数名`read`,但CSV.jl 包也提供了`CSV.read`。 如果我们要多次调用 CSV 读取,删除 `CSV.` 限定符会很方便。 但是,我们指的是`Base.read`还是`CSV.read`是模棱两可的: ```julia julia> read; julia> import CSV: read WARNING: ignoring conflicting import of CSV.read into Main ``` 重命名提供了一个解决方案: ```julia julia> import CSV: read as rd ``` 导入的包本身也可以重命名: ```julia import BenchmarkTools as BT ``` `as` 仅在将单个标识符引入作用域时才与 `using` 一起使用。 例如,`using CSV: read as rd` 有效,但`using CSV as C` 无效,因为它对 `CSV` 中的所有导出名称进行操作。 ### 混合使用多个 `using` 和 `import` 语句 当使用上述任何形式的多个 `using` 或 `import` 语句时,它们的效果将按照它们出现的顺序组合。 例如, ```julia using NiceStuff # exported names and the module name import NiceStuff: nice # allows adding methods to unqualified functions ``` 会将 `NiceStuff` 的所有导出名称和模块名称本身带入作用域,并且还允许向 `nice` 添加方法而不用模块名称作为前缀。 ### 处理名称冲突 考虑两个(或更多)包导出相同名称的情况,如 ```julia module A export f f() = 1 end module B export f f() = 2 end ``` `using A, B` 语句有效,但是当你尝试调用 `f` 时,你会收到警告 ```julia WARNING: both B and A export "f"; uses of it in module Main must be qualified ERROR: LoadError: UndefVarError: f not defined ``` 在这里,Julia 无法确定您指的是哪个 `f`,因此你必须做出选择。 常用的解决方法有以下几种: 1. 只需继续使用限定名称,如`A.f` 和`B.f`。 这使代码的读者可以清楚地了解上下文,特别是如果 `f` 恰好重合但在不同的包中具有不同的含义。 例如,`degree`在数学、自然科学和日常生活中有多种用途,这些含义应该分开。 2. 使用上面的 `as` 关键字重命名一个或两个标识符,例如 ```julia using A: f as f using B: f as g ``` 会使`B.f` 可用作`g`。 在这里,我们假设您之前没有使用 `using A`, 这会把`f`代入命名空间。 3. 当问题中的多个名称*确实*有相同的含义时,通常一个模块会从另一个模块导入它,或者有一个轻量级的“基础”包,它的唯一功能是定义这样的接口,可以被其他包使用。按照惯例,这些包名以 `...Base` 结尾(这与 Julia 的 `Base` 模块无关) ### 默认顶层定义以及裸模块 模块自动包含 `using Core`、`using Base` 以及 [`eval`](@ref) 和 [`include`](@ref) 函数的定义,这些函数在该模块的全局作用域内计算表达式/文件 . 如果不需要这些默认定义,可以使用关键字 [`baremodule`](@ref) 来定义模块(注意:`Core` 仍然是导入的)。 就 `baremodule` 而言,一个标准的 `module` 看起来像这样: ``` baremodule Mod using Base eval(x) = Core.eval(Mod, x) include(p) = Base.include(Mod, p) ... end ``` ### 标准模块 有三个重要的标准模块: * [`Core`](@ref) 包含了语言“内置”的所有功能。 * [`Base`](@ref) 包含了绝大多数情况下都会用到的基本功能。 * [`Main`](@ref) 是顶层模块,当 julia 启动时,也是当前模块。 !!! note "Standard library modules" 默认情况下,Julia 附带了一些标准库模块。 除了你不需要显式安装它们之外,它们的行为与常规 Julia 包类似。 例如,如果您想执行一些单元测试,你可以按如下方式加载 `Test` 标准库: ```julia using Test ``` ## 子模块和相对路径 模块可以包含 *子模块*,嵌套相同的语法`module ... end`。 它们可用于引入单独的命名空间,这有助于组织复杂的代码库。 请注意,每个 `module` 都引入了自己的 [作用域](@ref scope-of-variables),因此子模块不会自动从其父模块“继承”名称。 建议子模块在 `using` 和 `import` 语句中使用 *相对模块限定符* 来引用封闭父模块中的其他模块(包括后者)。 相对模块限定符以句点 (`.`) 开头,它对应于当前模块,每个连续的 `.` 都指向当前模块的父级。 如有必要,这应该跟在模块之后,最后是要访问的实际名称,所有名称都以`.`分隔。 考虑以下示例,其中子模块`SubA`定义了一个函数,然后在其“兄弟”模块中进行扩展: ```julia module ParentModule module SubA export add_D # exported interface const D = 3 add_D(x) = x + D end using .SubA # brings `add_D` into the namespace export add_D # export it from ParentModule too module SubB import ..SubA: add_D # relative path for a “sibling” module struct Infinity end add_D(x::Infinity) = x end end ``` 你可能会在包中看到代码,在类似的情况下,它使用 ```julia import ParentModule.SubA: add_D ``` 然而,这是通过 [代码加载](@ref code-loading) 操作的,因此仅当 `ParentModule` 在包中时才有效。 最好使用相对路径。 请注意,如果你正在评估值,定义的顺序也很重要。 考虑 ```julia module TestPackage export x, y x = 0 module Sub using ..TestPackage z = y # ERROR: UndefVarError: y not defined end y = 1 end ``` 其中 `Sub` 在定义之前尝试使用 `TestPackage.y`,因此它没有值。 出于类似的原因,你不能使用循环顺序: ```julia module A module B using ..C # ERROR: UndefVarError: C not defined end module C using ..B end end ``` ### 模块初始化和预编译 因为执行模块中的所有语句通常需要编译大量代码,大型模块可能需要几秒钟才能加载。Julia 会创建模块的预编译缓存以减少这个时间。 当用 `import` 或 `using` 加载一个模块时,模块增量预编译文件会自动创建并使用。这会让模块在第一次加载时自动编译。 另外,你也可以手工调用 [`Base.compilecache(modulename)`](@ref),产生的缓存文件会放在 `DEPOT_PATH[1]/compiled/` 目录下。 之后,当该模块的任何一个依赖发生变更时,该模块会在 `using` 或 `import` 时自动重新编译; 模块的依赖指的是:任何它导入的模块、Julia 自身、include 的文件或由 [`include_dependency(path)`](@ref) 显式声明的依赖。 对于文件依赖项,通过检查由 `include` 加载或由 `include_dependency` 显式添加的每个文件的修改时间(`mtime`)是否保持不变,或是否等于截断到最接近秒的修改时间(以适应无法以亚秒精度复制 mtime的系统),来确定更改。它还考虑由 `require` 中的搜索逻辑选择的文件路径是否与创建预编译文件的路径匹配。它还考虑了已加载到当前进程中的依赖项集,并且不会重新编译这些模块,即使它们的文件更改或消失,以避免在正在运行的系统和预编译缓存之间创建不兼容。 如果你知道一个模块预编译*不*安全(例如,由于下面描述的原因之一),你应该把`__precompile__(false)`放在模块文件中(通常放在顶部)。 这会导致`Base.compilecache` 抛出错误,并且会导致`using` / `import` 将其直接加载到当前进程中并跳过预编译和缓存。 这也因此防止了模块被任何其他预编译模块导入。 在开发模块的时候,你可能需要了解一些与增量编译相关的固有行为。例如,外部状态不会被保留。为了解决这个问题,需要显式分离运行时与编译期的部分。Julia 允许你定义一个 `__init__()` 函数来执行任何需要在运行时发生的初始化。在编译期(`--output-*`),此函数将不会被调用。你可以假设在代码的生存周期中,此函数只会被运行一次。当然,如果有必要,你也可以手动调用它,但在默认的情况下,请假定此函数是为了处理与本机状态相关的信息,注意这些信息不需要,更不应该存入预编译镜像。此函数会在模块被导入到当前进程之后被调用,这包括在一个增量编译中导入该模块的时候(`--output-incremental=yes`),但在完整编译时该函数不会被调用。 特别的,如果你在模块里定义了一个名为 `__init__()` 的函数,那么 Julia 在加载这个模块之后会在第一次运行时(runtime)立刻调用这个函数(例如,通过 `import`,`using`,或者 `require` 加载时),也就是说 `__init__` 只会在模块中所有其它命令都执行完以后被调用一次。因为这个函数将在模块完全载入后被调用,任何子模块或者已经载入的模块都将在当前模块调用 `__init__` **之前** 调用自己的 `__init__` 函数。 `__init__`的典型用法有二,一是用于调用外部 C 库的运行时初始化函数,二是用于初始化涉及到外部库所返回的指针的全局常量。例如,假设我们正在调用一个 C 库 `libfoo`,它要求我们在运行时调用`foo_init()` 这个初始化函数。假设我们还想定义一个全局常量 `foo_data_ptr`,它保存 `libfoo` 所定义的 `void *foo_data()` 函数的返回值——必须在运行时(而非编译时)初始化这个常量,因为指针地址不是固定的。可以通过在模块中定义 `__init__` 函数来完成这个操作。 ```julia const foo_data_ptr = Ref{Ptr{Cvoid}}(0) function __init__() ccall((:foo_init, :libfoo), Cvoid, ()) foo_data_ptr[] = ccall((:foo_data, :libfoo), Ptr{Cvoid}, ()) nothing end ``` 注意,在像 `__init__` 这样的函数里定义一个全局变量是完全可以的,这是动态语言的优点之一。但是把全局作用域的值定义成常量,可以让编译器能确定该值的类型,并且能让编译器生成更好的优化过的代码。显然,你的模块(Module)中,任何其他依赖于 `foo_data_ptr` 的全局量也必须在 `__init__` 中被初始化。 涉及大多数不是由 [`ccall`](@ref) 生成的 Julia 对象的常量不需要放在 `__init__` 中:它们的定义可以从缓存的模块映像中预编译和加载。 这包括复杂的堆分配对象,如数组。 但是,任何返回原始指针值的例程都必须在运行时调用才能使预编译工作([`Ptr`](@ref) 对象将变成空指针,除非它们隐藏在 [`isbits`](@ref) 目的)。 这包括 Julia 函数 [`@cfunction`](@ref) 和 [`pointer`](@ref) 的返回值。 字典和集合类型,或者通常任何依赖于 `hash(key)` 方法的类型,都是比较棘手的情况。 通常当键是数字、字符串、符号、范围、`Expr` 或这些类型的组合(通过数组、元组、集合、映射对等)时,可以安全地预编译它们。但是,对于一些其它的键类型,例如 `Function` 或 `DataType`、以及还没有定义散列方法的通用用户定义类型,回退(fallback)的散列(`hash`)方法依赖于对象的内存地址(通过 `objectid`),因此可能会在每次运行时发生变化。 如果您有这些关键类型中的一种,或者您不确定,为了安全起见,您可以在您的 `__init__` 函数中初始化这个字典。或者,您可以使用 [`IdDict`](@ref) 字典类型,它是由预编译专门处理的,因此在编译时初始化是安全的。 当使用预编译时,我们必须要清楚地区分代码的编译阶段和运行阶段。在此模式下,我们会更清楚发现 Julia 的编译器可以执行任何 Julia 代码,而不是一个用于生成编译后代码的独立的解释器。 其它已知的潜在失败场景包括: 1. 全局计数器,例如:为了试图唯一的标识对象。考虑以下代码片段: ```julia mutable struct UniquedById myid::Int let counter = 0 UniquedById() = new(counter += 1) end end ``` 尽管这段代码的目标是给每个实例赋一个唯一的 ID,但计数器的值会在代码编译结束时被记录。任何对此增量编译模块的后续使用,计数器都将从同一个值开始计数。 注意 `objectid` (工作原理是取内存指针的 hash)也有类似的问题,请查阅下面关于 `Dict` 的用法。 一种解决方案是用宏捕捉 [`@__MODULE__`](@ref),并将它与目前的 `counter` 值一起保存。然而,更好的方案是对代码进行重新设计,不要依赖这种全局状态变量。 2. 像 `Dict` 和 `Set` 这种关联集合需要在 `__init__` 中 re-hash。Julia 在未来很可能会提供一个机制来注册初始化函数。 3. 依赖编译期的副作用会在加载时蔓延。例子包括:更改其它 Julia 模块里的数组或变量,操作文件或设备的句柄,保存指向其它系统资源(包括内存)的指针。 4. 无意中从其它模块中“拷贝”了全局状态:通过直接引用的方式而不是通过查找的方式。例如,在全局作用域下: ```julia #mystdout = Base.stdout #= will not work correctly, since this will copy Base.stdout into this module =# # instead use accessor functions: getstdout() = Base.stdout #= best option =# # or move the assignment into the runtime: __init__() = global mystdout = Base.stdout #= also works =# ``` 此处为预编译中的操作附加了若干限制,以帮助用户避免其他误操作: 1. 调用 [`eval`](@ref) 来在另一个模块中引发副作用。当增量预编译被标记时,该操作同时会导致抛出一个警告。 2. 当 `__init__()` 已经开始执行后,在局部作用域中声明 `global const`(见 issue #12010,计划为此情况添加一个错误提示) 3. 在增量预编译时替换模块是一个运行时错误。 一些其他需要注意的点: 1. 在源代码文件本身被修改之后,不会执行代码重载或缓存失效化处理(包括由 `Pkg.update` 执行的修改,此外在 `Pkg.rm` 执行后也没有清理操作) 2. 变形数组的内存共享特性会被预编译忽略(每个数组样貌都会获得一个拷贝) 3. 文件系统在编译期间和运行期间被假设为不变的,比如使用 [`@__FILE__`](@ref)/`source_path()` 在运行期间寻找资源、或使用 BinDeps 宏 `@checked_lib`。有时这是不可避免的。但是可能的话,在编译期将资源复制到模块里面是个好做法,这样在运行期间,就不需要去寻找它们了。 4. `WeakRef` 对象和完成器目前在序列化器中无法被恰当地处理(在接下来的发行版中将修复)。 5. 通常,最好避免去捕捉内部元数据对象的引用,如 `Method`、`MethodInstance`、`TypeMapLevel`、`TypeMapEntry` 及这些对象的字段,因为这会迷惑序列化器,且可能会引发你不想要的结果。此操作不足以成为一个错误,但你需做好准备:系统会尝试拷贝一部分,然后创建其余部分的单个独立实例。 在开发模块时,关闭增量预编译可能会有所帮助。命令行标记 `--compiled-modules={yes|no}` 可以让你切换预编译的开启和关闭。当 Julia 附加 `--compiled-modules=no` 启动,在载入模块和模块依赖时,编译缓存中的序列化模块会被忽略。`Base.compilecache` 仍可以被手动调用。此命令行标记的状态会被传递给 `Pkg.build`,禁止其在安装、更新、显式构建包时触发自动预编译。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
6982
# [多线程](@id man-multithreading) 访问此 [博客文章](https://julialang.org/blog/2019/07/multithreading/) 以了解 Julia 多线程特性。 ## 启用Julia多线程 Julia 默认启动一个线程执行代码,这点可以通过 [`Threads.nthreads()`](@ref) 来确认: ```jldoctest julia> Threads.nthreads() 1 ``` 执行线程的数量通过使用`-t`/`--threads` 命令行参数或使用[`JULIA_NUM_THREADS`](@ref JULIA_NUM_THREADS) 环境变量。 当两者都被指定时,`-t`/`--threads` 优先级更高。 !!! compat "Julia 1.5" `-t`/`--threads` 命令行参数至少需要 Julia 1.5。在旧版本中,你必须改用环境变量。 让我们以4个线程启动Julia ```bash $ julia --threads 4 ``` 现在确认下确实有4个线程: ```julia-repl julia> Threads.nthreads() 4 ``` 不过我们现在是在 master 线程,用 [`Threads.threadid`](@ref) 确认下: ```jldoctest julia> Threads.threadid() 1 ``` !!! note 如果你更喜欢使用环境变量,可以按如下方式设置它 Bash (Linux/macOS): ```bash export JULIA_NUM_THREADS=4 ``` C shell on Linux/macOS, CMD on Windows: ```bash set JULIA_NUM_THREADS=4 ``` Powershell on Windows: ```powershell $env:JULIA_NUM_THREADS=4 ``` Note that this must be done *before* starting Julia. !!! note 使用 `-t`/`--threads` 指定的线程数传播到使用 `-p`/`--procs` 或 `--machine-file` 命令行选项产生的工作进程。 例如,`julia -p2 -t2` 产生 1 个主进程和 2 个工作进程,并且所有三个进程都启用了 2 个线程。 要对工作线程进行更细粒度的控制,请使用 [`addprocs`](@ref) 并将 `-t`/`--threads` 作为 `exeflags` 传递。 ## 数据竞争自由 你有责任确保程序没有数据竞争,如果你不遵守该要求,则不能假设这里承诺的任何内容。 观察到的结果可能是反直觉的。 为了确保这一点,最好的办法是获取多线程同时访问的数据的锁。 例如,在大多数情况下,你应该使用以下代码模板: ```julia-repl julia> lock(lk) do use(a) end julia> begin lock(lk) try use(a) finally unlock(lk) end end ``` 其中 `lk` 是一个锁(例如 `ReentrantLock()`), `a` 是数据。 此外,Julia 在出现数据竞争时不是内存安全的。如果另一个线程可能会写入数据,则在读取_任何_数据时都要非常小心! 相反,在更改其他线程访问的数据(例如分配给全局或闭包变量)时,请始终使用上述锁模式。 ```julia Thread 1: global b = false global a = rand() global b = true Thread 2: while !b; end bad_read1(a) # it is NOT safe to access `a` here! Thread 3: while !@isdefined(a); end bad_read2(a) # it is NOT safe to access `a` here ``` ## `@threads`宏 下面用一个简单的例子测试我们原生的线程,首先创建一个全零的数组: ```jldoctest julia> a = zeros(10) 10-element Vector{Float64}: 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 ``` 现在用4个线程模拟操作这个数组,每个线程往对应的位置写入线程ID。 Julia 用 [`Threads.@threads`](@ref) 宏实现并行循环,该宏加在 `for` 循环前面,提示 Julia 循环部分是一个多线程的区域: ```julia-repl julia> Threads.@threads for i = 1:10 a[i] = Threads.threadid() end ``` 根据线程调度,迭代在各线程中进行拆分,之后各线程将自己的线程ID写入对应区域。 ```julia-repl julia> a 10-element Vector{Float64}: 1.0 1.0 1.0 2.0 2.0 2.0 3.0 3.0 4.0 4.0 ``` 注意 [`Threads.@threads`](@ref) 并没有一个像 [`@distributed`](@ref) 一样的可选的 reduction 参数。 ## 原子操作 Julia 支持访问和修改值的**原子**操作,即以一种线程安全的方式来避免[竞态条件](https://en.wikipedia.org/wiki/Race_condition)。一个值(必须是基本类型的,primitive type)可以通过 [`Threads.Atomic`](@ref) 来包装起来从而支持原子操作。下面看个例子: ```julia-repl julia> i = Threads.Atomic{Int}(0); julia> ids = zeros(4); julia> old_is = zeros(4); julia> Threads.@threads for id in 1:4 old_is[id] = Threads.atomic_add!(i, id) ids[id] = id end julia> old_is 4-element Vector{Float64}: 0.0 1.0 7.0 3.0 julia> i[] 10 julia> ids 4-element Vector{Float64}: 1.0 2.0 3.0 4.0 ``` 如果不加 `Atomic` 的话,那么会因为竞态条件而得到错误的结果,下面是一个没有避免竞态条件的例子: ```julia-repl julia> using Base.Threads julia> nthreads() 4 julia> acc = Ref(0) Base.RefValue{Int64}(0) julia> @threads for i in 1:1000 acc[] += 1 end julia> acc[] 926 julia> acc = Atomic{Int64}(0) Atomic{Int64}(0) julia> @threads for i in 1:1000 atomic_add!(acc, 1) end julia> acc[] 1000 ``` ## [field粒度的原子操作](@id man-atomics) 我们还可以使用[`@atomic`](@ref Base.@atomic)、[`@atomicswap`](@ref Base.@atomicswap)和[`@atomicreplace`](@ref Base.@atomicreplace) 宏在更细粒度的级别上使用原子。 内存模型的具体细节和设计的其他细节写在[Julia Atomics Manifesto](https://gist.github.com/vtjnash/11b0031f2e2a66c9c24d33e810b34ec0)中,稍后将正式发布。 struct 声明中的任何字段都可以用 `@atomic` 修饰,然后任何写入也必须用 `@atomic` 标记,并且必须使用定义的原子顺序之一(:monotonic、:acquire、:release、:acquire \_release 或 :sequentially\_consistent)。 对原子字段的任何读取也可以使用原子排序约束进行注释,或者如果未指定,将使用单调(宽松)排序完成。 !!! compat "Julia 1.7" field粒度的原子操作至少需要 Julia 1.7. ## 副作用和可变的函数参数 使用多线程时,我们必须小心使用非 [纯](https://en.wikipedia.org/wiki/Pure_function) 的函数,因为我们可能会得到错误的答案。 例如,按照惯例具有 [名称以`!` 结尾](@ref bang-convention) 的函数会修改它们的参数,因此不是纯函数。 ## @threadcall 外部库,例如通过 [`ccall`](@ref) 调用的库,给 Julia 基于任务的 I/O 机制带来了问题。 如果 C 库执行阻塞操作,这会阻止 Julia 调度程序执行任何其他任务,直到调用返回。(例外情况是调用回调到 Julia 的自定义 C 代码,然后它可能会 yield,或者调用 `jl_yield()` 的 C 代码,`jl_yield` 是 [`yield`](@ref) 的 C 等价物。) [`@threadcall`](@ref) 宏提供了一种避免在这种情况下停止执行的方法。它调度一个 C 函数以在单独的线程中执行。为此使用默认大小为 4 的线程池。线程池的大小由环境变量`UV_THREADPOOL_SIZE`控制。 在等待空闲线程时,以及一旦线程可用后的函数执行期间,请求任务(在主 Julia 事件循环上)让步给其他任务。 注意,`@threadcall` 在执行完成之前不会返回。 因此,从用户的角度来看,它与其他 Julia API 一样是一个阻塞调用。 非常关键的一点是,被调用的函数不会再调用回 Julia。 `@threadcall` 在 Julia 未来的版本中可能会被移除或改变。 ## 注意! 此时,如果用户代码没有数据竞争,Julia 运行时和标准库中的大多数操作都可以以线程安全的方式使用。 然而,在某些领域,稳定线程支持的工作正在进行中。多线程编程有许多内在的困难,如果使用线程的程序表现出异常或与预期不符的行为(例如崩溃或神秘的结果),通常应该首先怀疑线程交互。 在 Julia 中使用线程时需要注意以下这些特定的限制和警告: * 如果多个线程同时使用基本容器类型,且至少有一个线程修改容器时,需要手动加锁(常见示例包括 `push!` 数组,或将项插入 `Dict`)。 * 任务开始在某个线程上运行后(例如通过`@spawn`),它会在阻塞后始终在同一线程上重新启动。 将来这个限制将被移除,任务会在线程之间迁移。 * `@threads` 当前使用静态调度,使用所有线程并为每个线程分配相等的迭代计数。将来,默认时间表可能会更改为动态的。 * `@spawn` 使用的时间表是不确定的,不应依赖。 * 计算绑定、非内存分配任务可以防止垃圾回收在其他正在分配内存的线程中运行。 在这些情况下,可能需要手动调用 `GC.safepoint()` 以允许 GC 运行。 该限制在未来会被移除。 * 避免并行运行顶层操作,例如,`include` 或 `eval` 评估类型、方法和模块定义。 * 请注意,如果启用线程,则库注册的终结器可能会中断。 这可能需要在整个生态系统中进行一些过渡工作,然后才能放心地广泛采用线程。 有关更多详细信息,请参阅下一节。 ## 终结器的安全使用 因为终结器可以中断任何代码,所以它们在如何与任何全局状态交互时必须非常小心。 不幸的是,使用终结器的主要原因是更新全局状态(纯函数作为终结器通常毫无意义)。 这让我们陷入了一个难题。 有几种方法可以处理这个问题: 1. 当单线程时,代码可以调用内部 `jl_gc_enable_finalizers` C 函数以防止在关键区域内调度终结器。 在内部,这在某些函数(例如我们的 C locks)中使用,以防止在执行某些操作(增量包加载、代码生成等)时发生递归。 锁和此标志的组合可用于使终结器安全。 2. Base 在几个地方采用的第二种策略是显式延迟终结器,直到它可以非递归地获取其锁。 以下示例演示了如何将此策略应用于 `Distributed.finalize_ref`: ```julia function finalize_ref(r::AbstractRemoteRef) if r.where > 0 # Check if the finalizer is already run if islocked(client_refs) || !trylock(client_refs) # delay finalizer for later if we aren't free to acquire the lock finalizer(finalize_ref, r) return nothing end try # `lock` should always be followed by `try` if r.where > 0 # Must check again here # Do actual cleanup here r.where = 0 end finally unlock(client_refs) end end nothing end ``` 3. 相关的第三种策略是使用不需要 yield 的队列。 我们目前没有在 Base 中实现无锁队列,但 `Base.InvasiveLinkedListSynchronized{T}` 是合适的。 这通常是用于带有事件循环的代码的好策略。 例如,这个策略被 `Gtk.jl` 用来管理生命周期引用计数。 在这种方法中,我们不会在终结器内部做任何显式工作,而是将其添加到队列中以在更安全的时间运行。 事实上,Julia 的任务调度器已经使用了这种方法,因此将终结器定义为 `x -> @spawn do_cleanup(x)` 就是这种方法的一个示例。 但是请注意,这并不控制 `do_cleanup` 在哪个线程上运行,因此 `do_cleanup` 仍需要获取锁。 如果你实现自己的队列,则不必如此,因为你只能明确地从线程中排出该队列。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
7098
# 网络和流 Julia 提供了一个功能丰富的接口来处理流式 I/O 对象,如终端、管道和 TCP 套接字。此接口虽然在系统级是异步的,但是其以同步的方式展现给程序员,通常也不需要考虑底层的异步操作。这是通过大量使用 Julia 协作线程([协程](@ref man-tasks))功能实现的。 ## 基础流 I/O 所有 Julia stream 都暴露了 [`read`](@ref) 和 [`write`](@ref) 方法,将 stream 作为它们的第一个参数,如: ```julia-repl julia> write(stdout, "Hello World"); # suppress return value 11 with ; Hello World julia> read(stdin, Char) '\n': ASCII/Unicode U+000a (category Cc: Other, control) ``` 注意,[`write`](@ref) 返回 11,字节数(`"Hello World"`)写入 [`stdout`](@ref),但是返回值使用 `;` 抑制。 这里按了两次回车,以便 Julia 能够读取到换行符。正如你在这个例子中所看到的,[`write`](@ref) 以待写入的数据作为其第二个参数,而 [`read`](@ref) 以待读取的数据的类型作为其第二个参数。 例如,为了读取一个简单的字节数组,我们可以这样做: ```julia-repl julia> x = zeros(UInt8, 4) 4-element Array{UInt8,1}: 0x00 0x00 0x00 0x00 julia> read!(stdin, x) abcd 4-element Array{UInt8,1}: 0x61 0x62 0x63 0x64 ``` 但是,因为这有些繁琐,所以提供了几个方便的方法。例如,我们可以把上面的代码编写为: ```julia-repl julia> read(stdin, 4) abcd 4-element Array{UInt8,1}: 0x61 0x62 0x63 0x64 ``` 或者如果我们想要读取一整行: ```julia-repl julia> readline(stdin) abcd "abcd" ``` 请注意,根据你的终端设置,你的 TTY 可能是行缓冲的,因此在数据发送给 Julia 前可能需要额外的回车。 若要读取 [`stdin`](@ref) 的每一行,可以使用 [`eachline`](@ref): ```julia for line in eachline(stdin) print("Found $line") end ``` 或者如果你想要按字符读取的话,使用 [`read`](@ref) : ```julia while !eof(stdin) x = read(stdin, Char) println("Found: $x") end ``` ## 文本 I/O 请注意,上面提到的 [`write`](@ref) 方法对二进制流进行操作。具体来说,值不会转换为任何规范的文本表示形式,而是按原样输出: ```jldoctest julia> write(stdout, 0x61); # suppress return value 1 with ; a ``` 请注意,`a` 被 [`write`](@ref) 函数写入到 [`stdout`](@ref) 并且返回值为 `1`(因为 `0x61` 为一个字节)。 对于文本 I/O,请根据需要使用 [`print`](@ref) 或 [`show`](@ref) 方法(有关这两个方法之间的差异的详细讨论,请参阅它们的文档): ```jldoctest julia> print(stdout, 0x61) 97 ``` 有关如何实现自定义类型的显示方法的更多信息,请参阅 [自定义 pretty-printing](@ref man-custom-pretty-printing)。 ## IO 输出的上下文信息 有时,IO 输出可受益于将上下文信息传递到 show 方法的能力。[`IOContext`](@ref) 对象提供了将任意元数据与 IO 对象相关联的框架。例如,`:compact => true` 向 IO 对象添加一个参数来提示调用的 show 方法应该打印一个较短的输出(如果适用)。有关常用属性的列表,请参阅 [`IOContext`](@ref) 文档。 ## 使用文件 和其他环境一样,Julia 有 [`open`](@ref) 函数,它接收文件名并返回一个 [`IOStream`](@ref) 对象,你可以用该对象来对文件进行读取和写入。例如,如果我们有文件 `hello.txt`,其内容为 `Hello, World!`: ```julia-repl julia> f = open("hello.txt") IOStream(<file hello.txt>) julia> readlines(f) 1-element Array{String,1}: "Hello, World!" ``` 若要写入文件,则可以带着 write(`"w"`)标志来打开它: ```julia-repl julia> f = open("hello.txt","w") IOStream(<file hello.txt>) julia> write(f,"Hello again.") 12 ``` 你如果在此刻检查 `hello.txt` 的内容,会注意到它是空的;改动实际上还没有写入到磁盘中。这是因为 `IOStream` 必须在写入实际刷新到磁盘前关闭: ```julia-repl julia> close(f) ``` 再次检查 `hello.txt` 将显示其内容已被更改。 打开文件,对其内容执行一些操作,并再次关闭它是一种非常常见的模式。为了使这更容易,[`open`](@ref) 还有另一种调用方式,它以一个函数作为其第一个参数,以文件名作为其第二个参数,以该文件为参数调用该函数,然后再次关闭它。例如,给定函数: ```julia function read_and_capitalize(f::IOStream) return uppercase(read(f, String)) end ``` 可以调用: ```julia-repl julia> open(read_and_capitalize, "hello.txt") "HELLO AGAIN." ``` 来打开 `hello.txt`,对它调用 `read_and_capitalize`,关闭 `hello.txt` 并返回大写的内容。 为了避免被迫定义一个命名函数,你可以使用 `do` 语法,它可以动态地创建匿名函数: ```julia-repl julia> open("hello.txt") do f uppercase(read(f, String)) end "HELLO AGAIN." ``` ## 一个简单的 TCP 示例 让我们直接进入一个 TCP 套接字相关的简单示例。此功能位于名为 `Sockets` 的标准库中。让我们先创建一个简单的服务器: ```julia-repl julia> using Sockets julia> errormonitor(@async begin server = listen(2000) while true sock = accept(server) println("Hello World\n") end end) Task (runnable) @0x00007fd31dc11ae0 ``` 对于那些熟悉 Unix 套接字 API 的人,这些方法名称会让人感觉很熟悉,可是它们的用法比原始的 Unix 套接字 API 要简单些。在本例中,首次调用 [`listen`](@ref) 会创建一个服务器,等待传入指定端口(2000)的连接。 ```julia-repl julia> listen(2000) # 监听(IPv4 下的)localhost:2000 Sockets.TCPServer(active) julia> listen(ip"127.0.0.1",2000) # 等价于第一个 Sockets.TCPServer(active) julia> listen(ip"::1",2000) # 监听(IPv6 下的)localhost:2000 Sockets.TCPServer(active) julia> listen(IPv4(0),2001) # 监听所有 IPv4 接口的端口 2001 Sockets.TCPServer(active) julia> listen(IPv6(0),2001) # 监听所有 IPv6 接口的端口 2001 Sockets.TCPServer(active) julia> listen("testsocket") # 监听 UNIX 域套接字 Sockets.PipeServer(active) julia> listen("\\\\.\\pipe\\testsocket") # 监听 Windows 命名管道 Sockets.PipeServer(active) ``` 请注意,最后一次调用返回的类型是不同的。这是因为此服务器不监听 TCP,而是监听命名管道(Windows)或 UNIX 域套接字。还请注意 Windows 命名管道格式必须具有特定的模式,即名称前缀(`\\.\pipe\`),以便唯一标识[文件类型](https://docs.microsoft.com/windows/desktop/ipc/pipe-names)。TCP 和命名管道或 UNIX 域套接字之间的区别是微妙的,这与 [`accept`](@ref) 和 [`connect`](@ref) 方法有关。[`accept`](@ref) 方法检索到连接到我们刚创建的服务器的客户端的连接,而 [`connect`](@ref) 函数使用指定的方法连接到服务器。[`connect`](@ref) 函数接收与 [`listen`](@ref) 相同的参数,因此,假设环境(即 host、cwd 等)相同,你应该能够将相同的参数传递给 [`connect`](@ref),就像你在监听建立连接时所做的那样。那么让我们尝试一下(在创建上面的服务器之后): ```julia-repl julia> connect(2000) TCPSocket(open, 0 bytes waiting) julia> Hello World ``` 不出所料,我们看到「Hello World」被打印出来。那么,让我们分析一下幕后发生的事情。在我们调用 [`connect`](@ref) 时,我们连接到刚刚创建的服务器。与此同时,accept 函数返回到新创建的套接字的服务器端连接,并打印「Hello World」来表明连接成功。 Julia 的强大优势在于,即使 I/O 实际上是异步发生的,API 也以同步方式暴露,我们不必担心回调,甚至不必确保服务器能够运行。在我们调用 [`connect`](@ref) 时,当前任务等待建立连接,并在这之后才继续执行。在此暂停中,服务器任务恢复执行(因为现在有一个连接请求是可用的),接受该连接,打印信息并等待下一个客户端。读取和写入以同样的方式运行。为了理解这一点,请考虑以下简单的 echo 服务器: ```julia-repl julia> errormonitor(@async begin server = listen(2001) while true sock = accept(server) @async while isopen(sock) write(sock, readline(sock, keep=true)) end end end) Task (runnable) @0x00007fd31dc12e60 julia> clientside = connect(2001) TCPSocket(RawFD(28) open, 0 bytes waiting) julia> errormonitor(@async while isopen(clientside) write(stdout, readline(clientside, keep=true)) end) Task (runnable) @0x00007fd31dc11870 julia> println(clientside,"Hello World from the Echo Server") Hello World from the Echo Server ``` 与其他流一样,使用 [`close`](@ref) 即可断开该套接字: ```julia-repl julia> close(clientside) ``` ## 解析 IP 地址 与 [`listen`](@ref) 方法不一致的 [`connect`](@ref) 方法之一是 `connect(host::String,port)`,它将尝试连接到由 `host` 参数给定的主机上的由 `port` 参数给定的端口。它允许你执行以下操作: ```julia-repl julia> connect("google.com", 80) TCPSocket(RawFD(30) open, 0 bytes waiting) ``` 此功能的基础是 [`getaddrinfo`](@ref),它将执行适当的地址解析: ```julia-repl julia> getaddrinfo("google.com") ip"74.125.226.225" ``` ## 异步 I/O [`Base.read`](@ref) 和 [`Base.write`](@ref) 的所有 I/O 操作都可以通过使用 [coroutines](@ref man-tasks) 异步执行。 你可以使用 [`@async`](@ref) 宏创建一个新的协程来读取或写入流: ```julia-repl julia> task = @async open("foo.txt", "w") do io write(io, "Hello, World!") end; julia> wait(task) julia> readlines("foo.txt") 1-element Array{String,1}: "Hello, World!" ``` 通常会遇到您想要同时执行多个异步操作并等待它们全部完成的情况。你可以使用[`@ sync`](@ ref)宏,这会阻塞你的程序直到它所包裹的所有协程运行完毕。 ```julia-repl julia> using Sockets julia> @sync for hostname in ("google.com", "github.com", "julialang.org") @async begin conn = connect(hostname, 80) write(conn, "GET / HTTP/1.1\r\nHost:$(hostname)\r\n\r\n") readline(conn, keep=true) println("Finished connection to $(hostname)") end end Finished connection to google.com Finished connection to julialang.org Finished connection to github.com ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
18932
# 与其他语言的显著差异 ## [与 MATLAB 的显著差异](@id Noteworthy-differences-from-MATLAB) 虽然 MATLAB 用户可能会发现 Julia 的语法很熟悉,但 Julia 不是 MATLAB 的克隆。 它们之间存在重大的语法和功能差异。 以下是一些可能会使习惯于 MATLAB 的 Julia 用户感到困扰的显著差异: * Julia 数组使用方括号 `A[i,j]` 进行索引。 * Julia 数组在分配给另一个变量时不会被复制。 在`A = B`之后,改变`B`的元素也会改变`A`的元素。 * Julia 的值在向函数传递时不发生复制。如果某个函数修改了数组,这一修改对调用者是可见的。 * Julia 不会在赋值语句中自动增长数组。 而在 MATLAB 中 `a(4) = 3.2` 可以创建数组 `a = [0 0 0 3.2]`,而 `a(5) = 7` 可以将它增长为 `a = [0 0 0 3.2 7]`。如果 `a` 的长度小于 5 或者这个语句是第一次使用标识符 `a`,则相应的 Julia 语句 `a[5] = 7` 会抛出错误。Julia 使用 [`push!`](@ref) 和 [`append!`](@ref) 来增长 `Vector`,它们比 MATLAB 的 `a(end+1) = val` 更高效。 * 虚数单位 `sqrt(-1)` 在 Julia 中表示为 [`im`](@ref),而不是在 MATLAB 中的 `i` 或 `j`。 * 在 Julia 中,没有小数点的数字字面量(例如 `42`)会创建整数而不是浮点数。也支持任意大整数字面量。因此,某些操作(如 `2^-1`)将抛出 domain error,因为结果不是整数(有关的详细信息,请参阅[常见问题中有关 domain errors 的条目](@ref faq-domain-errors))。 在 Julia 中,没有小数点的数字字面量(例如 `42`)会创建整数而不是浮点数。因此,某些操作会因为需要浮点数而抛出 domain error;例如 `julia > a = -1; 2^a` ,因为结果不是整数了。请参阅[常见问题中有关 domain errors 的条目](@ref faq-domain-errors))。 * 在 Julia 中,能返回多个值并将其赋值为元组,例如 `(a, b) = (1, 2)` 或 `a, b = 1, 2`。 在 Julia 中不存在 MATLAB 的 `nargout`,它通常在 MATLAB 中用于根据返回值的数量执行可选工作。取而代之的是,用户可以使用可选参数和关键字参数来实现类似的功能。 * Julia 拥有真正的一维数组。列向量的大小为 `N`,而不是 `Nx1`。例如,[`rand(N)`](@ref) 创建一个一维数组。 * 在 Julia 中,`[x,y,z]` 将始终构造一个包含`x`、`y` 和 `z` 的 3 元数组。 - 要在第一个维度(「垂直列」)中连接元素,请使用 [`vcat(x,y,z)`](@ref) 或用分号分隔(`[x; y; z]`)。 - 要在第二个维度(「水平行」)中连接元素,请使用 [`hcat(x,y,z)`](@ref) 或用空格分隔(`[x y z]`)。 - 要构造分块矩阵(在前两个维度中连接元素),请使用 [`hvcat`](@ref) 或组合空格和分号(`[a b; c d]`)。 * 在 Julia 中,`a:b` 和 `a:b:c` 构造 `AbstractRange` 对象。使用 [`collect(a:b)`](@ref) 构造一个类似 MATLAB 中完整的向量。通常,不需要调用 `collect`。在大多数情况下,`AbstractRange` 对象将像普通数组一样运行,但效率更高,因为它是懒惰求值。这种创建专用对象而不是完整数组的模式经常被使用,并且也可以在诸如 [`range`](@ref) 之类的函数中看到,或者在诸如 `enumerate` 和 `zip` 之类的迭代器中看到。特殊对象大多可以像正常数组一样使用。 * Julia 中的函数返回其最后一个表达式或 `return` 关键字的值而无需在函数定义中列出要返回的变量的名称(有关详细信息,请参阅 [return 关键字](@ref))。 * Julia 脚本可以包含任意数量的函数,并且在加载文件时,所有定义都将在外部可见。可以从当前工作目录之外的文件加载函数定义。 * 在 Julia 中,例如 [`sum`](@ref)、[`prod`](@ref) 和 [`max`](@ref) 的归约操作会作用到数组的每一个元素上,当调用时只有一个函数,例如 `sum(A)`,即使 `A` 并不只有一个维度。 * 在 Julia 中,调用无参数的函数时必须使用小括号,例如 [`rand()`](@ref)。 * Julia 不鼓励使用分号来结束语句。语句的结果不会自动打印(除了在 REPL 中),并且代码的一行不必使用分号结尾。[`println`](@ref) 或者 [`@printf`](@ref) 能用来打印特定输出。 * 在 Julia 中,如果 `A` 和 `B` 是数组,像 `A == B` 这样的逻辑比较运算符不会返回布尔值数组。相反地,请使用 `A .== B`。对于其他的像是 [`<`](@ref)、[`>`](@ref) 的布尔运算符同理。 * 在 Julia 中,运算符[`&`](@ref)、[`|`](@ref) 和 [`⊻`](@ref xor)([`xor`](@ref))进行按位操作,分别与MATLAB中的`and`、`or` 和 `xor` 等价,并且优先级与 Python 的按位运算符相似(不像 C)。他们可以对标量运算或者数组中逐元素运算,可以用来合并逻辑数组,但是注意运算顺序的区别:括号可能是必要的(例如,选择 `A` 中等于 1 或 2 的元素可使用 `(A .== 1) .| (A .== 2)`)。 * 在 Julia 中,集合的元素可以使用 splat 运算符 `...` 来作为参数传递给函数,如 `xs=[1,2]; f(xs...)`。 * Julia 的 [`svd`](@ref) 将奇异值作为向量而非密集对角矩阵返回。 * 在 Julia 中,`...` 不用于延续代码行。不同的是,Julia 中不完整的表达式会自动延续到下一行。 * 在 Julia 和 MATLAB 中,变量 `ans` 被设置为交互式会话中提交的最后一个表达式的值。在 Julia 中与 MATLAB 不同的是,当 Julia 代码以非交互式模式运行时并不会设置 `ans`。 * Julia 的 `struct` 不支持在运行时动态地添加字段,这与 MATLAB 的 `class` 不同。 如需支持,请使用 [`Dict`](@ref)。Julia 中的字典不是有序的。 * 在 Julia 中,每个模块有自身的全局作用域/命名空间,而在 MATLAB 中只有一个全局作用域。 * 在 MATLAB 中,删除不需要的值的惯用方法是使用逻辑索引,如表达式 `x(x>3)` 或语句 `x(x>3) = []` 来 in-place 修改 `x`。相比之下,Julia 提供了更高阶的函数 [`filter`](@ref) 和 [`filter!`](@ref),允许用户编写 `filter(z->z>3, x)` 和 `filter!(z->z>3, x)` 来代替相应直译 `x[x.>3]` 和 `x = x[x.>3]`。使用 [`filter!`](@ref) 可以减少临时数组的使用。 * 类似于提取(或「解引用」)元胞数组的所有元素的操作,例如 MATLAB 中的 `vertcat(A{:})`,在 Julia 中是使用 splat 运算符编写的,例如 `vcat(A...)`。 * 在 Julia 中,`adjoint` 函数执行共轭转置;在 MATLAB 中,`adjoint` 提供了经典伴随,它是余子式的转置。 * 在 Julia 中,a^b^c 被认为是 a^(b^c) 而在 MATLAB 中它是 (a^b)^c。 ## [与 R 的显著差异](@id Noteworthy-differences-from-R) Julia 的目标之一是为数据分析和统计编程提供高效的语言。对于从 R 转到 Julia 的用户来说,这是一些显著差异: * Julia 的单引号封闭字符,而不是字符串。 * Julia 可以通过索引字符串来创建子字符串。在 R 中,在创建子字符串之前必须将字符串转换为字符向量。 * 在 Julia 中,与 Python 相同但与 R 不同的是,字符串可由三重引号 `""" ... """` 创建。此语法对于构造包含换行符的字符串很方便。 * 在 Julia 中,可变参数使用 splat 运算符 `...` 指定,该运算符总是跟在具体变量的名称后面,与 R 的不同,R 的 `...` 可以单独出现。 * 在 Julia 中,模数是 `mod(a, b)`,而不是 `a %% b`。Julia 中的 `%` 是余数运算符。 * 在 Julia 中,并非所有数据结构都支持逻辑索引。此外,Julia 中的逻辑索引只支持长度等于被索引对象的向量。例如: * 在 R 中,`c(1, 2, 3, 4)[c(TRUE, FALSE)]` 等价于 `c(1, 3)`。 * 在 R 中,`c(1, 2, 3, 4)[c(TRUE, FALSE, TRUE, FALSE)]` 等价于 `c(1, 3)`。 * 在 Julia 中,`[1, 2, 3, 4][[true, false]]` 抛出 [`BoundsError`](@ref)。 * 在 Julia 中,`[1, 2, 3, 4][[true, false, true, false]]` 产生 `[1, 3]`。 * 与许多语言一样,Julia 并不总是允许对不同长度的向量进行操作,与 R 不同,R 中的向量只需要共享一个公共的索引范围。例如,`c(1, 2, 3, 4) + c(1, 2)` 是有效的 R,但等价的 `[1, 2, 3, 4] + [1, 2]` 在 Julia 中会抛出一个错误。 * 在逗号不改变代码含义时,Julia 允许使用可选的尾随括号。在索引数组时,这可能在 R 用户间造成混淆。例如,R 中的 `x[1,]` 将返回矩阵的第一行;但是,在 Julia 中,引号被忽略,于是 `x[1,] == x[1]`,并且将返回第一个元素。要提取一行,请务必使用 `:`,如 `x[1,:]`。 * Julia 的 [`map`](@ref) 首先接受函数,然后是该函数的参数,这与 R 中的 `lapply(<structure>, function, ...)` 不同。类似地,R 中的 `apply(X, MARGIN, FUN, ...)` 等价于 Julia 的 [`mapslices`](@ref),其中函数是第一个参数。 * R 中的多变量 apply,如 `mapply(choose, 11:13, 1:3)`,在 Julia 中可以编写成 `broadcast(binomial, 11:13, 1:3)`。等价地,Julia 提供了更短的点语法来向量化函数 `binomial.(11:13, 1:3)`。 * Julia 使用 `end` 来表示条件块(如 `if`)、循环块(如 `while`/`for`)和函数的结束。为了代替单行 `if ( cond ) statement`,Julia 允许形式为 `if cond; statement; end`、`cond && statement` 和 `!cond || statement` 的语句。后两种语法中的赋值语句必须显式地包含在括号中,例如 `cond && (x = value)`,这是因为运算符的优先级。 * 在 Julia 中,`<-`, `<<-` 和 `->` 不是赋值运算符。 * Julia 的 `->` 创建一个匿名函数。 * Julia 使用括号构造向量。Julia 的 `[1, 2, 3]` 等价于 R 的 `c(1, 2, 3)`。 * Julia 的 [`*`](@ref) 运算符可以执行矩阵乘法,这与 R 不同。如果 `A` 和 `B` 都是矩阵,那么 `A * B` 在 Julia 中表示矩阵乘法,等价于 R 的 `A %*% B`。在 R 中,相同的符号将执行逐元素(Hadamard)乘积。要在 Julia 中使用逐元素乘法运算,你需要编写 `A .* B`。 * Julia 使用 `transpose` 函数来执行矩阵转置,使用 `'` 运算符或 `adjoint` 函数来执行共轭转置。因此,Julia 的 `transpose(A)` 等价于 R 的 `t(A)`。另外,Julia 中的非递归转置由 `permutedims` 函数提供。 * Julia 在编写 `if` 语句或 `for`/`while` 循环时不需要括号:请使用 `for i in [1, 2, 3]` 代替 `for (int i=1; i <= 3; i++)`,以及 `if i == 1` 代替 `if (i == 1)` * Julia 不把数字 `0` 和 `1` 视为布尔值。在 Julia 中不能编写 `if (1)`,因为 `if` 语句只接受布尔值。相反,可以编写 `if true`、`if Bool(1)` 或 `if 1==1`。 * Julia 不提供 `nrow` 和 `ncol`。相反,请使用 `size(M, 1)` 代替 `nrow(M)` 以及 `size(M, 2)` 代替 `ncol(M)` * Julia 仔细区分了标量、向量和矩阵。在 R 中,`1` 和 `c(1)` 是相同的。在 Julia 中,它们不能互换地使用。 * Julia 的 [`diag`](@ref) 和 [`diagm`](@ref) 与 R 的不同。 * Julia 赋值操作的左侧不能为函数调用的结果:你不能编写 `diag(M) = fill(1, n)`。 * Julia 不鼓励使用函数填充主命名空间。Julia 的大多数统计功能都可在 [JuliaStats 组织](https://github.com/JuliaStats)的[包](https://pkg.julialang.org/)中找到。例如: * 与概率分布相关的函数由 [Distributions 包](https://github.com/JuliaStats/Distributions.jl)提供。 * [DataFrames 包](https://github.com/JuliaData/DataFrames.jl)提供数据帧。 * 广义线性模型由 [GLM 包](https://github.com/JuliaStats/GLM.jl)提供。 * Julia 提供了元组和真正的哈希表,但不提供 R 风格的列表。在返回多个项时,通常应使用元组或具名元组:请使用 `(1, 2)` 或 `(a=1, b=2)` 代替 `list(a = 1, b = 2)`。 * Julia 鼓励用户编写自己的类型,它比 R 中的 S3 或 S4 对象更容易使用。Julia 的多重派发系统意味着 `table(x::TypeA)` 和 `table(x::TypeB)` 类似于 R 的 `table.TypeA(x)` 和 `table.TypeB(x)`。 * Julia 的值在向函数传递时不发生复制。如果某个函数修改了数组,这一修改对调用者是可见的。这与 R 非常不同,允许新函数更高效地操作大型数据结构。 * 在 Julia 中,向量和矩阵使用 [`hcat`](@ref)、[`vcat`](@ref) 和 [`hvcat`](@ref) 拼接,而不是像在 R 中那样使用 `c`、`rbind` 和 `cbind`。 * 在 Julia 中,像 `a:b` 这样的 range 不是 R 中的向量简写,而是一个专门的 `AbstractRange` 对象,该对象用于没有高内存开销地进行迭代。要将 range 转换为 vector,请使用 [`collect(a:b)`](@ref)。 * Julia 的 [`max`](@ref) 和 [`min`](@ref) 分别等价于 R 中的 `pmax` 和 `pmin`,但两者的参数都需要具有相同的维度。虽然 [`maximum`](@ref) 和 [`minimum`](@ref) 代替了 R 中的 `max` 和 `min`,但它们之间有重大区别。 * Julia 的 [`sum`](@ref)、[`prod`](@ref)、[`maximum`](@ref) 和 [`minimum`](@ref) 与它们在 R 中的对应物不同。它们都接受一个可选的关键字参数 `dims`,它表示执行操作的维度。例如,在 Julia 中令 `A = [1 2; 3 4]`,在 R 中令 `B <- rbind(c(1,2),c(3,4))` 是与之相同的矩阵。然后 `sum(A)` 得到与 `sum(B)` 相同的结果,但 `sum(A, dims=1)` 是一个包含每一列总和的行向量,`sum(A, dims=2)` 是一个包含每一行总和的列向量。这与 R 的行为形成了对比,在 R 中,单独的 `colSums(B)` 和 `rowSums(B)` 提供了这些功能。如果 `dims` 关键字参数是向量,则它指定执行求和的所有维度,并同时保持待求和数组的维数,例如 `sum(A, dims=(1,2)) == hcat(10)`。应该注意的是,没有针对第二个参数的错误检查。 * Julia 具有一些可以改变其参数的函数。例如,它具有 [`sort`](@ref) 和 [`sort!`](@ref)。 * 在 R 中,高性能需要向量化。在 Julia 中,这几乎恰恰相反:性能最高的代码通常通过去向量化的循环来实现。 * Julia 是立即求值的,不支持 R 风格的惰性求值。对于大多数用户来说,这意味着很少有未引用的表达式或列名。 * Julia 不支持 `NULL` 类型。最接近的等价物是 [`nothing`](@ref),但它的行为类似于标量值而不是列表。请使用 `x === nothing` 代替 `is.null(x)`。 * 在 Julia 中,缺失值由 [`missing`](@ref) 表示,而不是由 `NA` 表示。请使用 [`ismissing(x)`](@ref)(或者在向量上使用逐元素操作 `ismissing.(x)`)代替 `isna(x)`。通常使用 [`skipmissing`](@ref) 代替 `na.rm=TRUE`(尽管在某些特定情况下函数接受 `skipmissing` 参数)。 * Julia 缺少 R 中的 `assign` 或 `get` 的等价物。 * 在 Julia 中,`return` 不需要括号。 * 在 R 中,删除不需要的值的惯用方法是使用逻辑索引,如表达式 `x[x>3]` 或语句 `x = x[x>3]` 来 in-place 修改 `x`。相比之下,Julia 提供了更高阶的函数 [`filter`](@ref) 和 [`filter!`](@ref),允许用户编写 `filter(z->z>3, x)` 和 `filter!(z->z>3, x)` 来代替相应直译 `x[x.>3]` 和 `x = x[x.>3]`。使用 [`filter!`](@ref) 可以减少临时数组的使用。 ## [与 Python 的显著差异](@id Noteworthy-differences-from-Python) * Julia 的 `for`, `if`, `while` 等语句块都以 `end` 关键字结束。代码的缩进不像在 Python 中那样重要。Julia 也没有 `pass` 关键字。 * Julia 中的字符串使用双引号构造,如 `"text"`,也可以使用三引号构造多行字符串。而在 Python 中可以使用单引号(`'text'`)或者双引号(`"text"`)。单引号在 Julia 中用来表示单个字符,例如 `'c'`。 * 在 Julia 中字符串的拼接使用 `*`,而不是像 Python 一样使用 `+`。类似的,字符串重复多次 Julia 使用 `^` 而不是 `*`。Julia 也不支持隐式的字符串拼接,例如 Python 中的 `'ab' 'cd' == 'abcd'`。 * Python 列表——灵活但缓慢——对应于 Julia 的 `Vector{Any}` 类型或更一般的 `Vector{T}`,其中 `T` 是一些非具体元素类型。 “快”的数组,如 NumPy 数组,它们就地存储元素(即,`dtype` 是 `np.float64`、`[('f1', np.uint64), ('f2', np.int32)]`, 等)可以用 `Array{T}` 表示,其中 `T` 是一个具体的、不可变的元素类型。 这包括内置类型,如 `Float64`、`Int32`、`Int64`,也包括更复杂的类型,如 `Tuple{UInt64,Float64}` 和许多用户定义的类型。 * 在 Julia 中,数组、字符串等的索引从 1 开始,而不是从 0 开始。 * Julia 里的切片包含最后一个元素。Julia 里的 `a[2:3]` 等同于 Python 中的 `a[1:3]`。 * Julia 不支持负数索引。特别地,列表或数组的最后一个元素在 Julia 中使用 `end` 索引,而不像在 Python 中使用 `-1`。 * Julia 的索引必须写全。Python 中的 `x[1:]` 等价于 Julia 中的 `x[2:end]`。 * Julia 的范围语法为 `x[start:step:stop]`,而 Python 的格式为 `x[start:(stop+1):step]`。 因此 Python 中的 `x[0:10:2]` 等价于 Julia 里的 `x[1:2:10]`。类似的 Python 中的反转数组 `x[::-1]` 等价于 Julia 中的 `x[end:-1:1]`。 * 在 Julia 中队一个矩阵取索引 `X[[1,2], [1,3]]` 返回一个子矩阵,它包含了第一和第二行与第一和第三列的交集。 在 Python 中 `X[[1,2], [1,3]]` 返回一个向量,它包含索引 `[1,1]` 和 `[2,3]` 的值。Julia 中的 `X[[1,2], [1,3]]` 等价于 Python 中的 `X[np.ix_([0,1],[0,2])]`。Python 中的 `X[[1,2], [1,3]]` 等价于 Julia 中的 `X[[CartesianIndex(1,1), CartesianIndex(2,3)]]`。 * Julia 没有用来续行的语法:如果在行的末尾,到目前为止的输入是一个完整的表达式,则认为其已经结束;否则,认为输入继续。强制表达式继续的一种方式是将其包含在括号中。 * 默认情况下,Julia 数组是列优先(Fortran 排序),而 NumPy 数组是行优先(C 排序)。为了在循环数组时获得最佳性能,Julia 中的循环顺序应相对于 NumPy 颠倒(请参阅[性能提示的相关部分](@ref man-performance-column-major))。 * Julia 的更新运算符(例如 `+=`,`-=`,···)是非原位操作(not in-place),而 Numpy 的是。这意味着 `A = [1, 1]; B = A; B += [3, 3]` 不会改变 `A` 中的值,而将名称 `B` 重新绑定到右侧表达式 `B = B + 3` 的结果,这是一个新的数组。对于 in-place 操作,使用 `B .+= 3`(另请参阅 [dot operators](@ref man-dot-operators))、显式的循环或者 `InplaceOps.jl`。 * Julia 的函数在调用时,每次都对默认参数重新求值,不像 Python 只在函数定义时对默认参数求一次值。 举例来说:Julia 的函数 `f(x=rand()) = x` 在无参数调用时(`f()`),每次都会返回不同的随机数。 另一方面,函数 `g(x=[1,2]) = push!(x,3)` 无参数调用时 `g()`,永远返回 `[1,2,3]`。 * 在 Julia 中,必须使用关键字来传递关键字参数,这与 Python 中通常可以按位置传递它们不同。尝试按位置传递关键字参数会改变方法签名,从而导致 `MethodError` 或调用错误的方法。 * 在 Julia 中,`%` 是余数运算符,而在 Python 中是模运算符。 (译注:二者在参数有负数时有区别) * 在 Julia 中,常用的整数类型 Int 对应机器的整数类型,`Int32` 或 `Int64`。不像 Python 中的整数 int 是任意精度的。这意味着 Julia 中默认的整数类型会溢出,因此 `2^64 == 0`。如果你要表示一个大数,请选择一个合适的类型。如:`Int128`、任意精度的 `BigInt` 或者浮点类型 `Flost64`。 * Julia 中虚数单位 `sqrt(-1)` 是 `im`,而不是 Python 中的 `j`。 * Julia 中指数是 `^`,而不是 Python 中的 `**`。 * Julia 使用 `Nothing` 类型的实例 `nothing` 代表空值(null),而不是 Python 中 `NoneType` 类的 `None`。 * 在 Julia 中,标准的运算符作用在矩阵上就得到矩阵操作,不像 Python 标准运算符默认是逐元素操作。当 A 和 B 都是矩阵时,`A * B` 在 Julia 中代表着矩阵乘法,而不是 Python 中的逐元素相乘。即:Julia 中的 `A * B` 等同于 Python 的 `A @ B`;Python 中的 `A * B` 等同于 Julia 中的 `A .* B`。 * Julia 中的伴随操作符 `'` 返回向量的转置(一种行向量的懒惰表示法)。Python 中对向量执行 `.T` 返回它本身(没有效果)。 * 在Julia中,一个函数可能包含多个具体实现(称为*方法*),与Python中的函数相比,这些实现是根据调用的所有参数的类型通过多重派发选择的,它只有一个实现,没有多态性(与Python方法调用相反,Python方法调用使用不同的语法,并允许在方法的接收者上进行派发)。 * Julia 没有类(class),取而代替的是结构体(structures),可以是可变的或不可变的,它们只包含数据而不包含方法。 * 在 Python 中调用类实例的方法 (`x = MyClass(*args); x.f(y)`) 对应于 Julia 中的函数调用,例如 `x = MyType(args...); f(x, y)`。 总的来说,多重派发比 Python 类系统更灵活和强大。 * Julia 的结构体有且只能有一个抽象超类型(abstract supertype),而 Python 的类可以纪成一个或多个、抽象或具体的超类(superclasses)。 * 逻辑 Julia 程序结构(包和模块)独立于文件结构(`include` 用于附加文件),而 Python 代码结构由目录(包)和文件(模块)定义。 * Julia 中的三元运算符 `x > 0 ? 1 : -1` 对应于 Python 中的条件表达式 `1 if x > 0 else -1`。 * Julia 中以 `@` 开头的符号是宏(macro),而 Python 中是装饰器(decorator)。 * Julia 的异常处理使用 `try` — `catch` — `finally`,而不是 Python 的 `try` — `except` — `finally`。与 Python 不同的是,因为性能的原因,Julia 不推荐在正常流程中使用异常处理。 * Julia 的循环很快,所以没必要手动向量化(vectorized)。 * 小心 Julia 中的非常量全局变量,尤其它出现在循环中时。因为你在 Julia 中可以写出贴近硬件的代码,这时使用全局变量的影响非常大(参见[性能建议](@ref man-performance-tips)) * Python 中大多数的值都能用在逻辑运算中。例如:`if "a"` 永真,`if ""` 恒假。在 Julia 中你只能使用布尔类型的值,或者显示的将其他值转为布尔类型,否则就会抛出异常。例如当你想测试字符串是否为空是,请使用 `if !isempty("")`。 * 在 Julia 中大多数代码块都会引入新的本地作用域(local scope)。例如:循环和异常处理的 try — catch — finally。注意:列表推断(comprehensions)与生成器在 Julia 和 Python 中都会引入新的作用域;而 if 分支则都不会引入。 ## [与 C/C++ 的显著差异](@id Noteworthy-differences-from-C/C++) * Julia 的数组由方括号索引,方括号中可以包含不止一个维度 `A[i,j]`。这样的语法不仅仅是像 C/C++ 中那样对指针或者地址引用的语法糖,参见[关于数组构造的语法的 Julia 文档](@ref man-multi-dim-arrays)。 * 在 Julia 中,数组、字符串等的索引从 1 开始,而不是从 0 开始。 * Julia 的数组在赋值给另一个变量时不发生复制。执行 `A = B` 后,改变 `B` 中元素也会修改 `A`。像 `+=` 这样的更新运算符不会以 in-place 的方式执行,而是相当于 `A = A + B`,将左侧绑定到右侧表达式的计算结果上。 * Julia 的数组是列优先的(Fortran 顺序),而 C/C++ 的数组默认是行优先的。要使数组上的循环性能最优,在 Julia 中循环的顺序应该与 C/C++ 相反(参见 [性能建议](@ref man-performance-tips))。 * Julia 的值在赋值或向函数传递时不发生复制。如果某个函数修改了数组,这一修改对调用者是可见的。 * 在 Julia 中,空格是有意义的,这与 C/C++ 不同,所以向 Julia 程序中添加或删除空格时必须谨慎。 * 在 Julia 中,没有小数点的数值字面量(如 `42`)生成有符号整数,类型为 `Int`,但如果字面量太长,超过了机器字长,则会被自动提升为容量更大的类型,例如 `Int64`(如果 `Int` 是 `Int32`)、`Int128`,或者任意精度的 `BigInt` 类型。不存在诸如 `L`, `LL`, `U`, `UL`, `ULL` 这样的数值字面量后缀指示无符号和/或有符号与无符号。十进制字面量始终是有符号的,十六进制字面量(像 C/C++ 一样由 `0x` 开头)是无符号的。另外,十六进制字面量与 C/C++/Java 不同,也与 Julia 中的十进制字面量不同,它们的类型取决于字面量的**长度**,包括开头的 0。例如,`0x0` 和 `0x00` 的类型是 [`UInt8`](@ref),`0x000` 和 `0x0000` 的类型是 [`UInt16`](@ref)。同理,字面量的长度在 5-8 之间,类型为 `UInt32`;在 9-16 之间,类型为 `UInt64`;在 17-32 之间,类型为 `UInt128`。当定义十六进制掩码时,就需要将这一问题考虑在内,比如 `~0xf == 0xf0` 与 `~0x000f == 0xfff0` 完全不同。64 位 `Float64` 和 32 位 [`Float32`](@ref) 的字面量分别表示为 `1.0` 和 `1.0f0`。浮点字面量在无法被精确表示时舍入(且不会提升为 `BigFloat` 类型)。浮点字面量在行为上与 C/C++ 更接近。八进制(前缀为 `0o`)和二进制(前缀为 `0b`)也被视为无符号的。 * 在 Julia 中,当两个操作数都是整数类型时,除法运算符 `/` 返回一个浮点数。 要执行整数除法,请使用 `div` 或 `÷`。 * 使用浮点类型索引数组在 Julia 中通常是错误的。 C 表达式 `a[i / 2]` 的 Julia 等价写法是 `a[i ÷ 2 + 1]`,其中 `i` 是整数类型。 * 字符串字面量可用 `"` 或 `"""` 分隔,用 `"""` 分隔的字面量可以包含 `"` 字符而无需像 `"\""` 这样来引用它。字符串字面量可以包含插入其中的其他变量或表达式,由 `$variablename` 或 `$(expression)` 表示,它在该函数所处的上下文中计算变量名或表达式。 * `//` 表示 [`Rational`](@ref) 数,而非单行注释(其在 Julia 中是 `#`) * `#=` 表示多行注释的开头,`=#` 结束之。 * Julia 中的函数返回其最后一个表达式或 `return` 关键字的值。可以从函数中返回多个值并将其作为元组赋值,如 `(a, b) = myfunction()` 或 `a, b = myfunction()`,而不必像在 C/C++ 中那样必须传递指向值的指针(即 `a = myfunction(&b)`)。 * Julia 不要求使用分号来结束语句。表达式的结果不会自动打印(除了在交互式提示符中,即 REPL),且代码行不需要以分号结尾。[`println`](@ref) 或 [`@printf`](@ref) 可用于打印特定输出。在 REPL 中,`;` 可用于抑制输出。`;` 在 `[ ]` 中也有不同的含义,需要注意。`;` 可用于在单行中分隔表达式,但在许多情况下不是绝对必要的,更经常是为了可读性。 * 在 Julia 中,运算符 [`⊻`](@ref xor)([`xor`](@ref))执行按位 XOR 操作,即 C/C++ 中的 [`^`](@ref)。此外,按位运算符不具有与 C/C++ 相同的优先级,所以可能需要括号。 * Julia 的 [`^`](@ref) 是取幂(pow),而非 C/C++ 中的按位 XOR(在 Julia 中请使用 [`⊻`](@ref xor) 或 `xor`) * Julia 有两个右移运算符,`>>` 和 `>>>`。 `>>` 执行算术移位,`>>>` 始终执行逻辑移位,这与 C/C++ 不同,其中 `>>` 的含义取决于被移位的值的类型。 * Julia 的 `->` 创建一个匿名函数,它并不通过指针访问成员。 * Julia 在编写 `if` 语句或 `for`/`while` 循环时不需要括号:请使用 `for i in [1, 2, 3]` 代替 `for (int i=1; i <= 3; i++)`,以及 `if i == 1` 代替 `if (i == 1)` * Julia 不把数字 `0` 和 `1` 视为布尔值。在 Julia 中不能编写 `if (1)`,因为 `if` 语句只接受布尔值。相反,可以编写 `if true`、`if Bool(1)` 或 `if 1==1`。 * Julia 使用 `end` 来表示条件块(如 `if`)、循环块(如 `while`/`for`)和函数的结束。为了代替单行 `if ( cond ) statement`,Julia 允许形式为 `if cond; statement; end`、`cond && statement` 和 `!cond || statement` 的语句。后两种语法中的赋值语句必须显式地包含在括号中,例如 `cond && (x = value)`,这是因为运算符的优先级。 * Julia 没有用来续行的语法:如果在行的末尾,到目前为止的输入是一个完整的表达式,则认为其已经结束;否则,认为输入继续。强制表达式继续的一种方式是将其包含在括号中。 * Julia 宏对已解析的表达式进行操作,而非程序的文本,这允许它们执行复杂的 Julia 代码转换。宏名称以 `@` 字符开头,具有类似函数的语法 `@mymacro(arg1, arg2, arg3)` 和类似语句的语法 `@mymacro arg1 arg2 arg3`。两种形式的语法可以相互转换;如果宏出现在另一个表达式中,则类似函数的形式尤其有用,并且它通常是最清晰的。类似语句的形式通常用于标注块,如在分布式 `for` 结构中:`@distributed for i in 1:n; #= body =#; end`。如果宏结构的结尾不那么清晰,请使用类似函数的形式。 * Julia 有一个枚举类型,使用宏 `@enum(name, value1, value2, ...)` 来表示,例如:`@enum(Fruit, banana=1, apple, pear)`。 * 按照惯例,修改其参数的函数在名称的末尾有个 `!`,例如 `push!`。 * 在 C++ 中,默认情况下,你具有静态分派,即为了支持动态派发,你需要将函数标注为 virtual 函数。另一方面,Julia 中的每个方法都是「virtual」(尽管它更通用,因为方法是在每个参数类型上派发的,而不仅仅是 `this`,并且使用的是最具体的声明规则)。 ## [与 Common Lisp 的显著差异](@id Noteworthy-differences-from-Common-Lisp) - Julia 默认使用 1 开始的数组索引,它也能处理任意的[索引顺序](@ref man-custom-indices)。 - 函数和变量共用一个命名空间("Lisp-1")。 - Julia 中有 [`Pair`](@ref) 类型,但这并不意味着它能用作 `COMMON-LISP:CONS`。在 Julia 中绝大多数可迭代的集合都能互换使用,例如:集合解包(splatting)、元组等。`Tuple` 最接近 Common Lisp 中用于异构元素的**短**列表。使用 `NamedTuple` 来代替关联表(alists)。对于更大的、同类型元素的集合,应该使用 `Array` 和 `Dict`。 - 典型的使用 Julia 进行原型开发时,也会对镜像进行连续的修改,[Revise.jl](https://github.com/timholy/Revise.jl) 包提供了这个功能。 - 对于性能,Julia 更喜欢操作具有 [类型稳定性](@ref man-type-stability)。 Common Lisp 从底层机器操作中抽象出来,而 Julia 则更接近它们。 例如: - 使用 `/` 的整数除法总是返回浮点结果,即使计算是精确的。 - `//` 总是返回一个有理数结果 - `÷` 总是返回一个(被截断的)整数结果 - Julia 支持大整数,但不会自动转换。默认的整数类型会[溢出](@ref faq-integer-arithmetic)。 - 支持复数,但要获得复数结果,[你需要复数输入](@ref faq-domain-errors)。 - 有多种 Complex 和 Rational 类型,具有不同的组成类型。 - 模块(名称空间)可以是分层的。[`import`](@ref) 和 [`using`](@ref) 有着双重角色:他们加载代码并让代码在命名空间中可用。`import` 用于仅有模块名是可用的情况,大致等价于 `ASDF:LOAD-OP`。槽名(Slot name)不需要单独导出。全局变量不能从模块的外部赋值,除了 `eval(mod, :(var = val))` 这个例外情况。 - 宏以 `@` 开头,并没有像 Common Lisp 那样无缝地集成到语言中;因此在 Julia 中,宏的使用不像在 Common Lisp 中那样广泛。Julia 支持[宏](@ref Metaprogramming)的一种卫生(hygiene)形式。因为不同的表层语法,Julia 中没有 `COMMON-LISP:&BODY` 的等价形式。 - **所有的**函数都是通用的并且使用多重分派。函数的参数列表也无需遵循一样的模板,这让我们有了一个强大的范式:[`do`](@ref)。可选参数与关键字参数的处理方式不同。方法的歧义没有像在 Common Lisp 对象系统中那样得到解决,因此需要为交集定义更具体的方法。 - 符号不属于任何包,它**本身**也不包含任何值。`M.var` 会对 `M` 模块里的  `var` 符号求值。 - Julia 完全支持函数式编程风格,包括闭包等特性。但这并不是 Julia 的惯用风格。修改捕获变量时需要一些额外的[变通](@ref man-performance-captured)以便提高性能。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
1010
# 并行计算 Julia 支持这四类并发和并行编程: 1. **异步“任务”或协程**: Julia Tasks 允许暂停和恢复 I/O、事件处理、生产者-消费者进程和类似模式的计算。 Tasks 可以通过[`wail`](@ref) 和[`fetch`](@ref) 等操作进行同步,并通过 [`Channel`](@ref) 进行通信。 虽然严格来说不是并行计算,但 Julia 允许在多个线程上调度任务。 2. **多线程**: Julia 的[多线程](@ref man-multithreading)提供了在多个线程、CPU 内核或共享内存上同时调度任务的能力。这通常是在个人 PC 或单个大型多核服务器上获得并行性的最简单方法。 Julia 的多线程是可组合的。当一个多线程函数调用另一个多线程函数时,Julia 将在可用资源上全局调度所有线程,而不会超额使用。 3. **分布式计算**: 分布式计算运行多个具有独立内存空间的 Julia 进程。 这些可以在同一台计算机或多台计算机上。 `Distributed` 标准库提供了远程执行 Julia 函数的能力。 使用这个基本构建块,可以构建许多不同类型的分布式计算抽象。 像 [`DistributedArrays.jl`](https://github.com/JuliaParallel/DistributedArrays.jl) 这样的包就是这种抽象的一个示例。 另一方面,像 [`MPI.jl`](https://github.com/JuliaParallel/MPI.jl) 和 [`Elemental.jl`](https://github.com/JuliaParallel/Elemental.jl) 这样的包提供对现有 MPI 生态库的访问。 4. **GPU 计算**: Julia GPU 编译器提供了在 GPU 上本地运行 Julia 代码的能力。 有一个针对 GPU 的丰富的 Julia 软件包生态系统。 [JuliaGPU.org](https://juliagpu.org) 网站提供了功能列表、支持的 GPU、相关包和文档。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
32995
# [性能建议](@id man-performance-tips) 下面几节简要地介绍了一些使 Julia 代码运行得尽可能快的技巧。 ## 影响性能的关键代码应该在函数内部 任何对性能至关重要的代码都应该在函数内部。 由于 Julia 编译器的工作方式,函数内部的代码往往比顶层代码运行得更快。 函数的使用不仅对性能很重要:函数更可重用和可测试,并阐明正在执行哪些步骤以及它们的输入和输出是什么,[编写函数,而不仅仅是脚本](@ref)也是 Julia 的风格指南。 函数应该接收参数,而不是直接对全局变量进行操作,请参阅下一点。 ## 避免全局变量 全局变量的值和类型随时都会发生变化, 这使编译器难以优化使用全局变量的代码。 变量应该是局部的,或者尽可能作为参数传递给函数。 我们发现全局变量经常是常量,将它们声明为常量可大幅提升性能。 ```julia const DEFAULT_VAL = 0 ``` 对于非常量的全局变量可以通过在使用的时候标注它们的类型来优化。 ```julia global x = rand(1000) function loop_over_global() s = 0.0 for i in x::Vector{Float64} s += i end return s end ``` 一个更好的编程风格是将变量作为参数传给函数。这样可以使得代码更易复用,以及清晰的展示函数的输入和输出。 !!! note 所有的REPL中的代码都是在全局作用域中求值的,因此在顶层的变量的定义与赋值都会成为一个**全局**变量。在模块的顶层作用域定义的变量也是全局变量。 在下面的REPL会话中: ```julia-repl julia> x = 1.0 ``` 等价于: ```julia-repl julia> global x = 1.0 ``` 因此,所有上文关于性能问题的讨论都适用于它们。 ## 使用 [`@time`](@ref)评估性能以及注意内存分配 [`@time`](@ref) 宏是一个有用的性能评估工具。这里我们将重复上面全局变量的例子,但是这次移除类型声明: ```jldoctest; setup = :(using Random; Random.seed!(1234)), filter = r"[0-9\.]+ seconds \(.*?\)" julia> x = rand(1000); julia> function sum_global() s = 0.0 for i in x s += i end return s end; julia> @time sum_global() 0.010414 seconds (9.07 k allocations: 373.448 KiB, 98.40% compilation time) 493.6199223951192 julia> @time sum_global() 0.000108 seconds (3.49 k allocations: 70.156 KiB) 493.6199223951192 ``` 在第一次调用(`@time sum_global()`)时,函数被编译。 (如果不在此会话中使用 [`@time`](@ref),它还会编译计时所需的函数。)你不用把此次运行的结果放在心上。对于第二次运行,请注意,除了报告时间外,它还表明分配了大量内存。 我们在这里只是计算 64 位浮点数向量中所有元素的总和,因此不需要分配内存(至少不是在堆上,这就是 `@time` 报告的内容)。 预料之外的内存分配几乎总是表示你的代码存在问题,通常是类型稳定性问题或创建了许多小的临时数组。 因此,除了分配本身之外,你的函数的代码很可能远非最优。请认真对待此类迹象并遵循以下建议。 如果我们改为将 `x` 作为参数传递给函数,它不再分配内存(下面报告的分配是由于在全局范围内运行 `@time` 宏)并且在第一次调用后明显更快: ```jldoctest sumarg; setup = :(using Random; Random.seed!(1234)), filter = r"[0-9\.]+ seconds \(.*?\)" julia> x = rand(1000); julia> function sum_arg(x) s = 0.0 for i in x s += i end return s end; julia> @time sum_arg(x) 0.007971 seconds (3.96 k allocations: 200.171 KiB, 99.83% compilation time) 493.6199223951192 julia> @time sum_arg(x) 0.000003 seconds (1 allocation: 16 bytes) 493.6199223951192 ``` 看到的 1 allocation 来自在全局范围内运行 `@time` 宏本身。 如果我们改为在函数中运行计时,我们可以看到确实没有执行任何分配: ```jldoctest sumarg; filter = r"[0-9\.]+ seconds" julia> time_sum(x) = @time sum_arg(x); julia> time_sum(x) 0.000001 seconds 493.6199223951192 ``` 在某些情况下,你的函数可能需要将分配内存作为其操作的一部分,这比上面的简单例子复杂的多。 在这种情况下,请考虑使用下面的 [工具](@ref tools) 之一来诊断问题,或者编写一个将分配内存与算法方面分开的函数版本(请参阅 [输出预分配](@ref Pre-allocating outputs))。 !!! note 对于更严格的基准测试,请考虑 [BenchmarkTools.jl](https://github.com/JuliaCI/BenchmarkTools.jl) 包,该包会多次评估函数以减少噪音。 ## [工具](@id tools) Julia 及其包生态系统包括可以帮助您诊断问题和提高代码性能的工具: * [Profiling](@ref profiling) 允许你测量正在运行的代码的性能并识别作为瓶颈的行。对于复杂的项目,[ProfileView](https://github.com/timholy/ProfileView.jl) 包可以帮助你可视化分析结果。 * [Traceur](https://github.com/JunoLab/Traceur.jl) 包可以帮助你找到代码中常见的性能问题。 * 预期之外的大内存分配——正如 [`@time`](@ref)、[`@allocated`](@ref) 或 Profiler(通过调用垃圾收集例程)所报告的那样——暗示你的代码可能有问题。 如果你没有看到分配的其他原因,请怀疑是类型问题。还可以使用 `--track allocation=user` 选项启动 Julia 并检查生成的 `*.mem` 文件以查看有关这些分配发生位置的信息。 参见[内存分配分析](@ref memory-allocation-analysis)。 * `@code_warntype` 生成代码的表示形式,这有助于查找导致类型不确定性的表达式。 请参阅下面的 [`@code_warntype`](@ref)。 ## [避免使用抽象类型参数的容器](@id man-performance-abstract-container) 使用参数化类型(包括数组)时,最好尽可能避免使用抽象类型进行参数化。 考虑如下: ```jldoctest julia> a = Real[] Real[] julia> push!(a, 1); push!(a, 2.0); push!(a, π) 3-element Vector{Real}: 1 2.0 π = 3.1415926535897... ``` 因为 `a` 是一个抽象类型 [`Real`](@ref) 的数组,所以它能够保存任何 `Real` 值。 由于`Real`对象允许具有任意大小和结构,因此`a`必须表示为指向单独分配的`Real`对象的指针数组。 但是,如果我们只允许相同类型的数字,例如 [`Float64`](@ref), `a` 可以更有效地存储: ```jldoctest julia> a = Float64[] Float64[] julia> push!(a, 1); push!(a, 2.0); push!(a, π) 3-element Vector{Float64}: 1.0 2.0 3.141592653589793 ``` 把数字赋值给`a`会即时将数字转换成`Float64`并且`a`会按照64位浮点数值的连续的块来储存,这就能高效地处理。 如果无法避免使用抽象值类型的容器,有时最好使用`Any`参数化以避免运行时类型检查。 例如。 `IdDict{Any, Any}` 的性能优于 `IdDict{Type, Vector}`。 也请参见在[参数类型](@ref)下的讨论。 ## 类型声明 在有可选类型声明的语言中,添加声明是使代码运行更快的原则性方法。在Julia中*并不是*这种情况。在Julia中,编译器都知道所有的函数参数,局部变量和表达式的类型。但是,有一些特殊的情况下声明是有帮助的。 ### 避免有抽象类型的字段 类型能在不指定其字段的类型的情况下被声明: ```jldoctest myambig julia> struct MyAmbiguousType a end ``` 这就允许`a`可以是任意类型。这经常很有用,但是有个缺点:对于类型`MyAmbiguousType`的对象,编译器不能够生成高性能的代码。原因是编译器使用对象的类型,而非值,来确定如何构建代码。不幸的是,几乎没有信息可以从类型`MyAmbiguousType`的对象中推导出来: ```jldoctest myambig julia> b = MyAmbiguousType("Hello") MyAmbiguousType("Hello") julia> c = MyAmbiguousType(17) MyAmbiguousType(17) julia> typeof(b) MyAmbiguousType julia> typeof(c) MyAmbiguousType ``` `b` 和 `c` 的值具有相同类型,但它们在内存中的数据的底层表示十分不同。即使你只在字段 `a` 中存储数值,[`UInt8`](@ref) 的内存表示与 [`Float64`](@ref) 也是不同的,这也意味着 CPU 需要使用两种不同的指令来处理它们。因为该类型中不提供所需的信息,所以必须在运行时进行这些判断。而这会降低性能。 通过声明 `a` 的类型,你能够做得更好。这里我们关注 `a` 可能是几种类型中任意一种的情况,在这种情况下,自然的一个解决方法是使用参数。例如: ```jldoctest myambig2 julia> mutable struct MyType{T<:AbstractFloat} a::T end ``` 比下面这种更好 ```jldoctest myambig2 julia> mutable struct MyStillAmbiguousType a::AbstractFloat end ``` 因为第一种通过包装对象的类型指定了 `a` 的类型。 例如: ```jldoctest myambig2 julia> m = MyType(3.2) MyType{Float64}(3.2) julia> t = MyStillAmbiguousType(3.2) MyStillAmbiguousType(3.2) julia> typeof(m) MyType{Float64} julia> typeof(t) MyStillAmbiguousType ``` 字段 `a` 的类型可以很容易地通过 `m` 的类型确定,而不是通过 `t` 的类型确定。事实上,在 `t` 中是可以改变字段 `a` 的类型的: ```jldoctest myambig2 julia> typeof(t.a) Float64 julia> t.a = 4.5f0 4.5f0 julia> typeof(t.a) Float32 ``` 反之,一旦 `m` 被构建出来,`m.a` 的类型就不能够更改了。 ```jldoctest myambig2 julia> m.a = 4.5f0 4.5f0 julia> typeof(m.a) Float64 ``` `m.a` 的类型是通过 `m` 的类型得知这一事实加上它的类型不能改变在函数中改变这一事实,这两者使得对于像 `m` 这样的对象编译器可以生成高度优化后的代码,但是对 `t` 这样的对象却不可以。 当然,如果我们将 `m` 构造成一个具体类型,那么这两者都可以。我们可以通过明确地使用一个抽象类型去构建它来破坏这一点: ```jldoctest myambig2 julia> m = MyType{AbstractFloat}(3.2) MyType{AbstractFloat}(3.2) julia> typeof(m.a) Float64 julia> m.a = 4.5f0 4.5f0 julia> typeof(m.a) Float32 ``` 对于一个实际的目的来说,这样的对象表现起来和那些 `MyStillAmbiguousType` 的对象一模一样。 比较为一个简单函数生成的代码的绝对数量是十分有指导意义的, ```julia func(m::MyType) = m.a+1 ``` 使用 ```julia code_llvm(func, Tuple{MyType{Float64}}) code_llvm(func, Tuple{MyType{AbstractFloat}}) ``` 由于长度的原因,代码的结果没有在这里显示出来,但是你可能会希望自己去验证这一点。因为在第一种情况中,类型被完全指定了,在运行时,编译器不需要生成任何代码来决定类型。这就带来了更短和更快的代码。 ### 避免使用带抽象容器的字段 上面的做法同样也适用于容器的类型: ```jldoctest containers julia> struct MySimpleContainer{A<:AbstractVector} a::A end julia> struct MyAmbiguousContainer{T} a::AbstractVector{T} end ``` 例如: ```jldoctest containers julia> c = MySimpleContainer(1:3); julia> typeof(c) MySimpleContainer{UnitRange{Int64}} julia> c = MySimpleContainer([1:3;]); julia> typeof(c) MySimpleContainer{Vector{Int64}} julia> b = MyAmbiguousContainer(1:3); julia> typeof(b) MyAmbiguousContainer{Int64} julia> b = MyAmbiguousContainer([1:3;]); julia> typeof(b) MyAmbiguousContainer{Int64} ``` 对于 `MySimpleContainer` 来说,它被它的类型和参数完全确定了,因此编译器能够生成优化过的代码。在大多数实例中,这点能够实现。 尽管编译器现在可以将它的工作做得非常好,但是还是有**你**可能希望你的代码能够能够根据 `a` 的**元素类型**做不同的事情的时候。通常达成这个目的最好的方式是将你的具体操作 (here, `foo`) 打包到一个独立的函数中。 ```jldoctest containers julia> function sumfoo(c::MySimpleContainer) s = 0 for x in c.a s += foo(x) end s end sumfoo (generic function with 1 method) julia> foo(x::Integer) = x foo (generic function with 1 method) julia> foo(x::AbstractFloat) = round(x) foo (generic function with 2 methods) ``` 这使事情变得简单,同时也允许编译器在所有情况下生成经过优化的代码。 但是,在某些情况下,你可能需要声明外部函数的不同版本,这可能是为了不同的元素类型,也可能是为了 `MySimpleContainer` 中的字段 `a` 所具有的不同 `AbstractVector` 类型。你可以这样做: ```jldoctest containers julia> function myfunc(c::MySimpleContainer{<:AbstractArray{<:Integer}}) return c.a[1]+1 end myfunc (generic function with 1 method) julia> function myfunc(c::MySimpleContainer{<:AbstractArray{<:AbstractFloat}}) return c.a[1]+2 end myfunc (generic function with 2 methods) julia> function myfunc(c::MySimpleContainer{Vector{T}}) where T <: Integer return c.a[1]+3 end myfunc (generic function with 3 methods) ``` ```jldoctest containers julia> myfunc(MySimpleContainer(1:3)) 2 julia> myfunc(MySimpleContainer(1.0:3)) 3.0 julia> myfunc(MySimpleContainer([1:3;])) 4 ``` ### 对从无类型位置获取的值进行类型注释 使用可能包含任何类型的值的数据结构(如类型为 `Array{Any}` 的数组)经常是很方便的。但是,如果你正在使用这些数据结构之一,并且恰巧知道某个元素的类型,那么让编译器也知道这一点会有所帮助: ```julia function foo(a::Array{Any,1}) x = a[1]::Int32 b = x+1 ... end ``` 在这里,我们恰巧知道 `a` 的第一个元素是个 [`Int32`](@ref)。留下这样的注释还有另外的好处,它将在该值不是预期类型时引发运行时错误,而这可能会更早地捕获某些错误。 在没有确切知道 `a[1]` 的类型的情况下,`x` 可以通过 `x = convert(Int32, a[1])::Int32` 来声明。使用 [`convert`](@ref) 函数则允许 `a[1]` 是可转换为 `Int32` 的任何对象(比如 `UInt8`),从而通过放松类型限制来提高代码的通用性。请注意,`convert` 本身在此上下文中需要类型注释才能实现类型稳定性。这是因为除非该函数所有参数的类型都已知,否则编译器无法推导出该函数返回值的类型,即使其为 `convert`。 如果类型是抽象的或在运行时构造的,则类型注释不会增强(实际上可能会阻碍)性能。 这是因为编译器无法使用注解来特例化后续代码,并且类型检查本身需要时间。 例如,在代码中: ```julia function nr(a, prec) ctype = prec == 32 ? Float32 : Float64 b = Complex{ctype}(a) c = (b + 1.0f0)::Complex{ctype} abs(c) end ``` `c` 的注释会损害性能。要编写涉及在运行时构造类型的高性能代码,请使用下面讨论的 [函数障碍技巧](@ref kernel-functions),并确保构造的类型出现在内核函数的参数类型中,以便内核操作由编译器合理地特例化。例如,在上面的代码片段中,一旦构建了 `b`,它就可以传递给另一个函数 `k`,即内核。 例如,如果函数 `k` 将 `b` 声明为类型为 `Complex{T}` 的参数,其中 `T` 是一个类型参数,那么出现在`k`的赋值语句中的类型注释的形式: ```julia c = (b + 1.0f0)::Complex{T} ``` 不会降低性能(但也不会有帮助),因为编译器可以在编译 `k` 时确定 `c` 的类型。 ### [注意Julia何时避免特例化](@id Be-aware-of-when-Julia-avoids-specializing) 作为一种启发式方法,Julia 避免在三种特定情况下自动特例化参数类型参数:`Type`、`Function` 和 `Vararg`。 当在方法中使用参数时,Julia 将始终特例化,但如果参数只是传递给另一个函数,则不会。 这通常在运行时没有性能影响并且[提高编译器性能](@ref compiler-efficiency-issues)。 如果你发现它在你的案例中在运行时确实有性能影响,您可以通过向方法声明添加类型参数来触发特例化。这里有些例子: 这不会特例化: ```julia function f_type(t) # or t::Type x = ones(t, 10) return sum(map(sin, x)) end ``` 但是这会: ```julia function g_type(t::Type{T}) where T x = ones(T, 10) return sum(map(sin, x)) end ``` 这些不会特例化: ```julia f_func(f, num) = ntuple(f, div(num, 2)) g_func(g::Function, num) = ntuple(g, div(num, 2)) ``` 但是这会: ```julia h_func(h::H, num) where {H} = ntuple(h, div(num, 2)) ``` 这不会特例化: ```julia f_vararg(x::Int...) = tuple(x...) ``` 但是这会: ```julia g_vararg(x::Vararg{Int, N}) where {N} = tuple(x...) ``` 只需要引入一个类型参数就可以强制特例化,即使其他类型不受约束。比如下面这个例子,它会特例化,并且在参数不是全部相同类型时很有用: ```julia h_vararg(x::Vararg{Any, N}) where {N} = tuple(x...) ``` 请注意, [`@code_typed`](@ref) 和你的朋友给你的始终是特例化的代码,即使 Julia 通常不会特例化该方法调用。如果要查看更改参数类型时是否生成特例化,则需要检查 [method internals](@ref ast-lowered-method),即是否 `(@which f(...)).specializations` 包含相关参数的特例化。 ## 将函数拆分为多个定义 将一个函数写成许多小的定义能让编译器直接调用最适合的代码,甚至能够直接将它内联。 这是一个真的该被写成许多小的定义的**复合函数**的例子: ```julia using LinearAlgebra function mynorm(A) if isa(A, Vector) return sqrt(real(dot(A,A))) elseif isa(A, Matrix) return maximum(svdvals(A)) else error("mynorm: invalid argument") end end ``` 这可以更简洁有效地写成: ```julia norm(x::Vector) = sqrt(real(dot(x, x))) norm(A::Matrix) = maximum(svdvals(A)) ``` 然而,应该注意的是,编译器会十分高效地优化掉编写得如同 `mynorm` 例子的代码中的死分支。 ## 编写「类型稳定的」函数 如果可能,确保函数总是返回相同类型的值是有好处的。考虑以下定义: ```julia pos(x) = x < 0 ? 0 : x ``` 虽然这看起来挺合法的,但问题是 `0` 是一个(`Int` 类型的)整数而 `x` 可能是任何类型。于是,根据 `x` 的值,此函数可能返回两种类型中任何一种的值。这种行为是允许的,并且在某些情况下可能是合乎需要的。但它可以很容易地以如下方式修复: ```julia pos(x) = x < 0 ? zero(x) : x ``` 还有 [`oneunit`](@ref) 函数,以及更通用的 [`oftype(x, y)`](@ref) 函数,它返回被转换为 `x` 的类型的 `y`。 ## 避免更改变量类型 类似的「类型稳定性」问题存在于在函数内重复使用的变量: ```julia function foo() x = 1 for i = 1:10 x /= rand() end return x end ``` 局部变量 `x` 一开始是整数,在一次循环迭代后变为浮点数([`/`](@ref) 运算符的结果)。这使得编译器更难优化循环体。有几种可能的解决方法: * 使用 `x = 1.0` 初始化 `x` * 显式声明 `x` 的类型:`x::Float64 = 1` * 使用 `x = oneunit(Float64)` 进行显式的类型转换 * 使用第一个循环迭代初始化,即 `x = 1 / rand()`,接着循环 `for i = 2:10` ## [分离核心函数(又称为函数屏障)] (@id kernel-functions) 许多函数遵循这一模式:先执行一些设置工作,再通过多次迭代来执行核心计算。如果可行,将这些核心计算放在单独的函数中是个好主意。例如,以下做作的函数返回一个数组,其类型是随机选择的。 ```jldoctest; setup = :(using Random; Random.seed!(1234)) julia> function strange_twos(n) a = Vector{rand(Bool) ? Int64 : Float64}(undef, n) for i = 1:n a[i] = 2 end return a end; julia> strange_twos(3) 3-element Vector{Int64}: 2 2 2 ``` 它应该这么写: ```jldoctest; setup = :(using Random; Random.seed!(1234)) julia> function fill_twos!(a) for i = eachindex(a) a[i] = 2 end end; julia> function strange_twos(n) a = Vector{rand(Bool) ? Int64 : Float64}(undef, n) fill_twos!(a) return a end; julia> strange_twos(3) 3-element Vector{Int64}: 2 2 2 ``` Julia 的编译器会在函数边界处针对参数类型特化代码,因此在原始的实现中循环期间无法得知 `a` 的类型(因为它是随即选择的)。于是,第二个版本通常更快,因为对于不同类型的 `a`,内层循环都可被重新编译为 `fill_twos!` 的一部分。 第二种形式通常是更好的风格,并且可以带来更多的代码的重复利用。 这个模式在 Julia Base 的几个地方中有使用。相关的例子,请参阅 [`abstractarray.jl`](https://github.com/JuliaLang/julia/blob/40fe264f4ffaa29b749bcf42239a89abdcbba846/base/abstractarray.jl#L1205-L1206) 中的 `vcat` 和 `hcat`,或者 [`fill!`](@ref) 函数,我们可使用该函数而不是编写自己的 `fill_twos!`。 诸如 `strange_twos` 的函数会在处理具有不确定类型的数据时出现,例如从可能包含整数、浮点数、字符串或其它内容的输入文件中加载的数据。 ## [具有值作为参数的类型](@id man-performance-value-type) 比方说你想创建一个每个维度大小都是3的 `N` 维数组。这种数组可以这样创建: ```jldoctest julia> A = fill(5.0, (3, 3)) 3×3 Matrix{Float64}: 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 ``` 这个方法工作得很好:编译器可以识别出来 `A` 是一个 `Array{Float64,2}` 因为它知道填充值 (`5.0::Float64`) 的类型和维度 (`(3, 3)::NTuple{2,Int}`). 但是现在打比方说你想写一个函数,在任何一个维度下,它都创建一个 3×3×... 的数组;你可能会心动地写下一个函数 ```jldoctest julia> function array3(fillval, N) fill(fillval, ntuple(d->3, N)) end array3 (generic function with 1 method) julia> array3(5.0, 2) 3×3 Matrix{Float64}: 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 ``` 这确实有用,但是(你可以自己使用 `@code_warntype array3(5.0, 2)` 来验证)问题是输出地类型不能被推断出来:参数 `N` 是一个 `Int` 类型的**值**,而且类型推断不会(也不能)提前预测它的值。这意味着使用这个函数的结果的代码在每次获取 `A` 时都不得不保守地检查其类型;这样的代码将会是非常缓慢的。 现在,解决此类问题的一种很好的方法是使用 [函数障碍技巧](@ref kernel-functions)。 但是,在某些情况下,你可能希望完全消除类型不稳定性。 在这种情况下,一种方法是将维度作为参数传递,例如通过 `Val{T}()`(参见 ["Value types"](@ref)): ```jldoctest julia> function array3(fillval, ::Val{N}) where N fill(fillval, ntuple(d->3, Val(N))) end array3 (generic function with 1 method) julia> array3(5.0, Val(2)) 3×3 Matrix{Float64}: 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 5.0 ``` Julia 有一个特别版本的 `ntuple`,它接受一个 `Val{::Int}` 实例作为第二个参数; 通过将 `N` 作为类型参数传递,你可以让编译器知道它的“值”。 因此,这个版本的 `array3` 允许编译器预测返回类型。 然而,使用这些技术可能非常微妙。 例如,如果你从这样的函数中调用 `array3` 将没有任何帮助: ```julia function call_array3(fillval, n) A = array3(fillval, Val(n)) end ``` 在这里,你又一次创造了同样的问题:编译器无法猜测 `n` 是什么,所以它不知道 `Val(n)` 的 *类型*。 在许多情况下,尝试使用 `Val` 但不正确地使用很容易使性能*变差*。 (只有在有效地将 `Val` 与函数障碍技巧结合起来的情况下,为了使内核函数更有效,才应使用上述代码。) 一个正确使用 `Val` 的例子是这样的: ```julia function filter3(A::AbstractArray{T,N}) where {T,N} kernel = array3(1, Val(N)) filter(A, kernel) end ``` 在此示例中,`N` 作为参数传递,因此编译器知道其“值”。 本质上,`Val(T)` 仅在 `T` 是硬编码/i字面量 (`Val(3)`) 或已在类型域中指定时才起作用。 ## 滥用多重派发的危险(也就是更多关于以值作为参数的类型) 一旦一个人理解了多重派发,就会有一个倾向,即过度使用它并尝试将其用于所有事情。 例如,您可能会想象使用它来存储信息,例如 ``` struct Car{Make, Model} year::Int ...more fields... end ``` 然后派发到像 `Car{:Honda,:Accord}(year, args...)` 的对象上。 当存在以下任一情况,这可能是值得做的: * 你需要对每个 `Car` 进行 CPU 密集型处理,如果你在编译时知道 `Make` 和 `Model`,并且将使用的不同`Make`或`Model`的总数不太大,则效率会大大提高。 * 你需要处理相同类型的 `Car` 的同类列表,因此可以将它们全部存储在一个数组`{Car{:Honda,:Accord},N}` 中。 当后者成立时,处理此类同型数组的函数可以高效地特例化:Julia 预先知道每个元素的类型(容器中的所有对象都具有相同的具体类型),因此当函数被编译时, Julia 可以“查找”正确的方法调用(不需要在运行时检查),从而产生有效的代码来处理整个列表。 当这些都不成立时,你很可能不会获得任何好处;更糟糕的是,由此产生的“类型组合爆炸”将适得其反。 如果 `items[i+1]` 与 `item[i]` 的类型不同,Julia 必须在运行时查找类型,在方法表中搜索适当的方法,决定(通过类型交集)哪一个匹配,确定它是否已经被 JIT 编译(如果没有,则执行),然后进行调用。 本质上,你是在要求完整的类型系统和 JIT 编译机制在你自己的代码中基本上执行相当于 switch 语句或字典查找的操作。 [在邮件列表中](https://groups.google.com/forum/#!msg/julia-users/jUMu9A3QKQQ/qjgVWr7vAwAJ) 可以找到一些运行时基准比较 (1) 类型派发、(2) 字典查找和 (3) “switch”语句 也许比运行时影响更糟糕的是编译期影响:Julia 将为每个不同的 `Car{Make, Model}` 编译专门的函数; 如果你有成百上千个这样的类型,那么每个接受这样一个对象作为参数的函数(从你可能自己编写的自定义 `get_year` 函数,到 Julia Base 中的通用 `push!` 函数)都将成百上千个为它编译了的变体。 这些都会增加编译代码缓存的大小、内部方法列表的长度等。对值作为参数的过度热情很容易浪费大量资源。 ## [沿列按内存顺序访问数组](@id man-performance-column-major) Julia 中的多维数组以列主序存储。这意味着数组一次堆叠一列。这可使用 `vec` 函数或语法 `[:]` 来验证,如下所示(请注意,数组的顺序是 `[1 3 2 4]`,而不是 `[1 2 3 4]`): ```jldoctest julia> x = [1 2; 3 4] 2×2 Matrix{Int64}: 1 2 3 4 julia> x[:] 4-element Vector{Int64}: 1 3 2 4 ``` 这种对数组进行排序的约定在许多语言中都很常见,例如 Fortran、Matlab 和 R(仅举几例)。 列优先排序的替代方法是行优先排序,在其它语言中,这是 C 和 Python (`numpy`) 采用的约定。 在遍历数组时,记住数组的顺序会对性能产生显着的影响。 要记住的一个经验法则是,对于列优先数组,第一个索引变化最快。 本质上,这意味着如果最内层的循环索引是第一个出现在切片表达式中的,则循环会更快。 请记住,使用 `:` 索引数组是一个隐式循环,它迭代访问特定维度内的所有元素; 例如,提取列比提取行更快。 考虑以下人为示例。假设我们想编写一个接收 [`Vector`](@ref) 并返回方阵 [`Matrix`](@ref) 的函数,所返回方阵的行或列都用输入向量的副本填充。并假设用这些副本填充的是行还是列并不重要(也许可以很容易地相应调整剩余代码)。我们至少可以想到四种方式(除了建议的调用内置函数 [`repeat`](@ref)): ```julia function copy_cols(x::Vector{T}) where T inds = axes(x, 1) out = similar(Array{T}, inds, inds) for i = inds out[:, i] = x end return out end function copy_rows(x::Vector{T}) where T inds = axes(x, 1) out = similar(Array{T}, inds, inds) for i = inds out[i, :] = x end return out end function copy_col_row(x::Vector{T}) where T inds = axes(x, 1) out = similar(Array{T}, inds, inds) for col = inds, row = inds out[row, col] = x[row] end return out end function copy_row_col(x::Vector{T}) where T inds = axes(x, 1) out = similar(Array{T}, inds, inds) for row = inds, col = inds out[row, col] = x[col] end return out end ``` 现在,我们使用相同的 `10000` 乘 `1` 的随机输入向量来对这些函数计时。 ```julia-repl julia> x = randn(10000); julia> fmt(f) = println(rpad(string(f)*": ", 14, ' '), @elapsed f(x)) julia> map(fmt, [copy_cols, copy_rows, copy_col_row, copy_row_col]); copy_cols: 0.331706323 copy_rows: 1.799009911 copy_col_row: 0.415630047 copy_row_col: 1.721531501 ``` 请注意,`copy_cols` 比 `copy_rows` 快得多。这与预料的一致,因为 `copy_cols` 尊重 `Matrix` 基于列的内存布局。另外,`copy_col_row` 比 `copy_row_col` 快得多,因为它遵循我们的经验法则,即切片表达式中出现的第一个元素应该与最内层循环耦合。 ## [输出预分配](@id Pre-allocating-outputs) 如果函数返回 `Array` 或其它复杂类型,则可能需要分配内存。不幸的是,内存分配及其反面垃圾收集通常是很大的瓶颈。 有时,你可以通过预分配输出结果来避免在每个函数调用上分配内存的需要。作为一个简单的例子,比较 ```jldoctest prealloc julia> function xinc(x) return [x, x+1, x+2] end; julia> function loopinc() y = 0 for i = 1:10^7 ret = xinc(i) y += ret[2] end return y end; ``` 和 ```jldoctest prealloc julia> function xinc!(ret::AbstractVector{T}, x::T) where T ret[1] = x ret[2] = x+1 ret[3] = x+2 nothing end; julia> function loopinc_prealloc() ret = Vector{Int}(undef, 3) y = 0 for i = 1:10^7 xinc!(ret, i) y += ret[2] end return y end; ``` 计时结果: ```jldoctest prealloc; filter = r"[0-9\.]+ seconds \(.*?\)" julia> @time loopinc() 0.529894 seconds (40.00 M allocations: 1.490 GiB, 12.14% gc time) 50000015000000 julia> @time loopinc_prealloc() 0.030850 seconds (6 allocations: 288 bytes) 50000015000000 ``` 预分配还有其它优点,例如允许调用者在算法中控制「输出」类型。在上述例子中,我们如果需要,可以传递 `SubArray` 而不是 [`Array`](@ref)。 极端情况下,预分配可能会使你的代码更丑陋,所以可能需要做性能测试和一些判断。但是,对于「向量化」(逐元素)函数,方便的语法 `x .= f.(y)` 可用于具有融合循环的 in-place 操作且无需临时数组(请参阅[向量化函数的点语法](@ref man-vectorized))。 ## 点语法:融合向量化操作 Julia 有特殊的[点语法](@ref man-vectorized),它可以将任何标量函数转换为「向量化」函数调用,将任何运算符转换为「向量化」运算符,其具有的特殊性质是嵌套「点调用」是*融合的*:它们在语法层级被组合为单个循环,无需分配临时数组。如果你使用 `.=` 和类似的赋值运算符,则结果也可以 in-place 存储在预分配的数组(参见上文)。 在线性代数的上下文中,这意味着即使诸如 `vector + vector` 和 `vector * scalar` 之类的运算,使用 `vector .+ vector` 和 `vector .* scalar` 来替代也可能是有利的,因为生成的循环可与周围的计算融合。例如,考虑两个函数: ```jldoctest dotfuse julia> f(x) = 3x.^2 + 4x + 7x.^3; julia> fdot(x) = @. 3x^2 + 4x + 7x^3 # equivalent to 3 .* x.^2 .+ 4 .* x .+ 7 .* x.^3; ``` `f` 和 `fdot` 都做相同的计算。但是,`fdot`(在 [`@.`](@ref @__dot__) 宏的帮助下定义)在作用于数组时明显更快: ```jldoctest dotfuse; filter = r"[0-9\.]+ seconds \(.*?\)" julia> x = rand(10^6); julia> @time f(x); 0.019049 seconds (16 allocations: 45.777 MiB, 18.59% gc time) julia> @time fdot(x); 0.002790 seconds (6 allocations: 7.630 MiB) julia> @time f.(x); 0.002626 seconds (8 allocations: 7.630 MiB) ``` 也就是说,`fdot(x)` 的速度是 `f(x)` 的 10 倍,分配的内存是 `f(x)` 的 1/6,因为 f(x) 中的每个 `*` 和 `+` 操作都会分配一个新的临时数组并在单独的循环中执行。 (当然,如果你只做 `f.(x)` 那么在这个例子中它和 `fdot(x)` 一样快,但在许多情况下,只在表达式中写一些点比为每个向量化操作定义单独的函数更方便。) ## [考虑对切片使用视图](@id man-performance-views) 在 Julia 中,像 `array[1:5, :]` 这样的数组“切片”表达式会创建该数据的副本(赋值的左侧除外,其中 `array[1:5, :] = ...` 原地对 `array` 的那一部分进行赋值)。 如果你在切片上执行许多操作,这对性能有好处,因为使用较小的连续副本比索引原始数组更有效。 另一方面,如果你只是对切片进行一些简单的操作,那么分配和复制操作的成本可能会很高。 另一种方法是创建数组的“视图”,它是一个数组对象(一个`SubArray`),它实际上就地引用了原始数组的数据,而不进行复制。(如果你写入视图,它也会修改原始数组的数据。)这可以通过调用 [`view`](@ref) 对单个切片完成,或者更简单地通过将整个表达式或代码块放入 [`@views`](@ref) 在该表达式前面。 例如: ```jldoctest; filter = r"[0-9\.]+ seconds \(.*?\)" julia> fcopy(x) = sum(x[2:end-1]); julia> @views fview(x) = sum(x[2:end-1]); julia> x = rand(10^6); julia> @time fcopy(x); 0.003051 seconds (3 allocations: 7.629 MB) julia> @time fview(x); 0.001020 seconds (1 allocation: 16 bytes) ``` 请注意,该函数的 `fview` 版本提速了 3 倍且减少了内存分配。 ## 复制数据不总是坏的 数组被连续地存储在内存中,这使其可被 CPU 向量化,并且会由于缓存减少内存访问。这与建议以列序优先方式访问数组的原因相同(请参见上文)。由于不按顺序访问内存,无规律的访问方式和不连续的视图可能会大大减慢数组上的计算速度。 在对无规律访问的数据进行操作前,将其复制到连续的数组中可能带来巨大的加速,正如下例所示。其中,矩阵和向量在相乘前会访问其 800,000 个已被随机混洗的索引处的值。将视图复制到普通数组会加速乘法,即使考虑了复制操作的成本。 ```julia-repl julia> using Random julia> x = randn(1_000_000); julia> inds = shuffle(1:1_000_000)[1:800000]; julia> A = randn(50, 1_000_000); julia> xtmp = zeros(800_000); julia> Atmp = zeros(50, 800_000); julia> @time sum(view(A, :, inds) * view(x, inds)) 0.412156 seconds (14 allocations: 960 bytes) -4256.759568345458 julia> @time begin copyto!(xtmp, view(x, inds)) copyto!(Atmp, view(A, :, inds)) sum(Atmp * xtmp) end 0.285923 seconds (14 allocations: 960 bytes) -4256.759568345134 ``` 倘若副本本身的内存足够大,那么将视图复制到数组的成本可能远远超过在连续数组上执行矩阵乘法所带来的加速。 ## 使用 StaticArrays.jl 进行小型固定大小的向量/矩阵运算 如果您的应用程序涉及许多固定大小的小(`< 100` 个元素)数组(即在执行之前已知大小),那么你可能需要考虑使用 [StaticArrays.jl 包](https://github.com/JuliaArrays/StaticArrays.jl)。 这个包允许你以一种避免不必要的堆分配的方式来表示这样的数组,并允许编译器为数组的*大小*特例化代码,例如,通过完全展开向量操作(消除循环)并将元素存储在 CPU 寄存器中。 例如,如果你正在使用 2d 几何图形进行计算,你可能会使用 2-分量向量进行许多计算。 通过使用 StaticArrays.jl 中的 `SVector` 类型,你可以在向量 `v` 和 `w` 上使用方便的向量符号和操作,例如 `norm(3v - w)`,同时允许编译器将代码展开到最小,计算等效于`@inbounds hypot(3v[1]-w[1], 3v[2]-w[2])`。 ## 避免 I/0 中的字符串插值 将数据写入到文件(或其他 I/0 设备)中时,生成额外的中间字符串会带来开销。请不要写成这样: ```julia println(file, "$a $b") ``` 请写成这样: ```julia println(file, a, " ", b) ``` 第一个版本的代码生成一个字符串,然后将其写入到文件中,而第二个版本直接将值写入到文件中。另请注意,在某些情况下,字符串插值可能更难阅读。请考虑: ```julia println(file, "$(f(a))$(f(b))") ``` 与: ```julia println(file, f(a), f(b)) ``` ## 并发执行时优化网络 I/O 当并发地执行一个远程函数时: ```julia using Distributed responses = Vector{Any}(undef, nworkers()) @sync begin for (idx, pid) in enumerate(workers()) @async responses[idx] = remotecall_fetch(foo, pid, args...) end end ``` 会快于: ```julia using Distributed refs = Vector{Any}(undef, nworkers()) for (idx, pid) in enumerate(workers()) refs[idx] = @spawnat pid foo(args...) end responses = [fetch(r) for r in refs] ``` 第一种方式导致每个worker一次网络往返,而第二种方式是两次网络调用:一次 [`@spawnat`](@ref) 一次[`fetch`](@ref) (甚至是 [`wait`](@ref))。 [`fetch`](@ref) 和[`wait`](@ref) 都是同步执行,会导致较差的性能。 ## 修复过期警告 过期的函数在内部会执行查找,以便仅打印一次相关警告。 这种额外查找可能会显著影响性能,因此应根据警告建议修复掉过期函数的所有使用。 ## 小技巧 有一些小的注意事项可能会帮助改善循环性能。 * 避免使用不必要的数组。比如,使用 `x+y+z` 而不是 [`sum([x,y,z])`](@ref)。 * 对于复数 `z`,使用 [`abs2(z)`](@ref) 而不是 [`abs(z)^2`](@ref)。一般的, 对于复数参数,用 [`abs2`](@ref) 代替[`abs`](@ref)。 * 对于直接截断的整除,使用 [`div(x,y)`](@ref) 而不是 [`trunc(x/y)`](@ref),使用[`fld(x,y)`](@ref) 而不是 [`floor(x/y)`](@ref),使用 [`cld(x,y)`](@ref) 而不是 [`ceil(x/y)`](@ref)。 ## [性能标注](@id man-performance-annotations) 有时,你可以通过承诺某些程序性质来启用更好的优化。 * 使用 [`@inbounds`](@ref) 来取消表达式中的数组边界检查。使用前请再三确定,如果下标越界,可能会发生崩溃或潜在的故障。 * 使用 [`@fastmath`](@ref) 来允许对于实数是正确的、但是对于 IEEE 数字会导致差异的浮点数优化。使用时请多多小心,因为这可能改变数值结果。这对应于 clang 的 `-ffast-math` 选项。 * 在 `for` 循环前编写 [`@simd`](@ref) 来承诺迭代是相互独立且可以重新排序的。请注意,在许多情况下,Julia 可以在没有 `@simd` 宏的情况下自动向量化代码;只有在这种转换原本是非法的情况下才有用,包括允许浮点数重新结合和忽略相互依赖的内存访问(`@simd ivdep`)等情况。此外,在断言 `@simd` 时要十分小心,因为错误地标注一个具有相互依赖的迭代的循环可能导致意外结果。尤其要注意的是,某些 `AbstractArray` 子类型的 `setindex!` 本质上依赖于迭代顺序。**此功能是实验性的**,在 Julia 未来的版本中可能会更改或消失。 如果 Array 使用非常规索引,那么使用 1:n 索引到 AbstractArray 的常见习惯用法是不安全的,如果关闭边界检查,可能会导致段错误。请改用`LinearIndices(x)` 或`eachindex(x)`(另请参阅[具有自定义索引的数组](@ref man-custom-indices))。 !!! note 虽然 `@simd` 需要直接放在最内层 `for` 循环前面,但 `@inbounds` 和 `@fastmath` 都可作用于单个表达式或在嵌套代码块中出现的所有表达式,例如,可使用 `@inbounds begin` 或 `@inbounds for ...`。 下面是一个具有 `@inbounds` 和 `@simd` 标记的例子(我们这里使用 `@noinline` 来防止因优化器过于智能而破坏我们的基准测试): ```julia @noinline function inner(x, y) s = zero(eltype(x)) for i=eachindex(x) @inbounds s += x[i]*y[i] end return s end @noinline function innersimd(x, y) s = zero(eltype(x)) @simd for i = eachindex(x) @inbounds s += x[i] * y[i] end return s end function timeit(n, reps) x = rand(Float32, n) y = rand(Float32, n) s = zero(Float64) time = @elapsed for j in 1:reps s += inner(x, y) end println("GFlop/sec = ", 2n*reps / time*1E-9) time = @elapsed for j in 1:reps s += innersimd(x, y) end println("GFlop/sec (SIMD) = ", 2n*reps / time*1E-9) end timeit(1000, 1000) ``` 在配备 2.4GHz Intel Core i5 处理器的计算机上,其结果为: ``` GFlop/sec = 1.9467069505224963 GFlop/sec (SIMD) = 17.578554163920018 ``` (`GFlop/sec` 用来测试性能,数值越大越好。) 下面是一个具有三种标记的例子。此程序首先计算一个一维数组的有限差分,然后计算结果的 L2 范数: ```julia function init!(u::Vector) n = length(u) dx = 1.0 / (n-1) @fastmath @inbounds @simd for i in 1:n # 通过断言 `u` 是一个 `Vector`,我们可以假定它具有 1-based 索引 u[i] = sin(2pi*dx*i) end end function deriv!(u::Vector, du) n = length(u) dx = 1.0 / (n-1) @fastmath @inbounds du[1] = (u[2] - u[1]) / dx @fastmath @inbounds @simd for i in 2:n-1 du[i] = (u[i+1] - u[i-1]) / (2*dx) end @fastmath @inbounds du[n] = (u[n] - u[n-1]) / dx end function mynorm(u::Vector) n = length(u) T = eltype(u) s = zero(T) @fastmath @inbounds @simd for i in 1:n s += u[i]^2 end @fastmath @inbounds return sqrt(s) end function main() n = 2000 u = Vector{Float64}(undef, n) init!(u) du = similar(u) deriv!(u, du) nu = mynorm(du) @time for i in 1:10^6 deriv!(u, du) nu = mynorm(du) end println(nu) end main() ``` 在配备 2.7 GHz Intel Core i7 处理器的计算机上,其结果为: ``` $ julia wave.jl; 1.207814709 seconds 4.443986180758249 $ julia --math-mode=ieee wave.jl; 4.487083643 seconds 4.443986180758249 ``` 在这里,选项 `--math-mode=ieee` 禁用 `@fastmath` 宏,好让我们可以比较结果。 在这种情况下,`@fastmath` 加速了大约 3.7 倍。这非常大——通常来说,加速会更小。(在这个特定的例子中,基准测试的工作集足够小,可以放在该处理器的 L1 缓存中,因此内存访问延迟不起作用,计算时间主要由 CPU 使用率决定。在许多现实世界的程序中,情况并非如此。)此外,在这种情况下,此优化不会改变计算结果——通常来说,结果会略有不同。在某些情况下,尤其是数值不稳定的算法,计算结果可能会差很多。 标注 `@fastmath` 会重新排列浮点数表达式,例如更改求值顺序,或者假设某些特殊情况(如 inf、nan)不出现。在这种情况中(以及在这个特定的计算机上),主要区别是函数 `deriv` 中的表达式 `1 / (2*dx)` 会被提升出循环(即在循环外计算),就像编写了 `idx = 1 / (2*dx)`,然后,在循环中,表达式 `... / (2*dx)` 变为 `... * idx`,后者计算起来快得多。当然,编译器实际上采用的优化以及由此产生的加速都在很大程度上取决于硬件。你可以使用 Julia 的 [`code_native`](@ref) 函数来检查所生成代码的更改。 请注意,`@fastmath` 也假设了在计算中不会出现 `NaN`,这可能导致意想不到的行为: ```julia-repl julia> f(x) = isnan(x); julia> f(NaN) true julia> f_fast(x) = @fastmath isnan(x); julia> f_fast(NaN) false ``` ## 将次正规数视为零 次正规数,以前称为 [非正规数](https://en.wikipedia.org/wiki/Denormal_number),在许多情况下都很有用,但会在某些硬件上造成性能损失。 调用 [`set_zero_subnormals(true)`](@ref) 授予浮点运算权限,将次正规输入或输出视为零,这可能会提高某些硬件的性能。 调用 [`set_zero_subnormals(false)`](@ref) 对次正规数强制执行严格的 IEEE 行为。 下面是一个示例,其中次正规数显着影响某些硬件的性能: ```julia function timestep(b::Vector{T}, a::Vector{T}, Δt::T) where T @assert length(a)==length(b) n = length(b) b[1] = 1 # Boundary condition for i=2:n-1 b[i] = a[i] + (a[i-1] - T(2)*a[i] + a[i+1]) * Δt end b[n] = 0 # Boundary condition end function heatflow(a::Vector{T}, nstep::Integer) where T b = similar(a) for t=1:div(nstep,2) # Assume nstep is even timestep(b,a,T(0.1)) timestep(a,b,T(0.1)) end end heatflow(zeros(Float32,10),2) # Force compilation for trial=1:6 a = zeros(Float32,1000) set_zero_subnormals(iseven(trial)) # Odd trials use strict IEEE arithmetic @time heatflow(a,1000) end ``` 它的输出类似于 ``` 0.002202 seconds (1 allocation: 4.063 KiB) 0.001502 seconds (1 allocation: 4.063 KiB) 0.002139 seconds (1 allocation: 4.063 KiB) 0.001454 seconds (1 allocation: 4.063 KiB) 0.002115 seconds (1 allocation: 4.063 KiB) 0.001455 seconds (1 allocation: 4.063 KiB) ``` 注意,每个偶数迭代的速度明显更快。 这个例子产生了许多次正规数,因为`a`中的值变成了一个指数递减的曲线,随着时间的推移慢慢渐进趋于0。 应谨慎使用将次正规数视为零,因为这样做会破坏某些等式,例如 `x-y == 0` 意味着 `x == y`: ```jldoctest julia> x = 3f-38; y = 2f-38; julia> set_zero_subnormals(true); (x - y, x == y) (0.0f0, false) julia> set_zero_subnormals(false); (x - y, x == y) (1.0000001f-38, false) ``` 在某些应用程序中,将次正规数归零的另一种方法是加入一点点噪音。 例如,不是用零初始化`a`,而是用以下方法初始化它: ```julia a = rand(Float32,1000) * 1.f-9 ``` ## [[`@code_warntype`](@ref)](@id man-code-warntype) 宏 [`@code_warntype`](@ref)(或其函数变体 [`code_warntype`](@ref))有时可以帮助诊断类型相关的问题。这是一个例子: ```julia-repl julia> @noinline pos(x) = x < 0 ? 0 : x; julia> function f(x) y = pos(x) return sin(y*x + 1) end; julia> @code_warntype f(3.2) Variables #self#::Core.Const(f) x::Float64 y::UNION{FLOAT64, INT64} Body::Float64 1 ─ (y = Main.pos(x)) │ %2 = (y * x)::Float64 │ %3 = (%2 + 1)::Float64 │ %4 = Main.sin(%3)::Float64 └── return %4 ``` 理解 [`@code_warntype`](@ref) 的输出,就像理解它的同类工具 [`@code_lowered`](@ref), [`@code_typed`](@ref), [`@code_llvm`](@ ref) 和 [`@code_native`](@ref) 一样需要一些练习。你的代码以在生成编译机器代码的过程中经过大量摘要的形式呈现。大多数表达式都由类型注释,由 `::T` 表示(例如,其中 `T` 可能是 [`Float64`](@ref))。 [`@code_warntype`](@ref) 最大的特点就是非具体类型用红色显示; 由于本文档是用Markdown 编写的,没有颜色,所以本文档中红色文字用大写表示。 在顶部,该函数类型推导后的返回类型显示为 `Body::Float64`。下一行以 Julia 的 SSA IR 形式表示了 `f` 的主体。被数字标记的方块表示代码中(通过 `goto`)跳转的目标。查看主体,你会看到首先调用了 `pos`,其返回值经类型推导为 `Union` 类型 `UNION{FLOAT64, INT64}` 并以大写字母显示,因为它是非具体类型。这意味着我们无法根据输入类型知道 `pos` 的确切返回类型。但是,无论 `y` 是 `Float64` 还是 `Int64`,`y*x` 的结果都是 `Float64`。最终的结果是 `f(x::Float64)` 在其输出中不会是类型不稳定的,即使有些中间计算是类型不稳定的。 如何使用这些信息取决于你。显然,最好将 `pos` 修改为类型稳定的:如果这样做,`f` 中的所有变量都是具体的,其性能将是最佳的。但是,在某些情况下,这种*短暂的*类型不稳定性可能无关紧要:例如,如果 `pos` 从不单独使用,那么 `f` 的输出(对于 [`Float64`](@ref) 输入)是类型稳定的这一事实将保护之后的代码免受类型不稳定性的传播影响。这与类型不稳定性难以或不可能修复的情况密切相关。在这些情况下,上面的建议(例如,添加类型注释并/或分解函数)是你控制类型不稳定性的「损害」的最佳工具。另请注意,即使是 Julia Base 也有类型不稳定的函数。例如,函数 [`findfirst`](@ref) 如果找到键则返回数组索引,如果没有找到键则返回 `nothing`,这是明显的类型不稳定性。为了更易于找到可能很重要的类型不稳定性,包含 `missing` 或 `nothing` 的 `Union` 会用黄色着重显示,而不是用红色。 以下示例可以帮助你解释被标记为包含非叶类型的表达式: * 函数体以 `Body::UNION{T1,T2})` 开头 * 解释:函数具有不稳定返回类型 * 建议:使返回值类型稳定,即使你必须对其进行类型注释 * `invoke Main.g(%%x::Int64)::UNION{FLOAT64, INT64}` * 解释:调用类型不稳定的函数 `g`。 * 建议:修改该函数,或在必要时对其返回值进行类型注释 * `invoke Base.getindex(%%x::Array{Any,1}, 1::Int64)::ANY` * 解释:访问缺乏类型信息的数组的元素 * 建议:使用具有更佳定义的类型的数组,或在必要时对访问的单个元素进行类型注释 * `Base.getfield(%%x, :(:data))::ARRAY{FLOAT64,N} WHERE N` * 解释:获取一个非叶子类型的字段。 在这种情况下,`x` 的类型,比如说 `ArrayContainer`,有一个字段 `data::Array{T}`。 但是 `Array` 也需要维度 `N` 作为具体类型。 * 建议:使用类似于 `Array{T,3}` 或 `Array{T,N}` 的具体类型,其中的 `N` 现在是 `ArrayContainer` 的参数 ## [被捕获变量的性能](@id man-performance-captured) 请考虑以下定义内部函数的示例: ```julia function abmult(r::Int) if r < 0 r = -r end f = x -> x * r return f end ``` 函数 `abmult` 返回一个函数 `f`,它将其参数乘以 `r` 的绝对值。赋值给 `f` 的函数称为「闭包」。内部函数还被语言用于 `do` 代码块和生成器表达式。 这种代码风格为语言带来了性能挑战。解析器在将其转换为较低级别的指令时,基本上通过将内部函数提取到单独的代码块来重新组织上述代码。「被捕获的」变量,比如 `r`,被内部函数共享,且包含它们的作用域会被提取到内部函数和外部函数皆可访问的堆分配「box」中,这是因为语言指定内部作用域中的 `r` 必须与外部作用域中的 `r` 相同,就算在外部作用域(或另一个内部函数)修改 `r` 后也需如此。 前一段的讨论中提到了「解析器」,也就是,包含 `abmult` 的模块被首次加载时发生的编译前期,而不是首次调用它的编译后期。解析器不「知道」`Int` 是固定类型,也不知道语句 `r = -r` 将一个 `Int` 转换为另一个 `Int`。类型推断的魔力在编译后期生效。 因此,解析器不知道 `r` 具有固定类型(`Int`)。一旦内部函数被创建,`r` 的值也不会改变(因此也不需要 box)。因此,解析器向包含具有抽象类型(比如 `Any`)的对象的 box 发出代码,这对于每次出现的 `r` 都需要运行时类型分派。这可以通过在上述函数中使用 `@code_warntype` 来验证。装箱和运行时的类型分派都有可能导致性能损失。 如果捕获的变量用于代码的性能关键部分,那么以下提示有助于确保它们的使用具有高效性。首先,如果已经知道被捕获的变量不会改变类型,则可以使用类型注释来显式声明类型(在变量上,而不是在右侧): ```julia function abmult2(r0::Int) r::Int = r0 if r < 0 r = -r end f = x -> x * r return f end ``` 类型注释部分恢复由于捕获而导致的丢失性能,因为解析器可以将具体类型与 box 中的对象相关联。更进一步,如果被捕获的变量不再需要 box(因为它不会在闭包创建后被重新分配),就可以用 `let` 代码块表示,如下所示。 ```julia function abmult3(r::Int) if r < 0 r = -r end f = let r = r x -> x * r end return f end ``` `let` 代码块创建了一个新的变量 `r`,它的作用域只是内部函数。第二种技术在捕获变量存在时完全恢复了语言性能。请注意,这是编译器的一个快速发展的方面,未来的版本可能不需要依靠这种程度的程序员注释来获得性能。与此同时,一些用户提供的包(如 [FastClosures](https://github.com/c42f/FastClosures.jl))会自动插入像在 `abmult3` 中那样的 `let` 语句。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
10031
# [性能分析](@id profiling) `Profile` 模块提供了一些工具来帮助开发者提高其代码的性能。在使用时,它运行代码并进行测量,并生成输出,该输出帮助你了解在每行(或几行)上花费了多少时间。最常见的用法是识别性能「瓶颈」并将其作为优化目标。 `Profile` 实现了所谓的「抽样」或[统计分析器](https://en.wikipedia.org/wiki/Profiling_(computer_programming))。它通过在执行任何任务期间定期进行回溯来工作。每次回溯捕获当前运行的函数和行号,以及导致该行执行的完整函数调用链,因此是当前执行状态的「快照」。 如果大部分运行时间都花在执行特定代码行上,则此行会在所有回溯的集合中频繁出现。换句话说,执行给定行的「成本」——或实际上,调用及包含此行的函数序列的成本——与它在所有回溯的集合中的出现频率成正比。 抽样分析器不提供完整的逐行覆盖功能,因为回溯是间隔发生的(默认情况下,该时间间隔在 Unix 上是 1 ms,而在 Windows 上是 10 ms,但实际调度受操作系统负载的影响)。此外,正如下文中进一步讨论的,因为样本是在所有执行点的稀疏子集处收集的,所以抽样分析器收集的数据会受到统计噪声的影响。 尽管有这些限制,但抽样分析器仍然有很大的优势: * 你无需对代码进行任何修改即可进行时间测量。 * 它可以分析 Julia 的核心代码,甚至(可选)可以分析 C 和 Fortran 库。 * 通过「偶尔」运行,它只有很少的性能开销;代码在性能分析时能以接近本机的速度运行。 出于这些原因,建议你在考虑任何替代方案前尝试使用内置的抽样分析器。 ## 基本用法 让我们使用一个简单的测试用例: ```julia-repl julia> function myfunc() A = rand(200, 200, 400) maximum(A) end ``` 最好先至少运行一次你想要分析的代码(除非你想要分析 Julia 的 JIT 编译器): ```julia-repl julia> myfunc() # run once to force compilation ``` 现在我们准备分析这个函数: ```julia-repl julia> using Profile julia> @profile myfunc() ``` 有一些图形界面可以查看性能分析的结果。这其中有一类是基于 [FlameGraphs.jl](https://github.com/timholy/FlameGraphs.jl)打造的,只不过提供了不同的用户接口: - [Juno](https://junolab.org/) 是一个完整的 IDE,内置对性能分析可视化的支持 - [ProfileView.jl](https://github.com/timholy/ProfileView.jl) 是一个基于 GTK 的独立可视化工具 - [ProfileVega.jl](https://github.com/davidanthoff/ProfileVega.jl) 使用 VegaLight 并与 Jupyter notebooks 很好地集成 - [StatProfilerHTML](https://github.com/tkluck/StatProfilerHTML.jl) 生成 HTML 并提供一些额外的摘要,并且还与 Jupyter 笔记本很好地集成 - [ProfileSVG](https://github.com/timholy/ProfileSVG.jl) 渲染 SVG 一种完全独立的性能分析可视化方法是 [PProf.jl](https://github.com/vchuravy/PProf.jl),它使用外部 `pprof` 工具。 不过,在这里,我们将使用标准库附带的基于文本的显示: ```julia-repl julia> Profile.print() 80 ./event.jl:73; (::Base.REPL.##1#2{Base.REPL.REPLBackend})() 80 ./REPL.jl:97; macro expansion 80 ./REPL.jl:66; eval_user_input(::Any, ::Base.REPL.REPLBackend) 80 ./boot.jl:235; eval(::Module, ::Any) 80 ./<missing>:?; anonymous 80 ./profile.jl:23; macro expansion 52 ./REPL[1]:2; myfunc() 38 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type{B... 38 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr{F... 14 ./random.jl:278; rand 14 ./random.jl:277; rand 14 ./random.jl:366; rand 14 ./random.jl:369; rand 28 ./REPL[1]:3; myfunc() 28 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinear,... 3 ./reduce.jl:426; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F... 25 ./reduce.jl:428; mapreduce_impl(::Base.#identity, ::Base.#scalarmax, ::Array{F... ``` 显示结果中的每行表示代码中的特定点(行数)。缩进用来标明嵌套的函数调用序列,其中缩进更多的行在调用序列中更深。在每一行中,第一个「字段」是在*这一行或由这一行执行的任何函数*中获取的回溯(样本)数量。第二个字段是文件名和行数,第三个字段是函数名。请注意,具体的行号可能会随着 Julia 代码的改变而改变;如果你想跟上,最好自己运行这个示例。 在此例中,我们可以看到顶层的调用函数位于文件 `event.jl` 中。这是启动 Julia 时运行 REPL 的函数。如果你查看 `REPL.jl` 的第 97 行,你会看到这是调用函数 `eval_user_input()` 的地方。这是对你在 REPL 上的输入进行求值的函数,因为我们正以交互方式运行,所以当我们输入 `@profile myfunc()` 时会调用这些函数。下一行反映了 [`@profile`](@ref) 所采取的操作。 第一行显示在 `event.jl` 的第 73 行获取了 80 次回溯,但这并不是说此行本身「昂贵」:第三行表明所有这些 80 次回溯实际上它调用的 `eval_user_input` 中触发的,以此类推。为了找出实际占用时间的操作,我们需要深入了解调用链。 此输出中第一个「重要」的行是这行: ``` 52 ./REPL[1]:2; myfunc() ``` `REPL` 指的是我们在 REPL 中定义了 `myfunc`,而不是把它放在文件中;如果我们使用文件,这将显示文件名。`[1]` 表示函数 `myfunc` 是在当前 REPL 会话中第一个进行求值的表达式。`myfunc()` 的第 2 行包含对 `rand` 的调用,(80 次中)有 52 次回溯发生在该行。在此之下,你可以看到在 `dSFMT.jl` 中对 `dsfmt_fill_array_close_open!` 的调用。 更进一步,你会看到: ``` 28 ./REPL[1]:3; myfunc() ``` `myfunc` 的第 3 行包含对 `maximum` 的调用,(80 次中)有 28 次回溯发生在这里。在此之下,你可以看到对于这种类型的输入数据,`maximum` 函数中执行的耗时操作在 `base/reduce.jl` 中的具体位置。 总的来说,我们可以暂时得出结论,生成随机数的成本大概是找到最大元素的两倍。通过收集更多样本,我们可以增加对此结果的信心: ```julia-repl julia> @profile (for i = 1:100; myfunc(); end) julia> Profile.print() [....] 3821 ./REPL[1]:2; myfunc() 3511 ./random.jl:431; rand!(::MersenneTwister, ::Array{Float64,3}, ::Int64, ::Type... 3511 ./dSFMT.jl:84; dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_state, ::Ptr... 310 ./random.jl:278; rand [....] 2893 ./REPL[1]:3; myfunc() 2893 ./reduce.jl:270; _mapreduce(::Base.#identity, ::Base.#scalarmax, ::IndexLinea... [....] ``` 一般来说,如果你在某行上收集到 `N` 个样本,那你可以预期其有 `sqrt(N)` 的不确定性(忽略其它噪音源,比如计算机在其它任务上的繁忙程度)。这个规则的主要例外是垃圾收集,它很少运行但往往成本高昂。(因为 Julia 的垃圾收集器是用 C 语言编写的,此类事件可使用下文描述的 `C=true` 输出模式来检测,或者使用 [ProfileView.jl](https://github.com/timholy/ProfileView.jl) 来检测。) 这展示了默认的「树」形转储;另一种选择是「扁平」形转储,它会累积与其嵌套无关的计数: ```julia-repl julia> Profile.print(format=:flat) Count File Line Function 6714 ./<missing> -1 anonymous 6714 ./REPL.jl 66 eval_user_input(::Any, ::Base.REPL.REPLBackend) 6714 ./REPL.jl 97 macro expansion 3821 ./REPL[1] 2 myfunc() 2893 ./REPL[1] 3 myfunc() 6714 ./REPL[7] 1 macro expansion 6714 ./boot.jl 235 eval(::Module, ::Any) 3511 ./dSFMT.jl 84 dsfmt_fill_array_close_open!(::Base.dSFMT.DSFMT_s... 6714 ./event.jl 73 (::Base.REPL.##1#2{Base.REPL.REPLBackend})() 6714 ./profile.jl 23 macro expansion 3511 ./random.jl 431 rand!(::MersenneTwister, ::Array{Float64,3}, ::In... 310 ./random.jl 277 rand 310 ./random.jl 278 rand 310 ./random.jl 366 rand 310 ./random.jl 369 rand 2893 ./reduce.jl 270 _mapreduce(::Base.#identity, ::Base.#scalarmax, :... 5 ./reduce.jl 420 mapreduce_impl(::Base.#identity, ::Base.#scalarma... 253 ./reduce.jl 426 mapreduce_impl(::Base.#identity, ::Base.#scalarma... 2592 ./reduce.jl 428 mapreduce_impl(::Base.#identity, ::Base.#scalarma... 43 ./reduce.jl 429 mapreduce_impl(::Base.#identity, ::Base.#scalarma... ``` 如果你的代码有递归,那么可能令人困惑的就是「子」函数中的行的累积计数可以多于总回溯次数。考虑以下函数定义: ```julia dumbsum(n::Integer) = n == 1 ? 1 : 1 + dumbsum(n-1) dumbsum3() = dumbsum(3) ``` 如果你要分析 `dumbsum3`,并在执行 `dumbsum(1)` 时执行了回溯,那么该回溯将如下所示: ```julia dumbsum3 dumbsum(3) dumbsum(2) dumbsum(1) ``` 因此,即使父函数只获得 1 个计数,这个子函数也会获得 3 个计数。「树」形表示使这更清晰,因此(以及其它原因)可能是查看结果的最实用方法。 ## 结果累积和清空 [`@profile`](@ref) 的结果会累积在一个缓冲区中;如果你在 [`@profile`](@ref) 下运行多端代码,那么 [`Profile.print()`](@ref) 会显示合并的结果。这可能非常有用,但有时你会想重新开始,这可通过 [`Profile.clear()`](@ref)。 ## 用于控制性能分析结果显示的选项 [`Profile.print`](@ref) 还有一些未曾描述的选项。让我们看看完整的声明: ```julia function print(io::IO = stdout, data = fetch(); kwargs...) ``` 我们先讨论两个位置参数,然后讨论关键字参数: * `io`——允许你将结果保存到缓冲区,例如一个文件,但默认是打印到 `stdout`(控制台)。 * `data`——包含你要分析的数据;默认情况下,它是从 [`Profile.fetch()`](@ref) 中获取的,该函数从预先分配的缓冲区中拉出回溯。例如,如果你要分析性能分析器,可以说: ```julia data = copy(Profile.fetch()) Profile.clear() @profile Profile.print(stdout, data) # Prints the previous results Profile.print() # Prints results from Profile.print() ``` 关键字参数可以是以下参数的任意组合: * `format`——上文已经介绍,确定是使用(默认值,`:tree`)还是不使用(`:flat`)缩进来表示其树形结构。 * `C`——如果为 `true`,则显示 C 和 Fortran 代码中的回溯(通常它们被排除在外)。请尝试用 `Profile.print(C = true)` 运行介绍性示例。这对于判断是 Julia 代码还是 C 代码导致了性能瓶颈非常有帮助;设置 `C = true` 也可提高嵌套的可解释性,代价是更长的性能分析转储。 * `combine`——某些代码行包含多个操作;例如,`s += A[i]` 包含一个数组引用(`A[i]`)和一个求和操作。这些操作在所生成的机器代码中对应不同的行,因此回溯期间可能会在此行中捕获两个或以上地址。`combine = true` 把它们混合在一起,可能你通常想要这样,但使用 `combine = false`,你可为每个唯一的指令指针单独生成输出。 * `maxdepth`——限制 `:tree` 格式中深度大于 `maxdepth` 的帧。 *   * `sortedby`——控制 `:flat` 格式中的次序。为 `:filefuncline`(默认值)时按源代码行排序,而为 `:count` 时按收集的样本数排序。 * `noisefloor`——限制低于样本的启发式噪音下限的帧(只适用于格式 `:tree`)。尝试此选项的建议值是 2.0(默认值是 0)。此参数会隐藏 `n <= noisefloor * √N` 的样本,其中 `n` 是该行上的样本数,`N` 是被调用者的样本数。 * `mincount`——限制出现次数少于 `mincount` 的帧。 文件/函数名有时会被(用 `...`)截断,缩进也有可能在开头用 `+n` 截断,其中 `n` 是在空间充足的情况下应该插入的额外空格数。如果你想要深层嵌套代码的完整性能分析,保存到文件并在 [`IOContext`](@ref) 中使用宽的 `displaysize` 通常是个好主意: ```julia open("/tmp/prof.txt", "w") do s Profile.print(IOContext(s, :displaysize => (24, 500))) end ``` ## 配置 [`@profile`](@ref) 只是累积回溯,在你调用 [`Profile.print()`](@ref) 时才会进行性能分析。对于长时间运行的计算,完全有可能把用于存储回溯的预分配缓冲区填满。如果发生这种情况,回溯会停止,但你的计算会继续。因此,你也许会丢失一些重要的性能分析数据(当发生这种情况时,你会受到警告)。 你可通过以下方式获取和配置相关参数: ```julia Profile.init() # returns the current settings Profile.init(n = 10^7, delay = 0.01) ``` `n` 是能够存储的指令指针总数,默认值为 `10^6`。如果通常的回溯是 20 个指令指针,那么可以收集 50000 次回溯,这意味着统计不确定性少于 1%。这对于大多数应用来说可能已经足够了。 因此,你更可能需要修改 `delay`,它以秒为单位,设置在快照之间 Julia 用于执行所请求计算的时长。长时间运行的工作可能不需要经常回溯。默认设置为 `delay = 0.001`。当然,你可以减少和增加 delay;但是,一旦 delay 接近执行一次回溯所需的时间(在作者的笔记本上约为 30 微妙),性能分析的开销就会增加。 ## [内存分配分析](@id memory-allocation-analysis) 减少内存分配是提高性能的最常用技术之一。内存分配总量可以用 [`@time`](@ref) 和 [`@allocated`](@ref),触发内存分配的特定行通常可以通过这些行产生的垃圾分配成本从性能分析中推断出来。但是,直接测量每行代码的内存分配总量有时会更高效。 为了逐行测量内存分配,启动 Julia 时请使用命令行选项 `--track-allocation=<setting>`,该选项的可选值有 `none`(默认值,不测量内存分配)、`user`(测量除 Julia core 代码之外的所有代码的内存分配)或 `all`(测量 Julia 代码中每一行的内存分配)。这会为每行已编译的代码测量内存。在退出 Julia 时,累积的结果将写入到文本文件中,此文本文件名称为该文件名称后加 `.mem`,并与源文件位于同一目录下。该文件的每行列出内存分配的总字节数。[`Coverage` 包](https://github.com/JuliaCI/Coverage.jl)包括了一些基本分析工具,例如,按照内存分配的字节数对行进行排序的工具。 在解释结果时,有一些需要注意的细节。在 `user` 设定下,直接从 REPL 调用的任何函数的第一行都将会显示内存分配,这是由发生在 REPL 代码本身的事件造成的。更重要的是,JIT 编译也会添加内存分配计数,因为 Julia 的编译器大部分是用 Julia 编写的(并且编译通常需要内存分配)。建议的分析过程是先通过执行待分析的所有命令来强制编译,然后调用 [`Profile.clear_malloc_data()`](@ref) 来重置所有内存计数器。最后,执行所需的命令并退出 Julia 以触发 `.mem` 文件的生成。 ## 外部性能分析 Julia 目前支持的外部性能分析工具有 `Intel VTune`、`OProfile` 和 `perf`。 根据你所选择的工具,编译时请在 `Make.user` 中将 `USE_INTEL_JITEVENTS`、`USE_OPROFILE_JITEVENTS` 和 `USE_PERF_JITEVENTS` 设置为 1。多个上述编译标志是支持的。 在运行 Julia 前,请将环境变量 `ENABLE_JITPROFILING` 设置为 1。 现在,你可以通过多种方式使用这些工具!例如,可以使用 `OProfile` 来尝试做个简单的记录: ``` >ENABLE_JITPROFILING=1 sudo operf -Vdebug ./julia test/fastmath.jl >opreport -l `which ./julia` ``` 或与 `perf` 类似: ``` $ ENABLE_JITPROFILING=1 perf record -o /tmp/perf.data --call-graph dwarf -k 1 ./julia /test/fastmath.jl $ perf inject --jit --input /tmp/perf.data --output /tmp/perf-jit.data $ perf report --call-graph -G -i /tmp/perf-jit.data ``` 你可以测量关于程序的更多有趣数据,若要获得详尽的列表,请阅读 [Linux perf 示例页面](http://www.brendangregg.com/perf.html)。 请记住,perf 会为每次执行保存一个 `perf.data` 文件,即使对于小程序,它也可能变得非常大。此外,perf LLVM 模块会将调试对象保存在 `~/.debug/jit` 中,记得经常清理该文件夹。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
7815
# 运行外部程序 Julia 中命令的反引号记法借鉴于 shell、Perl 和 Ruby。然而,在 Julia 中编写 ```jldoctest julia> `echo hello` `echo hello` ``` 在多个方面上与 shell、Perl 和 Ruby 中的行为有所不同: * 反引号创建一个 [`Cmd`](@ref) 对象来表示命令,而不是立即运行命令。 你可以使用此对象将命令通过管道连接到其它命令、[`run`](@ref) 它以及对它进行 [`read`](@ref) 或 [`write`](@ref)。 * 在命令运行时,Julia 不会捕获命令的输出结果,除非你对它专门安排。相反,在默认情况下,命令的输出会被定向到 [`stdout`](@ref),因为它将使用 `libc` 的 `system` 调用。 * 命令从不会在 shell 中运行。相反地,Julia 会直接解析命令语法,适当地插入变量并像 shell 那样拆分单词,同时遵从 shell 的引用语法。命令会作为 `julia` 的直接子进程运行,使用 `fork` 和 `exec` 调用。 !!! note 下面假设在 Linux 或 MacOS 上使用 Posix 环境。 在 Windows 上,许多类似的命令,例如 `echo` 和 `dir`,不是外部程序,而是内置在 shell `cmd.exe` 本身中。 运行这些命令的一种选择是调用 `cmd.exe`,例如 `cmd /C echo hello`。 或者,Julia 可以在 Posix 环境中运行,例如 Cygwin。 这是运行外部程序的简单示例: ```jldoctest julia> mycommand = `echo hello` `echo hello` julia> typeof(mycommand) Cmd julia> run(mycommand); hello ``` `hello` 是 `echo` 命令的输出,发送到 [`stdout`](@ref)。 如果外部命令无法成功运行,则 run 方法会抛出 [`ErrorException`](@ref)。 如果要读取外部命令的输出,可以使用 [`read`](@ref) 或 [`readchomp`](@ref) 代替: ```jldoctest julia> read(`echo hello`, String) "hello\n" julia> readchomp(`echo hello`) "hello" ``` 更一般地,你可以使用 [`open`](@ref) 来读取或写入外部命令。 ```jldoctest julia> open(`less`, "w", stdout) do io for i = 1:3 println(io, i) end end 1 2 3 ``` 命令中的程序名称和各个参数可以访问和迭代,这就好像命令也是一个字符串数组: ```jldoctest julia> collect(`echo "foo bar"`) 2-element Vector{String}: "echo" "foo bar" julia> `echo "foo bar"`[2] "foo bar" ``` ## [插值](@id command-interpolation) 假设你想要做的事情更复杂,并使用以变量 `file` 表示的文件名作为命令的参数。那你可以像在字符串字面量中那样使用 `$` 进行插值: ```jldoctest julia> file = "/etc/passwd" "/etc/passwd" julia> `sort $file` `sort /etc/passwd` ``` 通过 shell 运行外部程序的一个常见陷阱是,如果文件名中包含 shell 中的特殊字符,那么可能会导致不希望出现的行为。例如,假设我们想要对其内容进行排序的文件是 `/Volumes/External HD/data.csv`,而不是 `/etc/passwd`。让我们来试试: ```jldoctest julia> file = "/Volumes/External HD/data.csv" "/Volumes/External HD/data.csv" julia> `sort $file` `sort '/Volumes/External HD/data.csv'` ``` 文件名是如何被引用的?Julia 知道 `file` 是作为单个参数插入的,因此它替你引用了此单词。事实上,这不太准确:`file` 的值始终不会被 shell 解释,因此并不需要实际引用;插入引号只是为了展现给用户。就算你把值作为 shell 单词的一部分插入,这也可以工作: ```jldoctest julia> path = "/Volumes/External HD" "/Volumes/External HD" julia> name = "data" "data" julia> ext = "csv" "csv" julia> `sort $path/$name.$ext` `sort '/Volumes/External HD/data.csv'` ``` 如你所见,`path` 变量中的空格被恰当地转义了。但是,如果你*想*插入多个单词怎么办?在此情况下,只需使用数组(或其它可迭代容器): ```jldoctest julia> files = ["/etc/passwd","/Volumes/External HD/data.csv"] 2-element Vector{String}: "/etc/passwd" "/Volumes/External HD/data.csv" julia> `grep foo $files` `grep foo /etc/passwd '/Volumes/External HD/data.csv'` ``` 如果将数组作为 shell 单词的一部分插入,Julia 将模拟 shell 的 `{a,b,c}` 参数生成: ```jldoctest julia> names = ["foo","bar","baz"] 3-element Vector{String}: "foo" "bar" "baz" julia> `grep xylophone $names.txt` `grep xylophone foo.txt bar.txt baz.txt` ``` 此外,若在同一单词中插入多个数组,则将模拟 shell 的笛卡尔积生成行为: ```jldoctest julia> names = ["foo","bar","baz"] 3-element Vector{String}: "foo" "bar" "baz" julia> exts = ["aux","log"] 2-element Vector{String}: "aux" "log" julia> `rm -f $names.$exts` `rm -f foo.aux foo.log bar.aux bar.log baz.aux baz.log` ``` 因为可以插入字面量数组,所以你可以使用此生成功能,而无需先创建临时数组对象: ```jldoctest julia> `rm -rf $["foo","bar","baz","qux"].$["aux","log","pdf"]` `rm -rf foo.aux foo.log foo.pdf bar.aux bar.log bar.pdf baz.aux baz.log baz.pdf qux.aux qux.log qux.pdf` ``` ## 引用 不可避免地,我们会想要编写不那么简单的命令,且有必要使用引号。下面是 shell 提示符下单行 Perl 程序的简单示例: ``` sh$ perl -le '$|=1; for (0..3) { print }' 0 1 2 3 ``` 该 Perl 表达式需要使用单引号有两个原因:一是为了避免空格将表达式分解为多个 shell 单词,二是为了在使用像 `$|`(是的,这在 Perl 中是变量名)这样的 Perl 变量时避免发生插值。在其它情况下,你可能想要使用双引号来*真的*进行插值: ``` sh$ first="A" sh$ second="B" sh$ perl -le '$|=1; print for @ARGV' "1: $first" "2: $second" 1: A 2: B ``` 总之,Julia 反引号语法是经过精心设计的,因此你可以只是将 shell 命令剪切并粘贴到反引号中,接着它们将会工作:转义、引用和插值行为与 shell 相同。唯一的不同是,插值是集成的并且知道在 Julia 的概念中什么是单个字符串值、什么是多个值的容器。让我们在 Julia 中尝试上面的两个例子: ```jldoctest julia> A = `perl -le '$|=1; for (0..3) { print }'` `perl -le '$|=1; for (0..3) { print }'` julia> run(A); 0 1 2 3 julia> first = "A"; second = "B"; julia> B = `perl -le 'print for @ARGV' "1: $first" "2: $second"` `perl -le 'print for @ARGV' '1: A' '2: B'` julia> run(B); 1: A 2: B ``` 结果是相同的,且 Julia 的插值行为模仿了 shell 的并对其做了一些改进,因为 Julia 支持头等的可迭代对象,但大多数 shell 通过使用空格分隔字符串来实现这一点,而这又引入了歧义。在尝试将 shell 命令移植到 Julia 中时,请先试着剪切并粘贴它。因为 Julia 会在运行命令前向你显示命令,所以你可以在不造成任何破坏的前提下轻松并安全地检查命令的解释。 ## 管道 Shell 元字符,如 `|`、`&` 和 `>`,在 Julia 的反引号中需被引用(或转义): ```jldoctest julia> run(`echo hello '|' sort`); hello | sort julia> run(`echo hello \| sort`); hello | sort ``` 此表达式调用 `echo` 命令并以三个单词作为其参数:`hello`、`|` 和 `sort`。结果是只打印了一行:`hello | sort`。那么,如何构造管道呢?为此,请使用 [`pipeline`](@ref),而不是在反引号内使用 `'|'`: ```jldoctest julia> run(pipeline(`echo hello`, `sort`)); hello ``` 这将 `echo` 命令的输出传输到 `sort` 命令中。当然,这不是很有趣,因为只有一行要排序,但是我们的当然可以做更多、更有趣的事: ```julia-repl julia> run(pipeline(`cut -d: -f3 /etc/passwd`, `sort -n`, `tail -n5`)) 210 211 212 213 214 ``` 这将打印在 UNIX 系统上最高的五个用户 ID。`cut`、`sort` 和 `tail` 命令都是当前 `julia` 进程的直接子进程,这中间没有 shell 进程的干预。Julia 自己负责设置管道和连接文件描述符,而这通常由 shell 完成。因为 Julia 自己做了这些事,所以它能更好的控制并做 shell 做不到的一些事情。 Julia 可以并行地运行多个命令: ```jldoctest; filter = r"(world\nhello|hello\nworld)" julia> run(`echo hello` & `echo world`); world hello ``` 这里的输出顺序是不确定的,因为两个 `echo` 进程几乎同时启动,并且争着先写入 [`stdout`](@ref) 描述符和 `julia` 父进程。Julia 允许你将这两个进程的输出通过管道传输到另一个程序: ```jldoctest julia> run(pipeline(`echo world` & `echo hello`, `sort`)); hello world ``` 在 UNIX 管道方面,这里发生的是,一个 UNIX 管道对象由两个 `echo` 进程创建和写入,管道的另一端由 `sort` 命令读取。 IO 重定向可以通过向 `pipeline` 函数传递关键字参数 `stdin`、`stdout` 和 `stderr` 来实现: ```julia pipeline(`do_work`, stdout=pipeline(`sort`, "out.txt"), stderr="errs.txt") ``` ### 避免管道中的死锁 在单个进程中读取和写入管道的两端时,避免强制内核缓冲所有数据是很重要的。 例如,在读取命令的所有输出时,请调用 `read(out, String)`,而非 `wait(process)`,因为前者会积极地消耗由该进程写入的所有数据,而后者在等待读取者连接时会尝试将数据存储内核的缓冲区中。 另一个常见的解决方案是将读取者和写入者分离到单独的 [`Task`](@ref) 中: ```julia writer = @async write(process, "data") reader = @async do_compute(read(process, String)) wait(writer) fetch(reader) ``` (通常,reader 不是一个单独的任务,因为无论如何我们都会立即`fetch`它)。 ### 复杂示例 高级编程语言、头等的命令抽象以及进程间管道的自动设置,三者组合起来非常强大。为了更好地理解可被轻松创建的复杂管道,这里有一些更复杂的例子,以避免对单行 Perl 程序的滥用。 ```jldoctest prefixer; filter = r"([A-B] [0-5])" julia> prefixer(prefix, sleep) = `perl -nle '$|=1; print "'$prefix' ", $_; sleep '$sleep';'`; julia> run(pipeline(`perl -le '$|=1; for(0..5){ print; sleep 1 }'`, prefixer("A",2) & prefixer("B",2))); B 0 A 1 B 2 A 3 B 4 A 5 ``` 这是一个经典的例子,一个生产者为两个并发的消费者提供内容:一个 `perl` 进程生成从数字 0 到 5 的行,而两个并行进程则使用该输出,一个行首加字母「A」,另一个行首加字母「B」。哪个进程使用第一行是不确定的,但是一旦赢得了竞争,这些行会先后被其中一个进程及另一个进程交替使用。(在 Perl 中设置 `$|=1` 会导致每个 print 语句刷新 [`stdout`](@ref) 句柄,这是本例工作所必需的。此外,所有输出将被缓存并一次性打印到管道中,以便只由一个消费者进程读取。) 这是一个更加复杂的多阶段生产者——消费者示例: ```jldoctest prefixer; filter = r"[A-B] [X-Z] [0-5]" julia> run(pipeline(`perl -le '$|=1; for(0..5){ print; sleep 1 }'`, prefixer("X",3) & prefixer("Y",3) & prefixer("Z",3), prefixer("A",2) & prefixer("B",2))); A X 0 B Y 1 A Z 2 B X 3 A Y 4 B Z 5 ``` 此示例与前一个类似,不同之处在于本例中的消费者有两个阶段,并且阶段间有不同的延迟,因此它们使用不同数量的并行 worker 来维持饱和的吞吐量。 我们强烈建议你尝试所有这些例子,以便了解它们的工作原理。 ## `Cmd`对象 反引号语法创建一个 [`Cmd`](@ref) 类型的对象。 此类对象也可以直接从现有的 `Cmd` 或参数列表构造: ```julia run(Cmd(`pwd`, dir="..")) run(Cmd(["pwd"], detach=true, ignorestatus=true)) ``` 这允许你通过关键字参数指定 `Cmd` 的执行环境的几个方面。 例如,`dir` 关键字提供对 `Cmd` 工作目录的控制: ```jldoctest julia> run(Cmd(`pwd`, dir="/")); / ``` 并且 `env` 关键字允许您设置执行环境变量: ```jldoctest julia> run(Cmd(`sh -c "echo foo \$HOWLONG"`, env=("HOWLONG" => "ever!",))); foo ever! ``` 有关其它关键字参数,请参阅 [`Cmd`](@ref)。 [`setenv`](@ref) 和 [`addenv`](@ref) 命令分别提供了另一种替换或添加到 `Cmd` 执行环境变量的方法: ```jldoctest julia> run(setenv(`sh -c "echo foo \$HOWLONG"`, ("HOWLONG" => "ever!",))); foo ever! julia> run(addenv(`sh -c "echo foo \$HOWLONG"`, "HOWLONG" => "ever!")); foo ever! ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
8153
# 栈跟踪 `StackTraces` 模块提供了简单的栈跟踪功能,这些栈跟踪信息既可读又易于编程使用。 ## 查看栈跟踪 获取栈跟踪信息的主要函数是 [`stacktrace`](@ref): ```julia-repl 6-element Array{Base.StackTraces.StackFrame,1}: top-level scope eval at boot.jl:317 [inlined] eval(::Module, ::Expr) at REPL.jl:5 eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 macro expansion at REPL.jl:116 [inlined] (::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92 ``` 调用 [`stacktrace()`](@ref) 会返回一个 [`StackTraces.StackFrame`](@ref) 数组。为了使用方便,可以用 [`StackTraces.StackTrace`](@ref) 来代替 `Vector{StackFrame}`。下面例子中 `[...]` 的意思是这部分输出的内容可能会根据代码的实际执行情况而定。 ```julia-repl julia> example() = stacktrace() example (generic function with 1 method) julia> example() 7-element Array{Base.StackTraces.StackFrame,1}: example() at REPL[1]:1 top-level scope eval at boot.jl:317 [inlined] [...] julia> @noinline child() = stacktrace() child (generic function with 1 method) julia> @noinline parent() = child() parent (generic function with 1 method) julia> grandparent() = parent() grandparent (generic function with 1 method) julia> grandparent() 9-element Array{Base.StackTraces.StackFrame,1}: child() at REPL[3]:1 parent() at REPL[4]:1 grandparent() at REPL[5]:1 [...] ``` 注意,在调用 [`stacktrace()`](@ref) 的时,通常会出现 `eval at boot.jl` 这帧。 当从 REPL 里调用 [`stacktrace()`](@ref) 的时候,还会显示 `REPL.jl` 里的一些额外帧,就像下面一样: ```julia-repl julia> example() = stacktrace() example (generic function with 1 method) julia> example() 7-element Array{Base.StackTraces.StackFrame,1}: example() at REPL[1]:1 top-level scope eval at boot.jl:317 [inlined] eval(::Module, ::Expr) at REPL.jl:5 eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 macro expansion at REPL.jl:116 [inlined] (::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92 ``` ## 抽取有用信息 每个 [`StackTraces.StackFrame`](@ref) 都会包含函数名,文件名,代码行数,lambda 信息,一个用于确认此帧是否被内联的标帜,一个用于确认函数是否为 C 函数的标帜(在默认的情况下 C 函数不会出现在栈跟踪信息中)以及一个用整数表示的指针,它是由 [`backtrace`](@ref) 返回的: ```julia-repl julia> frame = stacktrace()[3] eval(::Module, ::Expr) at REPL.jl:5 julia> frame.func :eval julia> frame.file Symbol("~/julia/usr/share/julia/stdlib/v0.7/REPL/src/REPL.jl") julia> frame.line 5 julia> frame.linfo MethodInstance for eval(::Module, ::Expr) julia> frame.inlined false julia> frame.from_c false julia> frame.pointer 0x00007f92d6293171 ``` 这使得我们可以通过编程的方式将栈跟踪信息用于打印日志,处理错误以及其它更多用途。 ## 错误处理 能够轻松地获取当前调用栈的状态信息在许多场景下都很有用,但最直接的应用是错误处理和调试。 ```julia-repl julia> @noinline bad_function() = undeclared_variable bad_function (generic function with 1 method) julia> @noinline example() = try bad_function() catch stacktrace() end example (generic function with 1 method) julia> example() 7-element Array{Base.StackTraces.StackFrame,1}: example() at REPL[2]:4 top-level scope eval at boot.jl:317 [inlined] [...] ``` 你可能已经注意到了,上述例子中第一个栈帧指向了[`stacktrace`](@ref)被调用的第 4 行,而不是 *bad_function* 被调用的第 2 行,且完全没有出现 `bad_function` 的栈帧。这是也是可以理解的,因为 [`stacktrace`](@ref) 是在 *catch* 的上下文中被调用的。虽然在这个例子中很容易查找到错误的真正源头,但在复杂的情况下查找错误源并不是一件容易的事。 为了补救,我们可以将 [`catch_backtrace`](@ref) 的输出传递给 [`stacktrace`](@ref)。[`catch_backtrace`](@ref) 会返回最近发生异常的上下文中的栈信息,而不是返回当前上下文中的调用栈信息。 ```julia-repl julia> @noinline bad_function() = undeclared_variable bad_function (generic function with 1 method) julia> @noinline example() = try bad_function() catch stacktrace(catch_backtrace()) end example (generic function with 1 method) julia> example() 8-element Array{Base.StackTraces.StackFrame,1}: bad_function() at REPL[1]:1 example() at REPL[2]:2 [...] ``` 可以看到,现在栈跟踪会显示正确的行号以及之前缺失的栈帧。 ```julia-repl julia> @noinline child() = error("Whoops!") child (generic function with 1 method) julia> @noinline parent() = child() parent (generic function with 1 method) julia> @noinline function grandparent() try parent() catch err println("ERROR: ", err.msg) stacktrace(catch_backtrace()) end end grandparent (generic function with 1 method) julia> grandparent() ERROR: Whoops! 10-element Array{Base.StackTraces.StackFrame,1}: error at error.jl:33 [inlined] child() at REPL[1]:1 parent() at REPL[2]:1 grandparent() at REPL[3]:3 [...] ``` ## 异常栈与[`current_exceptions`](@ref) !!! compat "Julia 1.1" 异常栈需要 Julia 1.1 及以上版本。 在处理一个异常时,后续的异常同样可能被抛出。观察这些异常对定位问题的源头极有帮助。Julia runtime 支持将每个异常发生后推入一个内部的*异常栈*。当代码正常退出一个`catch`语句,可认为所有被推入栈中的异常在相应的`try`语句中被成功处理并已从栈中移除。 存放当前异常的栈可通过测试函数 [`current_exceptions`](@ref) 获取,例如 ```julia-repl julia> try error("(A) The root cause") catch try error("(B) An exception while handling the exception") catch for (exc, bt) in current_exceptions() showerror(stdout, exc, bt) println(stdout) end end end (A) The root cause Stacktrace: [1] error(::String) at error.jl:33 [2] top-level scope at REPL[7]:2 [3] eval(::Module, ::Any) at boot.jl:319 [4] eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 [5] macro expansion at REPL.jl:117 [inlined] [6] (::getfield(REPL, Symbol("##26#27")){REPL.REPLBackend})() at task.jl:259 (B) An exception while handling the exception Stacktrace: [1] error(::String) at error.jl:33 [2] top-level scope at REPL[7]:5 [3] eval(::Module, ::Any) at boot.jl:319 [4] eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 [5] macro expansion at REPL.jl:117 [inlined] [6] (::getfield(REPL, Symbol("##26#27")){REPL.REPLBackend})() at task.jl:259 ``` 在本例中,根源异常(A)排在栈头,其后放置着延伸异常(B)。 在正常退出(例如,不抛出新异常)两个 catch 块后,所有异常都被移除出栈,无法访问。 异常栈被存放于发生异常的 `Task` 处。当某个任务失败,出现意料外的异常时,`current_exceptions(task)` 可被用于观察该任务的异常栈。 ## [`stacktrace`](@ref) 与 [`backtrace`](@ref) 的比较 调用 [`backtrace`](@ref) 会返回一个 `Union{Ptr{Nothing}, Base.InterpreterIP}` 的数组,可以将其传给 [`stacktrace`](@ref) 函数进行转化: ```julia-repl julia> trace = backtrace() 18-element Array{Union{Ptr{Nothing}, Base.InterpreterIP},1}: Ptr{Nothing} @0x00007fd8734c6209 Ptr{Nothing} @0x00007fd87362b342 Ptr{Nothing} @0x00007fd87362c136 Ptr{Nothing} @0x00007fd87362c986 Ptr{Nothing} @0x00007fd87362d089 Base.InterpreterIP(CodeInfo(:(begin Core.SSAValue(0) = backtrace() trace = Core.SSAValue(0) return Core.SSAValue(0) end)), 0x0000000000000000) Ptr{Nothing} @0x00007fd87362e4cf [...] julia> stacktrace(trace) 6-element Array{Base.StackTraces.StackFrame,1}: top-level scope eval at boot.jl:317 [inlined] eval(::Module, ::Expr) at REPL.jl:5 eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 macro expansion at REPL.jl:116 [inlined] (::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92 ``` 需要注意的是,[`backtrace`](@ref) 返回的向量有 18 个元素,而 [`stacktrace`](@ref) 返回的向量只包含6 个元素。这是因为 [`stacktrace`](@ref) 在默认情况下会移除所有底层 C 函数的栈信息。如果你想显示 C 函数调用的栈帧,可以这样做: ```julia-repl julia> stacktrace(trace, true) 21-element Array{Base.StackTraces.StackFrame,1}: jl_apply_generic at gf.c:2167 do_call at interpreter.c:324 eval_value at interpreter.c:416 eval_body at interpreter.c:559 jl_interpret_toplevel_thunk_callback at interpreter.c:798 top-level scope jl_interpret_toplevel_thunk at interpreter.c:807 jl_toplevel_eval_flex at toplevel.c:856 jl_toplevel_eval_in at builtins.c:624 eval at boot.jl:317 [inlined] eval(::Module, ::Expr) at REPL.jl:5 jl_apply_generic at gf.c:2167 eval_user_input(::Any, ::REPL.REPLBackend) at REPL.jl:85 jl_apply_generic at gf.c:2167 macro expansion at REPL.jl:116 [inlined] (::getfield(REPL, Symbol("##28#29")){REPL.REPLBackend})() at event.jl:92 jl_fptr_trampoline at gf.c:1838 jl_apply_generic at gf.c:2167 jl_apply at julia.h:1540 [inlined] start_task at task.c:268 ip:0xffffffffffffffff ``` [`backtrace`](@ref) 返回的单个指针可以通过 [`StackTraces.lookup`](@ref) 来转化成一组 [`StackTraces.StackFrame`](@ref): ```julia-repl julia> pointer = backtrace()[1]; julia> frame = StackTraces.lookup(pointer) 1-element Array{Base.StackTraces.StackFrame,1}: jl_apply_generic at gf.c:2167 julia> println("The top frame is from $(frame[1].func)!") The top frame is from jl_apply_generic! ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
23600
# [字符串](@id man-strings) 字符串是由有限个字符组成的序列。而字符在英文中一般包括字母 `A`,`B`, `C` 等、数字和常用的标点符号。这些字符由 [ASCII](https://en.wikipedia.org/wiki/ASCII) 标准统一标准化并且与 0 到 127 范围内的整数一一对应。当然,还有很多非英文字符,包括 ASCII 字符在注音或其他方面的变体,例如西里尔字母和希腊字母,以及与 ASCII 和英文均完全无关的字母系统,包括阿拉伯语,中文, 希伯来语,印度语, 日本语, 和韩语。[Unicode](https://en.wikipedia.org/wiki/Unicode) 标准对这些复杂的字符做了统一的定义,是一种大家普遍接受标准。 根据需求,写代码时可以忽略这种复杂性而只处理 ASCII 字符,也可针对可能出现的非 ASCII 文本而处理所有的字符或编码。Julia 可以简单高效地处理纯粹的 ASCII 文本以及 Unicode 文本。 甚至,在 Julia 中用 C 语言风格的代码来处理 ASCII 字符串,可以在不失性能和易读性的前提下达到预期效果。当遇到非 ASCII 文本时,Julia会优雅明确地提示错误信息而不是引入乱码。 这时,直接修改代码使其可以处理非 ASCII 数据即可。 关于 Julia 的字符串类型有一些值得注意的高级特性: * Julia 中用于字符串(和字符串字面量)的内置具体类型是 [`String`](@ref)。 它支持全部 [Unicode](https://en.wikipedia.org/wiki/Unicode) 字符 通过 [UTF-8](https://en.wikipedia.org/wiki/UTF-8) 编码。([`transcode`](@ref) 函数是 提供 Unicode 编码和其他编码转换的函数。) * 所有的字符串类型都是抽象类型 `AbstractString` 的子类型,而一些外部包定义了别的 `AbstractString` 子类型(例如为其它的编码定义的子类型)。若要定义需要字符串参数的函数,你应当声明此类型为 `AbstractString` 来让这函数接受任何字符串类型。 * 类似 C 和 Java,但是和大多数动态语言不同的是,Julia 有优秀的表示单字符的类型,即 [`AbstractChar`](@ref)。[`Char`](@ref) 是 `AbstractChar` 的内置子类型,它能表示任何 Unicode 字符的 32 位原始类型(基于 UTF-8 编码)。 * 如 Java 中那样,字符串不可改——任何 `AbstractString` 对象的值不可改变。 若要构造不同的字符串值,应当从其它字符串的部分构造一个新的字符串。 * 从概念上讲,字符串是从索引到字符的*部分函数*:对于某些索引值,它不返回字符值,而是引发异常。这允许通过编码表示形式的字节索引来实现高效的字符串索引,而不是通过字符索引——它不能简单高效地实现可变宽度的 Unicode 字符串编码。 ## [字符](@id man-characters) `Char` 类型的值代表单个字符:它只是带有特殊文本表示法和适当算术行为的 32 位原始类型,不能转化为代表 [Unicode 代码](https://en.wikipedia.org/wiki/Code_point) 的数值。(Julia 的包可能会定义别的 `AbstractChar` 子类型,比如当为了优化对其它 [字符编码](https://en.wikipedia.org/wiki/Character_encoding) 的操作时)`Char` 类型的值以这样的方式输入和显示: ```jldoctest julia> c = 'x' 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase) julia> typeof(c) Char ``` 你可以轻松地将 `Char` 转换为其对应的整数值,即 Unicode 代码: ```jldoctest julia> c = Int('x') 120 julia> typeof(c) Int64 ``` 在 32 位的计算机中,[`typeof(c)`](@ref) 将显示为 [`Int32`](@ref)。你可以轻松地将一个整数值转回 Char: ```jldoctest julia> Char(120) 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase) ``` 并非所有的整数值都是有效的 Unicode 代码,但是为了性能,`Char` 的转化不会检查每个值是否有效。如果你想检查每个转换的值是否为有效值,请使用 [`isvalid`](@ref) 函数: ```jldoctest julia> Char(0x110000) '\U110000': Unicode U+110000 (category In: Invalid, too high) julia> isvalid(Char, 0x110000) false ``` 目前,有效的 Unicode 码点为,从 `U+0000` 至 `U+D7FF`,以及从 `U+E000` 至 `U+10FFFF`。 它们还未全部被赋予明确的含义,也还没必要能被程序识别;然而,所有的这些值都被认为是有效的 Unicode 字符。 你可以在单引号中输入任何 Unicode 字符,通过使用 `\u` 加上至多 4 个十六进制数字或者 `\U` 加上至多 8 个十六进制数(最长的有效值也只需要 6 个): ```jldoctest julia> '\u0' '\0': ASCII/Unicode U+0000 (category Cc: Other, control) julia> '\u78' 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase) julia> '\u2200' '∀': Unicode U+2200 (category Sm: Symbol, math) julia> '\U10ffff' '\U10ffff': Unicode U+10FFFF (category Cn: Other, not assigned) ``` Julia 使用系统默认的区域和语言设置来确定,哪些字符可以被正确显示,哪些需要用 `\u` 或 `\U` 的转义来显示。除 Unicode 转义格式之外,还可以使用所有的[传统 C 语言转义输入形式](https://en.wikipedia.org/wiki/C_syntax#Backslash_escapes): ```jldoctest julia> Int('\0') 0 julia> Int('\t') 9 julia> Int('\n') 10 julia> Int('\e') 27 julia> Int('\x7f') 127 julia> Int('\177') 127 ``` 你可以对 `Char` 的值进行比较和有限的算术运算: ```jldoctest julia> 'A' < 'a' true julia> 'A' <= 'a' <= 'Z' false julia> 'A' <= 'X' <= 'Z' true julia> 'x' - 'a' 23 julia> 'A' + 1 'B': ASCII/Unicode U+0042 (category Lu: Letter, uppercase) ``` ## 字符串基础 字符串字面量由双引号或三重双引号分隔: ```jldoctest helloworldstring julia> str = "Hello, world.\n" "Hello, world.\n" julia> """Contains "quote" characters""" "Contains \"quote\" characters" ``` Long lines in strings can be broken up by preceding the newline with a backslash (`\`): ```jldoctest julia> "This is a long \ line" "This is a long line" ``` 如果要字符串中提取字符,可以对其进行索引: ```jldoctest helloworldstring julia> str[begin] 'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase) julia> str[1] 'H': ASCII/Unicode U+0048 (category Lu: Letter, uppercase) julia> str[6] ',': ASCII/Unicode U+002C (category Po: Punctuation, other) julia> str[end] '\n': ASCII/Unicode U+000A (category Cc: Other, control) ``` 许多的 Julia 对象,包括字符串,都可以用整数进行索引。第一个元素的索引(字符串的第一个字符)由 [`firstindex(str)`](@ref) 返回,最后一个元素(字符)的索引由 [`lastindex(str)` ](@ref) 返回。关键字 `begin` 和 `end` 可以在索引操作中使用,它们分别表示给定维度上的第一个和最后一个索引。字符串索引就像 Julia 中的大多数索引一样,是从 1 开始的:对于任何 `AbstractString`, `firstindex` 方法总是返回 `1`。但是,下面我们将会看到,对于一个字符串来说 `lastindex(str)` 和 `length(str)` 的结果*不一定*相同,因为 Unicode 字符可能由多个编码单元组成。 你可以用 [`end`](@ref) 进行算术以及其它操作,就像一个普通值一样: ```jldoctest helloworldstring julia> str[end-1] '.': ASCII/Unicode U+002E (category Po: Punctuation, other) julia> str[end÷2] ' ': ASCII/Unicode U+0020 (category Zs: Separator, space) ``` 使用小于 `begin` (`1`) 或大于 `end` 的索引会引发错误: ```jldoctest helloworldstring julia> str[begin-1] ERROR: BoundsError: attempt to access 14-codeunit String at index [0] [...] julia> str[end+1] ERROR: BoundsError: attempt to access 14-codeunit String at index [15] [...] ``` 你也可以用范围索引来提取子字符串: ```jldoctest helloworldstring julia> str[4:9] "lo, wo" ``` 注意,表达式 `str[k]` 和 `str[k:k]` 不会给出相同的结果: ```jldoctest helloworldstring julia> str[6] ',': ASCII/Unicode U+002C (category Po: Punctuation, other) julia> str[6:6] "," ``` 前者是一个 `Char` 类型的单个字符,而后者是一个恰好只包含一个字符的字符串。在 Julia 中,这些是不同的。 范围索引复制原始字符串的选定部分。此外,可以使用类型 [`SubString`](@ref),将视图创建为字符串, 例如: ```jldoctest julia> str = "long string" "long string" julia> substr = SubString(str, 1, 4) "long" julia> typeof(substr) SubString{String} ``` 几个标准函数,像 [`chop`](@ref), [`chomp`](@ref) 或者 [`strip`](@ref) 都会返回一个 [`SubString`](@ref)。 ## Unicode 和 UTF-8 Julia 完全支持 Unicode 字符和字符串。[如上所述](@ref man-characters),在字符字面量中,Unicode 代码可以用 Unicode `\u` 和 `\U` 转义序列表示,也可以用所有标准 C 转义序列表示。这些同样可以用来写字符串字面量: ```jldoctest unicodestring julia> s = "\u2200 x \u2203 y" "∀ x ∃ y" ``` 这些 Unicode 字符是作为转义还是特殊字符显示,取决于你终端的语言环境设置以及它对 Unicode 的支持。字符串字面量用 UTF-8 编码。UTF-8 是一种可变长度的编码,也就是说并非所有字符都以相同的字节数(code units)编码。在 UTF-8 中,ASCII 字符(小于 0x80(128) 的那些)如它们在 ASCII 中一样使用单字节编码;而 0x80 及以上的字符使用最多 4 个字节编码。 在 Julia 中字符串索引指的是代码单元(对于 UTF-8 来说等同于字节/byte),固定宽度的构建块用于编码任意字符(code point)。这意味着并非每个索引到 UTF-8 字符串的字节都必须是一个字符的有效索引。如果在这种无效字节索引处索引字符串,将会报错: ```jldoctest unicodestring julia> s[1] '∀': Unicode U+2200 (category Sm: Symbol, math) julia> s[2] ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'∀', [4]=>' ' Stacktrace: [...] julia> s[3] ERROR: StringIndexError: invalid index [3], valid nearby indices [1]=>'∀', [4]=>' ' Stacktrace: [...] julia> s[4] ' ': ASCII/Unicode U+0020 (category Zs: Separator, space) ``` 在这种情况下,字符 `∀` 是一个三字节字符,因此索引 2 和 3 都是无效的,而下一个字符的索引是 4;这个接下来的有效索引可以用 [`nextind(s,1)`](@ref) 来计算,再接下来的用 `nextind(s,4)`,依此类推。 如果倒数第二个字符是多字节字符,由于 `end` 总是集合中最后一个有效索引,这时 `end-1` 将会是无效索引。 ```jldoctest unicodestring julia> s[end-1] ' ': ASCII/Unicode U+0020 (category Zs: Separator, space) julia> s[end-2] ERROR: StringIndexError: invalid index [9], valid nearby indices [7]=>'∃', [10]=>' ' Stacktrace: [...] julia> s[prevind(s, end, 2)] '∃': Unicode U+2203 (category Sm: Symbol, math) ``` 第一种情况可以,因为最后一个字符 `y` 和空格都是一字节的字符,而 `end-2` 索引到中间的 `∃` 由多字节表示。正确的方法是使用 `prevind(s, lastindex(s), 2)`,或者,如果你使用该值来索引`s`,则可以写为`s[prevind(s, end, 2) ]` , `end` 展开为 `lastindex(s)`。 使用范围索引提取子字符串也需要有效的字节索引,不然就会抛出错误:   ```jldoctest unicodestring julia> s[1:1] "∀" julia> s[1:2] ERROR: StringIndexError: invalid index [2], valid nearby indices [1]=>'∀', [4]=>' ' Stacktrace: [...] julia> s[1:4] "∀ " ``` 由于可变长度的编码,字符串中的字符数(由 [`length(s)`](@ref) 给出)并不总是等于最后一个索引的数字。如果你从 1 到 [`lastindex(s)`](@ref) 迭代并索引到 `s`,未报错时返回的字符序列是包含字符串 `s` 的字符序列。所以,总是有 `length(s) <= lastindex(s)`,这是因为字符串中的每个字符必须有它自己的索引。下面是对 `s` 的字符进行迭代的一个冗长而低效的方式: ```jldoctest unicodestring julia> for i = firstindex(s):lastindex(s) try println(s[i]) catch # ignore the index error end end ∀ x ∃ y ``` 空行上面其实是有空格的。幸运的是,上面的笨拙写法不是对字符串中字符进行迭代所必须的——因为你只需把字符串本身用作迭代对象,而不需要额外处理: ```jldoctest unicodestring julia> for c in s println(c) end ∀ x ∃ y ``` 如果需要为字符串获取有效索引,可以使用 [`nextind`](@ref) 和 [`prevind`](@ref) 函数递增/递减到下一个/前一个有效索引,如前所述。你也可以使用 [`eachindex`](@ref) 函数迭代有效的字符索引: ```jldoctest unicodestring julia> collect(eachindex(s)) 7-element Vector{Int64}: 1 4 5 6 7 10 11 ``` 要访问编码的原始代码单位(UTF-8 的字节),可以使用 [`codeunit(s,i)`](@ref)函数,其中索引 `i` 从 `1` 连续运行到 [`ncodeunits(s)`](@ref)。 [`codeunits(s)`](@ref) 函数返回一个 `AbstractVector{UInt8}` 包装器,允许您以数组的形式访问这些原始代码单元(字节)。 Julia 中的字符串可以包含无效的 UTF-8 代码单元序列。这个惯例允许把任何字序列当作 `String`。在这种情形下的一个规则是,当从左到右解析代码单元序列时,字符由匹配下面开头位模式之一的最长的 8 位代码单元序列组成(每个 `x` 可以是 `0` 或者 `1`): * `0xxxxxxx`; * `110xxxxx` `10xxxxxx`; * `1110xxxx` `10xxxxxx` `10xxxxxx`; * `11110xxx` `10xxxxxx` `10xxxxxx` `10xxxxxx`; * `10xxxxxx`; * `11111xxx`. 特别地,这意味着过长和过高的代码单元序列及其前缀将被视为单个无效字符,而不是多个无效字符。这个规则最好用一个例子来解释: ```julia-repl julia> s = "\xc0\xa0\xe2\x88\xe2|" "\xc0\xa0\xe2\x88\xe2|" julia> foreach(display, s) '\xc0\xa0': [overlong] ASCII/Unicode U+0020 (category Zs: Separator, space) '\xe2\x88': Malformed UTF-8 (category Ma: Malformed, bad data) '\xe2': Malformed UTF-8 (category Ma: Malformed, bad data) '|': ASCII/Unicode U+007C (category Sm: Symbol, math) julia> isvalid.(collect(s)) 4-element BitArray{1}: 0 0 0 1 julia> s2 = "\xf7\xbf\xbf\xbf" "\U1fffff" julia> foreach(display, s2) '\U1fffff': Unicode U+1FFFFF (category In: Invalid, too high) ``` 我们可以看到字符串 `s` 中的前两个代码单元形成了一个过长的空格字符编码。这是无效的,但是在字符串中作为单个字符是可以接受的。接下来的两个代码单元形成了一个有效的 3 位 UTF-8 序列开头。然而,第五个代码单元 `\xe2` 不是它的有效延续,所以代码单元 3 和 4 在这个字符串中也被解释为格式错误的字符。同理,由于 `|` 不是它的有效延续,代码单元 5 形成了一个格式错误的字符。最后字符串 `s2` 包含了一个太高的代码。 Julia 默认使用 UTF-8 编码,对于新编码的支持可以通过包加上。例如,[LegacyStrings.jl](https://github.com/JuliaStrings/LegacyStrings.jl) 包实现了 `UTF16String` 和 `UTF32String` 类型。关于其它编码的额外讨论以及如何实现对它们的支持暂时超过了这篇文档的讨论范围。UTF-8 编码相关问题的进一步讨论参见下面的[字节数组字面量](@ref man-byte-array-literals)章节。[`transcode`](@ref) 函数可在各种 UTF-xx 编码之间转换,主要用于外部数据和包。 ## [拼接](@id man-concatenation) 最常见最有用的字符串操作是级联: ```jldoctest stringconcat julia> greet = "Hello" "Hello" julia> whom = "world" "world" julia> string(greet, ", ", whom, ".\n") "Hello, world.\n" ``` 意识到像对无效 UTF-8 字符进行级联这样的潜在危险情形是非常重要的。生成的字符串可能会包含和输入字符串不同的字符,并且其中字符的数目也可能少于被级联字符串中字符数目之和,例如: ```julia-repl julia> a, b = "\xe2\x88", "\x80" ("\xe2\x88", "\x80") julia> c = a*b "∀" julia> collect.([a, b, c]) 3-element Array{Array{Char,1},1}: ['\xe2\x88'] ['\x80'] ['∀'] julia> length.([a, b, c]) 3-element Array{Int64,1}: 1 1 1 ``` 这种情形只可能发生于无效 UTF-8 字符串上。对于有效 UTF-8 字符串,级联保留字符串中的所有字符和字符串的总长度。 Julia 也提供 [`*`](@ref) 用于字符串级联: ```jldoctest stringconcat julia> greet * ", " * whom * ".\n" "Hello, world.\n" ``` 尽管对于提供 `+` 函数用于字符串拼接的语言使用者而言,`*` 似乎是一个令人惊讶的选择,但 `*` 的这种用法在数学中早有先例,尤其是在抽象代数中。 在数学上,`+` 通常表示可交换运算(*commutative* operation)——运算对象的顺序不重要。一个例子是矩阵加法:对于任何形状相同的矩阵 `A` 和 `B`,都有 `A + B == B + A`。与之相反,`*` 通常表示不可交换运算——运算对象的顺序很重要。例如,对于矩阵乘法,一般 `A * B != B * A`。同矩阵乘法类似,字符串拼接是不可交换的:`greet * whom != whom * greet`。在这一点上,对于插入字符串的拼接操作,`*` 是一个自然而然的选择,与它在数学中的用法一致。 更确切地说,有限长度字符串集合 *S* 和字符串拼接操作 `*` 构成了一个[自由幺半群](https://en.wikipedia.org/wiki/Free_monoid) (*S*, `*`)。该集合的单位元是空字符串,`""`。当一个自由幺半群不是交换的时,它的运算通常表示为 `\cdot`,`*`,或者类似的符号,而非暗示交换性的 `+`。 ## [插值](@id string-interpolation) 拼接构造字符串的方式有时有些麻烦。为了减少对于 [`string`](@ref) 的冗余调用或者重复地做乘法,Julia 允许像 Perl 中一样使用 `$` 对字符串字面量进行插值: ```jldoctest stringconcat julia> "$greet, $whom.\n" "Hello, world.\n" ``` 这更易读更方便,而且等效于上面的字符串拼接——系统把这个显然一行的字符串字面量重写成带参数的字符串字面量拼接 `string(greet, ", ", whom, ".\n")`。 在 `$` 之后最短的完整表达式被视为插入其值于字符串中的表达式。因此,你可以用括号向字符串中插入任何表达式: ```jldoctest julia> "1 + 2 = $(1 + 2)" "1 + 2 = 3" ``` 拼接和插值都调用 [`string`](@ref) 以转换对象为字符串形式。 然而,`string` 实际上仅仅返回了 [`print`](@ref) 的输出,因此,新的类型应该添加 [`print`](@ref) 或 [`show`](@ref) 方法,而不是 `string` 方法。 多数非 `AbstractString` 对象被转换为和它们作为文本表达式输入的方式密切对应的字符串: ```jldoctest julia> v = [1,2,3] 3-element Vector{Int64}: 1 2 3 julia> "v: $v" "v: [1, 2, 3]" ``` [`string`](@ref) 是 `AbstractString` 和 `AbstractChar` 值的标识,所以它们作为自身被插入字符串,无需引用,无需转义: ```jldoctest julia> c = 'x' 'x': ASCII/Unicode U+0078 (category Ll: Letter, lowercase) julia> "hi, $c" "hi, x" ``` 若要在字符串字面量中包含文本 `$`,就用反斜杠转义: ```jldoctest julia> print("I have \$100 in my account.\n") I have $100 in my account. ``` ## 三引号字符串字面量 当使用三引号(`"""..."""`)创建字符串时,它们有一些在创建更长文本块时可能用到的特殊行为。 首先,三引号字符串也被反缩进到最小缩进线的水平。这在定义包含缩进的字符串时很有用。例如: ```jldoctest julia> str = """ Hello, world. """ " Hello,\n world.\n" ``` 在这里,后三引号 `"""` 前面的最后一(空)行设置了缩进级别。 反缩进级别被确定为所有行中空格或制表符的最大公共起始序列,不包括前三引号 `"""` 后面的一行以及只包含空格或制表符的行(总包含结尾 `"""` 的行)。那么对于所有不包括前三引号 `"""` 后面文本的行而言,公共起始序列就被移除了(包括只含空格和制表符而以此序列开始的行),例如: ```jldoctest julia> """ This is a test""" " This\nis\n a test" ``` 接下来,如果前三引号 `"""` 后面紧跟换行符,那么换行符就从生成的字符串中被剥离。 ```julia """hello""" ``` 等价于 ```julia """ hello""" ``` 但是 ```julia """ hello""" ``` 将在开头包含一个文本换行符。 换行符的移除是在反缩进之后进行的。例如: ```jldoctest julia> """ Hello, world.""" "Hello,\nworld." ``` 如果使用反斜杠消除换行符,下一行的缩进也会被消除: ```jldoctest julia> """ Averylong\ word""" "Averylongword" ``` 尾随空格保持不变。 三引号字符串字面量可不带转义地包含 `"` 符号。 注意,无论是用单引号还是三引号,在文本字符串中换行符都会生成一个换行 (LF) 字符 `\n`,即使你的编辑器使用回车组合符 `\r` (CR) 或 CRLF 来结束行。为了在字符串中包含 CR,总是应该使用显式转义符 `\r`;比如,可以输入文本字符串 `"a CRLF line ending\r\n"`。 ## 常见操作 你可以使用标准的比较操作符按照字典顺序比较字符串: ```jldoctest julia> "abracadabra" < "xylophone" true julia> "abracadabra" == "xylophone" false julia> "Hello, world." != "Goodbye, world." true julia> "1 + 2 = 3" == "1 + 2 = $(1 + 2)" true ``` 你可以使用 [`findfirst`](@ref) 与 [`findlast`](@ref) 函数搜索特定字符的索引: ```jldoctest julia> findfirst(isequal('o'), "xylophone") 4 julia> findlast(isequal('o'), "xylophone") 7 julia> findfirst(isequal('z'), "xylophone") ``` 你可以带上第三个参数,用 [`findnext`](@ref) 与 [`findprev`](@ref) 函数来在给定偏移量处搜索字符: ```jldoctest julia> findnext(isequal('o'), "xylophone", 1) 4 julia> findnext(isequal('o'), "xylophone", 5) 7 julia> findprev(isequal('o'), "xylophone", 5) 4 julia> findnext(isequal('o'), "xylophone", 8) ``` 你可以用 [`occursin`](@ref) 函数检查在字符串中某子字符串可否找到。 ```jldoctest julia> occursin("world", "Hello, world.") true julia> occursin("o", "Xylophon") true julia> occursin("a", "Xylophon") false julia> occursin('o', "Xylophon") true ``` 最后那个例子表明 [`occursin`](@ref) 也可用于搜寻字符字面量。 另外还有两个方便的字符串函数 [`repeat`](@ref) 和 [`join`](@ref): ```jldoctest julia> repeat(".:Z:.", 10) ".:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:..:Z:." julia> join(["apples", "bananas", "pineapples"], ", ", " and ") "apples, bananas and pineapples" ``` 其它有用的函数还包括: * [`firstindex(str)`](@ref) 给出可用来索引到 `str` 的最小(字节)索引(对字符串来说这总是 1,对于别的容器来说却不一定如此)。 * [`lastindex(str)`](@ref) 给出可用来索引到 `str` 的最大(字节)索引。 * [`length(str)`](@ref),`str` 中的字符个数。 * [`length(str, i, j)`](@ref),`str` 中从 `i` 到 `j` 的有效字符索引个数。 * [`ncodeunits(str)`](@ref),字符串中[代码单元](https://en.wikipedia.org/wiki/Character_encoding#Terminology)([码元](https://zh.wikipedia.org/wiki/字符编码#字符集、代码页,与字符映射))的数目。 * [`codeunit(str, i)`](@ref) 给出在字符串 `str` 中索引为 `i` 的代码单元值。 * [`thisind(str, i)`](@ref),给定一个字符串的任意索引,查找索引点所在的首个索引。 * [`nextind(str, i, n=1)`](@ref) 查找在索引 `i` 之后第 `n` 个字符的开头。 * [`prevind(str, i, n=1)`](@ref) 查找在索引 `i` 之前第 `n` 个字符的开始。 ## [非标准字符串字面量](@id non-standard-string-literals) 有时当你想构造字符串或者使用字符串语义,标准的字符串构造却不能很好的满足需求。Julia 为这种情形提供了非标准字符串字面量。非标准字符串字面量看似常规双引号字符串字面量,但却直接加上了标识符前缀因而并不那么像普通的字符串字面量。 下面将提到,[正则表达式](@ref man-regex-literals),[字节数组字面量] (@ref man-byte-array-literals) 和 [版本号字面量](@ref man-version-number-literals) 都是非标准字符串字面量的例子。 更详细的文档见 [元编程](@ref meta-non-standard-string-literals) 章。 ## [正则表达式](@id man-regex-literals) Julia 具有与 Perl 兼容的正则表达式 (regexes),就像 [PCRE](http://www.pcre.org/) 包所提供的那样,详细信息参见 [PCRE 的语法说明](http://www.pcre.org/current/doc/html/pcre2syntax.html)。 正则表达式以两种方式和字符串相关:一个显然的关联是,正则表达式被用于找到字符串中的正则模式;另一个关联是,正则表达式自身就是作为字符串输入,它们被解析到可用来高效搜索字符串中模式的状态机中。 在 Julia 中正则表达式的输入使用了前缀各类以 `r` 开头的标识符的非标准字符串字面量。最基本的不打开任何选项的正则表达式只用到了 `r"..."`: ```jldoctest julia> re = r"^\s*(?:#|$)" r"^\s*(?:#|$)" julia> typeof(re) Regex ``` 若要检查正则表达式是否匹配某字符串,就用 [`occursin`](@ref): ```jldoctest julia> occursin(r"^\s*(?:#|$)", "not a comment") false julia> occursin(r"^\s*(?:#|$)", "# a comment") true ``` 可以看到,[`occursin`](@ref) 只返回正确或错误,表明给定正则表达式是否在该字符串中出现。然而,通常我们不只想知道字符串是否匹配,更想了解它是如何匹配的。要捕获匹配的信息,可以改用 [`match`](@ref) 函数: ```jldoctest julia> match(r"^\s*(?:#|$)", "not a comment") julia> match(r"^\s*(?:#|$)", "# a comment") RegexMatch("#") ``` 若正则表达式与给定字符串不匹配,[`match`](@ref) 返回 [`nothing`](@ref)——在交互式提示框中不打印任何东西的特殊值。除了不打印,它是一个完全正常的值,这可以用程序来测试: ```julia m = match(r"^\s*(?:#|$)", line) if m === nothing println("not a comment") else println("blank or comment") end ``` 如果正则表达式匹配,[`match`](@ref) 的返回值是一个 [`RegexMatch`](@ref) 对象。这些对象记录了表达式是如何匹配的,包括该模式匹配的子字符串和任何可能被捕获的子字符串。上面的例子仅仅捕获了匹配的部分子字符串,但也许我们想要捕获的是注释字符后面的任何非空文本。我们可以这样做: ```jldoctest julia> m = match(r"^\s*(?:#\s*(.*?)\s*$|$)", "# a comment ") RegexMatch("# a comment ", 1="a comment") ``` 当调用 [`match`](@ref) 时,你可以选择指定开始搜索的索引。例如: ```jldoctest julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",1) RegexMatch("1") julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",6) RegexMatch("2") julia> m = match(r"[0-9]","aaaa1aaaa2aaaa3",11) RegexMatch("3") ``` 你可以从 `RegexMatch` 对象中提取如下信息: * 匹配的整个子字符串:`m.match` * 作为字符串数组捕获的子字符串:`m.captures` * 整个匹配开始处的偏移:`m.offset` * 作为向量的捕获子字符串的偏移:`m.offsets` 当捕获不匹配时,`m.captures` 在该处不再包含一个子字符串,而是 `什么也不` 包含;此外,`m.offsets` 的偏移量为 0(回想一下,Julia 的索引是从 1 开始的,因此字符串的零偏移是无效的)。下面是两个有些牵强的例子: ```jldoctest acdmatch julia> m = match(r"(a|b)(c)?(d)", "acd") RegexMatch("acd", 1="a", 2="c", 3="d") julia> m.match "acd" julia> m.captures 3-element Vector{Union{Nothing, SubString{String}}}: "a" "c" "d" julia> m.offset 1 julia> m.offsets 3-element Vector{Int64}: 1 2 3 julia> m = match(r"(a|b)(c)?(d)", "ad") RegexMatch("ad", 1="a", 2=nothing, 3="d") julia> m.match "ad" julia> m.captures 3-element Vector{Union{Nothing, SubString{String}}}: "a" nothing "d" julia> m.offset 1 julia> m.offsets 3-element Vector{Int64}: 1 0 2 ``` 让捕获作为数组返回是很方便的,这样就可以用解构语法把它们和局域变量绑定起来。为了方便,`RegexMatch` 对象实现了传递到 `captures` 字段的迭代器方法,因此您可以直接解构匹配对象: ```jldoctest acdmatch julia> first, second, third = m; first "a" ``` 通过使用捕获组的编号或名称对 `RegexMatch` 对象进行索引,也可实现对捕获的访问: ```jldoctest julia> m=match(r"(?<hour>\d+):(?<minute>\d+)","12:45") RegexMatch("12:45", hour="12", minute="45") julia> m[:minute] "45" julia> m[2] "45" ``` 使用 [`replace`](@ref) 时利用 `\n` 引用第 n 个捕获组和给替换字符串加上 `s` 的前缀,可以实现替换字符串中对捕获的引用。捕获组 0 指的是整个匹配对象。可在替换中用 `\g<groupname>` 对命名捕获组进行引用。例如: ```jldoctest julia> replace("first second", r"(\w+) (?<agroup>\w+)" => s"\g<agroup> \1") "second first" ``` 为明确起见,编号捕获组也可用 `\g<n>` 进行引用,例如: ```jldoctest julia> replace("a", r"." => s"\g<0>1") "a1" ``` 你可以在后双引号的后面加上 `i`, `m`, `s` 和 `x` 等标志对正则表达式进行修改。这些标志和 Perl 里面的含义一样,详见以下对 [perlre 手册](http://perldoc.perl.org/perlre.html#Modifiers)的摘录: ``` i 不区分大小写的模式匹配。 若区域设置规则有效,相应映射中代码点小于 255 的部分取自当前区域设置,更大代码点的部分取自 Unicode 规则。然而,跨越 Unicode 规则(ords 255/256)和 非 Unicode 规则边界的匹配将失败。 m 将字符串视为多行。也即更改 "^" 和 "$", 使其从匹配字符串的开头和结尾变为匹配字符串中任意一行的开头或结尾。 s 将字符串视为单行。也即更改 "." 以匹配任何字符,即使是通常不能匹配的换行符。 像这样一起使用,r""ms,它们让 "." 匹配任何字符,同时也支持分别在字符串中换行符的后面和前面用 "^" 和 "$" 进行匹配。 x 令正则表达式解析器忽略多数既不是反斜杠也不属于字符类的空白。它可以用来把正则表达式分解成(略为)更易读的部分。和普通代码中一样,`#` 字符也被当作引入注释的元字符。 ``` 例如,下面的正则表达式已打开所有三个标志: ```jldoctest julia> r"a+.*b+.*?d$"ism r"a+.*b+.*?d$"ims julia> match(r"a+.*b+.*?d$"ism, "Goodbye,\nOh, angry,\nBad world\n") RegexMatch("angry,\nBad world") ``` `r"..."` 文本的构造没有插值和转义(除了引号 `"` 仍然需要转义)。下面例子展示了它和标准字符串字面量之间的差别: ```julia-repl julia> x = 10 10 julia> r"$x" r"$x" julia> "$x" "10" julia> r"\x" r"\x" julia> "\x" ERROR: syntax: invalid escape sequence ``` Julia 也支持 `r"""..."""` 形式的三引号正则表达式字符串(或许便于处理包含引号和换行符的正则表达式)。 `Regex()` 构造函数可以用于以编程方式创建合法的正则表达式字符串。这允许在构造正则表达式字符串时使用字符串变量的内容和其他字符串操作。上面的任何正则表达式代码可以在 `Regex()` 的单字符串参数中使用。下面是一些例子: ```jldoctest julia> using Dates julia> d = Date(1962,7,10) 1962-07-10 julia> regex_d = Regex("Day " * string(day(d))) r"Day 10" julia> match(regex_d, "It happened on Day 10") RegexMatch("Day 10") julia> name = "Jon" "Jon" julia> regex_name = Regex("[\"( ]\\Q$name\\E[\") ]") # interpolate value of name r"[\"( ]\QJon\E[\") ]" julia> match(regex_name, " Jon ") RegexMatch(" Jon ") julia> match(regex_name, "[Jon]") === nothing true ``` 注意 `\Q...\E` 转义序列的使用。 `\Q` 和 `\E` 之间的所有字符都被解释为字符字面量(在字符串插值之后)。在插入可能是恶意的用户输入时,此转义序列非常有用。 ## [字节数组字面量](@id man-byte-array-literals) 另一个有用的非标准字符串字面量是字节数组字面量:`b"..."`。这种形式使你能够用字符串表示法来表达只读字面量字节数组,也即 [`UInt8`](@ref) 值的数组。字节数组字面量的规则如下: * ASCII 字符和 ASCII 转义生成单个字节。 * `\x` 和八进制转义序列生成与转义值对应的*字节*。 * Unicode 转义序列生成编码 UTF-8 中该代码点的字节序列。 这些规则有一些重叠,这是因为 `\x` 的行为和小于 0x80(128) 的八进制转义被前两个规则同时包括了;但这两个规则又是一致的。通过这些规则可以方便地同时使用 ASCII 字符,任意字节值,以及 UTF-8 序列来生成字节数组。下面是一个用到全部三个规则的例子: ```jldoctest julia> b"DATA\xff\u2200" 8-element Base.CodeUnits{UInt8, String}: 0x44 0x41 0x54 0x41 0xff 0xe2 0x88 0x80 ``` 其中,ASCII 字符串 "DATA" 对应于字节 68, 65, 84, 65。`\xff` 生成单个字节 255。Unicode 转义 `\u2200` 在 UTF-8 中被编码为三个字节 226, 136, 128。注意生成的字节数组不对应任何有效 UTF-8 字符串。 ```jldoctest julia> isvalid("DATA\xff\u2200") false ``` 正如前面所述,`CodeUnits{UInt8,String}` 类型的行为类似于只读 `UInt8` 数组。如果需要标准数组,你可使用 `Vector{UInt8}` 进行转换。   ```jldoctest julia> x = b"123" 3-element Base.CodeUnits{UInt8, String}: 0x31 0x32 0x33 julia> x[1] 0x31 julia> x[1] = 0x32 ERROR: setindex! not defined for Base.CodeUnits{UInt8, String} [...] julia> Vector{UInt8}(x) 3-element Vector{UInt8}: 0x31 0x32 0x33 ``` 同时,要注意到 `\xff` 和 `\uff` 之间的显著差别:前面的转义序列编码为*字节 255*,而后者代表 *代码 255*,它在 UTF-8 中编码为两个字节: ```jldoctest julia> b"\xff" 1-element Base.CodeUnits{UInt8, String}: 0xff julia> b"\uff" 2-element Base.CodeUnits{UInt8, String}: 0xc3 0xbf ``` 字符字面量也用到了相同的行为。 对于小于 `\u80` 的代码,每个代码的 UTF-8 编码恰好只是由相应 `\x` 转义产生的单个字节,因此忽略两者的差别无伤大雅。然而,从 `x80` 到 `\xff` 的转义比起从 `u80` 到 `\uff` 的转义来,就有一个主要的差别:前者都只编码为一个字节,它没有形成任何有效 UTF-8 数据,除非它后面有非常特殊的连接字节;而后者则都代表 2 字节编码的 Unicode 代码。 如果这些还是太难理解,试着读一下 ["每个软件开发人员绝对必须知道的最基础 Unicode 和字符集知识"](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/)。它是一个优质的 Unicode 和 UTF-8 指南,或许能帮助解除一些这方面的疑惑。 ## [版本号字面量](@id man-version-number-literals) 版本号很容易用 [`v"..."`](@ref) 形式的非标准字符串字面量表示。版本号字面量生成遵循[语义版本](https://semver.org/)规范的 [`VersionNumber`](@ref) 对象,因此由主、次、补丁号构成,后跟预发行 (pre-release) 和生成阿尔法数注释(build alpha-numeric)。例如,`v"0.2.1-rc1+win64"` 可分为主版本号 `0`,次版本号 `2`,补丁版本号 `1`,预发行版号 `rc1`,以及生成版本 `win64`。输入版本字面量时,除了主版本号以外所有内容都是可选的,因此 `v"0.2"` 等效于 `v"0.2.0"`(预发行号和生成注释为空),`v"2"` 等效于 `v"2.0.0"`,等等。 `VersionNumber` 对象在轻松正确地比较两个(或更多)版本时非常有用。例如,常数 `VERSION` 把 Julia 的版本号保留为一个 `VersionNumber` 对象,因此可以像下面这样用简单的声明定义一些特定版本的行为: ```julia if v"0.2" <= VERSION < v"0.3-" # 针对 0.2 发行版系列做些事情 end ``` 注意在上例中用到了非标准版本号 `v"0.3-"`,其中有尾随符 `-`:这个符号是 Julia 标准的扩展,它可以用来表明低于任何 `0.3` 发行版的版本,包括所有的预发行版。所以上例中代码只能在稳定版本 `0.2` 上运行,而不能在 `v"0.3.0-rc1"` 这样的版本上运行。为了支持非稳定(即预发行)的 `0.2` 版本,下限检查应像这样应该改为:`v"0.2-" <= VERSION`。 另一个非标准版本规范扩展使得能够使用 `+` 来表示生成版本的上限,例如 `VERSION > v"0.2-rc1+"` 可以用来表示任意高于 `0.2-rc1` 和其任意生成版本的版本:它对 `v"0.2-rc1+win64"` 返回 `false` 而对 `v"0.2-rc2"` 返回 `true`。 在比较中使用这样的特殊版本是个好办法(特别是,总是应该对高版本使用尾随 `-`,除非有好理由不这样),但它们不应该被用作任何内容的实际版本,因为它们在语义版本控制方案中无效。 除了用于定义常数 [`VERSION`](@ref),`VersionNumber` 对象在 `Pkg` 模块应用广泛,常用于指定软件包的版本及其依赖。 ## [原始字符串字面量](@id man-raw-string-literals) 无插值和非转义的原始字符串可用 `raw"..."` 形式的非标准字符串字面量表示。原始字符串字面量生成普通的 `String` 对象,它无需插值和非转义地包含和输入完全一样的封闭式内容。这对于包含其他语言中使用 "$" 或 "\" 作为特殊字符的代码或标记的字符串很有用。 例外的是,引号仍必须转义,例如 `raw"\""` 等效于 `"\""`。为了能够表达所有字符串,反斜杠也必须转义,不过只是当它刚好出现在引号前面时。 ```jldoctest julia> println(raw"\\ \\\"") \\ \" ``` 请注意,前两个反斜杠在输出中逐字显示,这是因为它们不是在引号前面。然而,接下来的一个反斜杠字符转义了后面的一个反斜杠;又由于这些反斜杠出现在引号前面,最后一个反斜杠转义了一个引号。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
8005
# 代码风格指南 接下来的部分将介绍如何写出具有 Julia 风格的代码。当然,这些规则并不是绝对的,它们只是一些建议,以便更好地帮助你熟悉这门语言,以及在不同的代码设计中做出选择。 ## 缩进 每个缩进级别使用 4 个空格。 ## 写函数,而不是仅仅写脚本 一开始解决问题的时候,直接从最外层一步步写代码的确很便捷,但你应该尽早地将代码组织成函数。函数有更强的复用性和可测试性,并且能更清楚地让人知道哪些步骤做完了,以及每一步骤的输入输出分别是什么。此外,由于 Julia 编译器特殊的工作方式,写在函数中的代码往往要比最外层的代码运行地快得多。 此外值得一提的是,函数应当接受参数,而不是直接使用全局变量进行操作([`pi`](@ref) 等常数除外)。 ## 类型不要写得过于具体 代码应该写得尽可能通用。例如,下面这段代码: ```julia Complex{Float64}(x) ``` 更好的写法是写成下面的通用函数: ```julia complex(float(x)) ``` 第二个版本会把 `x` 转换成合适的类型,而不是某个写死的类型。 这种代码风格与函数的参数尤其相关。例如,当一个参数可以是任何整型时,不要将它的类型声明为 `Int` 或 [`Int32`](@ref),而要使用抽象类型(abstract type)[`Integer`](@ref) 来表示。事实上,除非确实需要将其与其它的方法定义区分开,很多情况下你可以干脆完全省略掉参数的类型,因为如果你的操作中有不支持某种参数类型的操作的话,反正都会抛出 [`MethodError`](@ref) 的。这也称作 [鸭子类型](https://zh.wikipedia.org/wiki/%E9%B8%AD%E5%AD%90%E7%B1%BB%E5%9E%8B))。 例如,考虑这样的一个叫做 `addone` 的函数,其返回值为它的参数加 1 : ```julia addone(x::Int) = x + 1 # works only for Int addone(x::Integer) = x + oneunit(x) # any integer type addone(x::Number) = x + oneunit(x) # any numeric type addone(x) = x + oneunit(x) # any type supporting + and oneunit ``` 最后一种定义可以处理所有支持 [`oneunit`](@ref) (返回和 `x` 相同类型的 1,以避免不需要的类型提升(type promotion))以及 [`+`](@ref) 函数的类型。这里的关键点在于,**只**定义通用的 `addone(x) = x + oneunit(x)` 并**不会**带来性能上的损失,因为 Julia 会在需要的时候自动编译特定的版本。比如说,当第一次调用 `addone(12)` 时,Julia 会自动编译一个特定的 `addone` 函数,它接受一个 `x::Int` 的参数,并把调用的 `oneunit` 替换为内连的值 `1`。因此,上述的前三种 `addone` 的定义对于第四种来说是完全多余的。 ## 让调用者处理多余的参数多样性 如下的代码: ```julia function foo(x, y) x = Int(x); y = Int(y) ... end foo(x, y) ``` 请写成这样: ```julia function foo(x::Int, y::Int) ... end foo(Int(x), Int(y)) ``` 这种风格更好,因为 `foo` 函数其实不需要接受所有类型的数,而只需要接受 `Int`。 这里的关键在于,如果一个函数需要处理的是整数,强制让调用者来决定非整数如何被转换(比如说向下还是向上取整)会更好。同时,把类型声明得具体一些的话可以为以后的方法定义留有更多的空间。 ## [在修改其参数的函数名称后加 `!`](@id bang-convention) 如下的代码: ```julia function double(a::AbstractArray{<:Number}) for i = firstindex(a):lastindex(a) a[i] *= 2 end return a end ``` 请写成这样: ```julia function double!(a::AbstractArray{<:Number}) for i = firstindex(a):lastindex(a) a[i] *= 2 end return a end ``` Julia 的 Base 模块中的函数都遵循了这种规范,且包含很多例子:有的函数同时有拷贝和修改的形式(比如 [`sort`](@ref) 和 [`sort!`](@ref)),还有一些只有修改(比如 [`push!`](@ref),[`pop!`](@ref) 和 [`splice!`](@ref))。为了方便起见,这类函数通常也会把修改后的数组作为返回值。 ## 避免使用奇怪的 `Union` 类型 使用 `Union{Function,AbstractString}` 这样的类型的时候通常意味着设计还不够清晰。 ## 避免复杂的容器类型 像下面这样构造数组通常没有什么好处: ```julia a = Vector{Union{Int,AbstractString,Tuple,Array}}(undef, n) ``` 这种情况下,`Vector{Any}(undef, n)`更合适些。此外,相比将所有可能的类型都打包在一起,直接在使用时标注具体的数据类型(比如:`a[i]::Int`)对编译器来说更有用。 ## 方法导出优先于直接字段访问 惯例上,Julia 代码通常应将模块的导出方法视为其类型的接口。 一个对象的字段通常被认为是实现细节,如果这被声明为 API,用户代码应该只直接访问它们。 这有几个好处: 包开发人员可以更自由地更改实现而不会破坏用户代码。 - - 方法可以传递给高阶结构,如 [`map`](@ref)(例如 `map(imag, zs)`)而不是 `[z.im for z in zs]`)。 - 方法可以定义在抽象类型上。 - 方法可以描述可以在不同类型之间共享的概念操作(例如 `real(z)` 适用于复数或四元数)。 Julia 的调度系统鼓励这种风格,因为 `play(x::MyType)` 只在该特定类型上定义了 `play` 方法,其它类型有自己的实现。 同样,除非文档另有说明,否则非导出函数通常是内部的并且可能会发生变化。 名称有时会被赋予一个 `_` 前缀(或后缀)以进一步暗示某些是“内部”或实现细节,但这不是规则。 该规则的反例包括 [`NamedTuple`](@ref)、[`RegexMatch`](@ref match)、[`StatStruct`](@ref stat)。 ## 使用和 Julia `base/` 文件夹中的代码一致的命名习惯 * module 和 type 的名字使用大写开头的驼峰命名法:`module SparseArrays`,`struct UnitRange`。 * 函数名使用小写字母,且当可读时可以将多个单词拼在一起。必要的时候,可以使用下划线作为单词分隔符。下划线也被用于指明概念的组合(比如 [`remotecall_fetch`](@ref) 作为 `fetch(remotecall(...))` 的一个更高效的实现)或者变化。 * 至少改变其中一个参数的函数名称以`!`结尾。 * 虽然简洁性很重要,但避免使用缩写(用 [`indexin`](@ref) 而不是 `indxin`),因为这会让记住单词有没有被缩写或如何被缩写变得十分困难。 如果一个函数名需要多个单词,请考虑这个函数是否代表了超过一个概念,是不是分成几个更小的部分更好。 ## 使用与 Julia Base 中的函数类似的参数顺序 一般来说,Base 库使用以下的函数参数顺序(如适用): 1. **函数参数**. 函数的第一个参数可以接受 `Function` 类型,以便使用 [`do`](@ref) blocks 来传递多行匿名函数。 2. **I/O stream**. 函数的第一个参数可以接受 `IO` 对象,以便将函数传递给 [`sprint`](@ref) 之类的函数,例如 `sprint(show, x)`。 3. **在输入参数的内容会被更改的情况下**. 比如,在 [`fill!(x, v)`](@ref fill!) 中,`x` 是要被修改的对象,所以放在要被插入 `x` 中的值前面。 4. **Type**. 把类型作为参数传入函数通常意味着返回值也会是同样的类型。 在 [`parse(Int, "1")`](@ref parse) 中,类型在需要解析的字符串之前。 还有很多类似的将类型作为函数第一个参数的例子,但是同时也需要注意到例如 [`read(io, String)`](@ref read) 这样的函数中,会把 `IO` 参数放在类型的更前面,这样还是保持着这里描述的顺序。 5. **在输入参数的内容不会被更改的情况下**. 比如在 `fill!(x, v)` 中的**不**被修改的 `v`,会放在 `x` 之后传入。 6. **Key**. 对于关联集合来说,指的是键值对的键。 对于其它有索引的集合来说,指的是索引。 7. **Value**. 对于关联集合来说,指的是键值对的值。 像[`fill!(x, v)`](@ref fill!)这样的情况, 是`v`。 8. **Everything else**. 任何的其它参数。 9. **Varargs**. 指的是在函数调用时可以被无限列在后面的参数。 比如在 `Matrix{T}(uninitialized, dims)` 中,维数(dims)可以作为 [`Tuple`](@ref) 被传入(如 `Matrix{T}(uninitialized, (1,2))`),也可以作为可变参数([`Vararg`](@ref),如 `Matrix{T}(uninitialized, 1, 2)`。 10. **Keyword arguments**. 在 Julia 中,关键字参数本来就不得不定义在函数定义的最后,列在这里仅仅是为了完整性。 大多数函数并不会接受上述所有种类的参数,这些数字仅仅是表示当适用时的优先权。 当然,在一些情况下有例外。例如,[`convert`](@ref) 函数总是把类型作为第一个参数。[`setindex!`](@ref) 函数的值参数在索引参数之前,这样可以让索引作为可变参数传入。 设计 API 时,尽可能秉承着这种一般顺序会让函数的使用者有一种更一致的体验。 ## 不要过度使用 try-catch 比起依赖于捕获错误,更好的是避免错误。 ## 不要给条件语句加括号 Julia 不要求在 `if` 和 `while` 后的条件两边加括号。使用如下写法: ```julia if a == b ``` 而不是: ```julia if (a == b) ``` ## 不要过度使用 `...` 拼接函数参数是会上瘾的。请用简单的 `[a; b]` 来代替 `[a..., b...]`,因为前者已经是被拼接的数组了。[`collect(a)`](@ref) 也比 `[a...]` 更好,但因为 `a` 已经是一个可迭代的变量了,通常不把它转换成数组就直接使用甚至更好。 ## 不要使用不必要的静态参数 如下的函数签名: ```julia foo(x::T) where {T<:Real} = ... ``` 应当被写作: ```julia foo(x::Real) = ... ``` 尤其是当 `T` 没有被用在函数体中时格外有意义。即使 `T` 被用到了,通常也可以被替换为 [`typeof(x)`](@ref),后者不会导致性能上的差别。注意这并不是针对静态参数的一般警告,而仅仅是针对那些不必要的情况。 同样需要注意的是,容器类型在函数调用中可能明确地需要类型参数。详情参见[避免使用带抽象容器的字段](@ref)。 ## 避免判断变量是实例还是类型的混乱 如下的一组定义容易令人困惑: ```julia foo(::Type{MyType}) = ... foo(::MyType) = foo(MyType) ``` 请决定问题里的概念应当是 `MyType` 还是 `MyType()`,然后坚持使用其一。 首选风格应是默认使用实例,只有在需要解决某些问题时才添加涉及`Type{MyType}`的方法。 如果一个类型实际上是个枚举,它应该被定义成一个单一的类型(理想的情况是不可变结构或原始类型),把枚举值作为它的实例。构造器和转换器可以检查那些值是否有效。这种设计比把枚举做成抽象类型,并把“值”做成子类型来得更受推崇。 ## 不要过度使用宏 请注意有的宏实际上可以被写成一个函数。 在宏内部调用 [`eval`](@ref) 是一个特别危险的警告标志,它意味着这个宏仅在被最外层调用时起作用。如果这样的宏被写成函数,它会自然地访问得到它所需要的运行时值。 ## 不要把不安全的操作暴露在接口层 如果你有一个使用本地指针的类型: ```julia mutable struct NativeType p::Ptr{UInt8} ... end ``` 不要定义类似如下的函数: ```julia getindex(x::NativeType, i) = unsafe_load(x.p, i) ``` 这里的问题在于,这个类型的用户可能会在意识不到这个操作不安全的情况下写出 `x[i]`,然后容易遇到内存错误。 在这样的函数中,可以加上对操作的检查来确保安全,或者可以在名字的某处加上 `unsafe` 来警告调用者。 ## 不要重载基础容器类型的方法 有时可能会想要写这样的定义: ```julia show(io::IO, v::Vector{MyType}) = ... ``` 这样可以提供对特定的某种新元素类型的向量的自定义显示。这种做法虽然很诱人,但应当被避免。这里的问题在于用户会想着一个像 `Vector()` 这样熟知的类型以某种方式表现,但过度自定义的行为会让使用变得更难。 ## 避免类型盗版 “类型盗版”(type piracy)指的是扩展或是重定义 Base 或其它包中的并不是你所定义的类型的方法。在某些情况下,你可以几乎毫无副作用地逃避类型盗版。但在极端情况下,你甚至会让 Julia 崩溃(比如说你的方法扩展或重定义造成了对 `ccall` 传入了无效的输入)。类型盗版也让代码推导变得更复杂,且可能会引入难以预料和诊断的不兼容性。 例如,你也许想在一个模块中定义符号上的乘法: ```julia module A import Base.* *(x::Symbol, y::Symbol) = Symbol(x,y) end ``` 这里的问题时现在其它用到 `Base.*` 的模块同样会看到这个定义。由于 `Symbol` 是定义在 Base 里再被其它模块所使用的,这可能不可预料地改变无关代码的行为。这里有几种替代的方式,包括使用一个不同的函数名称,或是把 `Symbol` 给包在另一个你自己定义的类型中。 有时候,耦合的包可能会使用类型盗版,以此来从定义分隔特性,尤其是当那些包是一些合作的作者设计的时候,且那些定义是可重用的时候。例如,一个包可能提供一些对处理色彩有用的类型,另一个包可能为那些类型定义色彩空间之间转换的方法。再举一个例子,一个包可能是一些 C 代码的简易包装,另一个包可能就“盗版”来实现一些更高级别的、对 Julia 友好的 API。 ## 注意类型相等 通常会用 [`isa`](@ref) 和 [`<:`](@ref) 来对类型进行测试,而不会用到 `==`。检测类型的相等通常只对和一个已知的具体类型比较有意义(例如 `T == Float64`),或者你**真的真的**知道自己在做什么。 ## 不要写 `x->f(x)` 因为调用高阶函数时经常会用到匿名函数,很容易认为这是合理甚至必要的。但任何函数都可以被直接传递,并不需要被“包"在一个匿名函数中。比如 `map(x->f(x), a)` 应当被写成 [`map(f, a)`](@ref)。 ## 尽可能避免使用浮点数作为通用代码的字面量 当写处理数字,且可以处理多种不同数字类型的参数的通用代码时,请使用对参数影响(通过类型提升)尽可能少的类型的字面量。 例如, ```jldoctest julia> f(x) = 2.0 * x f (generic function with 1 method) julia> f(1//2) 1.0 julia> f(1/2) 1.0 julia> f(1) 2.0 ``` 而应当被写作: ```jldoctest julia> g(x) = 2 * x g (generic function with 1 method) julia> g(1//2) 1//1 julia> g(1/2) 1.0 julia> g(1) 2 ``` 如你所见,使用了 `Int` 字面量的第二个版本保留了输入参数的类型,而第一个版本没有。这是因为例如 `promote_type(Int, Float64) == Float64`,且做乘法时会需要类型提升。类似地,[`Rational`](@ref) 字面量比 [`Float64`](@ref) 字面量对类型有着更小的破坏性,但比 `Int` 大。 ```jldoctest julia> h(x) = 2//1 * x h (generic function with 1 method) julia> h(1//2) 1//1 julia> h(1/2) 1.0 julia> h(1) 2//1 ``` 所以,可能时尽量使用 `Int` 字面量,对非整数字面量使用 `Rational{Int}`,这样可以让代码变得更容易使用。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
31971
# [类型](@id man-types) 通常,我们把程序语言中的类型系统划分成两类:静态类型和动态类型。对于静态类型系统,在程序运行之前,我们就可计算每一个表达式的类型。而对于动态类型系统,我们只有通过运行那个程序,得到表达式具体的值,才能确定其具体的类型。通过让编写的代码无需在编译时知道值的确切类型,面向对象允许静态类型语言具有一定的灵活性。可以编写在不同类型上都能运行的代码的能力被称为多态。在经典的动态类型语言中,所有的代码都是多态的,这意味着这些代码对于其中值的类型没有约束,除非在代码中去具体的判断一个值的类型,或者对对象做一些它不支持的操作。 Julia 类型系统是动态的,但由于允许指出某些变量具有特定类型,因此占有静态类型系统的一些优势。这对于生成高效的代码非常有帮助,但更重要的是,它允许针对函数参数类型的方法派发与语言深度集成。方法派发将在[方法](@ref)中详细探讨,但它根植于此处提供的类型系统。 在类型被省略时,Julia 的默认行为是允许值为任何类型。因此,可以编写许多有用的 Julia 函数,而无需显式使用类型。然而,当需要额外的表达力时,很容易逐渐将显式的类型注释引入先前的「无类型」代码中。添加类型注释主要有三个目的:利用 Julia 强大的多重派发机制、提高代码可读性以及捕获程序错误。 用[类型系统](https://zh.wikipedia.org/wiki/类型系统)的术语描述,Julia是动态(dynamic)、主格(nominative)和参数(parametric)的。泛型可以被参数化,并且类型之间的层次关系可以被[显式地声明](https://en.wikipedia.org/wiki/Nominal_type_system),而不是[隐含地通过兼容的结构](https://en.wikipedia.org/wiki/Structural_type_system)。Julia 类型系统的一个特别显著的特征是具体类型相互之间不能是子类型:所有具体类型都是最终的,并且超类只能是抽象类型。虽然这乍一看可能过于严格,但它有许多益处,且缺点却少得出奇。事实证明,能够继承行为比继承结构更重要,同时继承两者在传统的面向对象语言中导致了重大困难。Julia 类型系统的其它高级方面应当在先言明: * 对象值和非对象值之间没有分别:Julia 中的所有值都是具有类型的真实对象且其类型属于一个单独的、完全连通的类型图,该类型图的所有节点作为类型一样都是头等的。 * 「编译期类型」是没有任何意义的概念:变量所具有的唯一类型是程序运行时的实际类型。这在面向对象被称为「运行时类型」,其中静态编译和多态的组合使得这种区别变得显著。 * 只有值,而不是变量,有类型——变量只是绑定到值的名称,尽管为了简单起见,我们可以说“变量的类型”作为“变量所引用的值的类型”的简写。 * 抽象类型和具体类型都可以通过其它类型进行参数化。它们的参数化还可通过符号、使得 [`isbits`](@ref) 返回 true 的任意类型的值(实质上,也就是像数字或布尔变量这样的东西,存储方式像 C 类型或不包含指向其它对象的指针的 `struct`)和其元组。类型参数在不需要被引用或限制时可以省略。 Julia 的类型系统设计得强大而富有表现力,却清晰、直观且不引人注目。许多 Julia 程序员可能从未感觉需要编写明确使用类型的代码。但是,某些场景的编程可通过声明类型变得更加清晰、简单、快速和稳健。 ## 类型声明 `::` 运算符可以用来在程序中给表达式和变量附加类型注释。这有两个主要原因: 1. 作为断言,帮助程序确认能是否正常运行, 2. 给编译器提供额外的类型信息,在一些情况下这可以提升程序性能。 置于到计算值的表达式后面时,`::` 操作符读作「是······的实例(is an instance of)」。在任何地方都可以用它来断言左侧表达式的值是右侧类型的实例。当右侧类型是具体类型时,左侧的值必须能够以该类型作为其实现——回想一下,所有具体类型都是最终的,因此没有任何实现是任何其它具体类型的子类型。当右侧类型是抽象类型时,值是由该抽象类型子类型中的某个具体类型实现的才能满足该断言。如果类型断言非真,抛出一个异常,否则返回左侧的值: ```jldoctest julia> (1+2)::AbstractFloat ERROR: TypeError: in typeassert, expected AbstractFloat, got a value of type Int64 julia> (1+2)::Int 3 ``` 这将允许类型断言作用在任意表达式上。 置于赋值语句左侧的变量之后,或作为 `local` 声明的一部分时,`::` 操作符的意义有所不同:它声明变量始终具有指定的类型,就像静态类型语言(如 C)中的类型声明。每个被赋给该变量的值都将使用 [`convert`](@ref) 转换为被声明的类型: ```jldoctest julia> function foo() x::Int8 = 100 x end foo (generic function with 1 method) julia> x = foo() 100 julia> typeof(x) Int8 ``` 这个特性对避免特定的性能「陷阱」很有帮助,比如给一个变量赋值时意外地更改了其类型。 此「声明」行为仅发生在特定上下文中: ```julia local x::Int8 # in a local declaration x::Int8 = 10 # as the left-hand side of an assignment ``` 并应用于整个当前作用域,甚至在该声明之前。目前,类型声明不能在全局作用域中使用,例如在 REPL 中就不可以,因为 Julia 还没有常量类型的全局变量。 声明也可以附加到函数定义: ```julia function sinc(x)::Float64 if x == 0 return 1 end return sin(pi*x)/(pi*x) end ``` 从函数返回时就如同给一个已被声明类型的变量赋值:返回值始终会被转换为`Float64`。 ## [抽象类型](@id man-abstract-types) 抽象类型不能实例化,只能作为类型图中的节点使用,从而描述相关具体类型的集,即那些作为其后代的具体类型。即便抽象类型没有实例, 由于它们是类型系统的主干,故我们首先从抽象类型谈起:抽象类型形成了概念的层次结构,这使得 Julia 的类型系统不只是对象实现的集合。 回想一下,在[整数和浮点数](@ref)中,我们介绍了各种数值的具体类型:[`Int8`](@ref)、[`UInt8`](@ref)、[`Int16`](@ref)、[`UInt16`](@ref)、[`Int32`](@ref)、[`UInt32`](@ref)、[`Int64`](@ref)、[`UInt64`](@ref)、[`Int128`](@ref)、[`UInt128`](@ref)、[`Float16`](@ref)、[`Float32`](@ref) 和 [`Float64`](@ref)。尽管 `Int8`、`Int16`、`Int32`、`Int64` 和 `Int128` 具有不同的表示大小,但都具有共同的特征,即它们都是带符号的整数类型。类似地,`UInt8`、`UInt16`、`UInt32`、`UInt64` 和 `UInt128` 都是无符号整数类型,而 `Float16`、`Float32` 和 `Float64` 是不同的浮点数类型而非整数类型。一段代码只对某些类型有意义是很常见的,比如,只在其参数是某种类型的整数,而不真正取决于特定*类型*的整数时有意义。例如,最大公分母算法适用于所有类型的整数,但不适用于浮点数。抽象类型允许构造类型的层次结构,这给具体类型提供了可以适应的环境。例如,你可以轻松地为任何类型的整数编程,而不用将算法限制为某种特殊类型的整数。 抽象类型可以由 [`abstract type`](@ref) 关键字来声明。声明抽象类型的一般语法是: ``` abstract type «name» end abstract type «name» <: «supertype» end ``` 该 `abstract type` 关键字引入了一个新的抽象类型,`«name»` 为其名称。此名称后面可以跟 [`<:`](@ref) 和一个已存在的类型,表示新声明的抽象类型是此「父」类型的子类型。 如果没有给出超类型,则默认超类型为 `Any`——一个已经定义好的抽象类型,所有对象都是 `Any` 的实例并且所有类型都是 `Any` 的子类型。在类型理论中,`Any` 通常称为「top」,因为它位于类型图的顶点。Julia 还有一个预定义了的抽象「bottom」类型,在类型图的最低点,写成 `Union{}`。这与 `Any` 完全相反:任何对象都不是 `Union{}` 的实例,所有的类型都是 `Union{}` 的超类型。 让我们考虑一些构成 Julia 数值类型层次结构的抽象类型: ```julia abstract type Number end abstract type Real <: Number end abstract type AbstractFloat <: Real end abstract type Integer <: Real end abstract type Signed <: Integer end abstract type Unsigned <: Integer end ``` [`Number`](@ref) 类型为 `Any` 类型的直接子类型,并且 [`Real`](@ref) 为它的子类型。接下来,`Real` 有两个子类型(它还有更多的子类型,但这里只展示了两个,稍后将会看到其它的子类型): [`Integer`](@ref) 和 [`AbstractFloat`](@ref),将世界分为整数的表示和实数的表示。实数的表示当然包括浮点类型,但也包括其他类型,例如有理数。因此,`AbstractFloat` 是一个 `Real` 的子类型,仅包括实数的浮点表示。整数被进一步细分为 [`Signed`](@ref) 和 [`Unsigned`](@ref) 两类。 `<:` 运算符的通常意义为「是······的子类型(is a subtype of)」,可以用在声明中,声明右侧类型是新声明类型的直接超类型;也可以在表达式中用作子类型运算符,在其左操作数为其右操作数的子类型时返回 `true`: ```jldoctest julia> Integer <: Number true julia> Integer <: AbstractFloat false ``` 抽象类型的一个重要用途是为具体类型提供默认实现。举个简单的例子,考虑: ```julia function myplus(x,y) x+y end ``` 首先需要注意的是上述的参数声明等价于 `x::Any` 和 `y::Any`。当函数被调用时,例如 `myplus(2,5)`,派发器会选择与给定参数相匹配的名称为 `myplus` 的最具体方法。(有关多重派发的更多信息,请参阅[方法](@ref)。) 假设没有找到比上述方法更具体的方法,Julia 则会基于上面给出的泛型函数,在内部定义并编译一个名为 `myplus` 的方法,专门用于处理两个 `Int` 参数,即它隐式地定义并编译: ```julia function myplus(x::Int,y::Int) x+y end ``` 最后,调用这个具体的方法。 因此,抽象类型允许程序员编写泛型函数,泛型函数可以通过许多具体类型的组合用作默认方法。多重派发使得程序员可以完全控制是使用默认方法还是更具体的方法。 需要注意的重点是,即使程序员依赖参数为抽象类型的函数,性能也不会有任何损失,因为它会针对每个调用它的参数元组的具体类型重新编译。(但在函数参数是抽象类型的容器的情况下,可能存在性能问题;请参阅[性能建议](@ref man-performance-abstract-container)。) ## 原始类型 !!! warning 通常情况下更建议在新的复合类型中封装现有的原始类型,而不是重新定义自己的原始类型。 这个功能的存在是为了允许 Julia 能引导受 LLVM 支持的标准基本类型。一旦一些标准类型被定义,就不需要再定义更多了。 原始类型是具体类型,其数据是由简单的位组成。原始类型的经典示例是整数和浮点数。与大多数语言不同,Julia 允许你声明自己的原始类型,而不是只提供一组固定的内置原始类型。实际上,标准原始类型都是在语言本身中定义的: ```julia primitive type Float16 <: AbstractFloat 16 end primitive type Float32 <: AbstractFloat 32 end primitive type Float64 <: AbstractFloat 64 end primitive type Bool <: Integer 8 end primitive type Char <: AbstractChar 32 end primitive type Int8 <: Signed 8 end primitive type UInt8 <: Unsigned 8 end primitive type Int16 <: Signed 16 end primitive type UInt16 <: Unsigned 16 end primitive type Int32 <: Signed 32 end primitive type UInt32 <: Unsigned 32 end primitive type Int64 <: Signed 64 end primitive type UInt64 <: Unsigned 64 end primitive type Int128 <: Signed 128 end primitive type UInt128 <: Unsigned 128 end ``` 声明原始类型的一般语法是: ``` primitive type «name» «bits» end primitive type «name» <: «supertype» «bits» end ``` bits 的数值表示该类型需要多少存储空间,name 为新类型指定名称。可以选择将一个原始类型声明为某个超类型的子类型。如果省略超类型,则默认 `Any` 为其直接超类型。上述声明中意味着 [`Bool`](@ref) 类型需要 8 位来储存,并且直接超类型为 [`Integer`](@ref)。目前支持的大小只能是 8 位的倍数,不然你就会遇到 LLVM 的 bug。因此,布尔值虽然确实只需要一位,但不能声明为小于 8 位的值。 [`Bool`](@ref),[`Int8`](@ref) 和 [`UInt8`](@ref) 类型都具有相同的表现形式:它们都是 8 位内存块。然而,由于 Julia 的类型系统是主格的,它们尽管具有相同的结构,但不是通用的。它们之间的一个根本区别是它们具有不同的超类型:[`Bool`](@ref) 的直接超类型是 [`Integer`](@ref)、[`Int8`](@ref) 的是 [`Signed`](@ref) 而 [`UInt8`](@ref) 的是 [`Unsigned`](@ref)。[`Bool`](@ref),[`Int8`](@ref) 和 [`UInt8`](@ref) 的所有其它差异是行为上的——定义函数的方式在这些类型的对象作为参数给定时起作用。这也是为什么主格的类型系统是必须的:如果结构确定类型,类型决定行为,就不可能使 [`Bool`](@ref) 的行为与 [`Int8`](@ref) 或 [`UInt8`](@ref) 有任何不同。 ## 复合类型 [复合类型](https://en.wikipedia.org/wiki/Composite_data_type)在各种语言中被称为 record、struct 和 object。复合类型是命名字段的集合,其实例可以视为单个值。复合类型在许多语言中是唯一一种用户可定义的类型,也是 Julia 中最常用的用户定义类型。 在主流的面向对象语言中,比如 C++、Java、Python 和 Ruby,复合类型也具有与它们相关的命名函数,并且该组合称为「对象」。在纯粹的面向对象语言中,例如 Ruby 或 Smalltalk,所有值都是对象,无论它们是否为复合类型。在不太纯粹的面向对象语言中,包括 C++ 和 Java,一些值,比如整数和浮点值,不是对象,而用户定义的复合类型是具有相关方法的真实对象。在 Julia 中,所有值都是对象,但函数不与它们操作的对象捆绑在一起。这是必要的,因为 Julia 通过多重派发选择函数使用的方法,这意味着在选择方法时考虑*所有*函数参数的类型,而不仅仅是第一个(有关方法和派发的更多信息,请参阅[方法](@ref))。因此,函数仅仅「属于」它们的第一个参数是不合适的。将方法组织到函数对象中而不是在每个对象「内部」命名方法最终成为语言设计中一个非常有益的方面。 [`struct`](@ref) 关键字与复合类型一起引入,后跟一个字段名称的块,可选择使用 `::` 运算符注释类型: ```jldoctest footype julia> struct Foo bar baz::Int qux::Float64 end ``` 没有类型注释的字段默认为 `Any` 类型,所以可以包含任何类型的值。 类型为 `Foo` 的新对象通过将 `Foo` 类型对象像函数一样应用于其字段的值来创建: ```jldoctest footype julia> foo = Foo("Hello, world.", 23, 1.5) Foo("Hello, world.", 23, 1.5) julia> typeof(foo) Foo ``` 像函数一样使用的类型称为**构造函数**。有两个构造函数已被自动生成(这些构造函数称为**默认构造函数**)。其中一个接受任何参数并调用 [`convert`](@ref) 函数将它其转换为字段的类型,另一个接受与字段类型完全匹配的参数。两者都生成的原因是,这使得更容易添加新定义而不会在无意中替换默认构造函数。 由于 `bar` 字段在类型上不受限制,因此任何值都可以。但是 `baz` 的值必须可转换为 `Int` 类型: ```jldoctest footype julia> Foo((), 23.5, 1) ERROR: InexactError: Int64(23.5) Stacktrace: [...] ``` 可以使用 [`fieldnames`](@ref) 函数找到字段名称列表。 ```jldoctest footype julia> fieldnames(Foo) (:bar, :baz, :qux) ``` 可以使用传统的 `foo.bar` 表示法访问复合对象的字段值: ```jldoctest footype julia> foo.bar "Hello, world." julia> foo.baz 23 julia> foo.qux 1.5 ``` 用 `struct` 声明的复合对象是*不可变的*;创建后不能修改。乍一看这似乎很奇怪,但它有几个优点: * 它可以更高效。某些 struct 可以被高效地打包到数组中,并且在某些情况下,编译器可以避免完全分配不可变对象。 * 不可能违反类型构造函数提供的不变性。 * 使用不可变对象的代码更容易推理。 不可变对象可以包含可变对象(比如数组)作为字段。那些被包含的对象将保持可变;只是不可变对象本身的字段不能更改为指向不同的对象。 如果需要,可以使用关键字 [`mutable struct`](@ref) 声明可变复合对象,这将在下一节中讨论。 如果一个不可变结构的所有字段都是不可区分的(`===`),那么包含这些字段的两个不可变值也是不可区分的: ```jldoctest julia> struct X a::Int b::Float64 end julia> X(1, 2) === X(1, 2) true ``` 关于如何构造复合类型的实例还有很多要说的,但这种讨论依赖于[参数类型](@ref)和[方法](@ref),并且这是非常重要的,应该在专门的章节中讨论:[构造函数](@ref man-constructors)。 ## 可变复合类型 如果使用 `mutable struct` 而不是 `struct` 声明复合类型,则它的实例可以被修改: ```jldoctest bartype julia> mutable struct Bar baz qux::Float64 end julia> bar = Bar("Hello", 1.5); julia> bar.qux = 2.0 2.0 julia> bar.baz = 1//2 1//2 ``` 为了支持修改,这种对象通常分配在堆上,并且具有稳定的内存地址。可变对象就像一个小容器,随着时间的推移,可能保持不同的值,因此只能通过其地址可靠地识别。相反地,不可变类型的实例与特定字段值相关——仅字段值就告诉你该对象的所有内容。在决定是否使类型为可变类型时,请询问具有相同字段值的两个实例是否被视为相同,或者它们是否可能需要随时间独立更改。如果它们被认为是相同的,该类型就应该是不可变的。 总结一下,Julia 的两个基本属性定义了不变性: * 不允许修改不可变类型的值。 * 对于位类型,这意味着值的位模式一旦设置将不再改变,并且该值是位类型的标识。 * 对于复合类型,这意味着其字段值的标识将不再改变。当字段是位类型时,这意味着它们的位将不再改变,对于其值是可变类型(如数组)的字段,这意味着字段将始终引用相同的可变值,尽管该可变值的内容本身可能被修改。 * 具有不可变类型的对象可以被编译器自由复制,因为其不可变性使得不可能以编程方式区分原始对象和副本。 * 特别地,这意味着足够小的不可变值(如整数和浮点数)通常在寄存器(或栈分配)中传递给函数。 * 另一方面,可变值是堆分配的,并作为指向堆分配值的指针传递给函数,除非编译器确定没有办法知道这不是正在发生的事情。 ## [已声明的类型](@id man-declared-types) 前面章节中讨论的三种类型(抽象、原始、复合)实际上都是密切相关的。它们共有相同的关键属性: * 它们都是显式声明的。 * 它们都具有名称。 * 它们都已经显式声明超类型。 * 它们可以有参数。 由于这些共有属性,它们在内部表现为相同概念 `DataType` 的实例,其是任何这些类型的类型: ```jldoctest julia> typeof(Real) DataType julia> typeof(Int) DataType ``` `DataType` 可以是抽象的或具体的。它如果是具体的,就具有指定的大小、存储布局和字段名称(可选)。因此,原始类型是具有非零大小的 `DataType`,但没有字段名称。复合类型是具有字段名称或者为空(大小为零)的 `DataType`。 每一个具体的值在系统里都是某个 `DataType` 的实例。 ## 类型共用体 类型共用体是一种特殊的抽象类型,它包含作为对象的任何参数类型的所有实例,使用特殊[`Union`](@ref)关键字构造: ```jldoctest julia> IntOrString = Union{Int,AbstractString} Union{Int64, AbstractString} julia> 1 :: IntOrString 1 julia> "Hello!" :: IntOrString "Hello!" julia> 1.0 :: IntOrString ERROR: TypeError: in typeassert, expected Union{Int64, AbstractString}, got a value of type Float64 ``` 许多语言都有内建的共用体结构来推导类型;Julia 简单地将它暴露给程序员。Julia 编译器能在 `Union` 类型只具有少量类型[^1]的情况下生成高效的代码,方法是为每个可能类型的不同分支都生成专用代码。 `Union` 类型的一种特别有用的情况是 `Union{T, Nothing}`,其中 `T` 可以是任何类型,[`Nothing`](@ref) 是单态类型,其唯一实例是对象 [`nothing`](@ref)。此模式是其它语言中 [`Nullable`、`Option` 或 `Maybe`](https://en.wikipedia.org/wiki/Nullable_type) 类型在 Julia 的等价。通过将函数参数或字段声明为 `Union{T, Nothing}`,可以将其设置为类型为 `T` 的值,或者 `nothing` 来表示没有值。有关详细信息,请参阅[常见问题的此条目](@ref faq-nothing)。 ## [参数类型](@id Parametric-Types) Julia 类型系统的一个重要和强大的特征是它是参数的:类型可以接受参数,因此类型声明实际上引入了一整套新类型——每一个参数值的可能组合引入一个新类型。许多语言支持某种版本的[泛型编程](https://en.wikipedia.org/wiki/Generic_programming),其中,可以指定操作泛型的数据结构和算法,而无需指定所涉及的确切类型。例如,某些形式的泛型编程存在于 ML、Haskell、Ada、Eiffel、C++、Java、C#、F#、和 Scala 中,这只是其中的一些例子。这些语言中的一些支持真正的参数多态(例如 ML、Haskell、Scala),而其它语言基于模板的泛型编程风格(例如 C++、Java)。由于在不同语言中有多种不同种类的泛型编程和参数类型,我们甚至不会尝试将 Julia 的参数类型与其它语言的进行比较,而是专注于解释 Julia 系统本身。然而,我们将注意到,因为 Julia 是动态类型语言并且不需要在编译时做出所有类型决定,所以许多在静态参数类型系统中遇到的传统困难可以被相对容易地处理。 所有已声明的类型(`DataType` 类型)都可被参数化,在每种情况下都使用一样的语法。我们将按一下顺序讨论它们:首先是参数复合类型,接着是参数抽象类型,最后是参数原始类型。 ### [参数复合类型](@id man-parametric-composite-types) 类型参数在类型名称后引入,用大括号扩起来: ```jldoctest pointtype julia> struct Point{T} x::T y::T end ``` 此声明定义了一个新的参数类型,`Point{T}`,拥有类型为 `T` 的两个「坐标」。有人可能会问 `T` 是什么?嗯,这恰恰是参数类型的重点:它可以是任何类型(或者任何位类型值,虽然它实际上在这里显然用作类型)。`Point{Float64}` 是一个具体类型,该类型等价于通过用 [`Float64`](@ref) 替换 `Point` 的定义中的 `T` 所定义的类型。因此,单独这一个声明实际上声明了无限个类型:`Point{Float64}`,`Point{AbstractString}`,`Point{Int64}`,等等。这些类型中的每一个类型现在都是可用的具体类型: ```jldoctest pointtype julia> Point{Float64} Point{Float64} julia> Point{AbstractString} Point{AbstractString} ``` `Point{Float64}` 类型是坐标为 64 位浮点值的点,而 `Point{AbstractString}` 类型是「坐标」为字符串对象(请参阅 [Strings](@id man-strings))的「点」。 `Point` 本身也是一个有效的类型对象,包括所有实例 `Point{Float64}`、`Point{AbstractString}` 等作为子类型: ```jldoctest pointtype julia> Point{Float64} <: Point true julia> Point{AbstractString} <: Point true ``` 当然,其他类型不是它的子类型: ```jldoctest pointtype julia> Float64 <: Point false julia> AbstractString <: Point false ``` `Point` 不同 `T` 值所声明的具体类型之间,不能互相作为子类型: ```jldoctest pointtype julia> Point{Float64} <: Point{Int64} false julia> Point{Float64} <: Point{Real} false ``` !!! warning 最后一点*非常*重要:即使 `Float64 <: Real` 也**没有** `Point{Float64} <: Point{Real}`。 换成类型理论说法,Julia 的类型参数是*不变的*,而不是[协变的(或甚至是逆变的)](https://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29)。这是出于实际原因:虽然任何 `Point{Float64}` 的实例在概念上也可能像是 `Point{Real}` 的实例,但这两种类型在内存中有不同的表示: * `Point{Float64}` 的实例可以紧凑而高效地表示为一对 64 位立即数; * `Point{Real}` 的实例必须能够保存任何一对 [`Real`](@ref) 的实例。由于 `Real` 实例的对象可以具有任意的大小和结构,`Point{Real}` 的实例实际上必须表示为一对指向单独分配的 `Real` 对象的指针。 在数组的情况下,能够以立即数存储 `Point{Float64}` 对象会极大地提高效率:`Array{Float64}` 可以存储为一段 64 位浮点值组成的连续内存块,而 `Array{Real}` 必须是一个由指向单独分配的 [`Real`](@ref) 的指针组成的数组——这可能是 [boxed](https://en.wikipedia.org/wiki/Object_type_%28object-oriented_programming%29#Boxing) 64 位浮点值,但也可能是任意庞大和复杂的对象,且其被声明为 `Real` 抽象类型的表示。 由于 `Point{Float64}` 不是 `Point{Real}` 的子类型,下面的方法不适用于类型为 `Point{Float64}` 的参数: ```julia function norm(p::Point{Real}) sqrt(p.x^2 + p.y^2) end ``` 一种正确的方法来定义一个接受类型的所有参数的方法,`Point{T}`其中`T`是一个子类型[`Real`](@ref): ```julia function norm(p::Point{<:Real}) sqrt(p.x^2 + p.y^2) end ``` (等效地,另一种定义方法 `function norm(p::Point{T} where T<:Real)` 或 `function norm(p::Point{T}) where T<:Real`;查看 [UnionAll 类型](@ref)。) 稍后将在[方法](@ref)中讨论更多示例。 如何构造一个 `Point` 对象?可以为复合类型定义自定义的构造函数,这将在[构造函数](@ref man-constructors)中详细讨论,但在没有任何特别的构造函数声明的情况下,有两种默认方式可以创建新的复合对象,一种是显式地给出类型参数,另一种是通过传给对象构造函数的参数隐式地推断出。 由于 `Point{Float64}` 类型等价于在 `Point` 声明时用 [`Float64`](@ref) 替换 `T` 得到的具体类型,它可以相应地作为构造函数使用: ```jldoctest pointtype julia> p = Point{Float64}(1.0, 2.0) Point{Float64}(1.0, 2.0) julia> typeof(p) Point{Float64} ``` 对于默认的构造函数,必须为每个字段提供一个参数: ```jldoctest pointtype julia> Point{Float64}(1.0) ERROR: MethodError: no method matching Point{Float64}(::Float64) [...] julia> Point{Float64}(1.0,2.0,3.0) ERROR: MethodError: no method matching Point{Float64}(::Float64, ::Float64, ::Float64) [...] ``` 参数类型只生成一个默认的构造函数,因为它无法覆盖。这个构造函数接受任何参数并将它们转换为字段的类型。 许多情况下,没有必要提供想要构造的 `Point` 对象的类型,因为构造函数调用参数的类型已经隐式地提供了类型信息。因此,你也可以将 `Point` 本身用作构造函数,前提是参数类型 `T` 的隐含值是明确的: ```jldoctest pointtype julia> p1 = Point(1.0,2.0) Point{Float64}(1.0, 2.0) julia> typeof(p1) Point{Float64} julia> p2 = Point(1,2) Point{Int64}(1, 2) julia> typeof(p2) Point{Int64} ``` 在 `Point` 的例子中,当且仅当 `Point` 的两个参数类型相同时,`T` 的类型才确实是隐含的。如果不是这种情况,构造函数将失败并出现 [`MethodError`](@ref): ```jldoctest pointtype julia> Point(1,2.5) ERROR: MethodError: no method matching Point(::Int64, ::Float64) Closest candidates are: Point(::T, !Matched::T) where T at none:2 ``` 可以定义适当处理此类混合情况的函数构造方法,将在后面的[构造函数](@ref man-constructors)中讨论。 ### 参数抽象类型 参数抽象类型声明以非常相似的方式声明了一族抽象类型: ```jldoctest pointytype julia> abstract type Pointy{T} end ``` 在此声明中,对于每个类型或整数值 `T`,`Pointy{T}` 都是不同的抽象类型。与参数复合类型一样,每个此类型的实例都是 `Pointy` 的子类型: ```jldoctest pointytype julia> Pointy{Int64} <: Pointy true julia> Pointy{1} <: Pointy true ``` 参数抽象类型是不变的,就像参数复合类型: ```jldoctest pointytype julia> Pointy{Float64} <: Pointy{Real} false julia> Pointy{Real} <: Pointy{Float64} false ``` 符号 `Pointy{<:Real}` 可用于表示*协变*类型的 Julia 类似物,而 `Pointy{>:Int}` 类似于*逆变*类型,但从技术上讲,它们都代表了类型的*集合*(参见 [UnionAll 类型](@ref))。 ```jldoctest pointytype julia> Pointy{Float64} <: Pointy{<:Real} true julia> Pointy{Real} <: Pointy{>:Int} true ``` 正如之前的普通抽象类型用于在具体类型上创建实用的类型层次结构一样,参数抽象类型在参数复合类型上具有相同的用途。例如,我们可以将 `Point{T}` 声明为 `Pointy{T}` 的子类型,如下所示: ```jldoctest pointytype julia> struct Point{T} <: Pointy{T} x::T y::T end ``` 鉴于此类声明,对每个 `T`,都有 `Point{T}` 是 `Pointy{T}` 的子类型: ```jldoctest pointytype julia> Point{Float64} <: Pointy{Float64} true julia> Point{Real} <: Pointy{Real} true julia> Point{AbstractString} <: Pointy{AbstractString} true ``` 下面的关系依然不变: ```jldoctest pointytype julia> Point{Float64} <: Pointy{Real} false julia> Point{Float64} <: Pointy{<:Real} true ``` 参数抽象类型(比如 `Pointy`)的用途是什么?考虑一下如果点都在对角线 *x = y* 上,那我们创建的点的实现可以只有一个坐标: ```jldoctest pointytype julia> struct DiagPoint{T} <: Pointy{T} x::T end ``` 现在,`Point{Float64}` 和 `DiagPoint{Float64}` 都是抽象 `Pointy{Float64}` 的实现,每个类型 `T` 的其它可能选择与之类似。这允许对被所有 `Pointy` 对象共享的公共接口进行编程,接口都由 `Point` 和 `DiagPoint` 实现。但是,直到我们在下一节[方法](@ref)中引入方法和分派前,这无法完全证明。 有时,类型参数取遍所有可能类型也许是无意义的。在这种情况下,可以像这样约束 `T` 的范围: ```jldoctest realpointytype julia> abstract type Pointy{T<:Real} end ``` 在这样的声明中,可以使用任何 [`Real`](@ref) 的子类型替换 `T`,但不能使用不是 `Real` 子类型的类型: ```jldoctest realpointytype julia> Pointy{Float64} Pointy{Float64} julia> Pointy{Real} Pointy{Real} julia> Pointy{AbstractString} ERROR: TypeError: in Pointy, in T, expected T<:Real, got Type{AbstractString} julia> Pointy{1} ERROR: TypeError: in Pointy, in T, expected T<:Real, got a value of type Int64 ``` 参数化复合类型的类型参数可用相同的方式限制: ```julia struct Point{T<:Real} <: Pointy{T} x::T y::T end ``` 这里给出了一个真实示例,展示了所有这些参数类型机制如何发挥作用,下面是 Julia 的不可变类型 [`Rational`](@ref) 的实际定义(除了我们为了简单起见省略了的构造函数),用来表示准确的整数比例: ```julia struct Rational{T<:Integer} <: Real num::T den::T end ``` 只有接受整数值的比例才是有意义的,因此参数类型 `T` 被限制为 [`Integer`](@ref) 的子类型,又整数的比例代表实数轴上的值,因此任何 [`Rational`](@ref) 都是抽象 [`Real`](@ref) 的实现。 ### 元组类型 元组类型是函数参数的抽象化——不带函数本身。函数参数的突出特征是它们的顺序和类型。因此,元组类型类似于参数化的不可变类型,其中每个参数都是一个字段的类型。例如,二元元组类型类似于以下不可变类型: ```julia struct Tuple2{A,B} a::A b::B end ``` 然而,有三个主要差异: * 元组类型可以具有任意数量的参数。 * 元组类型的参数是**协变的**(covariant):`Tuple{Int}` 是 `Tuple{Any}` 的子类型。因此,`Tuple{Any}` 被认为是一种抽象类型,且元组类型只有在它们的参数都是具体类型时才是具体类型。 * 元组没有字段名称; 字段只能通过索引访问。 元组值用括号和逗号书写。构造元组时,会根据需要生成适当的元组类型: ```jldoctest julia> typeof((1,"foo",2.5)) Tuple{Int64, String, Float64} ``` 请注意协变性的含义: ```jldoctest julia> Tuple{Int,AbstractString} <: Tuple{Real,Any} true julia> Tuple{Int,AbstractString} <: Tuple{Real,Real} false julia> Tuple{Int,AbstractString} <: Tuple{Real,} false ``` 直观地,这对应于函数参数的类型是函数签名(当函数签名匹配时)的子类型。 ### 变参元组类型 元组类型的最后一个参数可以是特殊值[`Vararg`](@ref),它表示任意数量的尾随参数:   ```jldoctest julia> mytupletype = Tuple{AbstractString,Vararg{Int}} Tuple{AbstractString, Vararg{Int64}} julia> isa(("1",), mytupletype) true julia> isa(("1",1), mytupletype) true julia> isa(("1",1,2), mytupletype) true julia> isa(("1",1,2,3.0), mytupletype) false ``` 此外,`Vararg{T}` 对应于零个或更多的类型为 `T` 的元素。变参元组类型被用来表示变参方法接受的参数(请参阅[变参函数](@ref))。   特殊值 `Vararg{T,N}`(当用作元组类型的最后一个参数时)正好对应于类型为 `T` 的 `N` 个元素。 `NTuple{N,T}` 是 `Tuple{Vararg{T,N}}` 的一个方便的别名,即一个包含正好包含 `T` 类型的 `N` 个元素的元组类型。 ### 具名元组类型 具名元组是 [`NamedTuple`](@ref) 类型的实例,该类型有两个参数:一个给出字段名称的符号元组,和一个给出字段类型的元组类型。 ```jldoctest julia> typeof((a=1,b="hello")) NamedTuple{(:a, :b), Tuple{Int64, String}} ``` [`@NamedTuple`](@ref) 宏提供了类结构体(`struct`)的具名元组(`NamedTuple`)声明,使用 `key::Type` 的语法,如果省略 `::Type` 则默认为 `::Any`。 ```jldoctest julia> @NamedTuple{a::Int, b::String} NamedTuple{(:a, :b), Tuple{Int64, String}} julia> @NamedTuple begin a::Int b::String end NamedTuple{(:a, :b), Tuple{Int64, String}} ``` `NamedTuple` 类型可以用作构造函数,接受一个单独的元组作为参数。构造出来的 `NamedTuple` 类型可以是具体类型,如果参数都被指定,也可以是只由字段名称所指定的类型: ```jldoctest julia> @NamedTuple{a::Float32,b::String}((1,"")) (a = 1.0f0, b = "") julia> NamedTuple{(:a, :b)}((1,"")) (a = 1, b = "") ``` 如果指定了字段类型,参数会被转换。否则,就直接使用参数的类型。 ### 参数原始类型 原始类型也可以参数化声明,例如,指针都能表示为原始类型,其在 Julia 中以如下方式声明: ```julia # 32-bit system: primitive type Ptr{T} 32 end # 64-bit system: primitive type Ptr{T} 64 end ``` 与典型的参数复合类型相比,此声明中略显奇怪的特点是类型参数 `T` 并未在类型本身的定义里使用——它实际上只是一个抽象的标记,定义了一整族具有相同结构的类型,类型间仅由它们的类型参数来区分。因此,`Ptr{Float64}` 和 `Ptr{Int64}` 是不同的类型,就算它们具有相同的表示。当然,所有特定的指针类型都是总类型 [`Ptr`](@ref) 的子类型: ```jldoctest julia> Ptr{Float64} <: Ptr true julia> Ptr{Int64} <: Ptr true ``` ## UnionAll 类型 我们已经说过,像 `Ptr` 这样的参数类型可充当它所有实例(`Ptr{Int64}` 等)的超类型。这是如何办到的?`Ptr` 本身不能是普通的数据类型,因为在不知道引用数据的类型时,该类型显然不能用于存储器操作。答案是 `Ptr`(或其它参数类型像 `Array`)是一种不同种类的类型,称为 [`UnionAll`](@ref) 类型。这种类型表示某些参数的所有值的类型的*迭代并集*。 `UnionAll` 类型通常使用关键字 `where` 编写。例如,`Ptr` 可以更精确地写为 `Ptr{T} where T`,也就是对于 `T` 的某些值,所有类型为 `Ptr{T}` 的值。在这种情况下,参数 `T` 也常被称为「类型变量」,因为它就像一个取值范围为类型的变量。每个 `where` 只引入一个类型变量,因此在具有多个参数的类型中这些表达式会被嵌套,例如 `Array{T,N} where N where T`。 类型应用语法 `A{B,C}` 要求 `A` 是个 `UnionAll` 类型,并先代入 `B` 作为 `A` 中最外层的类型变量。结果应该是另一个 `UnionAll` 类型,然后再将 `C` 代入。所以 `A{B,C}` 等价于 `A{B}{C}`。这解释了为什么可以部分实例化一个类型,比如 `Array{Float64}`:第一个参数已经被固定,但第二个参数仍取遍所有可能值。通过使用 `where` 语法,任何参数子集都能被固定。例如,所有一维数组的类型可以写为 `Array{T,1} where T`。 类型变量可以用子类型关系来加以限制。`Array{T} where T<:Integer` 指的是元素类型是某种 [`Integer`](@ref) 的所有数组。语法 `Array{<:Integer}` 是 `Array{T} where T<:Integer` 的便捷的缩写。类型变量可同时具有上下界。`Array{T} where Int<:T<:Number` 指的是元素类型为能够包含 `Int` 的 [`Number`](@ref) 的所有数组(因为 `T` 至少和 `Int` 一样大)。语法 `where T>:Int` 也能用来只指定类型变量的下界,且 `Array{>:Int}` 等价于 `Array{T} where T>:Int`。 由于 `where` 表达式可以嵌套,类型变量界可以引用更外层的类型变量。比如 `Tuple{T,Array{S}} where S<:AbstractArray{T} where T<:Real` 指的是二元元组,其第一个元素是某个 [`Real`](@ref),而第二个元素是数组的数组 `Array`,其包含的内部数组的元素类型由元组的第一个元素类型决定。 `where` 关键字本身可以嵌套在更复杂的声明里。例如,考虑由以下声明创建的两个类型: ```jldoctest julia> const T1 = Array{Array{T, 1} where T, 1} Vector{Vector} (alias for Array{Array{T, 1} where T, 1}) julia> const T2 = Array{Array{T, 1}, 1} where T Array{Vector{T}, 1} where T ``` 类型 `T1` 定义了由一维数组组成的一维数组;每个内部数组由相同类型的对象组成,但此类型对于不同内部数组可以不同。另一方面,类型 `T2` 定义了由一维数组组成的一维数组,其中的每个内部数组必须具有相同的类型。请注意,`T2` 是个抽象类型,比如 `Array{Array{Int,1},1} <: T2`,而 `T1` 是个具体类型。因此,`T1` 可由零参数构造函数 `a=T1()` 构造,但 `T2` 不行。 命名此类型有一种方便的语法,类似于函数定义语法的简短形式: ```julia Vector{T} = Array{T, 1} ``` 这等价于 `const Vector = Array{T,1} where T`。编写 `Vector{Float64}` 等价于编写 `Array{Float64,1}`,总类型 `Vector` 具有所有 `Array` 对象的实例,其中 `Array` 对象的第二个参数——数组维数——是 1,而不考虑元素类型是什么。在参数类型必须总被完整指定的语言中,这不是特别有用,但在 Julia 中,这允许只编写 `Vector` 来表示包含任何元素类型的所有一维密集数组的抽象类型。 ## [单例类型](@id man-singleton-types) 没有字段的不可变复合类型称为 *单例类型*。正式地,如果 1. `T` 是一个不可变的复合类型(即用 `struct` 定义), 1. `a isa T && b isa T` 暗含 `a === b`, 那么`T`是单例类型。[^2] [`Base.issingletontype`](@ref) 可以用来检查一个类型是否是单例类型。 [抽象类型](@ref man-abstract-types) 不能通过构造成为单例类型。 根据定义,此类类型只能有一个实例: ```jldoctest julia> struct NoFields end julia> NoFields() === NoFields() true julia> Base.issingletontype(NoFields) true ``` [`===`](@ref) 函数确认`NoFields` 的构造实例实际上是一个且相同的。 当上述条件成立时,参数类型可以是单例类型。例如, ```jldoctest julia> struct NoFieldsParam{T} end julia> Base.issingletontype(NoFieldsParam) # can't be a singleton type ... false julia> NoFieldsParam{Int}() isa NoFieldsParam # ... because it has ... true julia> NoFieldsParam{Bool}() isa NoFieldsParam # ... multiple instances true julia> Base.issingletontype(NoFieldsParam{Int}) # parametrized, it is a singleton true julia> NoFieldsParam{Int}() === NoFieldsParam{Int}() true ``` ## [`Type{T}` 类型选择器](@id man-typet-type) 对于每个类型`T`,`Type{T}` 是一个抽象的参数类型,它的唯一实例是对象`T`。 在我们讨论 [参数方法](@ref) 和 [类型转换](@ref conversion-and-promotion) 之前,很难解释这个构造的效用,但简而言之,它允许人们专门针对特定类型的函数行为 作为*值*。 这对于编写其行为取决于作为显式参数给出的类型而不是由其参数之一的类型隐含的类型的方法(尤其是参数方法)很有用。 由于定义有点难理解,我们来看一些例子: ```jldoctest julia> isa(Float64, Type{Float64}) true julia> isa(Real, Type{Float64}) false julia> isa(Real, Type{Real}) true julia> isa(Float64, Type{Real}) false ``` 换句话说,[`is(A, Type{B})`](@ref) 当且仅当 `A` 和 `B` 是同一个对象并且该对象是一个类型时才为真。 特别的,由于参数类型是 [不变量](@ref man-parametric-composite-types),我们有 ```jldoctest julia> struct TypeParamExample{T} x::T end julia> TypeParamExample isa Type{TypeParamExample} true julia> TypeParamExample{Int} isa Type{TypeParamExample} false julia> TypeParamExample{Int} isa Type{TypeParamExample{Int}} true ``` 如果没有参数,`Type` 只是一个抽象类型,所有类型对象都是其实例: ```jldoctest julia> isa(Type{Float64}, Type) true julia> isa(Float64, Type) true julia> isa(Real, Type) true ``` 不是类型的对象不是 `Type` 的实例: ```jldoctest julia> isa(1, Type) false julia> isa("foo", Type) false ``` 虽然 `Type` 与任何其他抽象参数类型一样是 Julia 类型层次结构的一部分,但它并不常用在方法签名之外,除非在某些特殊情况下。 `Type` 的另一个重要用法是使不太精确的字段类型更加清晰,例如[`DataType`](@ref man-declared-types) 在下面的示例中,默认构造函数可能会导致依赖精确包装类型的代码出现性能问题(类似于 [抽象类型参数](@ref man-performance-abstract-container))。 ```jldoctest julia> struct WrapType{T} value::T end julia> WrapType(Float64) # default constructor, note DataType WrapType{DataType}(Float64) julia> WrapType(::Type{T}) where T = WrapType{Type{T}}(T) WrapType julia> WrapType(Float64) # sharpened constructor, note more precise Type{Float64} WrapType{Type{Float64}}(Float64) ``` ## 类型别名 有时为一个已经可表达的类型引入新名称是很方便的。这可通过一个简单的赋值语句完成。例如,`UInt` 是 [`UInt32`](@ref) 或 [`UInt64`](@ref) 的别名,因为它的大小与系统上的指针大小是相适应的。 ```julia-repl # 32-bit system: julia> UInt UInt32 # 64-bit system: julia> UInt UInt64 ``` 这是由 `base/boot.jl` 中以下代码实现的: ```julia if Int === Int64 const UInt = UInt64 else const UInt = UInt32 end ``` 当然,这依赖于 `Int` 的别名,但它被预定义成正确的类型—— [`Int32`](@ref) 或 [`Int64`](@ref)。 (注意,与 `Int` 不同,`Float` 不作为特定大小的 [`AbstractFloat`](@ref) 类型的别名而存在。与整数寄存器不同,浮点数寄存器大小由 IEEE-754 标准指定,而 `Int` 的大小反映了该机器上本地指针的大小。) ## 类型操作 因为 Julia 中的类型本身就是对象,所以一般的函数可以对它们进行操作。已经引入了一些对于使用或探索类型特别有用的函数,例如 `<:` 运算符,它表示其左操作数是否为其右操作数的子类型。 [`isa`](@ref) 函数测试对象是否具有给定类型并返回 true 或 false: ```jldoctest julia> isa(1, Int) true julia> isa(1, AbstractFloat) false ``` 在文档示例中随处可见的 [`typeof`](@ref) 函数返回其参数的类型。如上所述,因为类型都是对象,所以它们也有类型,我们可以询问它们的类型: ```jldoctest julia> typeof(Rational{Int}) DataType julia> typeof(Union{Real,String}) Union ``` 如果我们重复这个过程会怎样?一个类型的类型是什么?碰巧,每个类型都是复合值,因此都具有 `DataType` 类型: ```jldoctest julia> typeof(DataType) DataType julia> typeof(Union) DataType ``` `DataType` 是它自己的类型。 另一个适用于某些类型的操作是 [`supertype`](@ref),它显示了类型的超类型。只有已声明的类型(`DataType`)才有明确的超类型: ```jldoctest julia> supertype(Float64) AbstractFloat julia> supertype(Number) Any julia> supertype(AbstractString) Any julia> supertype(Any) Any ``` 如果将 [`supertype`](@ref) 应用于其它类型对象(或非类型对象),则会引发 [`MethodError`](@ref): ```jldoctest; filter = r"Closest candidates.*"s julia> supertype(Union{Float64,Int64}) ERROR: MethodError: no method matching supertype(::Type{Union{Float64, Int64}}) Closest candidates are: [...] ``` ## [自定义 pretty-printing](@id man-custom-pretty-printing) 通常,人们会想要自定义显示类型实例的方式。这可通过重载 [`show`](@ref) 函数来完成。举个例子,假设我们定义一个类型来表示极坐标形式的复数: ```jldoctest polartype julia> struct Polar{T<:Real} <: Number r::T Θ::T end julia> Polar(r::Real,Θ::Real) = Polar(promote(r,Θ)...) Polar ``` 在这里,我们添加了一个自定义的构造函数,这样就可以接受不同 [`Real`](@ref) 类型的参数并将它们类型提升为共同类型(请参阅[构造函数](@ref man-constructors)和[类型转换和类型提升](@ref conversion-and-promotion))。(当然,为了让它表现地像个 [`Number`](@ref),我们需要定义许多其它方法,例如 `+`、`*`、`one`、`zero` 及类型提升规则等。)默认情况下,此类型的实例只是相当简单地显示有关类型名称和字段值的信息,比如,`Polar{Float64}(3.0,4.0)`。 如果我们希望它显示为 `3.0 * exp(4.0im)`,我们可定义以下方法来将对象打印到给定的输出对象 `io`(其代表文件、终端、及缓冲区等;请参阅[网络和流](@ref)): ```jldoctest polartype julia> Base.show(io::IO, z::Polar) = print(io, z.r, " * exp(", z.Θ, "im)") ``` `Polar` 对象的输出可以被更精细地控制。特别是,人们有时想要啰嗦的多行打印格式,用于在 REPL 和其它交互式环境中显示单个对象,以及一个更紧凑的单行格式,用于 [`print`](@ref) 函数或在作为其它对象(比如一个数组)的部分是显示该对象。虽然在两种情况下默认都会调用 `show(io, z)` 函数,你仍可以定义一个*不同*的多行格式来显示单个对象,这通过重载三参数形式的 `show` 函数,该函数接收 `text/plain` MIME 类型(请参阅 [多媒体 I/O](@ref))作为它的第二个参数,举个例子: ```jldoctest polartype julia> Base.show(io::IO, ::MIME"text/plain", z::Polar{T}) where{T} = print(io, "Polar{$T} complex number:\n ", z) ``` (请注意 `print(..., z)` 在这里调用的是双参数的 `show(io, z)` 方法。)这导致: ```jldoctest polartype julia> Polar(3, 4.0) Polar{Float64} complex number: 3.0 * exp(4.0im) julia> [Polar(3, 4.0), Polar(4.0,5.3)] 2-element Vector{Polar{Float64}}: 3.0 * exp(4.0im) 4.0 * exp(5.3im) ``` 其中单行格式的 `show(io, z)` 仍用于由 `Polar` 值组成的数组。从技术上讲,REPL 调用 `display(z)` 来显示单行的执行结果,其默认为 `show(stdout, MIME("text/plain"), z)`,而后者又默认为 `show(stdout, z)`,但是你*不应该*定义新的 [`display`](@ref) 方法,除非你正在定义新的多媒体显示管理器(请参阅[多媒体 I/O](@ref))。 此外,你还可以为其它 MIME 类型定义 `show` 方法,以便在支持的环境(比如 IJulia)中实现更丰富的对象显示(HTML、图像等)。例如,我们可以定义 `Polar` 对象的 HTML 显示格式,使其带有上标和斜体: ```jldoctest polartype julia> Base.show(io::IO, ::MIME"text/html", z::Polar{T}) where {T} = println(io, "<code>Polar{$T}</code> complex number: ", z.r, " <i>e</i><sup>", z.Θ, " <i>i</i></sup>") ``` 之后会在支持 HTML 显示的环境中自动使用 HTML 显示 `Polar` 对象,但你也可以手动调用 `show` 来获取 HTML 输出: ```jldoctest polartype julia> show(stdout, "text/html", Polar(3.0,4.0)) <code>Polar{Float64}</code> complex number: 3.0 <i>e</i><sup>4.0 <i>i</i></sup> ``` ```@raw html <p>An HTML renderer would display this as: <code>Polar{Float64}</code> complex number: 3.0 <i>e</i><sup>4.0 <i>i</i></sup></p> ``` 根据经验,单行 `show` 方法应为创建的显示对象打印有效的 Julia 表达式。当这个 `show` 方法包含中缀运算符时,比如上面的 `Polar` 的单行 `show` 方法里的乘法运算符(`*`),在作为另一个对象的部分打印时,它可能无法被正确解析。要查看此问题,请考虑下面的表达式对象(请参阅[程序表示](@ref)),它代表 `Polar` 类型的特定实例的平方: ```jldoctest polartype julia> a = Polar(3, 4.0) Polar{Float64} complex number: 3.0 * exp(4.0im) julia> print(:($a^2)) 3.0 * exp(4.0im) ^ 2 ``` 因为运算符 `^` 的优先级高于 `*`(请参阅[运算符的优先级与结合性](@ref)),所以此输出错误地表示了表达式 `a ^ 2`,而该表达式等价于 `(3.0 * exp(4.0im)) ^ 2`。为了解决这个问题,我们必须为 `Base.show_unquoted(io::IO, z::Polar, indent::Int, precedence::Int)` 创建一个自定义方法,在打印时,表达式对象会在内部调用它: ```jldoctest polartype julia> function Base.show_unquoted(io::IO, z::Polar, ::Int, precedence::Int) if Base.operator_precedence(:*) <= precedence print(io, "(") show(io, z) print(io, ")") else show(io, z) end end julia> :($a^2) :((3.0 * exp(4.0im)) ^ 2) ``` 当正在调用的运算符的优先级大于等于乘法的优先级时,上面定义的方法会在 `show` 调用的两侧加上括号。这个检查允许,在没有括号时也可被正确解析的表达式(例如 `:($a + 2)` 和 `:($a == 2)`),在打印时省略括号: ```jldoctest polartype julia> :($a + 2) :(3.0 * exp(4.0im) + 2) julia> :($a == 2) :(3.0 * exp(4.0im) == 2) ``` 在某些情况下,根据上下文调整 `show` 方法的行为是很有用的。这可通过 [`IOContext`](@ref) 类型实现,它允许同时传递上下文属性和封装后的 IO 流。例如,我们可以在 `:compact` 属性设置为 `true` 时创建一个更短的表示,而在该属性为 `false` 或不存在时返回长的表示: ```jldoctest polartype julia> function Base.show(io::IO, z::Polar) if get(io, :compact, false) print(io, z.r, "ℯ", z.Θ, "im") else print(io, z.r, " * exp(", z.Θ, "im)") end end ``` 当传入的 IO 流是设置了 `:compact`(译注:该属性还应当设置为 `true`)属性的 `IOContext` 对象时,新的紧凑表示将被使用。特别地,当打印具有多列的数组(由于水平空间有限)时就是这种情况: ```jldoctest polartype julia> show(IOContext(stdout, :compact=>true), Polar(3, 4.0)) 3.0ℯ4.0im julia> [Polar(3, 4.0) Polar(4.0,5.3)] 1×2 Matrix{Polar{Float64}}: 3.0ℯ4.0im 4.0ℯ5.3im ``` 有关调整打印效果的常用属性列表,请参阅文档 [`IOContext`](@ref)。 ## 值类型 在 Julia 中,你无法根据诸如 `true` 或 `false` 之类的*值*进行分派。然而,你可以根据参数类型进行分派,Julia 允许你包含「plain bits」值(类型、符号、整数、浮点数和元组等)作为类型参数。`Array{T,N}` 里的维度参数就是一个常见的例子,在这里 `T` 是类型(比如 [`Float64`](@ref)),而 `N` 只是个 `Int`。 你可以创建把值作为参数的自定义类型,并使用它们控制自定义类型的分派。为了说明这个想法,让我们引入参数类型 `Val{x}` 和构造函数 `Val(x) = Val{x}()`,在不需要更精细的层次结构时,这是利用此技巧的一种习惯的方式。 [`Val`](@ref) 的定义为: ```jldoctest valtype julia> struct Val{x} end julia> Val(x) = Val{x}() Val ``` `Val` 的实现就只需要这些。一些 Julia 标准库里的函数接收 `Val` 的实例作为参数,你也可以使用它来编写你自己的函数,例如: ```jldoctest valtype julia> firstlast(::Val{true}) = "First" firstlast (generic function with 1 method) julia> firstlast(::Val{false}) = "Last" firstlast (generic function with 2 methods) julia> firstlast(Val(true)) "First" julia> firstlast(Val(false)) "Last" ``` 为了保证 Julia 的一致性,调用处应当始终传递 `Val` **实例** 而不是 **类型**,也就是使用 `foo(Val(:bar))` 而不是 `foo(Val{:bar})`。 值得注意的是,参数「值」类型非常容易被误用,包括 `Val`;在不适用的情形下,你很容易使代码性能变得更*糟糕*。特别是,你可能永远都不会想要写出如上所示的代码。有关 `Val` 的正确(和不正确)使用的更多信息,请阅读[性能建议](@ref man-performance-value-type)中更广泛的讨论。 [^1]: 「少数」由常数 `MAX_UNION_SPLITTING` 定义,目前设置为 4。 [^2]: 一些流行的编程语言具有单例类型,包括 Haskell、Scala 和 Ruby。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2455
# [Unicode 输入表](@id Unicode-Input) 在 Julia REPL 或其它编辑器中,可以像输入 LaTeX 符号一样,用 tab 补全下表列出的 Unicode 字符。在 REPL 中,可以先按 `?` 进入帮助模式,然后将 Unicode 字符复制粘贴进去,一般在文档开头就会写输入方式。 !!! warning 此表第二列可能会缺失一些字符,对某些字符的显示效果也可能会与在 Julia REPL 中不一致。如果发生了这种状况,强烈建议用户检查一下浏览器或 REPL 的字体设置,目前已知很多字体都有显示问题。 ```@eval # # Generate a table containing all LaTeX and Emoji tab completions available in the REPL. # import REPL, Markdown const NBSP = '\u00A0' function tab_completions(symbols...) completions = Dict{String, Vector{String}}() for each in symbols, (k, v) in each completions[v] = push!(get!(completions, v, String[]), k) end return completions end function unicode_data() file = normpath(Sys.BINDIR, "..", "UnicodeData.txt") names = Dict{UInt32, String}() open(file) do unidata for line in readlines(unidata) id, name, desc = split(line, ";")[[1, 2, 11]] codepoint = parse(UInt32, "0x$id") names[codepoint] = titlecase(lowercase( name == "" ? desc : desc == "" ? name : "$name / $desc")) end end return names end # Surround combining characters with no-break spaces (i.e '\u00A0'). Follows the same format # for how unicode is displayed on the unicode.org website: # http://unicode.org/cldr/utility/character.jsp?a=0300 function fix_combining_chars(char) cat = Base.Unicode.category_code(char) return cat == 6 || cat == 8 ? "$NBSP$char$NBSP" : "$char" end function table_entries(completions, unicode_dict) entries = [[ "Code point(s)", "Character(s)", "Tab completion sequence(s)", "Unicode name(s)" ]] for (chars, inputs) in sort!(collect(completions), by = first) code_points, unicode_names, characters = String[], String[], String[] for char in chars push!(code_points, "U+$(uppercase(string(UInt32(char), base = 16, pad = 5)))") push!(unicode_names, get(unicode_dict, UInt32(char), "(No Unicode name)")) push!(characters, isempty(characters) ? fix_combining_chars(char) : "$char") end push!(entries, [ join(code_points, " + "), join(characters), join(inputs, ", "), join(unicode_names, " + ") ]) end return Markdown.Table(entries, [:l, :l, :l, :l]) end table_entries( tab_completions( REPL.REPLCompletions.latex_symbols, REPL.REPLCompletions.emoji_symbols ), unicode_data() ) ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
15863
# [变量作用域](@id scope-of-variables) 变量的 **作用域** 是代码的一个区域,在这个区域中这个变量是可见的。给变量划分作用域有助于解决变量命名冲突。这个概念是符合直觉的:两个函数可能同时都有叫做 `x` 的参量,而这两个 `x` 并不指向同一个东西。 相似地,也有很多其他的情况,代码的不同块会使用同样名字,但并不指向同一个东西。相同的变量名是否指向同一个东西的规则被称为作用域规则;这一节会详细地把这个规则讲清楚。 语言中的某些结构会引入*作用域块*,这是可以成为一些变量集合的作用域的代码区域。一个变量的作用域不是源代码行的任意集合;相反,它始终与这些块之一关系密切。在 Julia 中主要有两种作用域,*全局作用域* 与 *局部作用域*,后者可以嵌套。 在 Julia 中还存在引入“硬作用域”的构造和只引入“软作用域”的构造之间的区别,这影响到是否允许以相同的名称[遮蔽](https://en.wikipedia.org/wiki/Variable_shadowing)全局变量。 ### [作用域结构](@id man-scope-table) 引入作用域块的结构有: | 结构 | 作用域类型 | 允许使用在 | |:----------|:-----------|:---------------| | [`module`](@ref), [`baremodule`](@ref) | 全局 | 全局 | | [`struct`](@ref) | 局部(软) | 全局 | | [`for`](@ref), [`while`](@ref), [`try`](@ref try) | 局部(软) | global, local | | [`macro`](@ref) | 局部(硬) | 全局 | | 函数, [`do`](@ref) 语句块, [`let`](@ref)语句块, 数组推导, 生成器 | 局部(硬) | global, local | 值得注意的是,这个表内没有的是 [begin 块](@ref man-compound-expressions)和[ if 块](@ref man-conditional-evaluation),这两个块**不会**引进新的作用域块。这两种作用域遵循的规则有点不一样,会在下面解释。 Julia 使用[词法作用域](https://en.wikipedia.org/wiki/Scope_%28computer_science%29#Lexical_scoping_vs._dynamic_scoping),也就是说一个函数的作用域不继承自调用了函数的调用者作用域,而继承自该函数定义处作用域。举例如下,`foo` 中的 `x` 指向模块 `Bar` 的全局作用域中 `x`。 ```jldoctest moduleBar julia> module Bar x = 1 foo() = x end; ``` 而非调用了 `foo` 的作用域中的 `x`: ```jldoctest moduleBar julia> import .Bar julia> x = -1; julia> Bar.foo() 1 ``` 因此**词法作用域**意味着,某段代码内某变量的指向只从它出现之处就可以推断出来,而不依赖于程序的执行方式。在嵌套的作用域结构里,内层作用域能”看“到所有外层作用域内变量。相对地,外层作用域不能看到内层作用域的变量。 ## 全局作用域 每个模块会引进一个新全局作用域,与其他所有模块的全局作用域分开;无所不包的全局作用域不存在。模块可以把其他模块的变量引入到它的作用域中,通过[using 或者 import](@ref modules)语句或者通过点符号这种有资格的通路,也就是说每个模块都是所谓的*命名空间*或者关联着含值的名字的第一类数据结构。值得注意的是,即便变量绑定能在外部被读取,变量绑定也只能在它们的全局作用域中改变。 作为一个逃生窗口,你总是可以执行该模块内代码来修改一个变量;这特别保证了不调用 `eval` 的外部代码绝不会修改模块绑定。 ```jldoctest julia> module A a = 1 # a global in A's scope end; julia> module B module C c = 2 end b = C.c # can access the namespace of a nested global scope # through a qualified access import ..A # makes module A available d = A.a end; julia> module D b = a # errors as D's global scope is separate from A's end; ERROR: UndefVarError: a not defined julia> module E import ..A # make module A available A.a = 2 # throws below error end; ERROR: cannot assign variables in other modules ``` 注意交互式提示行(即REPL)是在模块`Main`的全局作用域中。 ## 局部作用域 大多数代码块都引入了新的局部作用域(完整[列表](@ref man-scope-table)请参见上表)。如果这样的代码块在语法上嵌套在另一个局部作用域内,则它创建的作用域嵌套在它出现的所有局部作用域内,这些局部作用域最终都嵌套在评估代码的模块的全局作用域内。 外部作用域中的变量在它们包含的任何作用域中都是可见的——这意味着它们可以在内部作用域中读取和写入——除非有一个同名的局部变量“遮蔽”了同名的外部变量。 即使外部的本地变量是在内部块之后(在下面的文本意义上)声明的,也是如此。 当我们说一个变量在给定范围内“存在”时,这意味着具有该名称的变量存在于当前范围嵌套在其中的任何范围内,包括当前范围。 一些编程语言需要在使用新变量之前显式声明它们。显式声明也适用于 Julia:在任何局部作用域中,编写 `local x` 都会在该作用域中声明一个新的局部变量,无论外部作用域中是否已经存在名为 `x` 的变量。像这样声明每个新变量有点冗长乏味,但是,与许多其他语言一样,Julia 考虑对不存在的变量名称进行赋值以隐式声明该变量。如果当前作用域是全局的,则新变量是全局的;如果当前作用域是局部的,则新变量对最内部的局部作用域是局部的,并且在该作用域内可见,但在该作用域外不可见。如果你给现有的局部变量赋值,它_总是_更新现有的局部变量:你只能通过使用 `local` 关键字在嵌套范围内显式声明新的局部变量来隐藏原局部变量。特别是,这适用于在内部函数中分配的变量,这可能会让来自 Python 的用户感到惊讶,其中内部函数中的赋值会创建一个新的局部变量,除非该变量被明确声明为非局部变量。 大多数情况下,这是非常直观的,但与许多直觉行为一样,细节比人们天真地想象的要微妙得多。 当 `x = <value>` 出现在某局部作用域,Julia 根据赋值表达式出现位置、 `x` 在此处已经引用的内容,采取如下规则确定表达式的意义: 1. **现存的局部变量:**如果 `x` **已经是一个局部变量**,那现存的局部变量 `x` 将被 赋值; 2. **硬作用域:如果 `x` 还*不是局部变量*并且赋值发生的作用域结构是硬作用域(即在 `let` 语句块、函数体、宏、推导式或生成器中),则会在赋值作用域中创建一个名为 `x` 的新局部变量; 3. **软作用域:**如果 `x` **并非已经是局部变量**,并且所有包含 此次赋值的作用域结构是软作用域(循环、`try`/`catch` 块、或者 `struct` 块), 最后行为取决于全局变量 `x` 是否被定义: * 如果全局变量 `x` 是**未定义**,最终此次赋值会在该作用域创建一个名为 `x` 的新局部变量 ; * 如果全局变量 `x` 是**已定义**,此次赋值会被认为是有歧义的: * 在**非交互**的上下文(文件、eval)中,会打印一个有歧义警告,同时创建一个新 局部变量; * 在**交互**的上下文(REPL, notebooks)中,会向全局变量 `x` 赋值。 你或许注意到,当某隐性局部变量(比如未经 `local x` 声明)遮掩某全局变量,非交互的上下文中硬作用域和软作用域有相同行为,除了会输出警告。方便起见,交互的上下文遵从一套更复杂的启发式规则。下面的例子将会深入讲解。 既然你知道这个规则,那就看看一些例子。每个例子都是一个新的REPL会话中进行的,因此每个片段中唯一的全局变量就是在该代码块中分配的全局变量。 我们将从一个良好且明确的情况开始——在一个硬作用域内赋值,在这个情况下是一个函数体,当同名的局部变量不存在时: ```jldoctest julia> function greet() x = "hello" # new local println(x) end greet (generic function with 1 method) julia> greet() hello julia> x # global ERROR: UndefVarError: x not defined ``` 在 `greet` 函数内部,赋值 `x = "hello"` 导致 `x` 成为函数作用域中的一个新局部变量。 有两个相关的事实:赋值发生在局部作用域内,并且没有现有的局部 `x` 变量。 由于 `x` 是局部的,所以是否存在名为 `x` 的全局变量并不重要。 例如,我们在定义和调用 `greet` 之前定义了 `x = 123`: ```jldoctest julia> x = 123 # global 123 julia> function greet() x = "hello" # new local println(x) end greet (generic function with 1 method) julia> greet() hello julia> x # global 123 ``` 由于 `greet` 中的 `x` 是局部的,全局 `x` 的值(或缺少值)不会受到调用 `greet` 的影响。 硬作用域规则不关心名为 `x` 的全局变量是否存在:在硬作用域中对 `x` 的赋值是局部的(除非 `x` 被声明为全局的)。 我们将考虑的下一个明确的情况是已经有一个名为`x`的局部变量,在这种情况下,`x = 1`总是赋值给这个现有的局部`x`。 无论赋值发生在同一局部作用域、同一函数体的内部局部作用域,还是嵌套在另一个函数内部的函数体(也称为 [闭包](https://en.wikipedia.org/wiki/Closure_(computer_programming)))。 我们将使用 `sum_to` 函数,它计算从 1 到 `n` 的整数之和,例如: ```julia function sum_to(n) s = 0 # new local for i = 1:n s = s + i # assign existing local end return s # same local end ``` 与前面的示例一样,在 `sum_to` 函数先对 `s` 的第一次赋值导致 `s` 成为函数体中的一个新局部变量。 `for` 循环在函数作用域内有自己的内部局部作用域。 在 `s = s + i` 出现的地方,`s` 已经是一个局部变量,所以赋值更新了现有的 `s` 而不是创建一个新的局部变量。 我们可以通过在 REPL 中调用 `sum_to` 来测试: ```jldoctest julia> function sum_to(n) s = 0 # new local for i = 1:n s = s + i # assign existing local end return s # same local end sum_to (generic function with 1 method) julia> sum_to(10) 55 julia> s # global ERROR: UndefVarError: s not defined ``` 由于 `s` 是函数 `sum_to` 的局部变量,调用该函数对全局变量 `s` 没有影响。 我们还可以看到,`for` 循环中的更新 `s = s + i` 必须更新由初始化 `s = 0` 创建的相同 `s`,因为我们得到了整数 1 到 10 的正确总和 55。 让我们通过编写一个稍微详细一点的变体来深入了解一下 `for` 循环体有自己的作用域,我们将其称为 `sum_to_def`,其中,在更新 `s` 之前,我们将和 `s + i` 保存在一个变量中` t` : ```jldoctest julia> function sum_to_def(n) s = 0 # new local for i = 1:n t = s + i # new local `t` s = t # assign existing local `s` end return s, @isdefined(t) end sum_to_def (generic function with 1 method) julia> sum_to_def(10) (55, false) ``` 这个版本像先前一样返回 `s`,但它也使用 `@isdefined` 宏返回一个布尔值,指示是否在函数的最外层局部作用域中定义了一个名为 `t` 的局部变量。 正如你所看到的,在 `for` 循环体之外没有定义 `t`。 这又是因为硬作用域规则:由于对 `t` 的赋值发生在一个函数内部,这引入了一个硬作用域,赋值导致 `t` 在它出现的局部作用域中成为一个新的局部变量,即循环体内部。 即使有一个名为 `t` 的全局变量,它也没有任何区别——硬作用域规则不受全局作用域中的任何内容的影响。 请注意,for 循环体的局部作用域与内部函数的局部作用域没有区别。 这意味着我们可以重写此示例,以便将循环体实现为对内部辅助函数的调用,并且其行为方式相同: ```jldoctest julia> function sum_to_def_closure(n) function loop_body(i) t = s + i # new local `t` s = t # assign same local `s` as below end s = 0 # new local for i = 1:n loop_body(i) end return s, @isdefined(t) end sum_to_def_closure (generic function with 1 method) julia> sum_to_def_closure(10) (55, false) ``` 这个例子说明了几个要点: 1. 内部函数作用域就像任何其他嵌套的局部作用域一样。 特别是,如果一个变量已经是内部函数之外的局部变量,并且你在内部函数中为其赋值,则外部局部变量会被更新。 2. 外部的局部变量的定义是否发生在更新位置的下方并不重要,规则保持不变。在解析内部的局部变量含义之前,解析整个封闭局部作用域并确定其局部变量。 这种设计意味着你通常可以将代码移入或移出内部函数而不改变其含义,这给使用闭包语言中的许多常见习语提供了便利。(参见 [do blocks](@ref Do-Block-Syntax-for-Function-Arguments))。 让我们继续讨论软作用域规则涵盖的一些更模糊的情况。 我们将通过将 `gree`t 和 `sum_to_def `函数的主体提取到软作用域上下文中来探索这一点。 首先,让我们将 `greet` 的主体放在一个 `for` 循环中——它是软的,而不是硬的——并在 REPL 中运行: ```jldoctest julia> for i = 1:3 x = "hello" # new local println(x) end hello hello hello julia> x ERROR: UndefVarError: x not defined ``` 由于在执行`for`循环时未定义全局变量`x`,因此软作用域规则的第一个子句适用,并且`x`被创建为`for`循环内的局部变量,因此循环执行完后全局变量`x`一直没有定义 。 接下来,让我们考虑提取到全局作用域内的 `sum_to_def` 的函数体,将其参数固定为 `n = 10` ```julia s = 0 for i = 1:10 t = s + i s = t end s @isdefined(t) ``` 这段代码有什么作用? 提示:这是一个小把戏。 答案是“视情况而定”。 如果此代码以交互方式输入,则其行为方式与在函数体中的行为方式相同。 但是如果代码出现在文件中,它会打印一个歧义警告并抛出一个未定义的变量错误。 让我们先看看它在 REPL 中的情况: ```jldoctest julia> s = 0 # global 0 julia> for i = 1:10 t = s + i # new local `t` s = t # assign global `s` end julia> s # global 55 julia> @isdefined(t) # global false ``` REPL 内行为接近于函数体内,决定循环内部的赋值是分配给一个全局变量还是创建新的局部变量,取决于是否定义了具有该名称的全局变量。 如果存在同名的全局变量,则赋值会更新它。 如果不存在全局变量,则赋值会创建一个新的局部变量。 在这个例子中,我们看到两种情况都在起作用: * 没有名为 `t` 的全局变量,因此 `t = s + i` 创建了一个新的 `t`,它是 `for` 循环的局部变量; * 有一个名为 `s` 的全局变量,因此将 `s = t` 赋值给它。 第二个情况解释了为什么循环的执行会改变 `s` 的全局值,第一个情况解释了为什么在循环执行后 `t` 仍未定义。 现在,让我们尝试运行相同的代码,就像它在文件中一样: ```jldoctest julia> code = """ s = 0 # global for i = 1:10 t = s + i # new local `t` s = t # new local `s` with warning end s, # global @isdefined(t) # global """; julia> include_string(Main, code) ┌ Warning: Assignment to `s` in soft scope is ambiguous because a global variable by the same name exists: `s` will be treated as a new local. Disambiguate by using `local s` to suppress this warning or `global s` to assign to the existing global variable. └ @ string:4 ERROR: LoadError: UndefVarError: s not defined ``` 这里我们使用 [`include_string`](@ref) 来评估 `code`,就好像它是文件的内容一样。 我们也可以将 `code` 保存到一个文件中,然后对该文件调用 `include`——结果是一样的。 如你所见,这与在 REPL 中评估相同代码的行为完全不同。 让我们分解一下这里发生的事情: * 在循环运行之前,全局 `s` 被定义为值 `0` * 赋值 `s = t` 发生在软作用域中——任何函数体或其他硬作用域结构之外的 `for` 循环 * 因此软作用域规则的第二个子句适用,并且分配不明确,因此发出警告 * 继续执行,使 `s` 成为 `for` 循环体中的局部作用域 * 由于 `s` 是 `for` 循环的局部变量,所以在计算 `t = s + i` 时它是未定义的,从而导致错误 * 求值到此就结束了,但如果到了 `s` 和 `@isdefined(t)`,它将返回 `0` 和 `false`。 这展示了作用域的一些重要方面:在一个作用域中,每个变量只能有一个含义,而该含义的确定与表达式的顺序无关。 循环中表达式 `s = t` 的存在导致 `s` 在循环中是局部的,这意味着当它出现在 `t = s + i` 的右侧时它也是局部的,即使该表达式首先出现并首先计算。 有人可能会想象循环第一行上的 `s` 可以是全局的,而循环第二行上的 `s` 是局部的,但这是不可能的,因为这两行在同一个作用域块中并且每个变量 在给定的作用域内只能有一种含义。 #### 在软作用域 我们现在已经涵盖了所有局部作用域规则,但在结束本节之前,也许应该说几句关于为什么在交互式和非交互式上下文中处理模糊软作用域的情况不同。 人们可以问两个明显的问题: 1. 为什么不都像REPL那样? 2. 为什么不都表现得像在文件中那样?并跳过警告? 在 Julia ≤ 0.6 的版本中,所有全局作用域确实像当前的 REPL 一样工作:当 `x = <value>` 发生在循环中(或 `try`/`catch` ,`struct`内)但在函数体(或 `let` 语句块或推导式)之外时,它根据是否定义了一个名为 `x` 的全局变量来决定 `x` 是否应该是循环的局部变量。这种行为具有直观和方便的优点,因为它尽可能接近函数体内部的行为。特别是,当尝试调试函数时,它可以轻松地在函数体和 REPL 之间来回移动代码。 但是,它有一些缺点。首先,这是一种相当复杂的行为:多年来,许多人对这种行为感到困惑,并抱怨说它既复杂又难以解释和理解。这是有道理的。其次,可以说更糟的是,它不利于“大规模”编程。 当你在这样的地方看到一小段代码时,很清楚发生了什么: ```julia s = 0 for i = 1:10 s += i end ``` 显然,代码的意图是修改现有的全局变量`s`。 这还能是什么意思? 然而,并非所有现实世界的代码都如此简短或清晰。 我们发现像下面这样的代码经常出现: ```julia x = 123 # much later # maybe in a different file for i = 1:10 x = "hello" println(x) end # much later # maybe in yet another file # or maybe back in the first one where `x = 123` y = x + 234 ``` 我们非常不清楚这里应该发生什么。 由于 `x + "hello"` 是一个方法错误,似乎意图是让 `x` 在 `for` 循环中是局部的。 但是运行时值和碰巧存在的方法不能用于确定变量的范围。 对于 Julia ≤ 0.6 的行为,尤其令人担忧的是,有人可能先编写了 `for` 循环,让它工作得很好,但后来当其他人在远处添加了一个新的全局时——可能是在不同的文件——代码突然改变了含义,要么中断,要么更糟糕的是,默默地做执行了错误的命令。 这种 [“幽灵般的远距离动作”](https://en.wikipedia.org/wiki/Action_at_a_distance_(computer_programming)) 是好的编程语言设计应该防止的。 因此,在 Julia 1.0 中,我们简化了作用域的规则:在任何局部作用域中,对一个还不是局部变量的名称进行赋值会创建一个新的局部变量。 这完全消除了软作用域的概念,并消除了幽灵行为的可能性。 由于移除了软作用域,我们发现并修复了大量错误,证明我们选择摆脱它是正确的。我们有很多的欣喜! 嗯,不,不是真的。 因为有些人很生气,他们现在不得不写: ```julia s = 0 for i = 1:10 global s += i end ``` 你看到那里的`global`注解了吗?非常令人讨厌。 显然,这种情况是不能容忍的。但更严重的是,这种需要`global`顶层代码的情况有两个主要问题: 1. 从函数体内部复制和粘贴代码到 REPL 来debug不再方便——你必须加上`global`注释,然后把它删了再复制回去。 2. 初学者编写这种代码往往不会加 `global` ,并且不知道为什么他们的代码不起作用 - 他们得到的错误是 `s` 未定义,这似乎并没有启发犯错的人。 从 Julia 1.5 开始,此代码在 REPL 或 Jupyter 笔记本(就像 Julia 0.6)等交互式上下文中无需`global`注解即可正确执行,同时,在文件和其他非交互式上下文中,它会打印出以下非常直接的警告: > 在软作用域中对 `s` 的赋值是不明确的,因为存在同名的全局变量:`s` 将被视为新的局部变量。 通过使用 `local s` 来消除此警告或使用 `global s` 赋值给现有的全局变量来消除歧义。 这解决了这两个问题,同时保留了 1.0 行为的“大规模编程”好处:全局变量对可能很远的代码的含义没有幽灵般的影响; 在 REPL 复制粘贴调试工作,初学者没有任何问题; 任何时候有人忘记`global`注解或不小心用软作用域中的局部变量遮蔽了现有的全局变量,这无论如何都会令人困惑,他们会得到一个很好的明确警告。 这种设计的一个重要特点是,在没有警告的情况下在文件中执行的任何代码在新的 REPL 中的行为方式相同。 另一方面,如果您使用 REPL 会话并将其保存到文件中,如果它的行为与 REPL 中的行为不同,那么您将收到警告。 ### Let 块 `let` 语句创建一个新的 *硬作用域* 块(见上文)并在每次运行时引入新的变量绑定。 赋值可能会为现有值地址重新分配一个新值,而 `let` 总是会创建一个新地址。 这种差异通常并不重要,并且只有在通过闭包超出其作用域的变量的情况下才能检测到。 `let` 语法接受以逗号分隔的一系列赋值和变量名: ```jldoctest julia> x, y, z = -1, -1, -1; julia> let x = 1, z println("x: $x, y: $y") # x is local variable, y the global println("z: $z") # errors as z has not been assigned yet but is local end x: 1, y: -1 ERROR: UndefVarError: z not defined ``` 赋值将按次序执行:作用域右侧先于左侧引入新变量前被执行。这使得类似 `let x = x` 的写法是有意义的,因为这两个 `x` 变量并不一样,拥有不同存储位置。`let` 的行为在如下例子中是必要的: ```jldoctest julia> Fs = Vector{Any}(undef, 2); i = 1; julia> while i <= 2 Fs[i] = ()->i global i += 1 end julia> Fs[1]() 3 julia> Fs[2]() 3 ``` 在这里,我们创建并存储了两个返回变量 `i` 的闭包。但是因为始终是同一个变量`i`,所以这两个闭包行为是相同的。我们可以使用 `let` 为 `i` 创建新绑定: ```jldoctest julia> Fs = Vector{Any}(undef, 2); i = 1; julia> while i <= 2 let i = i Fs[i] = ()->i end global i += 1 end julia> Fs[1]() 1 julia> Fs[2]() 2 ``` 由于 `begin` 结构不会引入新的作用域,使用零参数 `let` 来引入一个新的作用域块而不立即创建任何新的绑定是很有用的: ```jldoctest julia> let local x = 1 let local x = 2 end x end 1 ``` 由于`let` 引入了一个新的作用域块,内部局部变量`x` 与外部局部变量`x` 是一个不同的变量。这个特定的例子相当于: ```jldoctest julia> let x = 1 let x = 2 end x end 1 ``` ### 循环和数组推导 对于循环和[数组推导](@ref man-comprehensions):在其内部作用域中引入的新变量在每次循环迭代中都会被新分配一块内存,如同被 `let` 块包围。 ```jldoctest julia> Fs = Vector{Any}(undef, 2); julia> for j = 1:2 Fs[j] = ()->j end julia> Fs[1]() 1 julia> Fs[2]() 2 ``` `for` 循环或者推导式的迭代变量始终是个新变量: ```julia-repl enable_doctest_when_deprecation_warning_is_removed julia> function f() i = 0 for i = 1:3 # empty end return i end; julia> f() 0 ``` 但是偶然地,把一个已有的局部变量作为迭代变量也是有用的。 添加关键字 `outer` 就能方便地做到: ```jldoctest julia> function f() i = 0 for outer i = 1:3 # empty end return i end; julia> f() 3 ``` ## 常量 变量普遍地用于命名一个特定、不变的值。这些变量只被赋值一次。向编译器传递 [`const`](@ref) 关键字,即可声明这个意图: ```jldoctest julia> const e = 2.71828182845904523536; julia> const pi = 3.14159265358979323846; ``` 单个 `const` 关键字能同时声明多个变量: ```jldoctest julia> const a, b = 1, 2 (1, 2) ``` `const` 声明只应使用在全局作用域中的全局变量。因为全局变量的值(甚至类型)可以随时改变,编译器很难优化包含全局变量的代码。而用 `const` 声明一个不变的全局变量,就能处理这个问题。 局部常量却大有不同。编译器能够自动确定一个局部变量什么时候是不变的,所以局部常量声明是不必要的,其实现在也并不支持。 一些特殊的顶层赋值,比如用了 `function` 和 `structure` 关键字,默认就是常量。 注意 `const` 只会影响变量绑定;变量可能会绑定到一个可变的对象上(比如一个数组)使得其仍然能被改变。另外当尝试给一个声明为常量的变量赋值时,可能出现下列情景: * 如果新赋值的类型与原常量类型不一样,会扔出一个错误: ```jldoctest julia> const x = 1.0 1.0 julia> x = 1 ERROR: invalid redefinition of constant x ``` * 如果新赋值的类型与原常量一样,会打印一个警告: ```jldoctest julia> const y = 1.0 1.0 julia> y = 2.0 WARNING: redefinition of constant y. This may fail, cause incorrect answers, or produce other errors. 2.0 ``` * 如果赋值不导致原变量值变化,则不会给出任何信息: ```jldoctest julia> const z = 100 100 julia> z = 100 100 ``` 最后一条规则也适用于不可变对象,即使变量绑定的地址改变了,例如: ```julia-repl julia> const s1 = "1" "1" julia> s2 = "1" "1" julia> pointer.([s1, s2], 1) 2-element Array{Ptr{UInt8},1}: Ptr{UInt8} @0x00000000132c9638 Ptr{UInt8} @0x0000000013dd3d18 julia> s1 = s2 "1" julia> pointer.([s1, s2], 1) 2-element Array{Ptr{UInt8},1}: Ptr{UInt8} @0x0000000013dd3d18 Ptr{UInt8} @0x0000000013dd3d18 ``` 然而对于可变对象,警告会如预期出现: ```jldoctest julia> const a = [1] 1-element Vector{Int64}: 1 julia> a = [1] WARNING: redefinition of constant a. This may fail, cause incorrect answers, or produce other errors. 1-element Vector{Int64}: 1 ``` 注意,虽然有时是可能更改常量的值,但是十分不推荐这样做。这样做仅仅是为了便于交互式使用。更改常量可引发多种问题或者非预期行为。举个例子,如果一个方法引用了一个常量并且在常量被更改前已经被编译了,那么该函数很有可能继续使用旧值: ```jldoctest julia> const x = 1 1 julia> f() = x f (generic function with 1 method) julia> f() 1 julia> x = 2 WARNING: redefinition of constant x. This may fail, cause incorrect answers, or produce other errors. 2 julia> f() 1 ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3446
# [变量](@id man-variables) Julia 语言中,变量是与某个值相关联(或绑定)的名字。你可以用它来保存一个值(例如某些计算得到的结果),供之后的代码使用。例如: ```julia-repl # 将 10 赋值给变量 x julia> x = 10 10 # 使用 x 的值做计算 julia> x + 1 11 # 重新给 x 赋值 julia> x = 1 + 1 2 # 也可以给 x 赋其它类型的值, 比如字符串文本 julia> x = "Hello World!" "Hello World!" ``` Julia 提供了非常灵活的变量命名策略。变量名是大小写敏感的,且不包含语义,意思是说,Julia 不会根据变量的名字来区别对待它们。 (译者注:Julia **不会**自动将全大写的变量识别为常量,也**不会**将有特定前后缀的变量自动识别为某种特定类型的变量,即不会根据变量名字,自动判断变量的任何属性。) ```jldoctest julia> x = 1.0 1.0 julia> y = -3 -3 julia> Z = "My string" "My string" julia> customary_phrase = "Hello world!" "Hello world!" julia> UniversalDeclarationOfHumanRightsStart = "人人生而自由,在尊严和权利上一律平等。" "人人生而自由,在尊严和权利上一律平等。" ``` 你还可以使用 UTF-8 编码的 Unicode 字符作为变量名: ```jldoctest julia> δ = 0.00001 1.0e-5 julia> 안녕하세요 = "Hello" "Hello" ``` 在 Julia REPL 和一些其它 Julia 的编辑器中,很多 Unicode 数学符号可以使用反斜杠加 LaTeX 符号接 tab 健打出。例如: 变量名 `δ` 可以通过 `\delta`-*tab* 来输入,甚至可以用 `\alpha`-*tab*-`\hat`-*tab*-`\^(2)`-*tab*来输入 `α̂⁽²⁾` 这种复杂的变量名。(如果你在某个地方发现了一个不知道怎么输入的符号,比如在别人的代码里,输入`?` 接着复制那个符号,REPL的帮助功能会告诉你输入方法。) 如果有需要的话,Julia 甚至允许你重定义内置常量和函数。(这样做可能引发潜在的混淆,所以并不推荐) ```jldoctest julia> pi = 3 3 julia> pi 3 julia> sqrt = 4 4 ``` 然而,如果你试图重定义一个已经在使用中的内置常量或函数,Julia 会报错: ```jldoctest julia> pi π = 3.1415926535897... julia> pi = 3 ERROR: cannot assign a value to variable MathConstants.pi from module Main julia> sqrt(100) 10.0 julia> sqrt = 4 ERROR: cannot assign a value to variable Base.sqrt from module Main ``` ## [合法的变量名](@id man-allowed-variable-names) 变量名字必须以英文字母(A-Z 或 a-z)、下划线或编码大于 00A0 的 Unicode 字符的一个子集开头。 具体来说指的是,[Unicode字符分类](http://www.fileformat.info/info/unicode/category/index.htm)中的 Lu/Ll/Lt/Lm/Lo/Nl(字母)、Sc/So(货币和其他符号)以及一些其它像字母的符号(例如 Sm 类别数学符号中的一部分)。 变量名的非首字符还允许使用惊叹号 `!`、数字(包括 0-9 和其他 Nd/No 类别中的 Unicode 字符)以及其它 Unicode 字符:变音符号和其他修改标记(Mn/Mc/Me/Sk 类别)、标点和连接符(Pc 类别)、引号和少许其他字符。 像 `+` 这样的运算符也是合法的标识符,但是它们会被特别地解析。 在一些上下文中,运算符可以像变量一样使用,比如 `(+)` 表示加函数,语句 `(+) = f`会把它重新赋值。大部分 Unicode 中缀运算符(Sm 类别),像 `⊕`,会被解析成真正的中缀运算符,并且支持用户自定义方法(举个例子,你可以使用语句 `const ⊗ = kron `将 `⊗` 定义为中缀的 Kronecker 积)。 运算符也可以使用修改标记、引号和上标/下标进行加缀,例如 `+̂ₐ″` 被解析成一个与 `+` 具有相同优先级的中缀运算符。以下标/上标字母结尾的运算符与后续变量名之间需要一个空格。举个例子,如果 `+ᵃ` 是一个运算符,那么 `+ᵃx` 应该被写为`+ᵃ x`,以区分表达式 `+ ᵃx` ,其中 `ᵃx` 是变量名。 一类特定的变量名是只包含下划线的变量名。这些标识符只能赋值,不能用于给其他变量赋值。严格来说,它们只能用作[左值](https://en.wikipedia.org/wiki/Value_(computer_science)#lrvalue) 而不能作[右值](https://en.wikipedia.org/wiki/R-value): ```julia-repl julia> x, ___ = size([2 2; 1 1]) (2, 2) julia> y = ___ ERROR: syntax: all-underscore identifier used as rvalue ``` 唯一明确禁止的变量名称是内置[关键字](@ref Keywords)的名称: ```julia-repl julia> else = false ERROR: syntax: unexpected "else" julia> try = "No" ERROR: syntax: unexpected "=" ``` 某些 Unicode 字符被认为是等效的标识符。不同的输入 Unicode 组合字符的方法(例如:重音)被视为等价的(Julia 标识符采用 [NFC](http://www.macchiato.com/unicode/nfc-faq) 标准)。Julia 还加入了一些非标准的等价字符,用于在视觉上相似且易于通过某些输入法输入的字符。Unicode 字符 `ɛ` (U+025B: Latin small letter open e) 和 `µ` (U+00B5: micro sign) 被视为等同于相应的希腊字母。点 `·` (U+00B7) 和希腊字符[间断](https://en.wikipedia.org/wiki/Interpunct) `·` (U+0387) 都被当作数学上的点积运算符 `⋅` (U+22C5)。减号 `−` (U+2212) 与连接号 `-` (U+002D) 也被视作相同的符号。 ## 命名规范 虽然 Julia 语言对合法名字的限制非常少,但是遵循以下这些命名规范是非常有用的: * 变量的名字采用小写。 * 使用下划线(`'_'`)来分隔名字中的单词,但是不鼓励使用下划线 除非在不使用下划线时名字会非常难读。 * 类型 (`Type`) 和模块(`Module`)的名字使用大写字母开头,并且用大写字母 而不是用下划线分隔单词。 * 函数(`function`)和宏(`macro`)的名字使用小写,不使用下划线。 * 会对输入参数进行更改的函数要使用 `!` 结尾。这些函数有时叫做 “mutating” 或 “in-place” 函数,因为它们在被调用后会修改他们的输入参数的内容 而不仅仅只是返回一个值。 关于命名规范的更多信息,可查看[代码风格指南](@ref)。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2903
# [工作流程建议](@id man-workflow-tips) 这里是高效使用 Julia 的一些建议。 ## 基于 REPL 的工作流程 正如在 [Julia REPL](@ref) 中演示的那样,Julia 的 REPL 为高效的交互式工作流程提供了丰富的功能。这里是一些可能进一步提升你在命令行下的体验的建议。 ### 一个基本的编辑器 / REPL 工作流程 最基本的 Julia 工作流程是将一个文本编辑器配合 `julia` 的命令行使用。一般会包含下面一些步骤: * **把还在开发中的代码放到一个临时的模块中。**新建一个文件,例如 `Tmp.jl`,并放到模块中。 ```julia module Tmp export say_hello say_hello() = println("Hello!") # your other definitions here end ``` * **把测试代码放到另一个文件中。**新建另一个文件,例如 `tst.jl`,开头为 ```julia include("Tmp.jl") import .Tmp # using .Tmp # we can use `using` to bring the exported symbols in `Tmp` into our namespace Tmp.say_hello() # say_hello() # your other test code here ``` 并把测试作为 `Tmp` 的内容。或者,你可以把测试文件的内容打包到一个模块中,例如 ```julia module Tst include("Tmp.jl") import .Tmp #using .Tmp Tmp.say_hello() # say_hello() # your other test code here end ``` 优点是你的测试代码现在包含在一个模块中,并且不会在 `Main` 的全局作用域中引入新定义,这样更加整洁。 * 使用 `include("tst.jl")` 来在 Julia REPL 中 `include` `tst.jl` 文件。 * **打肥皂,冲洗,重复。**(译者注:此为英语幽默,被称为[“洗发算法”](https://en.wikipedia.org/wiki/Lather,_rinse,_repeat)描述洗头发的过程)在 `julia` REPL 中摸索不同的想法,把好的想法存入 `tst.jl`。要在 `tst.jl` 被更改后执行它,只需再次 `include` 它。 ## 基于浏览器的工作流程 也可以通过 [IJulia](https://github.com/JuliaLang/IJulia.jl) 在浏览器中与 Julia REPL 进行交互,请到该库的主页查看详细用法。 ## 基于Revise的工作流程 无论你是在REPL还是在IJulia,你通常可以通过 [Revise](https://github.com/timholy/Revise.jl)优化 你的开发经历。 通常情况,无论何时启动Julia,就请按照[Revise文档](https://timholy.github.io/Revise.jl/stable/)中的说明配置好Revise。 一旦配置好,Revise将跟踪任何加载模块中的文件变化。 和任何用`includet`加载到 REPL 的文件 (但不包括普通的`include`); 然后你就可以编辑这些文件,并且更改会在不重新启动julia会话的情况下生效。 标准工作流与上面基于 REPL 的工作流类似,区别如下: 1. 把你的代码放到一个在你的加载路径里的模块中。 要这样做有很多种方法,通常推荐以下两种选择: - 对于长期的项目,使用[PkgTemplates](https://github.com/invenia/PkgTemplates.jl): ```julia using PkgTemplates t = Template() t("MyPkg") ``` 这将在 `.julia/dev` 目录中创建一个空白包`"MyPkg"`。 请注意,通过它的 `Template` 构造器,PkgTemplates 允许控制许多不同的选项。 在下面的第 2 步中,编辑 `MyPkg/src/MyPkg.jl` 以更改源代码,并编辑 `MyPkg/test/runtests.jl` 以进行测试。 - 对于“一次性”项目,您可以通过在临时目录(例如 `/tmp`)中进行工作来避免任何清理需求。 切换到临时目录并启动 Julia,然后执行以下操作: ```julia pkg> generate MyPkg # type ] to enter pkg mode julia> push!(LOAD_PATH, pwd()) # hit backspace to exit pkg mode ``` 如果你重新启动 Julia 会话,则必须重新发出修改 `LOAD_PATH` 的命令。 在下面的第 2 步中,编辑 `MyPkg/src/MyPkg.jl` 以更改源代码,并创建你选择的任何测试文件。 2. 构建你自己的包 **在加载任何代码之前**, 确保 Revise 已经被启用: `using Revise` 或者按照教程设置自动加载。 然后切换到包含测试文件(假设文件为`"runtests.jl"`)的目录下,并: ```julia julia> using MyPkg julia> include("runtests.jl") ``` 你可以修改在 MyPkg 文件夹中的代码然后用`include("runtests.jl")`重新跑一遍测试。 通常,你可能需要重新启动Julia 会话来使得这些变化生效(受一些 [限制](https://timholy.github.io/Revise.jl/stable/limitations/))。
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
575
# Artifacts ```@meta DocTestSetup = :(using Artifacts) ``` Starting with Julia 1.6, the artifacts support has moved from `Pkg.jl` to Julia itself. Until proper documentation can be added here, you can learn more about artifacts in the `Pkg.jl` manual at <https://julialang.github.io/Pkg.jl/v1/artifacts/>. !!! compat "Julia 1.6" Julia's artifacts API requires at least Julia 1.6. In Julia versions 1.3 to 1.5, you can use `Pkg.Artifacts` instead. ```@docs Artifacts.artifact_meta Artifacts.artifact_hash Artifacts.find_artifacts_toml Artifacts.@artifact_str ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
143
# Base64 ```@docs Base64.Base64 Base64.Base64EncodePipe Base64.base64encode Base64.Base64DecodePipe Base64.base64decode Base64.stringmime ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
78
# CRC32c ```@docs CRC32c.crc32c CRC32c.crc32c(::IO, ::Integer, ::UInt32) ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
28355
# 日期 ```@meta DocTestSetup = :(using Dates) ``` `Dates` 模块提供了两种类型来处理日期:[`Date`](@ref) 和 [`DateTime`](@ref),分别精确到日和毫秒;两者都是抽象类型 [`TimeType`](@ref) 的子类型。区分类型的动机很简单:不必处理更高精度所带来的复杂性时,一些操作在代码和思维推理上都更加简单。例如,由于 [`Date`](@ref) 类型仅精确到日(即没有时、分或秒),因此避免了时区、夏令时和闰秒等不必要的通常考虑。 [`Date`](@ref) 和 [`DateTime`](@ref) 类型都是基本不可变类型 [`Int64`](@ref) 的包装类。这两种类型的单个 `instant` 字段实际上属于 `UTInstant{P}` 类型。这种类型表示的是一种基于世界时间(UT)持续增长的机器时间 [^1]。[`DateTime`](@ref) 类型并不考虑时区(用 Python 的话讲,它是 *naive* 的),与 Java 8 中的 *LocalDateTime* 类似。如果需要附加时区功能,可以通过 [TimeZones.jl 包](https://github.com/JuliaTime/TimeZones.jl/) 实现,其汇编了来自 [IANA 时区数据库](http://www.iana.org/time-zones) 的数据。[`Date`](@ref) 和 [`DateTime`](@ref) 都基于 [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) 标准,遵循公历(格里高利历)。 值得注意的是,ISO 8601 标准对公元前的日期需要特别处理。通常来说,公元前的最后一天是公元前 1 年的 12 月 31 日,接下来的一天是公元 1 年的 1 月 1 日,公元 0 年是不存在的。但是,在 ISO 8601 标准中,公元前 1 年被表示为 0 年,即 `0001-01-01` 的前一天是 `0000-12-31`,而 `-0001`(没错,年数为-1)的那一年则实际上是公元前 2 年,`-0002` 则表示公元前 3 年,以此类推。 [^1]: The notion of the UT second is actually quite fundamental. There are basically two different notions of time generally accepted, one based on the physical rotation of the earth (one full rotation = 1 day), the other based on the SI second (a fixed, constant value). These are radically different! Think about it, a "UT second", as defined relative to the rotation of the earth, may have a different absolute length depending on the day! Anyway, the fact that [`Date`](@ref) and [`DateTime`](@ref) are based on UT seconds is a simplifying, yet honest assumption so that things like leap seconds and all their complexity can be avoided. This basis of time is formally called [UT](https://en.wikipedia.org/wiki/Universal_Time) or UT1. Basing types on the UT second basically means that every minute has 60 seconds and every day has 24 hours and leads to more natural calculations when working with calendar dates. ## 构造函数 [`Date`](@ref) 和 [`DateTime`](@ref) 类型可以通过整数或 [`Period`](@ref) 类型,解析,或调整器来构造(稍后会详细介绍): ```jldoctest julia> DateTime(2013) 2013-01-01T00:00:00 julia> DateTime(2013,7) 2013-07-01T00:00:00 julia> DateTime(2013,7,1) 2013-07-01T00:00:00 julia> DateTime(2013,7,1,12) 2013-07-01T12:00:00 julia> DateTime(2013,7,1,12,30) 2013-07-01T12:30:00 julia> DateTime(2013,7,1,12,30,59) 2013-07-01T12:30:59 julia> DateTime(2013,7,1,12,30,59,1) 2013-07-01T12:30:59.001 julia> Date(2013) 2013-01-01 julia> Date(2013,7) 2013-07-01 julia> Date(2013,7,1) 2013-07-01 julia> Date(Dates.Year(2013),Dates.Month(7),Dates.Day(1)) 2013-07-01 julia> Date(Dates.Month(7),Dates.Year(2013)) 2013-07-01 ``` [`Date`](@ref) or [`DateTime`](@ref) parsing is accomplished by the use of format strings. Format strings work by the notion of defining *delimited* or *fixed-width* "slots" that contain a period to parse and passing the text to parse and format string to a [`Date`](@ref) or [`DateTime`](@ref) constructor, of the form `Date("2015-01-01",dateformat"y-m-d")` or `DateTime("20150101",dateformat"yyyymmdd")`. 有分隔的插入点是通过指定解析器在两个时段之间的分隔符来进行标记的。例如,`"y-m-d"` 会告诉解析器,一个诸如 `"2014-07-16"` 的时间字符串,应该在第一个和第二个插入点之间查找 `-` 字符。`y`,`m` 和 `d` 字符则告诉解析器每一个插入点对应的时段名称。 As in the case of constructors above such as `Date(2013)`, delimited `DateFormat`s allow for missing parts of dates and times so long as the preceding parts are given. The other parts are given the usual default values. For example, `Date("1981-03", dateformat"y-m-d")` returns `1981-03-01`, whilst `Date("31/12", dateformat"d/m/y")` gives `0001-12-31`. (Note that the default year is 1 AD/CE.) Consequently, an empty string will always return `0001-01-01` for `Date`s, and `0001-01-01T00:00:00.000` for `DateTime`s. Fixed-width slots are specified by repeating the period character the number of times corresponding to the width with no delimiter between characters. So `dateformat"yyyymmdd"` would correspond to a date string like `"20140716"`. The parser distinguishes a fixed-width slot by the absence of a delimiter, noting the transition `"yyyymm"` from one period character to the next. Support for text-form month parsing is also supported through the `u` and `U` characters, for abbreviated and full-length month names, respectively. By default, only English month names are supported, so `u` corresponds to "Jan", "Feb", "Mar", etc. And `U` corresponds to "January", "February", "March", etc. Similar to other name=>value mapping functions [`dayname`](@ref) and [`monthname`](@ref), custom locales can be loaded by passing in the `locale=>Dict{String,Int}` mapping to the `MONTHTOVALUEABBR` and `MONTHTOVALUE` dicts for abbreviated and full-name month names, respectively. The above examples used the `dateformat""` string macro. This macro creates a `DateFormat` object once when the macro is expanded and uses the same `DateFormat` object even if a code snippet is run multiple times. ```jldoctest julia> for i = 1:10^5 Date("2015-01-01", dateformat"y-m-d") end ``` Or you can create the DateFormat object explicitly: ```jldoctest julia> df = DateFormat("y-m-d"); julia> dt = Date("2015-01-01",df) 2015-01-01 julia> dt2 = Date("2015-01-02",df) 2015-01-02 ``` Alternatively, use broadcasting: ```jldoctest julia> years = ["2015", "2016"]; julia> Date.(years, DateFormat("yyyy")) 2-element Vector{Date}: 2015-01-01 2016-01-01 ``` For convenience, you may pass the format string directly (e.g., `Date("2015-01-01","y-m-d")`), although this form incurs performance costs if you are parsing the same format repeatedly, as it internally creates a new `DateFormat` object each time. As well as via the constructors, a `Date` or `DateTime` can be constructed from strings using the [`parse`](@ref) and [`tryparse`](@ref) functions, but with an optional third argument of type `DateFormat` specifying the format; for example, `parse(Date, "06.23.2013", dateformat"m.d.y")`, or `tryparse(DateTime, "1999-12-31T23:59:59")` which uses the default format. The notable difference between the functions is that with [`tryparse`](@ref), an error is not thrown if the string is in an invalid format; instead `nothing` is returned. Note however that as with the constructors above, empty date and time parts assume default values and consequently an empty string (`""`) is valid for _any_ `DateFormat`, giving for example a `Date` of `0001-01-01`. Code relying on `parse` or `tryparse` for `Date` and `DateTime` parsing should therefore also check whether parsed strings are empty before using the result. A full suite of parsing and formatting tests and examples is available in [`stdlib/Dates/test/io.jl`](https://github.com/JuliaLang/julia/blob/master/stdlib/Dates/test/io.jl). ## Durations/Comparisons Finding the length of time between two [`Date`](@ref) or [`DateTime`](@ref) is straightforward given their underlying representation as `UTInstant{Day}` and `UTInstant{Millisecond}`, respectively. The difference between [`Date`](@ref) is returned in the number of [`Day`](@ref), and [`DateTime`](@ref) in the number of [`Millisecond`](@ref). Similarly, comparing [`TimeType`](@ref) is a simple matter of comparing the underlying machine instants (which in turn compares the internal [`Int64`](@ref) values). ```jldoctest julia> dt = Date(2012,2,29) 2012-02-29 julia> dt2 = Date(2000,2,1) 2000-02-01 julia> dump(dt) Date instant: Dates.UTInstant{Day} periods: Day value: Int64 734562 julia> dump(dt2) Date instant: Dates.UTInstant{Day} periods: Day value: Int64 730151 julia> dt > dt2 true julia> dt != dt2 true julia> dt + dt2 ERROR: MethodError: no method matching +(::Date, ::Date) [...] julia> dt * dt2 ERROR: MethodError: no method matching *(::Date, ::Date) [...] julia> dt / dt2 ERROR: MethodError: no method matching /(::Date, ::Date) julia> dt - dt2 4411 days julia> dt2 - dt -4411 days julia> dt = DateTime(2012,2,29) 2012-02-29T00:00:00 julia> dt2 = DateTime(2000,2,1) 2000-02-01T00:00:00 julia> dt - dt2 381110400000 milliseconds ``` ## Accessor Functions Because the [`Date`](@ref) and [`DateTime`](@ref) types are stored as single [`Int64`](@ref) values, date parts or fields can be retrieved through accessor functions. The lowercase accessors return the field as an integer: ```jldoctest tdate julia> t = Date(2014, 1, 31) 2014-01-31 julia> Dates.year(t) 2014 julia> Dates.month(t) 1 julia> Dates.week(t) 5 julia> Dates.day(t) 31 ``` While propercase return the same value in the corresponding [`Period`](@ref) type: ```jldoctest tdate julia> Dates.Year(t) 2014 years julia> Dates.Day(t) 31 days ``` Compound methods are provided because it is more efficient to access multiple fields at the same time than individually: ```jldoctest tdate julia> Dates.yearmonth(t) (2014, 1) julia> Dates.monthday(t) (1, 31) julia> Dates.yearmonthday(t) (2014, 1, 31) ``` One may also access the underlying `UTInstant` or integer value: ```jldoctest tdate julia> dump(t) Date instant: Dates.UTInstant{Day} periods: Day value: Int64 735264 julia> t.instant Dates.UTInstant{Day}(Day(735264)) julia> Dates.value(t) 735264 ``` ## Query Functions Query functions provide calendrical information about a [`TimeType`](@ref). They include information about the day of the week: ```jldoctest tdate2 julia> t = Date(2014, 1, 31) 2014-01-31 julia> Dates.dayofweek(t) 5 julia> Dates.dayname(t) "Friday" julia> Dates.dayofweekofmonth(t) # 5th Friday of January 5 ``` Month of the year: ```jldoctest tdate2 julia> Dates.monthname(t) "January" julia> Dates.daysinmonth(t) 31 ``` As well as information about the [`TimeType`](@ref)'s year and quarter: ```jldoctest tdate2 julia> Dates.isleapyear(t) false julia> Dates.dayofyear(t) 31 julia> Dates.quarterofyear(t) 1 julia> Dates.dayofquarter(t) 31 ``` The [`dayname`](@ref) and [`monthname`](@ref) methods can also take an optional `locale` keyword that can be used to return the name of the day or month of the year for other languages/locales. There are also versions of these functions returning the abbreviated names, namely [`dayabbr`](@ref) and [`monthabbr`](@ref). First the mapping is loaded into the `LOCALES` variable: ```jldoctest tdate2 julia> french_months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"]; julia> french_monts_abbrev = ["janv","févr","mars","avril","mai","juin", "juil","août","sept","oct","nov","déc"]; julia> french_days = ["lundi","mardi","mercredi","jeudi","vendredi","samedi","dimanche"]; julia> Dates.LOCALES["french"] = Dates.DateLocale(french_months, french_monts_abbrev, french_days, [""]); ``` The above mentioned functions can then be used to perform the queries: ```jldoctest tdate2 julia> Dates.dayname(t;locale="french") "vendredi" julia> Dates.monthname(t;locale="french") "janvier" julia> Dates.monthabbr(t;locale="french") "janv" ``` Since the abbreviated versions of the days are not loaded, trying to use the function `dayabbr` will error. ```jldoctest tdate2 julia> Dates.dayabbr(t;locale="french") ERROR: BoundsError: attempt to access 1-element Vector{String} at index [5] Stacktrace: [...] ``` ## TimeType-Period Arithmetic It's good practice when using any language/date framework to be familiar with how date-period arithmetic is handled as there are some [tricky issues](https://codeblog.jonskeet.uk/2010/12/01/the-joys-of-date-time-arithmetic/) to deal with (though much less so for day-precision types). The `Dates` module approach tries to follow the simple principle of trying to change as little as possible when doing [`Period`](@ref) arithmetic. This approach is also often known as *calendrical* arithmetic or what you would probably guess if someone were to ask you the same calculation in a conversation. Why all the fuss about this? Let's take a classic example: add 1 month to January 31st, 2014. What's the answer? Javascript will say [March 3](https://markhneedham.com/blog/2009/01/07/javascript-add-a-month-to-a-date/) (assumes 31 days). PHP says [March 2](https://stackoverflow.com/questions/5760262/php-adding-months-to-a-date-while-not-exceeding-the-last-day-of-the-month) (assumes 30 days). The fact is, there is no right answer. In the `Dates` module, it gives the result of February 28th. How does it figure that out? Consider the classic 7-7-7 gambling game in casinos. Now just imagine that instead of 7-7-7, the slots are Year-Month-Day, or in our example, 2014-01-31. When you ask to add 1 month to this date, the month slot is incremented, so now we have 2014-02-31. Then the day number is checked if it is greater than the last valid day of the new month; if it is (as in the case above), the day number is adjusted down to the last valid day (28). What are the ramifications with this approach? Go ahead and add another month to our date, `2014-02-28 + Month(1) == 2014-03-28`. What? Were you expecting the last day of March? Nope, sorry, remember the 7-7-7 slots. As few slots as possible are going to change, so we first increment the month slot by 1, 2014-03-28, and boom, we're done because that's a valid date. On the other hand, if we were to add 2 months to our original date, 2014-01-31, then we end up with 2014-03-31, as expected. The other ramification of this approach is a loss in associativity when a specific ordering is forced (i.e. adding things in different orders results in different outcomes). For example: ```jldoctest julia> (Date(2014,1,29)+Dates.Day(1)) + Dates.Month(1) 2014-02-28 julia> (Date(2014,1,29)+Dates.Month(1)) + Dates.Day(1) 2014-03-01 ``` What's going on there? In the first line, we're adding 1 day to January 29th, which results in 2014-01-30; then we add 1 month, so we get 2014-02-30, which then adjusts down to 2014-02-28. In the second example, we add 1 month *first*, where we get 2014-02-29, which adjusts down to 2014-02-28, and *then* add 1 day, which results in 2014-03-01. One design principle that helps in this case is that, in the presence of multiple Periods, the operations will be ordered by the Periods' *types*, not their value or positional order; this means `Year` will always be added first, then `Month`, then `Week`, etc. Hence the following *does* result in associativity and Just Works: ```jldoctest julia> Date(2014,1,29) + Dates.Day(1) + Dates.Month(1) 2014-03-01 julia> Date(2014,1,29) + Dates.Month(1) + Dates.Day(1) 2014-03-01 ``` Tricky? Perhaps. What is an innocent `Dates` user to do? The bottom line is to be aware that explicitly forcing a certain associativity, when dealing with months, may lead to some unexpected results, but otherwise, everything should work as expected. Thankfully, that's pretty much the extent of the odd cases in date-period arithmetic when dealing with time in UT (avoiding the "joys" of dealing with daylight savings, leap seconds, etc.). As a bonus, all period arithmetic objects work directly with ranges: ```jldoctest julia> dr = Date(2014,1,29):Day(1):Date(2014,2,3) Date("2014-01-29"):Day(1):Date("2014-02-03") julia> collect(dr) 6-element Vector{Date}: 2014-01-29 2014-01-30 2014-01-31 2014-02-01 2014-02-02 2014-02-03 julia> dr = Date(2014,1,29):Dates.Month(1):Date(2014,07,29) Date("2014-01-29"):Month(1):Date("2014-07-29") julia> collect(dr) 7-element Vector{Date}: 2014-01-29 2014-02-28 2014-03-29 2014-04-29 2014-05-29 2014-06-29 2014-07-29 ``` ## Adjuster Functions As convenient as date-period arithmetic is, often the kinds of calculations needed on dates take on a *calendrical* or *temporal* nature rather than a fixed number of periods. Holidays are a perfect example; most follow rules such as "Memorial Day = Last Monday of May", or "Thanksgiving = 4th Thursday of November". These kinds of temporal expressions deal with rules relative to the calendar, like first or last of the month, next Tuesday, or the first and third Wednesdays, etc. The `Dates` module provides the *adjuster* API through several convenient methods that aid in simply and succinctly expressing temporal rules. The first group of adjuster methods deal with the first and last of weeks, months, quarters, and years. They each take a single [`TimeType`](@ref) as input and return or *adjust to* the first or last of the desired period relative to the input. ```jldoctest julia> Dates.firstdayofweek(Date(2014,7,16)) # Adjusts the input to the Monday of the input's week 2014-07-14 julia> Dates.lastdayofmonth(Date(2014,7,16)) # Adjusts to the last day of the input's month 2014-07-31 julia> Dates.lastdayofquarter(Date(2014,7,16)) # Adjusts to the last day of the input's quarter 2014-09-30 ``` The next two higher-order methods, [`tonext`](@ref), and [`toprev`](@ref), generalize working with temporal expressions by taking a `DateFunction` as first argument, along with a starting [`TimeType`](@ref). A `DateFunction` is just a function, usually anonymous, that takes a single [`TimeType`](@ref) as input and returns a [`Bool`](@ref), `true` indicating a satisfied adjustment criterion. For example: ```jldoctest julia> istuesday = x->Dates.dayofweek(x) == Dates.Tuesday; # Returns true if the day of the week of x is Tuesday julia> Dates.tonext(istuesday, Date(2014,7,13)) # 2014-07-13 is a Sunday 2014-07-15 julia> Dates.tonext(Date(2014,7,13), Dates.Tuesday) # Convenience method provided for day of the week adjustments 2014-07-15 ``` This is useful with the do-block syntax for more complex temporal expressions: ```jldoctest julia> Dates.tonext(Date(2014,7,13)) do x # Return true on the 4th Thursday of November (Thanksgiving) Dates.dayofweek(x) == Dates.Thursday && Dates.dayofweekofmonth(x) == 4 && Dates.month(x) == Dates.November end 2014-11-27 ``` The [`Base.filter`](@ref) method can be used to obtain all valid dates/moments in a specified range: ```jldoctest # Pittsburgh street cleaning; Every 2nd Tuesday from April to November # Date range from January 1st, 2014 to January 1st, 2015 julia> dr = Dates.Date(2014):Day(1):Dates.Date(2015); julia> filter(dr) do x Dates.dayofweek(x) == Dates.Tue && Dates.April <= Dates.month(x) <= Dates.Nov && Dates.dayofweekofmonth(x) == 2 end 8-element Vector{Date}: 2014-04-08 2014-05-13 2014-06-10 2014-07-08 2014-08-12 2014-09-09 2014-10-14 2014-11-11 ``` Additional examples and tests are available in [`stdlib/Dates/test/adjusters.jl`](https://github.com/JuliaLang/julia/blob/master/stdlib/Dates/test/adjusters.jl). ## Period Types Periods are a human view of discrete, sometimes irregular durations of time. Consider 1 month; it could represent, in days, a value of 28, 29, 30, or 31 depending on the year and month context. Or a year could represent 365 or 366 days in the case of a leap year. [`Period`](@ref) types are simple [`Int64`](@ref) wrappers and are constructed by wrapping any `Int64` convertible type, i.e. `Year(1)` or `Month(3.0)`. Arithmetic between [`Period`](@ref) of the same type behave like integers, and limited `Period-Real` arithmetic is available. You can extract the underlying integer with [`Dates.value`](@ref). ```jldoctest julia> y1 = Dates.Year(1) 1 year julia> y2 = Dates.Year(2) 2 years julia> y3 = Dates.Year(10) 10 years julia> y1 + y2 3 years julia> div(y3,y2) 5 julia> y3 - y2 8 years julia> y3 % y2 0 years julia> div(y3,3) # mirrors integer division 3 years julia> Dates.value(Dates.Millisecond(10)) 10 ``` ## Rounding [`Date`](@ref) and [`DateTime`](@ref) values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with [`floor`](@ref), [`ceil`](@ref), or [`round`](@ref): ```jldoctest julia> floor(Date(1985, 8, 16), Dates.Month) 1985-08-01 julia> ceil(DateTime(2013, 2, 13, 0, 31, 20), Dates.Minute(15)) 2013-02-13T00:45:00 julia> round(DateTime(2016, 8, 6, 20, 15), Dates.Day) 2016-08-07T00:00:00 ``` Unlike the numeric [`round`](@ref) method, which breaks ties toward the even number by default, the [`TimeType`](@ref)[`round`](@ref) method uses the `RoundNearestTiesUp` rounding mode. (It's difficult to guess what breaking ties to nearest "even" [`TimeType`](@ref) would entail.) Further details on the available `RoundingMode` s can be found in the [API reference](@ref stdlib-dates-api). Rounding should generally behave as expected, but there are a few cases in which the expected behaviour is not obvious. ### Rounding Epoch In many cases, the resolution specified for rounding (e.g., `Dates.Second(30)`) divides evenly into the next largest period (in this case, `Dates.Minute(1)`). But rounding behaviour in cases in which this is not true may lead to confusion. What is the expected result of rounding a [`DateTime`](@ref) to the nearest 10 hours? ```jldoctest julia> round(DateTime(2016, 7, 17, 11, 55), Dates.Hour(10)) 2016-07-17T12:00:00 ``` That may seem confusing, given that the hour (12) is not divisible by 10. The reason that `2016-07-17T12:00:00` was chosen is that it is 17,676,660 hours after `0000-01-01T00:00:00`, and 17,676,660 is divisible by 10. As Julia [`Date`](@ref) and [`DateTime`](@ref) values are represented according to the ISO 8601 standard, `0000-01-01T00:00:00` was chosen as base (or "rounding epoch") from which to begin the count of days (and milliseconds) used in rounding calculations. (Note that this differs slightly from Julia's internal representation of [`Date`](@ref) s using Rata Die notation; but since the ISO 8601 standard is most visible to the end user, `0000-01-01T00:00:00` was chosen as the rounding epoch instead of the `0000-12-31T00:00:00` used internally to minimize confusion.) The only exception to the use of `0000-01-01T00:00:00` as the rounding epoch is when rounding to weeks. Rounding to the nearest week will always return a Monday (the first day of the week as specified by ISO 8601). For this reason, we use `0000-01-03T00:00:00` (the first day of the first week of year 0000, as defined by ISO 8601) as the base when rounding to a number of weeks. Here is a related case in which the expected behaviour is not necessarily obvious: What happens when we round to the nearest `P(2)`, where `P` is a [`Period`](@ref) type? In some cases (specifically, when `P <: Dates.TimePeriod`) the answer is clear: ```jldoctest julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Hour(2)) 2016-07-17T08:00:00 julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Minute(2)) 2016-07-17T08:56:00 ``` This seems obvious, because two of each of these periods still divides evenly into the next larger order period. But in the case of two months (which still divides evenly into one year), the answer may be surprising: ```jldoctest julia> round(DateTime(2016, 7, 17, 8, 55, 30), Dates.Month(2)) 2016-07-01T00:00:00 ``` Why round to the first day in July, even though it is month 7 (an odd number)? The key is that months are 1-indexed (the first month is assigned 1), unlike hours, minutes, seconds, and milliseconds (the first of which are assigned 0). This means that rounding a [`DateTime`](@ref) to an even multiple of seconds, minutes, hours, or years (because the ISO 8601 specification includes a year zero) will result in a [`DateTime`](@ref) with an even value in that field, while rounding a [`DateTime`](@ref) to an even multiple of months will result in the months field having an odd value. Because both months and years may contain an irregular number of days, whether rounding to an even number of days will result in an even value in the days field is uncertain. See the [API reference](@ref stdlib-dates-api) for additional information on methods exported from the `Dates` module. # [API reference](@id stdlib-dates-api) ## Dates and Time Types ```@docs Dates.Period Dates.CompoundPeriod Dates.Instant Dates.UTInstant Dates.TimeType Dates.DateTime Dates.Date Dates.Time Dates.TimeZone Dates.UTC ``` ## Dates Functions ```@docs Dates.DateTime(::Int64, ::Int64, ::Int64, ::Int64, ::Int64, ::Int64, ::Int64) Dates.DateTime(::Dates.Period) Dates.DateTime(::Function, ::Any...) Dates.DateTime(::Dates.TimeType) Dates.DateTime(::AbstractString, ::AbstractString) Dates.format(::Dates.TimeType, ::AbstractString) Dates.DateFormat Dates.@dateformat_str Dates.DateTime(::AbstractString, ::Dates.DateFormat) Dates.Date(::Int64, ::Int64, ::Int64) Dates.Date(::Dates.Period) Dates.Date(::Function, ::Any, ::Any, ::Any) Dates.Date(::Dates.TimeType) Dates.Date(::AbstractString, ::AbstractString) Dates.Date(::AbstractString, ::Dates.DateFormat) Dates.Time(::Int64::Int64, ::Int64, ::Int64, ::Int64, ::Int64) Dates.Time(::Dates.TimePeriod) Dates.Time(::Function, ::Any...) Dates.Time(::Dates.DateTime) Dates.Time(::AbstractString, ::AbstractString) Dates.Time(::AbstractString, ::Dates.DateFormat) Dates.now() Dates.now(::Type{Dates.UTC}) Base.eps(::Union{Type{DateTime}, Type{Date}, Type{Time}, TimeType}) ``` ### Accessor Functions ```@docs Dates.year Dates.month Dates.week Dates.day Dates.hour Dates.minute Dates.second Dates.millisecond Dates.microsecond Dates.nanosecond Dates.Year(::Dates.TimeType) Dates.Month(::Dates.TimeType) Dates.Week(::Dates.TimeType) Dates.Day(::Dates.TimeType) Dates.Hour(::DateTime) Dates.Minute(::DateTime) Dates.Second(::DateTime) Dates.Millisecond(::DateTime) Dates.Microsecond(::Dates.Time) Dates.Nanosecond(::Dates.Time) Dates.yearmonth Dates.monthday Dates.yearmonthday ``` ### Query Functions ```@docs Dates.dayname Dates.dayabbr Dates.dayofweek Dates.dayofmonth Dates.dayofweekofmonth Dates.daysofweekinmonth Dates.monthname Dates.monthabbr Dates.daysinmonth Dates.isleapyear Dates.dayofyear Dates.daysinyear Dates.quarterofyear Dates.dayofquarter ``` ### Adjuster Functions ```@docs Base.trunc(::Dates.TimeType, ::Type{Dates.Period}) Dates.firstdayofweek Dates.lastdayofweek Dates.firstdayofmonth Dates.lastdayofmonth Dates.firstdayofyear Dates.lastdayofyear Dates.firstdayofquarter Dates.lastdayofquarter Dates.tonext(::Dates.TimeType, ::Int) Dates.toprev(::Dates.TimeType, ::Int) Dates.tofirst Dates.tolast Dates.tonext(::Function, ::Dates.TimeType) Dates.toprev(::Function, ::Dates.TimeType) ``` ### Periods ```@docs Dates.Period(::Any) Dates.CompoundPeriod(::Vector{<:Dates.Period}) Dates.value Dates.default Dates.periods ``` ### Rounding Functions `Date` and `DateTime` values can be rounded to a specified resolution (e.g., 1 month or 15 minutes) with `floor`, `ceil`, or `round`. ```@docs Base.floor(::Dates.TimeType, ::Dates.Period) Base.ceil(::Dates.TimeType, ::Dates.Period) Base.round(::Dates.TimeType, ::Dates.Period, ::RoundingMode{:NearestTiesUp}) ``` Most `Period` values can also be rounded to a specified resolution: ```@docs Base.floor(::Dates.ConvertiblePeriod, ::T) where T <: Dates.ConvertiblePeriod Base.ceil(::Dates.ConvertiblePeriod, ::Dates.ConvertiblePeriod) Base.round(::Dates.ConvertiblePeriod, ::Dates.ConvertiblePeriod, ::RoundingMode{:NearestTiesUp}) ``` The following functions are not exported: ```@docs Dates.floorceil Dates.epochdays2date Dates.epochms2datetime Dates.date2epochdays Dates.datetime2epochms ``` ### Conversion Functions ```@docs Dates.today Dates.unix2datetime Dates.datetime2unix Dates.julian2datetime Dates.datetime2julian Dates.rata2datetime Dates.datetime2rata ``` ### Constants Days of the Week: | Variable | Abbr. | Value (Int) | |:----------- |:----- |:----------- | | `Monday` | `Mon` | 1 | | `Tuesday` | `Tue` | 2 | | `Wednesday` | `Wed` | 3 | | `Thursday` | `Thu` | 4 | | `Friday` | `Fri` | 5 | | `Saturday` | `Sat` | 6 | | `Sunday` | `Sun` | 7 | Months of the Year: | Variable | Abbr. | Value (Int) | |:----------- |:----- |:----------- | | `January` | `Jan` | 1 | | `February` | `Feb` | 2 | | `March` | `Mar` | 3 | | `April` | `Apr` | 4 | | `May` | `May` | 5 | | `June` | `Jun` | 6 | | `July` | `Jul` | 7 | | `August` | `Aug` | 8 | | `September` | `Sep` | 9 | | `October` | `Oct` | 10 | | `November` | `Nov` | 11 | | `December` | `Dec` | 12 | #### Common Date Formatters ```@docs ISODateTimeFormat ISODateFormat ISOTimeFormat RFC1123Format ``` ```@meta DocTestSetup = nothing ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
346
# 分隔符文件 ```@docs DelimitedFiles.readdlm(::Any, ::AbstractChar, ::Type, ::AbstractChar) DelimitedFiles.readdlm(::Any, ::AbstractChar, ::AbstractChar) DelimitedFiles.readdlm(::Any, ::AbstractChar, ::Type) DelimitedFiles.readdlm(::Any, ::AbstractChar) DelimitedFiles.readdlm(::Any, ::Type) DelimitedFiles.readdlm(::Any) DelimitedFiles.writedlm ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
2372
# [Distributed Computing](@id man-distributed) ```@docs Distributed.addprocs Distributed.nprocs Distributed.nworkers Distributed.procs() Distributed.procs(::Integer) Distributed.workers Distributed.rmprocs Distributed.interrupt Distributed.myid Distributed.pmap Distributed.RemoteException Distributed.Future Distributed.RemoteChannel Distributed.fetch(::Distributed.Future) Distributed.fetch(::RemoteChannel) Distributed.remotecall(::Any, ::Integer, ::Any...) Distributed.remotecall_wait(::Any, ::Integer, ::Any...) Distributed.remotecall_fetch(::Any, ::Integer, ::Any...) Distributed.remote_do(::Any, ::Integer, ::Any...) Distributed.put!(::RemoteChannel, ::Any...) Distributed.put!(::Distributed.Future, ::Any) Distributed.take!(::RemoteChannel, ::Any...) Distributed.isready(::RemoteChannel, ::Any...) Distributed.isready(::Distributed.Future) Distributed.AbstractWorkerPool Distributed.WorkerPool Distributed.CachingPool Distributed.default_worker_pool Distributed.clear!(::CachingPool) Distributed.remote Distributed.remotecall(::Any, ::AbstractWorkerPool, ::Any...) Distributed.remotecall_wait(::Any, ::AbstractWorkerPool, ::Any...) Distributed.remotecall_fetch(::Any, ::AbstractWorkerPool, ::Any...) Distributed.remote_do(::Any, ::AbstractWorkerPool, ::Any...) Distributed.@spawnat Distributed.@fetch Distributed.@fetchfrom Distributed.@distributed Distributed.@everywhere Distributed.clear!(::Any, ::Any; ::Any) Distributed.remoteref_id Distributed.channel_from_id Distributed.worker_id_from_socket Distributed.cluster_cookie() Distributed.cluster_cookie(::Any) ``` ## Cluster Manager Interface This interface provides a mechanism to launch and manage Julia workers on different cluster environments. There are two types of managers present in Base: `LocalManager`, for launching additional workers on the same host, and `SSHManager`, for launching on remote hosts via `ssh`. TCP/IP sockets are used to connect and transport messages between processes. It is possible for Cluster Managers to provide a different transport. ```@docs Distributed.ClusterManager Distributed.WorkerConfig Distributed.launch Distributed.manage Distributed.kill(::ClusterManager, ::Int, ::WorkerConfig) Distributed.connect(::ClusterManager, ::Int, ::WorkerConfig) Distributed.init_worker Distributed.start_worker Distributed.process_messages Distributed.default_addprocs_params ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
145
# 文件相关事件 ```@docs FileWatching.poll_fd FileWatching.poll_file FileWatching.watch_file FileWatching.watch_folder FileWatching.unwatch_folder ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
200
# Future The `Future` module implements future behavior of already existing functions, which will replace the current version in a future release of Julia. ```@docs Future.copy! Future.randjump ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
896
# [Interactive Utilities](@id man-interactive-utils) This module is intended for interactive work. It is loaded automaticaly in [interactive mode](@ref command-line-options). ```@docs InteractiveUtils.apropos InteractiveUtils.varinfo InteractiveUtils.versioninfo InteractiveUtils.methodswith InteractiveUtils.subtypes InteractiveUtils.supertypes InteractiveUtils.edit(::AbstractString, ::Integer) InteractiveUtils.edit(::Any) InteractiveUtils.@edit InteractiveUtils.define_editor InteractiveUtils.less(::AbstractString) InteractiveUtils.less(::Any) InteractiveUtils.@less InteractiveUtils.@which InteractiveUtils.@functionloc InteractiveUtils.@code_lowered InteractiveUtils.@code_typed InteractiveUtils.code_warntype InteractiveUtils.@code_warntype InteractiveUtils.code_llvm InteractiveUtils.@code_llvm InteractiveUtils.code_native InteractiveUtils.@code_native InteractiveUtils.clipboard ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
260
# Lazy Artifacts ```@meta DocTestSetup = :(using LazyArtifacts) ``` In order for a package to download artifacts lazily, `LazyArtifacts` must be explicitly listed as a dependency of that package. For further information on artifacts, see [Artifacts](@ref).
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
3585
# LibGit2 The LibGit2 module provides bindings to [libgit2](https://libgit2.org/), a portable C library that implements core functionality for the [Git](https://git-scm.com/) version control system. These bindings are currently used to power Julia's package manager. It is expected that this module will eventually be moved into a separate package. ### Functionality Some of this documentation assumes some prior knowledge of the libgit2 API. For more information on some of the objects and methods referenced here, consult the upstream [libgit2 API reference](https://libgit2.org/libgit2/#v0.25.1). ```@docs LibGit2.Buffer LibGit2.CheckoutOptions LibGit2.CloneOptions LibGit2.DescribeOptions LibGit2.DescribeFormatOptions LibGit2.DiffDelta LibGit2.DiffFile LibGit2.DiffOptionsStruct LibGit2.FetchHead LibGit2.FetchOptions LibGit2.GitAnnotated LibGit2.GitBlame LibGit2.GitBlob LibGit2.GitCommit LibGit2.GitHash LibGit2.GitObject LibGit2.GitRemote LibGit2.GitRemoteAnon LibGit2.GitRepo LibGit2.GitRepoExt LibGit2.GitRevWalker LibGit2.GitShortHash LibGit2.GitSignature LibGit2.GitStatus LibGit2.GitTag LibGit2.GitTree LibGit2.IndexEntry LibGit2.IndexTime LibGit2.BlameOptions LibGit2.MergeOptions LibGit2.ProxyOptions LibGit2.PushOptions LibGit2.RebaseOperation LibGit2.RebaseOptions LibGit2.RemoteCallbacks LibGit2.SignatureStruct LibGit2.StatusEntry LibGit2.StatusOptions LibGit2.StrArrayStruct LibGit2.TimeStruct LibGit2.add! LibGit2.add_fetch! LibGit2.add_push! LibGit2.addblob! LibGit2.author LibGit2.authors LibGit2.branch LibGit2.branch! LibGit2.checkout! LibGit2.clone LibGit2.commit LibGit2.committer LibGit2.count LibGit2.counthunks LibGit2.create_branch LibGit2.credentials_callback LibGit2.credentials_cb LibGit2.default_signature LibGit2.delete_branch LibGit2.diff_files LibGit2.entryid LibGit2.entrytype LibGit2.fetch LibGit2.fetchheads LibGit2.fetch_refspecs LibGit2.fetchhead_foreach_cb LibGit2.merge_base LibGit2.merge!(::LibGit2.GitRepo; ::Any...) LibGit2.merge!(::LibGit2.GitRepo, ::Vector{LibGit2.GitAnnotated}; ::LibGit2.MergeOptions, ::LibGit2.CheckoutOptions) LibGit2.merge!(::LibGit2.GitRepo, ::Vector{LibGit2.GitAnnotated}, ::Bool; ::LibGit2.MergeOptions, ::LibGit2.CheckoutOptions) LibGit2.ffmerge! LibGit2.fullname LibGit2.features LibGit2.filename LibGit2.filemode LibGit2.gitdir LibGit2.git_url LibGit2.@githash_str LibGit2.head LibGit2.head! LibGit2.head_oid LibGit2.headname LibGit2.init LibGit2.is_ancestor_of LibGit2.isbinary LibGit2.iscommit LibGit2.isdiff LibGit2.isdirty LibGit2.isorphan LibGit2.isset LibGit2.iszero LibGit2.lookup_branch LibGit2.map LibGit2.mirror_callback LibGit2.mirror_cb LibGit2.message LibGit2.merge_analysis LibGit2.name LibGit2.need_update LibGit2.objtype LibGit2.path LibGit2.peel LibGit2.posixpath LibGit2.push LibGit2.push!(::LibGit2.GitRevWalker, ::LibGit2.GitHash) LibGit2.push_head! LibGit2.push_refspecs LibGit2.raw LibGit2.read_tree! LibGit2.rebase! LibGit2.ref_list LibGit2.reftype LibGit2.remotes LibGit2.remove! LibGit2.reset LibGit2.reset! LibGit2.restore LibGit2.revcount LibGit2.set_remote_url LibGit2.shortname LibGit2.snapshot LibGit2.split_cfg_entry LibGit2.status LibGit2.stage LibGit2.tag_create LibGit2.tag_delete LibGit2.tag_list LibGit2.target LibGit2.toggle LibGit2.transact LibGit2.treewalk LibGit2.upstream LibGit2.update! LibGit2.url LibGit2.version LibGit2.with LibGit2.with_warn LibGit2.workdir LibGit2.GitObject(::LibGit2.GitTreeEntry) LibGit2.UserPasswordCredential LibGit2.SSHCredential LibGit2.isfilled LibGit2.CachedCredentials LibGit2.CredentialPayload LibGit2.approve LibGit2.reject ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git
[ "MIT" ]
1.6.0
a7dc7bfc2fc6638c18241bfcdb9d73c7dd256482
docs
181
# 动态链接器 ```@docs Libdl.dlopen Libdl.dlopen_e Libdl.RTLD_NOW Libdl.dlsym Libdl.dlsym_e Libdl.dlclose Libdl.dlext Libdl.dllist Libdl.dlpath Libdl.find_library Libdl.DL_LOAD_PATH ```
JuliaZH
https://github.com/JuliaCN/JuliaZH.jl.git