From 3b5bbb59bc0a5cd435cb211ec6aae2cfa95b07cf Mon Sep 17 00:00:00 2001 From: Cai Bingjun <1945458160@qq.com> Date: Sun, 4 Sep 2022 20:27:44 +0800 Subject: [PATCH] translate save --- doc/zh_CN/syntax/00_basic.md | 76 +++++++-------- doc/zh_CN/syntax/01_literal.md | 67 ++++++------- doc/zh_CN/syntax/02_name.md | 92 +++++++++--------- doc/zh_CN/syntax/03_declaration.md | 26 ++--- doc/zh_CN/syntax/04_function.md | 136 +++++++++++++-------------- doc/zh_CN/syntax/05_builtin_funcs.md | 14 +-- doc/zh_CN/syntax/06_operator.md | 18 ++-- doc/zh_CN/syntax/07_side_effect.md | 72 +++++++------- doc/zh_CN/syntax/08_procedure.md | 6 +- doc/zh_CN/syntax/09_builtin_procs.md | 10 +- doc/zh_CN/syntax/10_array.md | 26 ++--- doc/zh_CN/syntax/11_tuple.md | 53 +++++------ doc/zh_CN/syntax/12_dict.md | 30 +++--- doc/zh_CN/syntax/13_record.md | 92 +++++++++--------- doc/zh_CN/syntax/14_set.md | 17 ++-- doc/zh_CN/syntax/15_type.md | 4 +- doc/zh_CN/syntax/16_iterator.md | 30 +++--- doc/zh_CN/syntax/17_mutability.md | 64 ++++++------- doc/zh_CN/syntax/18_ownership.md | 82 ++++++++-------- doc/zh_CN/syntax/19_visibility.md | 68 +++++++------- doc/zh_CN/syntax/20_naming_rule.md | 26 ++--- doc/zh_CN/syntax/21_lambda.md | 53 ++++++----- doc/zh_CN/syntax/22_subroutine.md | 32 +++---- doc/zh_CN/syntax/23_closure.md | 38 ++++---- doc/zh_CN/syntax/24_module.md | 6 +- doc/zh_CN/syntax/25_object_system.md | 80 ++++++++-------- 26 files changed, 609 insertions(+), 609 deletions(-) diff --git a/doc/zh_CN/syntax/00_basic.md b/doc/zh_CN/syntax/00_basic.md index a1383dfd..1a86adf8 100644 --- a/doc/zh_CN/syntax/00_basic.md +++ b/doc/zh_CN/syntax/00_basic.md @@ -1,46 +1,46 @@ -# Basics +# 基本 -> __Warning__: This document is incomplete. It has not been proofread (style, correct links, mistranslation, etc.). Also, Erg's syntax may be change destructively during version 0.*, and the documentation may not have been updated accordingly. Please be aware of this beforehand. -> If you find any errors in this document, please report then to [here form](https://forms.gle/HtLYRfYzWCAaeTGb6) or [GitHub repo](https://github.com/mtshiba/TheErgBook/issues/new). We would appreciate your suggestions. +> __Warning__:本文档不完整。 它未经校对(样式、正确链接、误译等)。 此外,Erg 的语法可能在版本 0.* 期间发生破坏性更改,并且文档可能没有相应更新。 请事先了解这一点。 +> 如果您在本文档中发现任何错误,请报告至 [此处的表单](https://forms.gle/HtLYRfYzWCAaeTGb6) 或 [GitHub repo](https://github.com/mtshiba/TheErgBook/issues/new )。 我们将不胜感激您的建议。 > -> [The Erg book original version (Japanese)](http://mtshiba.me/TheErgBook/) +> [Erg原版(日文)](http://mtshiba.me/TheErgBook/) -This document describes the basic syntax of Erg. The [Standard API](./API/index.md) and [internal documents for Erg contributors](./dev_guide/index.md) are located in another directory. +本文档描述 Erg 的基本语法。 [标准 API](./API/index.md) 和 [Erg 贡献者的内部文档](./dev_guide/index.md) 位于另一个目录中。 -## Hello, World! +## 你好,世界! -First, let's do "Hello World". +首先,让我们做“Hello World”。 ```python print!("Hello, World!") ``` -This is almost identical to Python and other languages in the same family. The most striking feature is the `!`, the meaning of which will be explained later. -In Erg, parentheses `()` can be omitted unless there is some confusion in interpretation. -The omission of parentheses is similar to Ruby, but it is not possible to omit parentheses that can be interpreted in more than one way. +这与 Python 和同一家族中的其他语言几乎相同。 最显着的特征是`!`,后面会解释它的含义。 +在 Erg 中,括号 `()` 可以省略,除非在解释上有一些混淆。 +括号的省略与 Ruby 类似,但不能省略可以以多种方式解释的括号。 ```python print! "Hello, World!" # OK print! "Hello,", "World!" # OK print!() # OK -print! # OK, but this does not mean to call, simply to get `print!` as a callable object +print! # OK, 但这并不意味着调用,只是将 `print!` 作为可调用对象 -print! f x # OK, interpreted as `print!(f(x))` +print! f x # OK, 解释为 `print!(f(x))` print!(f(x, y)) # OK print! f(x, y) # OK print! f(x, g y) # OK -print! f x, y # NG, can be taken to mean either `print!(f(x), y)` or `print!(f(x, y))` print! -print!(f x, y) # NG, can be taken to mean either `print!(f(x), y)` or `print!(f(x, y))` -print! f(x, g y, z) # NG, can be taken to mean either `print!(x, g(y), z)` or `print!(x, g(y, z))` +print! f x, y # NG, 可以理解为 `print!(f(x), y)` 或 `print!(f(x, y))` print! +print!(f x, y) # NG, 可以表示“print!(f(x),y)”或“print!(f(x,y))” +print! f(x, g y, z) # NG, 可以表示“print!(x,g(y),z)”或“print!(x,g(y,z))” ``` -## Scripts +## 脚本 -Erg code is called a script. Scripts can be saved and executed in file format (.er). +Erg 代码称为脚本。 脚本可以以文件格式 (.er) 保存和执行。 -## REPL/File Execution +## REPL/文件执行 -To start REPL, simply type: +要启动 REPL,只需键入: ```sh > erg @@ -66,9 +66,9 @@ Or you can compile from a file. hello, world! ``` -## Comments +## 注释 -The code after `#` is ignored as a comment. Use this to explain the intent of the code or to temporarily disable the code. +`#` 之后的代码作为注释被忽略。 使用它来解释代码的意图或暂时禁用代码。 ```python # Comment @@ -79,21 +79,21 @@ Treated as a comment all the way up to the corresponding `]#` ]# ``` -## Expressions, separators +## 表达式,分隔符 -A script is a series of expressions. An expression is something that can be calculated or evaluated, and in Erg almost everything is an expression. -Each expression is separated by a separator - either a new line or a semicolon `;`-. -Erg scripts are basically evaluated from left to right, top to bottom. +脚本是一系列表达式。 表达式是可以计算或评估的东西,在 Erg 中几乎所有东西都是表达式。 +每个表达式由分隔符分隔 - 新行或分号 `;`-。 +Erg 脚本基本上是从左到右、从上到下进行评估的。 ```python -n = 1 # assignment expression -f(1, 2) # function-call expression -1 + 1 # operator-call expression +n = 1 # 赋值表达式 +f(1, 2) # 函数调用表达式 +1 + 1 # 运算符调用表达式 f(1, 2); 1 + 1 ``` -As shown below, there is a syntax called instant block that takes the last expression evaluated in the block as the value of the variable. -This differs from a function with no arguments, which does not add `()`. Note that instant blocks are evaluated only once on the fly. +如下所示,有一种称为 Instant block 的语法,它将块中评估的最后一个表达式作为变量的值。 +这与没有参数的函数不同,它不添加 `()`。 请注意,即时块仅在运行中评估一次 ```python i = @@ -102,15 +102,15 @@ i = assert i == 2 ``` -This cannot be accomplished with a semicolon (`;`). +这不能用分号 (`;`) 完成。 ```python -i = (x = 1; x + 1) # SyntaxError: cannot use `;` in parentheses +i = (x = 1; x + 1) # 语法错误:不能在括号中使用 `;` ``` -## Indentation +## 缩进 -Erg, like Python, uses indentation to represent blocks. There are five operators (special forms) that trigger the start of a block: `=`, `->`, `=>`, `do`, and `do!` (In addition, `:` and `|`, although not operators, also produce indentation). The meanings of each are described later. +Erg 和 Python 一样,使用缩进来表示块。 有五个运算符(特殊形式)触发块的开始:`=`、`->`、`=>`、`do` 和 `do!`(此外,`:` 和 `|` ,虽然不是运算符,但也会产生缩进)。 每个的含义将在后面描述。 ```python f x, y = @@ -129,15 +129,15 @@ ans = match x: _ -> "unknown" ``` -If a line is too long, it can be broken using `\`. +如果一行太长,可以使用 `\` 将其断开 ```python -# this does not means `x + y + z` but means `x; +y; +z` -x +# 这不是表示 `x + y + z` 而是表示 `x; +y; +z` +X + y + z -# this means `x + y + z` +# 这意味着`x + y + z` x \ + y \ + z diff --git a/doc/zh_CN/syntax/01_literal.md b/doc/zh_CN/syntax/01_literal.md index 8c85b141..a285d8d3 100644 --- a/doc/zh_CN/syntax/01_literal.md +++ b/doc/zh_CN/syntax/01_literal.md @@ -1,40 +1,40 @@ -# Literal +# 字面量 -## Basic Literals +## 基本字面量 -### Int Literal +### 整数字面量 ```python 0, -0, 1, -1, 2, -2, 3, -3, ... ``` -### Ratio Literal +### 比率文字 ```python 0.00, -0.0, 0.1, 400.104, ... ``` -If a `Ratio` literal has an integer or decimal part of `0`, you can omit the `0`. +如果“比率”文字的整数或小数部分为`0`,则可以省略`0` ```python assert 1.0 == 1. assert 0.5 == .5 ``` -> __Note__: This function `assert` was used to show that `1.0` and `1.` are equal. -Subsequent documents may use `assert` to indicate that the results are equal. +> __注意__:这个函数 `assert` 用于表明 `1.0` 和 `1.` 相等。 +后续文档可能会使用 `assert` 来表示结果是相等的。 -### Str Literal +### 字符串字面量 -Any Unicode-representable string can be used. -Unlike Python, quotation marks cannot be enclosed in `'`. If you want to use `"` in a string, use `\"`. +可以使用任何 Unicode 可表示的字符串。 +与 Python 不同,引号不能包含在 `'` 中。 如果要在字符串中使用 `"`,请使用 `\"`。 ```python "", "a", "abc", "111", "1# 3f2-3*8$", "こんにちは", "السَّلَامُ عَلَيْكُمْ", ... ``` -`{}` allows you to embed expressions in strings. This is called string interpolation. -If you want to output `{`, `}` itself, use `\{`, `\}`. +`{}` 允许您在字符串中嵌入表达式。 这称为字符串插值。 +如果要输出 `{`、`}` 本身,请使用 `\{`、`\}`。 ```python assert "1 + 1 is 2" == "{1} + {1} is {1+1}" @@ -42,10 +42,10 @@ s = "1+1" assert "\{1+1}\" == "\{{s}\}" ``` -### Exponential Literal +### 指数字面量 -This is a literal representing exponential notation often used in academic calculations. It is an instance of type ``Ratio``. -The notation is the same as in Python. +这是学术计算中常用的表示指数符号的文字。 它是“比率”类型的一个实例。 +该符号与 Python 中的符号相同。 ```python 1e-34, 0.4e-10, 2.455+e5, 245e5, 25E5, ... @@ -55,61 +55,61 @@ The notation is the same as in Python. assert 1e-10 == 0.0000000001 ``` -## Compound Literals +## 复合字面量 -Each of these literals has its own documentation describing them separately, so please refer to that documentation for details. +这些文字中的每一个都有自己的文档分别描述它们,因此请参阅该文档以获取详细信息。 -### [Array Literal](./10_array.md) +### [数组字面量](./10_array.md) ```python [], [1], [1, 2, 3], ["1", "2",], [1, "1", True, [1]], ... ``` -### [Dict Literal](./11_dict.md) +### [字典字面量](./11_dict.md) ```python {:}, {"one": 1}, {"one": 1, "two": 2}, {"1": 1, "2": 2}, {1: "1", 2: True, "three": [1]}, ... ``` -### [Tuple Literal](./12_tuple.md) +### [元组字面量](./12_tuple.md) ```python (), (1, 2, 3), (1, "hello", True), ... ``` -### [Record Literal](./13_record.md) +### [Record 字面量](./13_record.md) ```python {=}, {one = 1}, {one = 1; two = 2}, {.name = "John"; .age = 12}, {.name = Str; .age = Nat}, ... ``` -### [Set Literal](./14_set.md) +### [Set 字面量](./14_set.md) ```python {}, {1}, {1, 2, 3}, {"1", "2", "1"}, {1, "1", True, [1]} ... ``` -As a difference from `Array` literals, duplicate elements are removed in `Set`. +与 `Array` 字面量不同的是,`Set` 中删除了重复元素 ```python assert {1, 2, 1} == {1, 2} ``` -### What looks like a literal but isn't +### 看起来像文字但不是 -## Boolean Object +## 布尔对象 ```python True, False ``` -### None Object +### None 对象 ```python None ``` -## Range Object +## Range 对象 ```python assert 0..5 == {1, 2, 3, 4, 5} @@ -118,26 +118,27 @@ assert 0..<10 notin 10 assert 0..9 == 0..<10 ``` -## Float Object +## Float 对象 ```python assert 0.0f64 == 0 assert 0.0f32 == 0.0f64 ``` -Float objects are constructed by multiplying a `Ratio` object by `f64`, which is a `Float 64` unit object. +浮点对象是通过将 `Ratio` 对象乘以 `f64` 构造的,后者是 `Float 64` 单位对象 -## Complex Object +## Complex 对象 ```python 1+2im, 0.4-1.2im, 0im, im ``` -A `Complex` object is simply an arithmetic combination of an imaginary unit object, `im`. +一个“复杂”对象只是一个虚数单位对象`im`的算术组合 -## *-less multiplication -In Erg, you can omit the `*` to indicate multiplication as long as there is no confusion in interpretation. However, the combined strength of the operators is set stronger than `*`. +## *-less 乘法 + +在 Erg 中,您可以省略 `*` 来表示乘法,只要解释上没有混淆即可。 但是,运算符的组合强度设置为强于 `*`。 ```python # same as `assert (1*m) / (1*s) == 1*(m/s)` diff --git a/doc/zh_CN/syntax/02_name.md b/doc/zh_CN/syntax/02_name.md index 750cbfa8..a4f8a26f 100644 --- a/doc/zh_CN/syntax/02_name.md +++ b/doc/zh_CN/syntax/02_name.md @@ -1,81 +1,81 @@ -# Variable +# 多变的 -Variables are a type of algebra; algebra in Erg - sometimes simply referred to as variable if there is no confusion - refers to the feature to name objects and make them referable from elsewhere in the code. +变量是一种代数; Erg 中的代数 - 如果没有混淆,有时简称为变量 - 指的是命名对象并使它们可从代码的其他地方引用的功能。 -A variable is defined as follows. -The `n` part is called the variable name (or identifier), `=` is the assignment operator, and the `1` part is the assigned value. +变量定义如下。 +`n` 部分称为变量名(或标识符),`=` 是赋值运算符,`1` 部分是赋值。 ```python n = 1 ``` -The `n` defined in this way can thereafter be used as a variable to denote the integer object `1`. This system is called assignment (or binding). -We have just said that `1` is an object. We will discuss what an object is later, but for now we will assume that it is something that can be assigned to, i.e., on the right side of the assignment operator (`=`, etc.). +以这种方式定义的“n”此后可以用作表示整数对象“1”的变量。 该系统称为分配(或绑定)。 +我们刚刚说过`1`是一个对象。 稍后我们将讨论对象是什么,但现在我们假设它是可以赋值的,即在赋值运算符的右侧(`=` 等)。 -If you want to specify the "type" of a variable, do the following. The type is roughly the set to which an object belongs, as will be explained later. -Here we specify that `n` is a natural number (`Nat`) type. +如果要指定变量的“类型”,请执行以下操作。 类型大致是一个对象所属的集合,后面会解释。 +这里我们指定`n`是自然数(`Nat`)类型。 ```python n: Nat = 1 ``` -Note that, unlike other languages, multiple assignments are not allowed. +请注意,与其他语言不同,不允许多次分配 ```python # NG -l1 = l2 = [1, 2, 3] # SyntaxError: multiple assignment not allowed +l1 = l2 = [1, 2, 3] # 语法错误:不允许多重赋值 # OK l1 = [1, 2, 3] l2 = l1.clone() ``` -It is also not possible to reassign to a variable. The syntax that can be used instead, to hold mutable states, are described later. +也不能重新分配给变量。 稍后将描述可用于保存可变状态的语法 ```python i = 1 -i = i + 1 # AssignError: cannot assign twice +i = i + 1 # 分配错误:不能分配两次 ``` -You can define a variable with the same name in the inner scope, but you are only covering it over, not destructively rewriting its value. If you go back to the outer scope, the value will return as well. -Note that this is a different behavior than the Python "statement" scope. -This kind of functionality is generally referred to as shadowing. However, unlike shadowing in other languages, you cannot shadow in the same scope. +您可以在内部范围内定义具有相同名称的变量,但您只是覆盖它,而不是破坏性地重写它的值。 如果您返回外部范围,该值也会返回。 +请注意,这是与 Python “语句”范围不同的行为。 +这种功能通常称为阴影。 但是,与其他语言中的阴影不同,您不能在同一范围内进行阴影。 ```python x = 0 -# x = 1 # AssignError: cannot assign twice +# x = 1 # 赋值错误:不能赋值两次 if x.is_zero(), do: - x = 1 # different from outer x with same name + x = 1 # 与同名的外部 x 不同 assert x == 1 assert x == 0 ``` -The following may seem possible at first glance, but it is still not possible. This is a design decision, not a technical constraint. +乍一看,以下内容似乎可行,但仍然不可能。 这是一个设计决定,而不是技术限制。 ```python x = 0 if x.is_zero(), do: - x = x + 1 # NameError: cannot define variables refer to variables with the same name + x = x + 1 # 名称错误:无法定义变量引用同名变量 assert x == 1 assert x == 0 ``` -## Constants +## 常量 -Constants are also a type of algebra. If you start an identifier with a capital letter, it is treated as a constant. They are called constants because once defined, they do not change. -The `N` part is called the constant name (or identifier). Otherwise, it is the same as a variable. +常数也是一种代数。 如果标识符以大写字母开头,则将其视为常量。 它们被称为常量,因为一旦定义,它们就不会改变。 +`N` 部分称为常量名(或标识符)。 否则,它与变量相同。 ```python N = 0 if True, do: - N = 1 # AssignError: constants cannot be shadowed + N = 1 # 赋值错误:常量不能被遮蔽 pass() ``` -Constants are immutable beyond the defined scope. They cannot be shadowed. Because of this property, constants can be used in pattern matching. Pattern matching is explained later. +常量在定义的范围之外是不可变的。 他们不能被遮蔽。 由于这个属性,常量可以用于模式匹配。 模式匹配在后面解释。 -For example, constants are used for mathematical constants, information about external resources, and other immutable values. +例如,常量用于数学常量、有关外部资源的信息和其他不可变值。 -It is common practice to use all-caps (style in which all letters are capitalized) for identifiers of objects other than [types](./type/01_type_system.md). +除了 [types](./type/01_type_system.md) 之外的对象标识符使用全大写(所有字母大写的样式)是常见的做法。 ```python PI = 3.141592653589793 @@ -90,19 +90,19 @@ match! x: other => print! "other" ``` -The above code prints `π` when `x` is `3.141592653589793`. If `x` is changed to any other number, it prints `other`. +当 `x` 为 `3.141592653589793` 时,上面的代码会打印 `π`。 如果 `x` 更改为任何其他数字,它会打印 `other`。 -Some objects cannot be bound as constants. Mutable objects, for example. Mutable objects are objects whose states can be changed, as described in detail later. -This is because of the rule that only constant expressions can be assigned to constants. Constant expressions are also discussed later. +有些对象不能绑定为常量。 例如,可变对象。 可变对象是其状态可以改变的对象,后面会详细介绍。 +这是因为只有常量表达式才能分配给常量的规则。 常量表达式也将在后面讨论。 ```python X = 1 # OK -X = !1 # TypeError: cannot define Int! object as a constant +X = !1 # 类型错误:无法定义 Int! 对象作为常量 ``` -## Delete an Variable +## 删除变量 -You can delete an variable by using the `Del` function. All other variables that depend on the variable (that is, that refer directly to the value of the variable) are also removed. +您可以使用 `Del` 函数删除变量。 依赖于变量的所有其他变量(即直接引用变量值的变量)也将被删除。 ```python x = 1 @@ -114,19 +114,19 @@ assert f(2) == 3 Del x Del y, Z -f(2) # NameError: f is not defined (deleted in line 6) +f(2) # 名称错误:f 未定义(在第 6 行中删除) ``` -Note that `Del` can only delete variables defined in the user-defined module. Built-in constants such as `True` cannot be deleted. +注意 `Del` 只能删除用户自定义模块中定义的变量。 无法删除诸如“True”之类的内置常量。 ```python -Del True # TypeError: cannot delete built-in constants -Del print! # TypeError: cannot delete built-in variables +Del True # 类型错误:无法删除内置常量 +Del print! # TypeError: 无法删除内置变量 ``` -## Appendix: Assignment and Equivalence +## 附录:赋值和等价 -Note that `x == a` is not necessarily true when `x = a`. An example is `Float.NaN`. This is the formal specification of floating-point numbers as defined by IEEE 754. +请注意,当 `x = a` 时,`x == a` 不一定为真。 一个例子是`Float.NaN`。 这是 IEEE 754 定义的浮点数的正式规范。 ```python x = Float.NaN @@ -134,29 +134,29 @@ assert x ! = NaN assert x ! = x ``` -There are other objects for which no equivalence relation is defined in the first place. +还有其他对象首先没有定义等价关系。 ```python f = x -> x**2 + 2x + 1 g = x -> (x + 1)**2 -f == g # TypeError: cannot compare function objects +f == g # 类型错误:无法比较函数对象 C = Class {i: Int} D = Class {i: Int} -C == D # TypeError: cannot compare class objects +C == D # 类型错误:无法比较类对象 ``` -Strictly speaking, `=` does not assign the right-hand side value directly to the left-hand side identifier. -In the case of function and class objects, "modification" such as giving variable name information to the object is performed. However, this is not the case for structural types. +严格来说,`=` 不会将右侧的值直接分配给左侧的标识符。 +在函数和类对象的情况下,执行“修改”,例如将变量名称信息赋予对象。 但是,结构类型并非如此。 ```python f x = x -print! f # +print! f # <函数 f> g x = x + 1 -print! g # +print! g # <函数 g> C = Class {i: Int} -print! C # +print! C # <类 C> ```

diff --git a/doc/zh_CN/syntax/03_declaration.md b/doc/zh_CN/syntax/03_declaration.md index 5c9e8924..5dda32df 100644 --- a/doc/zh_CN/syntax/03_declaration.md +++ b/doc/zh_CN/syntax/03_declaration.md @@ -1,12 +1,12 @@ -# Declaration +# 宣言(Declaration) -Declaration is the syntax for specifying the type of variable to be used. -Declarations can be made anywhere in the code, but declarations alone do not refer to the variables. They must be initialized. -After the assignment, the declaration can be checked to ensure that the type is compatible with the object to which it is assigned. +声明是用于指定要使用的变量类型的语法。 +可以在代码中的任何地方进行声明,但单独的声明并不引用变量。 它们必须被初始化。 +分配后,可以检查声明以确保类型与分配它的对象兼容。 ```python i: Int -# Can be declared at the same time as the assignment, like i: Int = 2 +# 可以与赋值同时声明,如 i: Int = 2 i = 2 i: Num i: Nat @@ -14,24 +14,24 @@ i: -2..2 i: {2} ``` -Declaration after assignment is similar to type checking by `assert`, but has the feature that it is checked at compile time. -Type checking by `assert` at runtime can be checked for "may be type Foo", but type checking by `:` at compile time is strict: if the type is not determined to be "type Foo", it will not pass the check and an error will occur. +赋值后的声明类似于`assert`的类型检查,但具有在编译时检查的特点。 +在运行时通过`assert`进行类型检查可以检查“可能是Foo类型”,但是在编译时通过`:`进行类型检查是严格的:如果类型未确定为“类型Foo”,则不会通过 检查会出现错误。 ```python i = (-1..10).sample! -assert i in Nat # this may pass -i: Int # this will pass -i: Nat # this will not pass (-1 is not an element of Nat) +assert i in Nat # 这可能会通过 +i: Int # 这会通过 +i: Nat # 这不会通过(-1 不是 Nat 的元素) ``` -Functions can be declared in 2 different ways. +函数可以用两种不同的方式声明。 ```python f: (x: Int, y: Int) -> Int f: (Int, Int) -> Int ``` -If you declare the argument names explicitly, a type error will result if the names are different at definition time. If you want to give the argument names arbitrary names, you can declare them in the second way. In that case, only the method name and its type will be seen by type checking. +如果显式声明参数名称,如果在定义时名称不同,则会导致类型错误。 如果你想给参数名称任意命名,你可以用第二种方式声明它们。 在这种情况下,类型检查只会看到方法名称及其类型。 ```python T = Trait { @@ -39,7 +39,7 @@ T = Trait { } C = Class(U, Impl := T) -C.f(a: Int, b: Int): Int = ... # TypeError: `.f` must be type of `(x: Int, y: Int) -> Int`, not `(a: Int, b: Int) -> Int` +C.f(a: Int, b: Int): Int = ... # 类型错误:`.f` 必须是 `(x: Int, y: Int) -> Int` 的类型,而不是 `(a: Int, b: Int) -> Int` ```

diff --git a/doc/zh_CN/syntax/04_function.md b/doc/zh_CN/syntax/04_function.md index 962c90e0..21c016cd 100644 --- a/doc/zh_CN/syntax/04_function.md +++ b/doc/zh_CN/syntax/04_function.md @@ -1,17 +1,17 @@ -# Function +# 功能 -A function is a block that takes an "argument", processes it, and returns it as a "return value". It is defined as follows. +函数是一个块,它接受一个“参数”,对其进行处理,并将其作为“返回值”返回。 定义如下。 ```python add x, y = x + y -# or +# 或者 add(x, y) = x + y ``` -The names specified after a function name are called parameters. -In contrast, the objects passed to a function are called arguments. -The function `add` is a function that takes `x` and `y` as parameters and returns the sum of them, `x + y`. -The defined function can be called (applied/invoked) as follows. +在函数名之后指定的名称称为参数。 +相反,传递给函数的对象称为参数。 +函数 `add` 是一个以 `x` 和 `y` 作为参数并返回它们之和的函数,`x + y`。 +可以按如下方式调用(应用/调用)定义的函数。 ```python add 1, 2 @@ -19,9 +19,9 @@ add 1, 2 add(1, 2) ``` -## Colon application style +## 冒号应用风格 -Functions are invoked like `f x, y, ...`, but if there are too many arguments for a single line, they can be applied using `:` (colon). +函数像`f x, y, ...`一样被调用,但是如果单行参数太多,可以使用`:`(冒号)来应用它们。 ```python f some_long_name_variable_1 + some_long_name_variable_2, some_long_name_variable_3 * some_long_name_variable_4 @@ -38,7 +38,7 @@ f: some_long_name_variable_3 * some_long_name_variable_4 ``` -All three codes above mean the same thing. This style is also useful when using `if` functions, for example. +以上三个代码的含义相同。 例如,这种风格在使用 `if` 函数时也很有用 ```python result = if Bool.sample!(): @@ -50,39 +50,39 @@ result = if Bool.sample!(): 0 ``` -After `:`, no code other than comments may be written, and must always be on a new line. +在 `:` 之后,除了注释之外,不得编写任何代码,并且必须始终在新行上 -## Keyword Arguments +## 关键字参数 -If a function is defined with a large number of parameters, there is a danger of passing the arguments in the wrong order. -In such cases, it is safe to call the function using keyword arguments. +如果使用大量参数定义函数,则存在以错误顺序传递参数的危险。 +在这种情况下,使用关键字参数调用函数是安全的。 ```python f x, y, z, w, v, u: Int = ... ``` -The functions defined above have many arguments and are arranged in a confusing order. You should not create such a function, but you may encounter such code when using code written by others. Therefore, we use keyword arguments. If you use keyword arguments, the values are passed from the name to the correct argument, even if they are in the wrong order. +上面定义的函数有很多参数,并且排列顺序混乱。 您不应该创建这样的函数,但是在使用别人编写的代码时可能会遇到这样的代码。 因此,我们使用关键字参数。 如果使用关键字参数,则值会从名称传递到正确的参数,即使它们的顺序错误。 ```python f u: 6, v: 5, w: 4, x: 1, y: 2, z: 3 ``` -Note that keyword arguments and a new line immediately after the `:` are considered a colon-call style. +请注意,紧跟在 `:` 之后的关键字参数和新行被视为冒号调用样式 ```python -# means `f(x: y)` +# 意思是 `f(x: y)` f x: y -# means `f(x, y)` +# 意思是 `f(x, y)` f x: y ``` -## 定义ault parameters +## 定义错误参数 -Default parameters are used when some parameters are mostly fixed and you want to be able to omit them. +当某些参数大部分是固定的并且您希望能够省略它们时,使用默认参数。 -Default parameters are specified by `:=`(walrus operator). If `base` is not specified, assign `math.E` to `base`. +默认参数由`:=`(walrus运算符)指定。 如果未指定 `base`,则将 `math.E` 分配给 `base`。 ```python math_log x: Ratio, base := math.E = ... @@ -91,7 +91,7 @@ assert math_log(100, 10) == 2 assert math_log(100) == math_log(100, math.E) ``` -Note that there is a distinction between specifying no argument and assigning `None`. +请注意,不指定参数和指定`None`是有区别的 ```python p! x := 0 = print! @@ -100,34 +100,34 @@ p!() # 0 p!(None) # None ``` -Can also be used with type specification and patterns. +也可以与类型规范和模式一起使用 ```python math_log x, base: Ratio := math.E = ... f [x, y] := [1, 2] = ... ``` -However, within the default arguments, it is not possible to call the procedures (described later) or assign mutable objects. +但是,在默认参数中,不能调用过程(稍后描述)或分配可变对象 ```python f x := p! 1 = ... # NG ``` -Also, the argument just defined cannot be used as the value passed to the default argument. +此外,刚刚定义的参数不能用作传递给默认参数的值 ```python f x := 1, y := x = ... # NG ``` -## Variable-length arguments +## 可变长度参数 -The `log` function, which outputs a log (record) of its arguments, can take any number of arguments. +输出其参数的日志(记录)的 `log` 函数可以采用任意数量的参数。 -```python -log "Hello", "World", "!" # Hello World ! +```蟒蛇 +记录“你好”、“世界”、“!” # 你好世界 ! ``` -To define such a function, add `...` to a parameter. This way, the function receives arguments as a variable-length array. +要定义这样的函数,请将 `...` 添加到参数中。 这样,函数将参数作为可变长度数组接收 ```python f ...x = @@ -138,7 +138,7 @@ f ...x = f 1, 2, 3, 4, 5 ``` -## Function definition with multiple patterns +## 具有多种模式的函数定义 ```python fib n: Nat = @@ -148,7 +148,7 @@ fib n: Nat = n -> fib(n - 1) + fib(n - 2) ``` -Functions like the one above, where `match` appears directly under the definition, can be rewritten as follows. +像上面这样的函数,其中 `match` 直接出现在定义下,可以重写如下 ```python fib 0 = 0 @@ -156,26 +156,26 @@ fib 1 = 1 fib(n: Nat): Nat = fib(n - 1) + fib(n - 2) ``` -Note that a function definition with multiple patterns is not so-called overloading (multiple definition); a function has only a single definition. In the example above, `n` must be of the same type as `0` or `1`. Also, as with `match`, pattern matching is done from top to bottom. +注意一个函数定义有多个模式不是所谓的重载(multiple definition); 一个函数只有一个定义。 在上面的示例中,“n”必须与“0”或“1”属于同一类型。 此外,与 `match` 一样,模式匹配是从上到下完成的。 -If instances of different classes are mixed, the last definition must specify that the function argument is of type `Or`. +如果不同类的实例混合在一起,最后一个定义必须指定函数参数的类型为`Or` ```python f "aa" = ... f 1 = ... -# `f x = ... ` is invalid +# `f x = ... ` 无效 f x: Int or Str = ... ``` -Also, like `match`, it must also be exhaustive. +此外,像 `match` 一样,它也必须是详尽的。 ```python fib 0 = 0 fib 1 = 1 -# PatternError: pattern of fib's parameter is not exhaustive +# 模式错误:fib 参数的模式并不详尽 ``` -However, it can be made exhaustive by explicitly specifying the type using the [refinement type](./type/12_refinement.md) described later. +但是,可以通过使用稍后描述的 [refinement type](./type/12_refinement.md) 显式指定类型来使其详尽无遗。 ```python fib: 0..1 -> 0..1 @@ -184,12 +184,12 @@ fib 1 = 1 # OK ``` -## Recursive functions +## 递归函数 -A recursive function is a function that includes itself in its definition. +递归函数是在其定义中包含自身的函数。 -As a simple example, let us define a function `factorial` that performs a factorial calculation. Factorial is a computation that "multiplies all positive numbers less than or equal to". -The factorial of 5 is `5*4*3*2*1 == 120`. +作为一个简单的例子,让我们定义一个执行阶乘计算的函数`factorial`。 阶乘是“将所有小于或等于的正数相乘”的计算。 +5 的阶乘是 `5*4*3*2*1 == 120`。 ```python factorial 0 = 1 @@ -197,13 +197,13 @@ factorial 1 = 1 factorial(n: Nat): Nat = n * factorial(n - 1) ``` -First, from the definition of factorial, the factorial of 0 and 1 are both 1. -In turn, the factorial of 2 is `2*1 == 2`, the factorial of 3 is `3*2*1 == 6`, and the factorial of 4 is `4*3*2*1 == 24`. -If we look closely, we can see that the factorial of a number n is the factorial of the preceding number n-1 multiplied by n. -Putting this into code, we get `n * factorial(n - 1)`. -Since the definition of `factorial` contains itself, `factorial` is a recursive function. +首先,从阶乘的定义来看,0和1的阶乘都是1。 +反过来,2的阶乘是`2*1 == 2`,3的阶乘是`3*2*1 == 6`,4的阶乘是`4*3*2*1 == 24 `。 +如果我们仔细观察,我们可以看到一个数 n 的阶乘是前一个数 n-1 乘以 n 的阶乘。 +将其放入代码中,我们得到 `n * factorial(n - 1)`。 +由于 `factorial` 的定义包含自身,`factorial` 是一个递归函数。 -As a reminder, if you do not add a type specification, it is inferred like this. +提醒一下,如果您不添加类型规范,则会这样推断。 ```python factorial: |T <: Sub(Int, T) and Mul(Int, Int) and Eq(Int)| T -> Int @@ -212,20 +212,20 @@ factorial 1 = 1 factorial n = n * factorial(n - 1) ``` -However, even if you can reason about it, you should explicitly specify the type of the recursive function. In the example above, a code like ``factorial(-1)`` would work, but +但是,即使您可以推理,您也应该明确指定递归函数的类型。 在上面的例子中,像“factorial(-1)”这样的代码可以工作,但是 ```python factorial(-1) == -1 * factorial(-2) == -1 * -2 * factorial(-3) == ... ``` -and this computation does not stop. Recursive functions must carefully define the range of values or you may end up in an infinite loop. -So the type specification also helps to avoid accepting unexpected values. +并且这种计算不会停止。 递归函数必须仔细定义值的范围,否则您可能会陷入无限循环。 +所以类型规范也有助于避免接受意外的值。 -## Compile-time functions +## 编译时函数 -A function name begins with an uppercase letter to indicate a compile-time function. User-defined compile-time functions must have all arguments as constants and must specify their types. -Compile-time functions are limited in what they can do. Only constant expressions can be used in compile-time functions, i.e., only some operators (such as quadrature, comparison, and type construction operations) and compile-time functions. Arguments to be passed must also be constant expressions. -In return, the advantage is that the computation can be done at compile time. +函数名以大写字母开头,表示编译时函数。 用户定义的编译时函数必须将所有参数作为常量,并且必须指定它们的类型。 +编译时函数的功能有限。 在编译时函数中只能使用常量表达式,即只有一些运算符(例如求积、比较和类型构造操作)和编译时函数。 要传递的参数也必须是常量表达式。 +作为回报,优点是计算可以在编译时完成。 ```python Add(X, Y: Nat): Nat = X + Y @@ -236,32 +236,32 @@ Factorial(X: Nat): Nat = X * Factorial(X - 1) assert Factorial(10) == 3628800 math = import "math" -Sin X = math.sin X # ConstantError: this function is not computable at compile time +Sin X = math.sin X # 常量错误:此函数在编译时不可计算 ``` -Compile-time functions are also used in polymorphic type definitions. +编译时函数也用于多态类型定义。 ```python Option T: Type = T or NoneType Option: Type -> Type ``` -## Appendix: Function Comparison +## 附录:功能对比 -Erg does not define `==` for functions. This is because there is no structural equivalence algorithm for functions in general. +Erg 没有为函数定义 `==`。 这是因为通常没有函数的结构等价算法。 ```python f = x: Int -> (x + 1)**2 g = x: Int -> x**2 + 2x + 1 -assert f == g # TypeError: cannot compare functions +assert f == g # 类型错误:无法比较函数 ``` -Although `f` and `g` always return the same result, it is extremely difficult to make that determination. We have to teach algebra to the compiler. -So Erg gives up on function comparisons entirely, and `(x -> x) == (x -> x)` also results in a compile error. This is a different specification from Python and should be noted. +尽管 `f` 和 `g` 总是返回相同的结果,但要做出这样的决定是极其困难的。 我们必须向编译器教授代数。 +所以 Erg 完全放弃了函数比较,并且 `(x -> x) == (x -> x)` 也会导致编译错误。 这是与 Python 不同的规范,应该注意 ```python -# Python, weird example +# Python,奇怪的例子 f = lambda x: x assert f == f assert (lambda x: x) ! = (lambda x: x) @@ -271,19 +271,19 @@ assert (lambda x: x) ! = (lambda x: x) ```python f x: Object = ... -# will be completed to +# 将完成到 f(x: Object) = ... f a -# will be completed to +# 将完成到 f(a) -f a, b # TypeError: f() takes 1 positional argument but 2 were given -f(a, b) # TypeError: f() takes 1 positional argument but 2 were given +f a, b # 类型错误:f() 接受 1 个位置参数,但给出了 2 个 +f(a, b) # # 类型错误:f() 接受 1 个位置参数,但给出了 2 个 f((a, b)) # OK ``` -The function type `T -> U` is actually the syntax sugar of `(T,) -> U`. +函数类型`T -> U`实际上是`(T,) -> U`的语法糖。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/05_builtin_funcs.md b/doc/zh_CN/syntax/05_builtin_funcs.md index e696d9bb..9a21013c 100644 --- a/doc/zh_CN/syntax/05_builtin_funcs.md +++ b/doc/zh_CN/syntax/05_builtin_funcs.md @@ -1,8 +1,8 @@ -# Built-in functions +# 内置函数 -## if +## 如果 -`if` is a function that changes processing depending on a condition. +`if` 是一个根据条件改变处理的函数。 ```python result: Option Int = if! Bool.sample!(), do: @@ -11,8 +11,8 @@ result: Option Int = if! Bool.sample!(), do: print! result # None (or 1) ``` -`.sample!()` returns a random set of values. If the return value is true, `print! "True"` is executed. -You can also specify what to do if the condition is false; the second do block is called the else block. +`.sample!()` 返回一组随机值。 如果返回值为真,`print! “真”`被执行。 +如果条件为假,您还可以指定要执行的操作; 第二个 do 块称为 else 块。 ```python result: Nat = if Bool.sample!(): @@ -25,7 +25,7 @@ result: Nat = if Bool.sample!(): print! result # 1 (or 0) ``` -If the process is a single line, you can omit indentation. +如果进程是单行,则可以省略缩进。 ```python result = if Bool.sample!(): @@ -35,7 +35,7 @@ result = if Bool.sample!(): ## for -You can use `for` to write a repeating process. +你可以使用 `for` 来编写一个重复的过程。 ```python match_s(ss: Iterator(Str), pat: Pattern): Option Str = diff --git a/doc/zh_CN/syntax/06_operator.md b/doc/zh_CN/syntax/06_operator.md index f4a25d01..7f733b4a 100644 --- a/doc/zh_CN/syntax/06_operator.md +++ b/doc/zh_CN/syntax/06_operator.md @@ -1,26 +1,26 @@ -# operator +# 运算符 -Operators are symbols that represent operations. Operands are things to the (left) right of an operator. +运算符是表示操作的符号。 操作数是运算符(左)右侧的东西。 -Operators are a kind of function, and thus are themselves first-class objects that can be bound to variables. When binding, it is necessary to enclose it with ``. -For `+` (and `-`), there are both unary and binary operators, so `_+_`(binary operation)/`+_`(unary operation ) must be specified. +运算符是一种函数,因此它们本身就是可以绑定到变量的一流对象。 绑定时,需要用```括起来。 +对于`+`(和`-`),有一元和二元运算符,所以必须指定`_+_`(二元运算)/`+_`(一元运算)。 ```python -add = `+` # SyntaxError: specify `_+_` or `+_` +add = `+` # 语法错误:指定 `_+_` 或 `+_` add=`_+_` assert f(1, 2) == 3 assert f("a", "b") == "ab" -g = `*` # OK, this is binary only +g = `*` # OK, 这只是二进制 assert g(1, 2) == 2 ``` -Some fundamental operators, called special forms, cannot be bound. +一些称为特殊形式的基本运算符不能被绑定。 ```python -def = `=` # SyntaxError: cannot bind `=` operator, this is a special form +def = `=` # 语法错误:无法绑定 `=` 运算符,这是一种特殊形式 # NG: def x, 1 -function = `->` # SyntaxError: cannot bind `->` operator, this is a special form +function = `->` # 语法错误:无法绑定 `->` 运算符,这是一种特殊形式 # NG: function x, x + 1 ``` diff --git a/doc/zh_CN/syntax/07_side_effect.md b/doc/zh_CN/syntax/07_side_effect.md index e0604cbe..bbae2ecd 100644 --- a/doc/zh_CN/syntax/07_side_effect.md +++ b/doc/zh_CN/syntax/07_side_effect.md @@ -1,44 +1,44 @@ -# Side effects and procedures +# 副作用和程序 -We have been neglecting to explain the meaning of the `!`, but now its meaning will finally be revealed. This `!` indicates that this object is a "procedure" with a "side-effect". A procedure is a function with a side-effect. +我们一直忽略了解释“!”的含义,但现在它的含义终于要揭晓了。 这个 `!` 表示这个对象是一个带有“副作用”的“过程”。 过程是具有副作用的函数。 ```python -f x = print! x # EffectError: functions cannot be assigned objects with side effects -# hint: change the name to 'f!' +f x = print! x # EffectError: 不能为函数分配有副作用的对象 +# 提示:将名称更改为 'f!' ``` -The above code will result in a compile error. This is because you are using a procedure in a function. In such a case, you must define it as a procedure. +上面的代码会导致编译错误。 这是因为您在函数中使用了过程。 在这种情况下,您必须将其定义为过程。 ```python p! x = print! x ``` -`p!`, `q!`, ... are typical variable names for procedures. -Procedures defined in this way also cannot be used within a function, so side-effects are completely isolated. +`p!`, `q!`, ... 是过程的典型变量名。 +以这种方式定义的过程也不能在函数中使用,因此副作用是完全隔离的。 ## 方法 -Functions and procedures each can be 方法. Functional 方法 can only take immutable references to `self`, while procedural 方法 can take mutable references to `self`. -The `self` is a special parameter, which in the context of a method refers to the calling object itself. The reference `self` cannot be assigned to any other variable. +函数和过程中的每一个都可以是方法。 函数式方法只能对`self`进行不可变引用,而程序性方法可以对`self`进行可变引用。 +`self` 是一个特殊的参数,在方法的上下文中是指调用对象本身。 引用 `self` 不能分配给任何其他变量。 ```python C!. method ref self = - x = self # OwnershipError: cannot move out 'self' + x = self # 所有权错误:无法移出`self` x ``` -Procedural 方法 can also take [ownership](./18_ownership.md) of `self`. Remove `ref` or `ref!` from the method definition. +程序方法也可以采取 `self` 的 [ownership](./18_ownership.md)。 从方法定义中删除 `ref` 或 `ref!` ```python n = 1 s = n.into(Str) # '1' -n # ValueError: n was moved by .into (line 2) +n # 值错误:n 被 .into 移动(第 2 行) ``` -Only one procedural 方法 can have a mutable reference at any given time. In addition, while a mutable reference is taken, no more mutable reference can be taken from the original object. In this sense, `ref!` causes a side-effect on `self`. +在任何给定时间,只有一种程序方法可以具有可变引用。 此外,在获取可变引用时,不能从原始对象获取更多可变引用。 从这个意义上说,`ref!` 会对`self` 产生副作用。 -Note, however, that it is possible to create (immutable/mutable) references from mutable references. This allows recursion and `print!` of `self` in procedural 方法. +但是请注意,可以从可变引用创建(不可变/可变)引用。 这允许在程序方法中递归和 `print!` 的`self`。 ```python T -> T # OK (move) @@ -52,23 +52,23 @@ T -> Ref T # OK T => Ref! ``` -## Appendix: Strict definition of side-effects +## 附录:副作用的严格定义 -The rules for whether a code has a side-effect or not are not immediately understandable. -Until you can understand them, we recommend that you leave it to the compiler to define them as functions for the time being, and if an error occurs, add `!` to treat them as procedures. -However, for those who want to understand the exact specifications of the language, the following is a more detailed explanation of side-effects. +代码是否具有副作用的规则无法立即理解。 +直到你能理解它们,我们建议你暂时把它们定义为函数,如果出现错误,添加`!`将它们视为过程。 +但是,对于那些想了解该语言的确切规范的人,以下是对副作用的更详细说明。 -First, it must be stated that the equivalence of return values is irrelevant with respect to side effects in Erg. -There are procedures that for any given `x` will result in `p!(x) == p!(x)` (e.g. always return `None`), and there are functions that will result in `f(x) ! = f(x)`. +首先,必须声明返回值的等价与 Erg 中的副作用无关。 +有些过程对于任何给定的 `x` 都会导致 `p!(x) == p!(x)`(例如,总是返回 `None`),并且有些函数会导致 `f(x) ! = f(x)`。 -An example of the former is `print!`, and an example of the latter is the following function. +前者的一个例子是`print!`,后者的一个例子是下面的函数。 ```python nan _ = Float.NaN assert nan(1) ! = nan(1) ``` -There are also objects, such as classes, for which equivalence determination itself is not possible. +还有一些对象,例如类,等价确定本身是不可能的 ```python T = Structural {i = Int} @@ -77,16 +77,16 @@ assert T == U C = Class {i = Int} D = Class {i = Int} -assert C == D # TypeError: cannot compare classes +assert C == D # 类型错误:无法比较类 ``` -Back to the point: the precise definition of "side-effect" in Erg is +言归正传:Erg 中“副作用”的准确定义是 -* Accessing mutable external information. +* 访问可变的外部信息。 -"External" generally refers to the outer scope; computer resources that Erg cannot touch and pre-/post-execution information are not included in "external". "Access" includes reading as well as writing. +“外部”一般是指外部范围; Erg 无法触及的计算机资源和执行前/执行后的信息不包含在“外部”中。 “访问”包括阅读和写作。 -As an example, consider the `print!` procedure. At first glance, `print!` does not seem to rewrite any variables. But if it were a function, it could rewrite outer variables, for example, with code like this: +例如,考虑 `print!` 过程。 乍一看,`print!` 似乎没有重写任何变量。 但如果它是一个函数,它可以重写外部变量,例如,使用如下代码: ```python camera = import "some_camera_module" @@ -94,27 +94,27 @@ ocr = import "some_ocr_module" n = 0 _ = - f x = print x # Suppose we could use print as a function + f x = print x # 假设我们可以使用 print 作为函数 f(3.141592) -cam = camera.new() # camera faces PC display +cam = camera.new() # 摄像头面向 PC 显示器 image = cam.shot!() n = ocr.read_num(image) # n = 3.141592 ``` -Think of the `camera` module as an external library providing an API for a certain camera product, and `ocr` as a library for OCR (optical character recognition). -The direct side-effect is caused by `cam.shot!()`, but obviously that information is leaked from `f`. Therefore, `print!` cannot be a function by nature. +将“camera”模块视为为特定相机产品提供 API 的外部库,将“ocr”视为用于 OCR(光学字符识别)的库。 +直接的副作用是由 `cam.shot!()` 引起的,但显然这些信息是从 `f` 泄露的。 因此,`print!` 本质上不可能是一个函数。 -Nevertheless, there may be cases where you want to temporarily check a value in a function and do not want to add `!` in the related function just for that purpose. In such cases, the `log` function can be used. -`log` prints the value after the entire code has been executed. In this way, side-effects are not propagated. +然而,在某些情况下,您可能希望临时检查函数中的值,而不想为此目的在相关函数中添加 `!`。 在这种情况下,可以使用 `log` 函数。 +`log` 打印整个代码执行后的值。 这样,副作用就不会传播。 ```python log "this will be printed after execution" print! "this will be printed immediately" -# this will be printed immediately -# this will be printed after execution +# 这将立即打印 +# 这将在执行后打印 ``` -If there is no feedback to the program, or in other words, if no external object can use the internal information, then the "leakage" of the information may be allowed. It is only necessary that the information not be "propagated". +如果没有反馈给程序,或者换句话说,如果没有外部对象可以使用内部信息,那么信息的“泄漏”是可以允许的。 只需要不“传播”信息。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/08_procedure.md b/doc/zh_CN/syntax/08_procedure.md index 3b4def38..a9a9652e 100644 --- a/doc/zh_CN/syntax/08_procedure.md +++ b/doc/zh_CN/syntax/08_procedure.md @@ -1,7 +1,7 @@ -# Procedures +# 程序 -Procedures are necessary when dealing with mutable objects, but having a mutable object as an argument does not necessarily make it a procedure. -Here is a function takes a mutable object (not procedure). +处理可变对象时需要过程,但将可变对象作为参数并不一定使其成为过程。 +这是一个函数接受一个可变对象(不是过程)。 ```python peek_str s: Str! = log s diff --git a/doc/zh_CN/syntax/09_builtin_procs.md b/doc/zh_CN/syntax/09_builtin_procs.md index dd51f978..f2e878c2 100644 --- a/doc/zh_CN/syntax/09_builtin_procs.md +++ b/doc/zh_CN/syntax/09_builtin_procs.md @@ -1,10 +1,10 @@ -# Built-in procedure +# 内置程序 -## id! +## id! -Returns the unique identification number of the object. -Although in pure Erg semantics no difference can be found between objects with the same structure, in practice objects have different locations in memory. -`id!` returns a number representing this position. +返回对象的唯一标识号。 +尽管在纯 Erg 语义中,结构相同的对象之间没有区别,但实际上对象在内存中具有不同的位置。 +`id!` 返回一个代表这个位置的数字。 ```python ``` diff --git a/doc/zh_CN/syntax/10_array.md b/doc/zh_CN/syntax/10_array.md index d55c2135..cecdeb58 100644 --- a/doc/zh_CN/syntax/10_array.md +++ b/doc/zh_CN/syntax/10_array.md @@ -1,12 +1,12 @@ # Array -Arrays are the most basic __collection (aggregate)__. -A collection is an object that can hold multiple objects inside it. +数组是最基本的__collection(聚合)__。 +集合是一个可以在其中包含多个对象的对象。 ```python a = [1, 2, 3] -a: [Int; 3] # Type specification: number after semicolon is the number of elements -# Can be omitted if the number of elements is not known +a: [Int; 3] # 类型说明:分号后的数字为元素个数 +# 如果元素个数未知,可以省略 a: [Int] mut_a = [!1, !2, !3] @@ -14,34 +14,34 @@ mut_a[0].inc!() assert mut_a == [2, 2, 3] ``` -As a rule, arrays cannot contain objects of different types. +通常,数组不能包含不同类型的对象。 ```python. -[1, "a"] # TypeError: 1st element is Int, but 2nd element is Str +[1, "a"] # 类型错误:第一个元素是 Int,但第二个元素是 Str ``` -However, you can bypass the restriction by explicitly specifying the type like this. +但是,您可以通过像这样显式指定类型来绕过限制。 ```python [1, "a"]: [Int or Str]. ``` -## Slice +## 切片 -An array can also have multiple values taken out at once. This is called slicing. +一个数组也可以同时取出多个值。 这称为切片。 ```python l = [1, 2, 3, 4] -# Same as l[1:3] in Python +# 与 Python 中的 l[1:3] 相同 assert l[1.. <3] == [2, 3] assert l[1..2] == [2, 3] -# Same as l[1] +# 与 l[1] 相同 assert l[1..1] == [2] -# Same as l[::2] in Python +# 与 Python 中的 l[::2] 相同 assert l[..].step(2) == [2, 4] ``` -The object obtained by slicing is an (immutable) copy to an array. +通过切片获得的对象是数组的(不可变的)副本 ```python print! Typeof l[1..2] # [Int; 4] diff --git a/doc/zh_CN/syntax/11_tuple.md b/doc/zh_CN/syntax/11_tuple.md index f232038e..4548eca3 100644 --- a/doc/zh_CN/syntax/11_tuple.md +++ b/doc/zh_CN/syntax/11_tuple.md @@ -1,7 +1,7 @@ -# Tuple +# 元组 -Tuples are similar to arrays, but can hold objects of different types. -Such a collection is called an unequal collection. In contrast, homogeneous collections include arrays, sets, etc. +元组类似于数组,但可以保存不同类型的对象。 +这样的集合称为不等集合。 相比之下,同构集合包括数组、集合等。 ```python t = (1, True, "a") @@ -9,8 +9,8 @@ t = (1, True, "a") assert(i == 1 and b == True and s == "a") ``` -The tuple `t` can retrieve the nth element in the form `t.n`; note that unlike Python, it is not `t[n]`. -This is because accessing tuple elements is more like an attribute (the existence of the element is checked at compile time, and the type can change depending on `n`) than a method (an array's `[]` is a method). +元组`t`可以以`t.n`的形式检索第n个元素; 请注意,与 Python 不同,它不是 `t[n]`。 +这是因为访问元组元素更像是一个属性(在编译时检查元素的存在,并且类型可以根据 `n` 改变)而不是方法(数组的 `[]` 是一种方法)。 ```python assert t.0 == 1 @@ -18,55 +18,55 @@ assert t.1 == True assert t.2 == "a" ``` -Parentheses `()` are optional when not nested. +括号 `()` 在不嵌套时是可选的。 ```python t = 1, True, "a" i, b, s = t ``` -Tuples can hold objects of different types, so they cannot be iterated like arrays. +元组可以保存不同类型的对象,因此它们不能像数组一样被迭代。 ```python t: ({1}, {2}, {3}) = (1, 2, 3) -(1, 2, 3).iter().map(x -> x + 1) # TypeError: type ({1}, {2}, {3}) has no method `.iter()` -# If all types are the same, they can be represented by `(T; n)` like arrays, but this still does not allow iteration +(1, 2, 3).iter().map(x -> x + 1) # 类型错误:类型 ({1}, {2}, {3}) 没有方法 `.iter()` +# 如果所有类型都相同,则可以像数组一样用`(T; n)`表示,但这仍然不允许迭代 t: (Int; 3) = (1, 2, 3) assert (Int; 3) == (Int, Int, Int) ``` -However, nonhomogeneous collections (such as tuples) can be converted to homogeneous collections (such as arrays) by upcasting, intersecting, and so on. -This is called equalization. +但是,非同质集合(如元组)可以通过向上转换、相交等方式转换为同质集合(如数组)。 +这称为均衡。 ```python (Int, Bool, Str) can be [T; 3] where T :> Int, T :> Bool, T :> Str ``` ```python -t: (Int, Bool, Str) = (1, True, "a") # non-homogenous -a: [Int or Bool or Str; 3] = [1, True, "a"] # homogenous -_a: [Show; 3] = [1, True, "a"] # homogenous +t: (Int, Bool, Str) = (1, True, "a") # 非同质 +a: [Int or Bool or Str; 3] = [1, True, "a"] # 同质的 +_a: [Show; 3] = [1, True, "a"] # 同质的 _a.iter().map(x -> log x) # OK t.try_into([Show; 3])? .iter().map(x -> log x) # OK ``` -## Unit +## 单元 -A tuple with zero elements is called a __unit__. A unit is a value, but also refers to its own type. +零元素的元组称为 __unit__。 一个单元是一个值,但也指它自己的类型。 ```python unit = () (): () ``` -Unit is a superclass of all element 0 tuples. +Unit 是所有元素 0 元组的父类。 ```python () > (Int; 0) () > (Str; 0) ``` -The use of this object is for procedures with no arguments and no return value, etc. Erg subroutines must have arguments and a return value. However, in some cases, such as a procedure, there may be no meaningful arguments or return value, only side effects. In such cases, we use units as "meaningless, formal values. +该对象的用途是用于没有参数和没有返回值的过程等。Erg 子例程必须有参数和返回值。 但是,在某些情况下,例如过程,可能没有有意义的参数或返回值,只有副作用。 在这种情况下,我们将单位用作“无意义的正式值” ```python # ↓ Actually, this parenthesis is a unit @@ -76,31 +76,30 @@ p!() =. p!: () => () ``` -However, Python tends to use `None` instead of units in such cases. -In Erg, you should use `()` when you are sure from the beginning that the operation will not return a meaningful value, such as in a procedure, and return `None` when there is a possibility that the operation will fail and you will get nothing, such as when retrieving an element. +但是,在这种情况下,Python 倾向于使用“无”而不是单位。 +在 Erg 中,当您从一开始就确定操作不会返回有意义的值(例如在过程中)时,您应该使用 `()`,并且当操作可能失败并且您可能会返回 `None` 将一无所获,例如在检索元素时。 -## Arguments and Tuple +## 参数和元组 -Actually, all of Erg's `Callable` objects are one argument and one return value; a subroutine that takes N arguments was just receiving "one tuple with N elements" as an argument. +实际上,Erg 的所有 `Callable` 对象都是一个参数和一个返回值; 一个接受 N 个参数的子例程只是接收“一个具有 N 个元素的元组”作为参数。 ```python -# f x = ... is implicitly assumed to be f(x) = ... is considered to be +# f x = ... 被隐式假设为 f(x) = ... 被认为是 f x = x assert f(1) == 1 -f(1, 2, 3) # ArgumentError: f takes 1 positional argument but 3 were given -# ArgumentError: f takes 1 positional argument but 3 were given +f(1, 2, 3) # 参数错误:f 接受 1 个位置参数,但给出了 3 个 g x: Int, . . y: Int = y assert (2, 3) == g 1, 2, 3 ``` -This also explains the function type. +这也解释了函数类型。 ```python assert f in T: {(T,) -> T | T} assert g in {(Int, ... (Int; N)) -> (Int; N) | N: Nat} ``` -To be precise, the function's input is not a tuple but a "Named tuple with default attributes". This is a special tuple that can only be used in function arguments, can be named like a record, and can have a default value. +准确地说,函数的输入不是元组,而是“具有默认属性的命名元组”。 这是一个特殊的元组,只能在函数参数中使用,可以像记录一样命名,并且可以有默认值。 ```python f(x: Int, y=0) = x + y diff --git a/doc/zh_CN/syntax/12_dict.md b/doc/zh_CN/syntax/12_dict.md index 9f0b6929..747b27e6 100644 --- a/doc/zh_CN/syntax/12_dict.md +++ b/doc/zh_CN/syntax/12_dict.md @@ -1,37 +1,37 @@ -# Dict +# 字典 -Dict is a collection of key/value pairs. +Dict 是键/值对的集合。 ```python ids = {"Alice": 145, "Bob": 214, "Charlie": 301} assert ids["Alice"] == 145 ``` -The key does not have to be a string if it is a `Hash` object. +如果键是“哈希”对象,则键不必是字符串。 ```python -# deprecated to use a range object as a key (confused with slice) +# 不推荐使用范围对象作为键(与切片混淆) r = {1..3: "1~3", 4..6: "4~6", 7..9: "7~9"} assert r[1..3] == "1~3" l = {[]: "empty", [1]: "1"} assert l[[]] == "empty" ``` -Order does not matter for Dict. It also cannot have duplicate elements. In this respect, Dict is similar to Set. -You could say that a Dict is a Set with values. +对于字典来说,顺序无关紧要。 它也不能有重复的元素。 在这方面,Dict 与 Set 类似。 +您可以说 Dict 是具有值的 Set。 ```python {"Alice": 145, "Bob": 214, "Charlie": 301} == {"Alice": 145, "Charlie": 301, "Bob": 214} ``` -When generating a dict from a dict literal, it is checked for duplicate keys. -Any duplicates will result in a compile error. +从 dict 文字生成 dict 时,会检查重复键。 +任何重复都会导致编译错误。 ```python -{"Alice": 145, "Alice": 1} # KeyError: Duplicate key "Alice" +{"Alice": 145, "Alice": 1} # Key错误:重复键`Alice` ``` -Empty Dict is created with `{:}`. Note that `{}` denotes an empty set. +空字典是用 `{:}` 创建的。 请注意,`{}` 表示一个空集。 ```python mut_dict = !{:} @@ -40,9 +40,9 @@ mut_dict.insert! "Bob", 214 assert mut_dict["Alice"] == 145 ``` -## Heterogeneous Dict +## 异构字典 -There need not be a single key/value type. Such a dictionary is called a __heterogenous dict_. +不需要有单一的键/值类型。 这样的字典称为 __heterogenous dict_。 ```python d: {Str: Int, Int: Str} = {"a": 1, 1: "a"} @@ -50,14 +50,14 @@ assert d["a"] == 1 assert d[1] == "a" ``` -However, it is not possible to assign values of the same type to keys of different types, or values of different types to keys of the same type. -In such cases, use the type Or instead. +但是,不能将相同类型的值分配给不同类型的键,或者将不同类型的值分配给相同类型的键。 +在这种情况下,请改用 Or 类型。 ```python invalid1 = {1: "a", "a": "b"} invalid2 = {1: "a", 2: 2} -# Erg type inference does not infer Or type, so type specification is required +# Erg 类型推断不推断 Or 类型,因此需要类型说明 valid1: {Int or Str: Str} = {1: "a", "a": "b"} valid2: {Int: Int or Str} = {1: "a", 2: 2} ``` diff --git a/doc/zh_CN/syntax/13_record.md b/doc/zh_CN/syntax/13_record.md index d5b2570f..e855b998 100644 --- a/doc/zh_CN/syntax/13_record.md +++ b/doc/zh_CN/syntax/13_record.md @@ -1,7 +1,7 @@ -# Record +# 记录(Record) -A record is a collection that combines the properties of a Dict accessed by key and a tuple whose access is inspected at compile time. -If you know JavaScript, think of it as a (more enhanced) kind of object literal notation. +记录是一个集合,它结合了通过键访问的 Dict 和在编译时检查其访问的元组的属性。 +如果您了解 JavaScript,请将其视为一种(更增强的)对象字面量表示法。 ```python john = {.name = "John"; .age = 21} @@ -9,27 +9,27 @@ john = {.name = "John"; .age = 21} assert john.name == "John" assert john.age == 21 assert john in {.name = Str; .age = Nat} -john["name"] # Error: john is not subscribable +john["name"] # 错误:john 不可订阅 ``` -The `.name` and `.age` parts are called attributes, and the `"John"` and `21` parts are called attribute values. +`.name` 和 `.age` 部分称为属性,而 `"John"` 和 `21` 部分称为属性值。 -The difference from JavaScript object literals is that they are not accessible as strings. That is, attributes are not just strings. -This is because access to the value is determined at compile-time, and because dictionaries and records are different things. In other words, `{"name": "John"}` is a Dict and `{name = "John"}` is a record. -So how should we use dictionaries and records? -In general, we recommend using records. Records have the advantages of being checked at compile-time for the existence of elements and of being able to specify __visibility_. -Specifying visibility is equivalent to specifying public/private in Java and other languages. For details, see [visibility](./15_visibility.md) for details. +与 JavaScript 对象字面量的区别在于它们不能作为字符串访问。 也就是说,属性不仅仅是字符串。 +这是因为对值的访问是在编译时确定的,而且字典和记录是不同的东西。 换句话说,`{"name": "John"}` 是一个字典,`{name = "John"}` 是一个记录。 +那么我们应该如何使用字典和记录呢? +一般来说,我们建议使用记录。 记录具有在编译时检查元素是否存在以及能够指定 __visibility_ 的优点。 +指定可见性等同于在 Java 和其他语言中指定公共/私有。 有关详细信息,请参阅 [可见性](./15_visibility.md) 了解详细信息。 ```python a = {x = 1; .y = x + 1} -a.x # AttributeError: x is private -# Hint: declare as `.x`. +a.x # 属性错误:x 是私有的 +# 提示:声明为 `.x`。 assert a.y == 2 ``` -The above example may seem strange to someone familiar with JavaScript, but simply declaring `x` makes it inaccessible from the outside. `. `. `. +对于熟悉 JavaScript 的人来说,上面的示例可能看起来很奇怪,但简单地声明 `x` 会使其无法从外部访问 -You can also explicitly specify the type of an attribute. +您还可以显式指定属性的类型 ```python anonymous = { @@ -39,7 +39,7 @@ anonymous = { anonymous.name.set! "John" ``` -A record can also have the method. +一个记录也可以有方法。 ```python o = { @@ -52,27 +52,27 @@ o.inc!() assert o.i == 1 ``` -There is a notable syntax with respect to records. When all the attribute values of a record are classes (not structural types), the record itself behaves as a type with its own attributes as required attributes. -Such a type is called a record type. See the section [Record] for more details. +关于记录有一个值得注意的语法。 当记录的所有属性值都是类(不是结构类型)时,记录本身表现为一个类型,其自身的属性作为必需属性。 +这种类型称为记录类型。 有关详细信息,请参阅 [记录] 部分。 ```python -# record +# 记录 john = {.name = "John"} -# record type +# 记录 type john: {.name = Str} Named = {.name = Str} john: Named greet! n: Named = print! "Hello, I am {n.name}" -john # "Hello, I am John" print! +john # “你好,我是约翰 print! Named.name # Str ``` -## Deconstructing a record +## 解构记录 -Records can be deconstructed as follows. +记录可以按如下方式解构。 ```python record = {x = 1; y = 2} @@ -88,8 +88,8 @@ match point: {x = x; y = y; z = z} -> "({x}, {y}, {z})" ``` -`x = ...` can also be abbreviated to `x` when there is a variable with the same name as the attribute, for example, `x = x` or `x = .x` to `x`, and `.x = .x` or `.x = x` to `.x`. -However, when there is only one attribute, it must be followed by `;` to distinguish it from a set. +当存在与属性同名的变量时,`x = ...`也可以缩写为`x`,例如`x = x`或`x = .x`到`x`,和` .x = .x` 或 `.x = x` 到 `.x`。 +但是,当只有一个属性时,必须在其后加上`;`以与集合区分开来。 ```python x = 1 @@ -106,22 +106,22 @@ tuple = {x} assert tuple.1 == 1 ``` -This syntax can be used to deconstructed a record and assign it to a variable. +此语法可用于解构记录并将其分配给变量 ```python -# same as `{x = x; y = y} = xy` +# 一样 `{x = x; y = y} = xy` {x; y} = xy assert x == 1 assert y == 2 -# same as `{.a = a; .b = b} = ab` +# 一样 `{.a = a; .b = b} = ab` {a; b} = ab assert a == 1 assert b == 2 ``` -## Empty Record +## 空记录 -An empty record is represented by `{=}`. An empty record is also its own class, like Unit. +空记录由`{=}`表示。 空记录也是它自己的类,如 Unit ```python empty_record = {=} @@ -132,10 +132,10 @@ empty_record: Structural {=} {x = 3; y = 5}: Structural {=} ``` -An empty record is different from an empty Dict `{:}` or empty set `{}`. In particular, note that it is the opposite of `{}` in meaning (in Python, `{}` is an empty dictionary, while in Erg it is `!{:}` in Erg). -As an enumerated type, `{}` is an empty type that contains nothing in its elements. The `Never` type is a classification of this type. -Conversely, the record class `{=}` has no required instance attribute, so all objects are elements of it. An `Object` is an alias of this. -An `Object` (a patch of `Object`) is an element of `. __sizeof__` and other very basic provided 方法. +空记录不同于空 Dict `{:}` 或空集 `{}`。 特别要注意的是,它与 `{}` 的含义相反(在 Python 中,`{}` 是一个空字典,而在 Erg 中它是 Erg 中的 `!{:}`)。 +作为枚举类型,`{}` 是一个空类型,其元素中不包含任何内容。 `Never` 类型是这种类型的一个分类。 +相反,记录类 `{=}` 没有必需的实例属性,因此所有对象都是它的元素。 `Object` 是 this 的别名。 +一个`Object`(`Object`的一个补丁)是`的一个元素。 __sizeof__` 和其他非常基本的提供方法。 ```python AnyPatch = Patch Structural {=} @@ -145,13 +145,13 @@ AnyPatch = Patch Structural {=} Never = Class {} ``` -Note that no other type or class can be structurally equivalent to the `{}`, `Never` type, and it is an error if the user defines a type with `{}`, `Class {}` on the right side. -This means that, for example, `1..10 or -10. -1`, but `1..10 and -10... -1`. `-1` when it should be `1..10 or -10...-1`, for example. -Also, if you define a type (such as `Int and Str`) that results in a composition `Object`, you will be warned to simply set it to `Object`. +请注意,没有其他类型或类在结构上与 `{}`、`Never` 类型等效,如果用户在右侧使用 `{}`、`Class {}` 定义类型,则会出错。 +这意味着,例如,`1..10 或 -10。 -1`,但 `1..10 和 -10... -1`。 例如,当它应该是 1..10 或 -10...-1 时是 `-1`。 +此外,如果您定义的类型(例如 `Int 和 Str`)会导致组合 `Object`,则会警告您只需将其设置为 `Object`。 -## Instant Block +## 即时封锁 -Erg has another syntax, instant block, which simply returns the last value evaluated. Attributes cannot be retained. +Erg 有另一种语法 Instant 块,它只返回最后评估的值。 不能保留属性。 ```python x = @@ -161,13 +161,13 @@ x = assert x == 8 y = - .x = 1 # SyntaxError: cannot define an attribute in an entity block + .x = 1 # 语法错误:无法在实体块中定义属性 ``` -## Data Class +## 数据类 -A bare record (a record generated by a record literal) must be defined directly in the instance if you try to implement a method on its own. -This is inefficient, and as the number of attributes increases, error messages and the like become difficult to see and use. +如果您尝试自己实现方法,则必须直接在实例中定义裸记录(由记录文字生成的记录)。 +这是低效的,并且随着属性数量的增加,错误消息等变得难以查看和使用。 ```python john = { @@ -177,11 +177,11 @@ john = { .inc_age! ref! self = self::age.update! x -> x + 1 } john + 1 -# TypeError: + is not implemented for {name = Str; age = Int; .greet! = Ref(Self). () => None; inc_age! = Ref! () => None}, Int +# 类型错误:{name = Str; 没有实现 + 年龄=诠释; 。迎接! =参考(自我)。 () => 无; inc_age! =参考! () => 无}, 整数 ``` -So, in such a case, you can inherit a record class. Such a class is called a data class. -This is described in [class](./type/04_class.md). +因此,在这种情况下,您可以继承一个记录类。 这样的类称为数据类。 +这在 [class](./type/04_class.md) 中有描述。 ```python Person = Inherit {name = Str; age = Nat} @@ -191,7 +191,7 @@ Person. john = Person.new {name = "John Smith"; age = 20} john + 1 -# TypeError: + is not implemented for Person, Int +# 类型错误:Person、Int 没有实现 + ```

diff --git a/doc/zh_CN/syntax/14_set.md b/doc/zh_CN/syntax/14_set.md index ffbea36f..e209411d 100644 --- a/doc/zh_CN/syntax/14_set.md +++ b/doc/zh_CN/syntax/14_set.md @@ -1,14 +1,14 @@ # Set -A set represents a collection, which is structurally a duplicate, unordered array. +一个Set代表一个集合,它在结构上是一个重复的无序数组。 ```python assert Set.from([1, 2, 3, 2, 1]) == {1, 2, 3} -assert {1, 2} == {1, 1, 2} # duplicates are automatically removed +assert {1, 2} == {1, 1, 2} # 重复的被自动删除 assert {1, 2} == {2, 1} ``` -Sets can perform set operations. +Set可以执行集合操作。 ```python assert 1 in {1, 2, 3} @@ -18,23 +18,22 @@ assert {1, 2} and {2, 3} == {2} assert {1, 2} not {2} == {1} ``` -A set is a homogeneous collection. In order for objects of different classes to coexist, they must be homogenized. +Set是同质集合。 为了使不同类的对象共存,它们必须同质化 ```python s: {Int or Str} = {"a", 1, "b", -1} ``` -## Sets as types - -Sets can also be treated as types. Such types are called __Enum types__. +## Sets为类型 +Sets也可以被视为类型。 这种类型称为 _枚举类型_。 ```python i: {1, 2, 3} = 1 assert i in {1, 2, 3} ``` -Elements of the set are directly elements of the type. -Note that the sets themselves are different. +Set的元素直接是类型的元素。 +请注意,这些Set本身是不同的。 ```python mut_set = {1, 2, 3}.into {Int; !3} diff --git a/doc/zh_CN/syntax/15_type.md b/doc/zh_CN/syntax/15_type.md index 76f0cee9..37dd77c6 100644 --- a/doc/zh_CN/syntax/15_type.md +++ b/doc/zh_CN/syntax/15_type.md @@ -1,6 +1,6 @@ -# types +# 类型 -Types are a very important feature in Erg, so we have a [dedicated section](./type/01_type_system.md). Please see there. +类型是 Erg 中一个非常重要的特性,所以我们有一个 [dedicated section](./type/01_type_system.md)。 请看那里。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/16_iterator.md b/doc/zh_CN/syntax/16_iterator.md index 89ab4879..57121153 100644 --- a/doc/zh_CN/syntax/16_iterator.md +++ b/doc/zh_CN/syntax/16_iterator.md @@ -1,24 +1,24 @@ -# Iterator +# 迭代器 -An iterator is an object used to retrieve elements of a container. +迭代器是用于检索容器元素的对象。 ```python for! 0..9, i => print! i ``` -This code prints the numbers 0 through 9. -Each number (=Int object) is assigned to `i` and the following operation (=`print! i``) is executed. This kind of repetitive execution is called __iteration__. +此代码打印数字 0 到 9。 +每个数字(=Int 对象)都分配给`i`,并执行以下操作(=`print!i`)。 这种重复执行称为__iteration__。 -Now let's look at the type signature of the `for!` procedure. +现在让我们看看 `for!` 过程的类型签名。 ```python for!: |T: Type, I <: Iterable T| (I, T => None) => None ``` -The first argument seems to accept an object of type `Iterable`. +第一个参数似乎接受“Iterable”类型的对象。 -`Iterable` is a type with `.Iterator` attribute, `.iter` method in the request method. +`Iterable` 是一个具有`.Iterator` 属性的类型,`.iter` 方法在request 方法中。 ```python Iterable T = Trait { @@ -27,7 +27,7 @@ Iterable T = Trait { } ``` -The type `{Iterator}` of the `.Iterator` attribute is so-called set-kind (kind is described [here](./type/advanced/kind.md)). +`.Iterator` 属性的类型 `{Iterator}` 是所谓的 set-kind(kind 在 [here](./type/advanced/kind.md) 中描述) ```python assert [1, 2, 3] in Iterable(Int) @@ -35,13 +35,13 @@ assert 1..3 in Iterable(Int) assert [1, 2, 3].Iterator == ArrayIterator assert (1..3).Iterator == RangeIterator -log [1, 2, 3].iter() # +log [1, 2, 3].iter() # <数组迭代器对象> +log (1..3).iter() # ``` -Both `ArrayIterator` and `RangeIterator` are classes that implement `Iterator` and exist only to give `Array` and `Range` iteration functions. -Such a design pattern is called companion class [1](#1). -And the `IteratorImpl` patch is the core of the iteration functionality. `Iterator` requires only one `.next` method, `IteratorImpl` provides dozens of 方法 indeed. `ArrayIterator` and `RangeIterator` can use the implementation method of `IteratorImpl` just by implementing the `.next` method. For this convenience, the standard library implements a number of iterators. +`ArrayIterator` 和 `RangeIterator` 都是实现 `Iterator` 的类,它们的存在只是为了提供 `Array` 和 `Range` 迭代函数。 +这种设计模式称为伴生类 [1](#1)。 +而“IteratorImpl”补丁是迭代功能的核心。 `Iterator` 只需要一个`.next` 方法,`IteratorImpl` 确实提供了几十种方法。 `ArrayIterator`和`RangeIterator`只需实现`.next`方法就可以使用`IteratorImpl`的实现方法。 为了方便起见,标准库实现了许多迭代器。 ```mermaid classDiagram @@ -78,11 +78,11 @@ classDiagram Range <-- RangeIterator ``` -Types such as `Iterable` that provide an interface for handling traits (in this case `Iterator`) in a static dispatch yet unified manner are called companion class adapters. +诸如 `Iterable` 之类的以静态分派但统一的方式提供用于处理特征(在本例中为 `Iterator`)的接口的类型称为伴生类适配器。 --- -1 There doesn't seem to be a uniform name for this pattern, but in Rust, there is [companion struct pattern]( https://gist.github.com/qnighy/be99c2ece6f3f4b1248608a04e104b38#:~:text=%E3%82%8F%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8B%E3%80%82-,companion%20struct,-%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%A8%E3%80%81%E3 %81%9D%E3%81%AE), and was named after it. [↩](#f1) +1 这个模式似乎没有统一的名称,但是在 Rust 中,有 [companion struct 模式]( https://gist.github.com/qnighy/be99c2ece6f3f4b1248608a04e104b38#:~:text=%E3%82%8F%E3%82%8C%E3%81%A6%E3%81%84%E3%82 %8B%E3%80%82-,companion%20struct,-%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%A8%E3%80% 81%E3 %81%9D%E3%81%AE),并以此命名。 [↩](#f1)

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/17_mutability.md b/doc/zh_CN/syntax/17_mutability.md index f61711b9..7dff9f30 100644 --- a/doc/zh_CN/syntax/17_mutability.md +++ b/doc/zh_CN/syntax/17_mutability.md @@ -1,7 +1,7 @@ -# Mutability +# 可变性 -As we have already seen, all Erg variables are immutable. However, Erg objects have the concept of mutability. -Take the following code as an example. +正如我们已经看到的,所有 Erg 变量都是不可变的。 但是,Erg 对象具有可变性的概念。 +以下面的代码为例。 ```python a = [1, 2, 3] @@ -9,9 +9,9 @@ a = a + [4, 5, 6] print! a # [1, 2, 3, 4, 5, 6] ``` -The above code cannot actually be executed by Erg. This is because it is not reassignable. +上面的代码实际上不能被 Erg 执行。 这是因为它不可重新分配。 -This code can be executed. +可以执行此代码。 ```python b = ![1, 2, 3] @@ -19,8 +19,8 @@ b.concat! [4, 5, 6] print! b # [1, 2, 3, 4, 5, 6] ``` -The final result of `a, b` looks the same, but their meanings are very different. -Although `a` is a variable that represents an array of `Nat`, the objects pointed to in the first and second lines are different. The name `a` is the same, but the contents are different. +`a, b` 的最终结果看起来一样,但它们的含义却大不相同。 +虽然 `a` 是表示 `Nat` 数组的变量,但第一行和第二行指向的对象是不同的。 名称`a`相同,但内容不同。 ```python a = [1, 2, 3] @@ -29,9 +29,9 @@ _a = a + [4, 5, 6] print! id! _a # 0x000002A798DFE980 ``` -The `id!` procedure returns the address in memory where the object resides. +`id!` 过程返回对象驻留的内存地址。 -`b` is a `Nat` "dynamic" array. The content of the object changes, but the variables point to the same thing. +`b` 是一个 `Nat` “动态” 数组。 对象的内容发生了变化,但变量指向的是同一个东西 ```python b = ![1, 2, 3] @@ -48,13 +48,13 @@ if! True. do! print! i # 1 ``` -`!` is a special operator called the __mutation operator__. It makes immutable objects mutable. -The behavior of objects marked with `!` can be customized. +`!` 是一个特殊的运算符,称为 __mutation 运算符__。 它使不可变对象可变。 +标有“!”的对象的行为可以自定义。 ```python Point = Class {.x = Int; .y = Int} -# In this case .x is made mutable and .y remains immutable +# 在这种情况下 .x 是可变的,而 .y 保持不变 Point! = Class {.x = Int!; .y = Int} Point!. inc_x! ref!(self) = self.x.update! x -> x + 1 @@ -64,10 +64,10 @@ p.inc_x!() print! p.x # 1 ``` -## Constant +## 常量 -Unlike variables, constants point to the same thing in all scopes. -Constants are declared with the `=` operator. +与变量不同,常量在所有范围内都指向同一事物。 +常量使用 `=` 运算符声明。 ```python PI = 3.141592653589 @@ -75,28 +75,28 @@ match! x: PI => print! "this is pi" ``` -Constants are identical in all scopes below the global and cannot be overwritten. Therefore, they cannot be redefined by ``=``. This restriction allows it to be used in pattern matching. -The reason why `True` and `False` can be used in pattern matching is because they are constants. -Also, constants always point to immutable objects. Types such as `Str!` cannot be constants. -All built-in types are constants because they should be determined at compile time. Types that are not constants can be generated, but they cannot be used to specify a type and can only be used like a simple record. Conversely, a type is a record whose contents are determined at compile time. +常量在全局以下的所有范围内都是相同的,并且不能被覆盖。因此,它们不能被 ``=`` 重新定义。此限制允许它用于模式匹配。 +`True` 和 `False` 可以用于模式匹配的原因是因为它们是常量。 +此外,常量总是指向不可变对象。诸如 `Str!` 之类的类型不能是常量。 +所有内置类型都是常量,因为它们应该在编译时确定。可以生成非常量的类型,但不能用于指定类型,只能像简单记录一样使用。相反,类型是其内容在编译时确定的记录。 -## Variable, Name, Identifier, Symbol +## 变量、名称、标识符、符号 -Let's clear up a few terms related to variables in Erg. +让我们理清一些与 Erg 中的变量相关的术语。 -A Variable is a mechanism to give an object a Name so that it can be reused (or point to that Name). -Identifier is a grammar element that specifies a variable. -A symbol is a grammatical element, a token, that represents a name. +变量是一种为对象赋予名称以便可以重用(或指向该名称)的机制。 +标识符是指定变量的语法元素。 +符号是表示名称的语法元素、记号。 -Only non-symbolic characters are symbols, and symbols are not called symbols, although they can be identifiers as operators. -For example, `x` is an identifier and a symbol. `x.y` is also an identifier, but it is not a symbol. `x` and `y` are symbols. -And even if `x` were not tied to any object, `x` would still be a Symbol and an Identifier, but it would not be called a Variable. -Identifiers of the form `x.y` are called Field Accessors. -Identifiers of the form `x[y]` are called Subscript Accessors. +只有非符号字符是符号,符号不称为符号,尽管它们可以作为运算符的标识符。 +例如,`x` 是一个标识符和一个符号。 `x.y` 也是一个标识符,但它不是一个符号。 `x` 和 `y` 是符号。 +即使 `x` 没有绑定到任何对象,`x` 仍然是一个符号和一个标识符,但它不会被称为变量。 +`x.y` 形式的标识符称为字段访问器。 +`x[y]` 形式的标识符称为下标访问器。 -The difference between a variable and an identifier is that if we are talking about a variable in the sense of Erg's grammatical theory, the two are in effect the same. -In C, types and functions cannot be assigned to variables; int and main are identifiers, but not variables (strictly speaking, they can be assigned, but there are restrictions). -However, in Erg, "everything is an object". Not only functions and types, but even operators can be assigned to variables. +变量和标识符之间的区别在于,如果我们在 Erg 的语法理论意义上谈论变量,则两者实际上是相同的。 +在 C 中,类型和函数不能分配给变量; int 和 main 是标识符,而不是变量(严格来说可以赋值,但有限制)。 +然而,在尔格语中,“一切都是对象”。不仅函数和类型,甚至运算符都可以分配给变量。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/18_ownership.md b/doc/zh_CN/syntax/18_ownership.md index 492fa6bd..6f432ae4 100644 --- a/doc/zh_CN/syntax/18_ownership.md +++ b/doc/zh_CN/syntax/18_ownership.md @@ -1,13 +1,13 @@ -# Ownership system +#所有权制度 -Since Erg is a language that uses Python as the host language, the method of memory management depends on the Python implementation. -But semantically Erg's memory management is different from Python's. A notable difference is in the ownership system and the prohibition of circular references. +由于 Erg 是一种使用 Python 作为宿主语言的语言,因此内存管理的方法取决于 Python 的实现。 +但语义上 Erg 的内存管理与 Python 的不同。 一个显着的区别在于所有权制度和禁止循环引用。 -## Ownership +## 所有权 -Erg has an ownership system inspired by Rust. -Rust's ownership system is generally considered esoteric, but Erg's is simplified to be intuitive. -In Erg, __mutable objects__ are owned and cannot be referenced after ownership is lost. +Erg 有一个受 Rust 启发的所有权系统。 +Rust 的所有权系统通常被认为是深奥的,但 Erg 的所有权系统被简化为直观。 +在 Erg 中,__mutable objects__ 是拥有的,并且在所有权丢失后无法引用。 ```python v = [1, 2, 3].into [Int; !3] @@ -16,23 +16,23 @@ push! vec, x = vec.push!(x) vec -# The contents of v ([1, 2, 3]) are owned by w +# v ([1, 2, 3])的内容归w所有 w = push! v, 4 -print! v # error: v was moved +print! v # 错误:v 被移动了 print!w # [1, 2, 3, 4] ``` -Ownership transfer occurs, for example, when an object is passed to a subroutine. -If you want to still have ownership after giving it away, you'll need to clone, freeze, or borrow. -However, as will be explained later, there are limited situations in which it can be borrowed. +例如,当一个对象被传递给一个子程序时,就会发生所有权转移。 +如果您想在赠送后仍然拥有所有权,则需要克隆、冻结或借用。 +但是,如后所述,可以借用的情况有限。 -## replication +## 复制 -Duplicate an object and transfer its ownership. It does this by applying the `.clone` method to the actual arguments. -The duplicated object is exactly the same as the original, but independent of each other and unaffected by changes. +复制一个对象并转移其所有权。 它通过将 `.clone` 方法应用于实际参数来做到这一点。 +复制的对象与原始对象完全相同,但相互独立,不受更改影响。 -Duplication is equivalent to Python's deep copy, and since it recreates the same object entirely, the computation and memory costs are generally higher than freezing and borrowing. -A subroutine that needs to duplicate an object is said to be an "argument consuming" subroutine. +复制相当于 Python 的深拷贝,由于它完全重新创建相同的对象,因此计算和内存成本通常高于冻结和借用。 +需要复制对象的子例程被称为“参数消耗”子例程。 ```python capitalize s: Str!= @@ -44,30 +44,30 @@ s2 = capitalize s1.clone() log s2, s1 # !"HELLO hello" ``` -## freeze +## 冻结 -We take advantage of the fact that immutable objects can be referenced from multiple places and convert mutable objects to immutable objects. -This is called freezing. Freezing is used, for example, when creating an iterator from a mutable array. -Since you can't create an iterator directly from a mutable array, convert it to an immutable array. -If you don't want to destroy the array, use the [`.freeze_map` method](./type/mut.md). +我们利用了不可变对象可以从多个位置引用的事实,并将可变对象转换为不可变对象。 +这称为冻结。 例如,在从可变数组创建迭代器时会使用冻结。 +由于您不能直接从可变数组创建迭代器,请将其转换为不可变数组。 +如果您不想破坏数组,请使用 [`.freeze_map` 方法](./type/mut.md)。 ```python -# Compute the sum of the values ​​produced by the iterator +# 计算迭代器产生的值的总和 sum|T <: Add + HasUnit| i: Iterator T = ... x = [1, 2, 3].into [Int; !3] x.push!(4) -i = x.iter() # TypeError: [Int; !4] has no method `iter` +i = x.iter() # 类型错误:[Int; !4] 没有方法 `iter` y = x.freeze() i = y.iter() assert sum(i) == 10 -y # y can still be touched +y # y 仍然可以被触摸 ``` -## borrow +## 借 -Borrowing is cheaper than duplicating or freezing. -Borrowing can be done in the following simple cases: +借用比复制或冻结便宜。 +可以在以下简单情况下进行借款: ```python peek_str ref(s: Str!) = @@ -77,33 +77,33 @@ s = !"hello" peek_str s ``` -A borrowed value is called a __reference__ to the original object. -You can "sublease" the reference to another subroutine, but you cannot consume it because you are only borrowing it. +借来的值称为原始对象的 __reference__。 +您可以“转租”对另一个子例程的引用,但您不能使用它,因为您只是借用它。 ```python steal_str ref(s: Str!) = - # Since the log function only borrows the arguments, it can be sub-leased + # 由于日志函数只借用参数,所以可以转租 log s - # error because the discard function consumes arguments - discard s # OwnershipError: cannot consume a borrowed value - # hint: use `clone` method + # 错误,因为丢弃函数消耗了参数 + discard s # OwnershipError: 不能消费借来的值 + # 提示:使用 `clone` 方法 ``` ```python steal_str ref(s: Str!) = - # This is no good either (= consumes the right side) - x = s # OwnershipError: cannot consume a borrowed value + # 这也不好(=消耗右边) + x = s # OwnershipError: 不能消费借来的值 x ``` -Erg's references are more restrictive than Rust's. References are first-class objects in the language, but cannot be created explicitly, they can only be specified as argument passing via `ref`/`ref!`. -This means that you cannot stuff references into arrays or create classes with references as attributes. +Erg 的引用比 Rust 的更严格。 引用是语言中的一等对象,但不能显式创建,它们只能指定为通过 `ref`/`ref!` 传递的参数。 +这意味着您不能将引用填充到数组中或创建将引用作为属性的类。 -However, such restrictions are a natural specification in languages ​​without references in the first place, and they are not so inconvenient. +但是,这样的限制是语言中的自然规范,一开始就没有引用,而且它们并没有那么不方便。 -## circular references +## 循环引用 -Erg is designed to prevent unintentional memory leaks, and will issue an error if the memory checker detects a circular reference. In most cases, this error can be resolved with a weak reference `Weak`. However, since it is not possible to generate objects with circular structures such as cyclic graphs, we plan to implement an API that can generate circular references as unsafe operations. +Erg 旨在防止无意的内存泄漏,如果内存检查器检测到循环引用,则会发出错误。 在大多数情况下,这个错误可以通过弱引用 `Weak` 来解决。 但是,由于无法生成循环图等具有循环结构的对象,因此我们计划实现一个 API,可以将循环引用作为不安全操作生成。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/19_visibility.md b/doc/zh_CN/syntax/19_visibility.md index d03d4caf..d0af6a68 100644 --- a/doc/zh_CN/syntax/19_visibility.md +++ b/doc/zh_CN/syntax/19_visibility.md @@ -1,8 +1,8 @@ -# Visibility +# 可见性 -Erg variables have the concept of __visibility__. -All the variables we've seen so far are called __private variables__. This is an externally invisible variable. -For example, a private variable defined in the `foo` module cannot be referenced by another module. +Erg 变量具有 __visibility__ 的概念。 +到目前为止,我们看到的所有变量都称为 __private variables__。 这是一个外部不可见的变量。 +例如,`foo` 模块中定义的私有变量不能被另一个模块引用。 ```python # foo.er @@ -12,11 +12,11 @@ x = "this is an invisible variable" ```python #bar.er foo = import "foo" -foo.x # AttributeError: Module 'foo' has no attribute 'x' ('x' is private) +foo.x # AttributeError: 模块 'foo' 没有属性 'x' ('x' 是私有的) ``` -On the other hand, there are also __public variables__, which can be referenced from the outside. -Public variables are defined with `.`. +另一方面,也有__public variables__,可以从外部引用。 +公共变量用`.`定义。 ```python # foo.er @@ -29,7 +29,7 @@ foo = import "foo" assert foo.x == "this is a visible variable" ``` -You don't need to add anything to private variables, but you can also add `::` or `self::` (`Self::` for types etc.) to indicate that they are private. increase. It can also be `module::` if it is a module. +您不需要向私有变量添加任何内容,但您也可以添加 `::` 或 `self::`(用于类型等的`Self::`)以表明它们是私有的。 增加。 如果它是一个模块,它也可以是 `module::` ```python ::x = "this is an invisible variable" @@ -43,12 +43,12 @@ In the context of purely sequential execution, private variables are almost syno ```python ::x = "this is a private variable" y = - x + 1 # exactly module::x + x + 1 # 完全是 module::x ``` -By using `::`, you can distinguish variables with the same name within the scope. -Specify the scope of the variable you want to refer to on the left. Specify `module` for the top level. -If not specified, the innermost variable is referenced as usual. +通过使用`::`,可以区分作用域内同名的变量。 +在左侧指定要引用的变量的范围。 为顶层指定 `module`。 +如果未指定,则照常引用最里面的变量。 ```python ::x = 0 @@ -64,7 +64,7 @@ y = assert module::x == 0 ``` -In the anonymous subroutine scope, `self` specifies its own scope. +在匿名子程序作用域中,`self` 指定了它自己的作用域 ```python x = 0 @@ -73,21 +73,21 @@ f = x -> f1# 0 1 ``` -`::` is also responsible for accessing private instance attributes. +`::` 还负责访问私有实例属性。 ```python x = 0 C = Class {x = Int} C. - # Top-level x is referenced (warning to use module::x) + # 顶级 x 被引用(警告使用 module::x) f1 self = x - # instance attribute x is referenced + # 实例属性 x 被引用 f2 self = self::x ``` -## Visibility in external modules +## 外部模块中的可见性 -A class defined in one module can actually define 方法 from an external module. +在一个模块中定义的类实际上可以定义来自外部模块的方法。 ```python # foo.er @@ -106,35 +106,35 @@ Foo. .f() = foo = Foo.new() foo.public() - foo::private() # AttributeError + foo::private() # 属性错误 ``` -However, both of those 方法 are only available within that module. -Private 方法 defined externally are visible to 方法 of the `Foo` class only within the defining module. -Public 方法 are exposed outside the class, but not outside the module. +但是,这两种方法都只在该模块中可用。 +外部定义的私有方法对 Foo 类的方法仅在定义模块内可见。 +公共方法暴露在类之外,但不在模块之外。 ```python # baz.er {Foo; ...} = import "foo" foo = Foo.new() -foo.public() # AttributeError: 'Foo' has no attribute 'public' ('public' is defined in module 'bar') +foo.public() # 属性错误:“Foo”没有属性“public”(“public”在模块“bar”中定义) ``` -Also, 方法 cannot be defined in the type to be re-exported. -This is to avoid confusion about 方法 being found or not found depending on the module they are imported from. +此外,方法不能在要重新导出的类型中定义。 +这是为了避免混淆方法是否找到,具体取决于导入方法的模块。 ```python #bar.er {.Foo; ...} = import "foo" .Foo:: - private self = pass # Error + private self = pass # 错误 Foo. - public self = self::private() # Error + public self = self::private() # 错误 ``` -If you want to do something like this, define a [patch](./type/07_patch.md). +如果你想做这样的事情,定义一个 [patch](./type/07_patch.md)。 ```python #bar.er @@ -156,10 +156,10 @@ foo = Foo.new() foo.public() ``` -## restricted public variables +## 受限公共变量 -Variable visibility is not limited to complete public/private. -You can also publish with restrictions. +可变可见性不限于完全公共/私有。 +您也可以有限制地发布。 ```python # foo.er @@ -174,15 +174,15 @@ You can also publish with restrictions. _ = .a.z # OK } -_ = .record.a.x # VisibilityError +_ = .record.a.x # 可见性错误 _ = .record.a.y # OK _ = .record.a.z # OK ``` ```python foo = import "foo" -_ = foo.record.a.x # VisibilityError -_ = foo.record.a.y # VisibilityError +_ = foo.record.a.x # 可见性错误 +_ = foo.record.a.y # 可见性错误 _ = foo.record.a.z # OK ``` diff --git a/doc/zh_CN/syntax/20_naming_rule.md b/doc/zh_CN/syntax/20_naming_rule.md index 89117377..221c7a4c 100644 --- a/doc/zh_CN/syntax/20_naming_rule.md +++ b/doc/zh_CN/syntax/20_naming_rule.md @@ -1,6 +1,6 @@ -# Naming convention +# 命名约定 -If you want to use a variable as a constant expression, make sure it starts with a capital letter. Two or more letters may be lowercase. +如果要将变量用作常量表达式,请确保它以大写字母开头。 两个或多个字母可能是小写的。 ```python i: Option Type = Int @@ -9,36 +9,36 @@ match i: None -> log "None" ``` -Objects with side effects always end with `!`. Procedures and procedural 方法, and mutable types. -However, the `Proc` type itself is not mutable. +具有副作用的对象总是以 `!` 结尾。 程序和程序方法,以及可变类型。 +然而,`Proc` 类型本身是不可变的。 ```python # Callable == Func or Proc c: Callable = print! match c: - p! -> log "proc" # `: Proc` can be omitted since it is self-explanatory + p! -> log "proc" # `: Proc` 可以省略,因为它是不言自明的 f -> log "func" ``` -If you want to expose an attribute to the outside world, define it with `.` at the beginning. If you don't put `.` at the beginning, it will be private. To avoid confusion, they cannot coexist within the same scope. +如果您想向外界公开一个属性,请在开头使用 `.` 定义它。 如果你不把`.`放在开头,它将是私有的。 为避免混淆,它们不能在同一范围内共存。 ```python -o = {x = 1; .x = 2} # SyntaxError: private and public variables with the same name cannot coexist +o = {x = 1; .x = 2} # 语法错误:同名的私有变量和公共变量不能共存 ``` -## Literal Identifiers +## 文字标识符 -The above rule can be circumvented by enclosing the string in single quotes (''). That is, procedural objects can also be assigned without `!`. However, in this case, even if the value is a constant expression, it is not considered a constant. -A character string enclosed in single quotes like this is called a literal identifier. -This is used when calling APIs (FFI) of other languages ​​such as Python. +可以通过将字符串括在单引号 ('') 中来规避上述规则。 也就是说,程序对象也可以在没有 `!` 的情况下分配。 但是,在这种情况下,即使该值是常量表达式,也不会被视为常量。 +像这样用单引号括起来的字符串称为文字标识符。 +这在调用Python等其他语言的API(FFI)时使用。 ```python bar! = pyimport("foo").'bar' ``` -Identifiers that are also valid in Erg do not need to be enclosed in ''. +在 Erg 中也有效的标识符不需要用 '' 括起来。 -Furthermore, literal identifiers can contain both symbols and spaces, so strings that cannot normally be used as identifiers can be used as identifiers. +此外,文字标识符可以包含符号和空格,因此通常不能用作标识符的字符串可以用作标识符。 ```python '∂/∂t' y diff --git a/doc/zh_CN/syntax/21_lambda.md b/doc/zh_CN/syntax/21_lambda.md index 94aeb3a4..8cac3bea 100644 --- a/doc/zh_CN/syntax/21_lambda.md +++ b/doc/zh_CN/syntax/21_lambda.md @@ -1,50 +1,50 @@ -# anonymous function +# 匿名函数 -Anonymous functions are a syntax for creating function objects on the fly without naming them. +匿名函数是一种无需命名即可动态创建函数对象的语法。 ```python -# `->` is an anonymous function operator -# same as `f x, y = x + y` +# `->` 是匿名函数操作符 +# 同 `f x, y = x + y` f = (x, y) -> x + y # same as `g(x, y: Int): Int = x + y` g = (x, y: Int): Int -> x + y ``` -You can omit the `()` if there is only one argument. +如果只有一个参数,您可以省略 `()`。 ```python assert [1, 2, 3].map_collect(i -> i + 1) == [2, 3, 4] assert ((i, j) -> [i, j])(1, 2) == [1, 2] ``` -In the case below it is `0..9, (i -> ...)` and not `(0..9, i) -> ...`. -`->` takes only one argument on the left side. Multiple arguments are received as a single tuple. +在下面的情况下,它是 `0..9, (i -> ...)` 而不是 `(0..9, i) -> ...` +`->` 在左侧只接受一个参数。 多个参数作为单个元组接收 ```python for 0..9, i: Int -> ... ``` -In anonymous functions, there is a difference in parsing due to whitespace. +在匿名函数中,由于空格,解析存在差异 ```python -# In this case, interpreted as `T(() -> Int)` +# 在这种情况下,解释为 `T(() -> Int)` i: T() -> Int -# in this case it is interpreted as (U()) -> Int +# 在这种情况下,它被解释为 (U()) -> Int k: U() -> Int ``` -Anonymous functions can be used without arguments. +匿名函数可以不带参数使用。 ```python -# `=>` is an anonymous procedure operator -p! = () => print! "`p!` was called" -# `() ->`, `() =>` have syntax sugar `do`, `do!` -# p! = do! print! "`p!` was called" -p!() # `p!` was called +# `=>` 是一个匿名过程操作符 +p! = () => print! # `p!` 被调用 +# `() ->`, `() =>` 有语法糖 `do`, `do!` +# p! = do! print! "`p!` 被调用 +p!() # `p!` 被调用 ``` -No-argument functions can be used for lazy initialization. +无参数函数可用于延迟初始化 ```python time = import "time" @@ -56,20 +56,21 @@ now = if! True: do date.new("1970", "1", "1", "00", "00") ``` -You can also type and pattern match. Because of this, the `match` function is mostly implemented with the power of anonymous functions. -Anonymous functions given as arguments to the `match` function are tried in order from the top. So, you should describe the special cases at the top and the more general cases at the bottom. If you get the order wrong, the compiler will issue a warning (if possible). +您还可以键入和模式匹配。 正因为如此,`match` 函数大多是借助匿名函数的力量来实现的。 +作为 `match` 函数的参数给出的匿名函数从顶部开始按顺序尝试。 因此,您应该在顶部描述特殊情况,在底部描述更一般的情况。 如果你弄错了顺序,编译器会发出警告(如果可能的话) + ```python n = (Complex or Ratio or Int).sample!() i = matchn: - PI -> PI # if equal to constant PI - For (i: 1..10) -> i # Int from 1 to 10 + PI -> PI # 如果等于常数 PI + For (i: 1..10) -> i # 整数从 1 到 10 (i: Int) -> i # Int - (c: Complex) -> c.real() # For Complex. Int < Complex, but can fallback - _ -> panic "cannot convert to Int" # If none of the above apply. match must cover all patterns + (c: Complex) -> c.real() # 对于复杂。 Int < Complex,但可以回退 + _ -> panic "cannot convert to Int" # 如果以上都不适用。 match 必须涵盖所有模式 ``` -Error handling is also generally done using `?` or `match`. +错误处理通常也使用 `?` 或 `match` 完成。 ```python res: ParseResult Int @@ -83,10 +84,10 @@ match res2: err: Error -> panic err.msg ``` -## Anonymous polycorrelation coefficient +## 匿名多相关系数 ```python -# same as id|T| x: T = x +# 与此相同 id|T|x:T = x id = |T| x: T -> x ``` diff --git a/doc/zh_CN/syntax/22_subroutine.md b/doc/zh_CN/syntax/22_subroutine.md index 2371fd32..78728e20 100644 --- a/doc/zh_CN/syntax/22_subroutine.md +++ b/doc/zh_CN/syntax/22_subroutine.md @@ -1,55 +1,55 @@ -# Subroutine Signatures +# 子程序签名 -## Func +## 函数 ```python some_func(x: T, y: U) -> V some_func: (T, U) -> V ``` -## Proc +## 过程 ```python some_proc!(x: T, y: U) => V some_proc!: (T, U) => V ``` -## Func Method +## 函数方法 -The method type cannot be specified externally with ``Self``. +方法类型不能用`Self`在外部指定 ```python .some_method(self, x: T, y: U) => () -# Self.(T, U) => () takes ownership of self +# Self.(T, U) => () 拥有 self 的所有权 .some_method: Ref(Self). (T, U) => () ``` -## Proc Method (dependent) +## 过程方法(依赖) -In the following, assume that the type `T!` takes the type argument `N: Nat`. To specify it externally, use a type variable. +在下文中,假设类型 `T!` 采用类型参数 `N: Nat`。 要在外部指定它,请使用类型变量 ```python T!: Nat -> Type -# ~> indicates the state of the type argument before and after application (in this case, self must be a variable reference) +# ~> 表示应用前后类型参数的状态(此时self必须是变量引用) T!(N).some_method!: (Ref! T!(N ~> N+X), X: Nat) => () ``` -As a note, the type of `.some_method` is `Ref!(T(N ~> N+X)). ({X}) => () | N, X: Nat`. -For 方法 that do not have `ref!`, i.e., are deprived of ownership after application, the type argument transition (`~>`) cannot be used. +注意,`.some_method` 的类型是 `Ref!(T(N ~> N+X))。 ({X}) => () | N,X:Nat`。 +对于没有 `ref!` 的方法,即在应用后被剥夺所有权,不能使用类型参数转换(`~>`)。 -If ownership is taken, it is as follows. +如果取得所有权,则如下所示。 ```python -# If you don't use N, you can omit it with _. +# 如果不使用N,可以用_省略。 # .some_method!: |N, X: Nat| T!(N).({X}) => T!(N+X) .some_method!|N, X: Nat|(self(N), X: Nat) => T!(N+X) ``` -## Operator +## 运算符 -It can be defined as a normal function by enclosing it with ``. +可以通过用 ` 括起来将其定义为普通函数。 -Neuter alphabetic operators such as `and` and `or` can be defined as neuter operators by enclosing them with ``. +中性字母运算符,例如 `and` 和 `or` 可以通过用 ` 括起来定义为中性运算符。 ```python and(x, y, z) = x and y and z diff --git a/doc/zh_CN/syntax/23_closure.md b/doc/zh_CN/syntax/23_closure.md index 151fa2cb..eb3122ac 100644 --- a/doc/zh_CN/syntax/23_closure.md +++ b/doc/zh_CN/syntax/23_closure.md @@ -1,6 +1,6 @@ -# Closure +# 关闭 -Erg subroutines have a feature called a "closure" that captures external variables. +Erg 子例程有一个称为“闭包”的功能,可以捕获外部变量。 ```python outer = 1 @@ -8,7 +8,7 @@ f x = outer + x assert f(1) == 2 ``` -As with immutable objects, mutable objects can also be captured. +与不可变对象一样,可变对象也可以被捕获。 ```python sum = !0 @@ -22,11 +22,11 @@ p!(1) assert sum == 46 ``` -Note, however, that functions cannot capture mutable objects. -If a mutable object can be referenced in a function, you can write code like the following. +但是请注意,函数不能捕获可变对象。 +如果可以在函数中引用可变对象,则可以编写如下代码。 ```python -# !!! This code actually gives an error !!! +# !!! 这段代码实际上给出了一个错误!!! i = !0 f x = i + x assert f 1 == 1 @@ -34,10 +34,10 @@ i.add! 1 assert f 1 == 2 ``` -The function should return the same value for the same arguments, but the assumption is broken. -Note that `i` is evaluated only at call time. +该函数应该为相同的参数返回相同的值,但假设被打破了。 +请注意,`i` 仅在调用时进行评估。 -Call `.clone` if you want the contents of the mutable object at the time the function was defined. +如果您想在定义函数时获取可变对象的内容,请调用`.clone` ```python i = !0 @@ -58,7 +58,7 @@ for! 1..10, i => assert sum == 45 ``` -The equivalent program above can be written in Python as follows: +上面的等效程序可以用 Python 编写如下: ```python # Python @@ -68,28 +68,28 @@ for i in range(1, 10): assert sum == 45 ``` -However, Erg recommends a simpler notation. -Instead of carrying around state using subroutines and mutable objects, use a style of localizing state using functions. This is called functional programming. +但是,Erg 建议使用更简单的表示法。 +与其使用子例程和可变对象来传递状态,不如使用一种使用函数来定位状态的风格。这称为函数式编程 ```python -# Functional style +# 功能风格 sum = (1..10).sum() assert sum == 45 ``` -The code above gives exactly the same result as before, but you can see that this one is much simpler. +上面的代码给出了与之前完全相同的结果,但是您可以看到这个代码要简单得多。 -The `fold` function can be used to do more than sum. -`fold` is an iterator method that executes the argument `f` for each iteration. -The initial value of the counter that accumulates results is specified in `init` and accumulated in `acc`. +`fold` 函数可以用来做比 sum 更多的事情。 +`fold` 是一个迭代器方法,它为每次迭代执行参数 `f`。 +累加结果的计数器的初始值在 `init` 中指定,并在 `acc` 中累加。 ```python -# start with 0, result will +# 从0开始,结果会 sum = (1..10).fold(init: 0, f: (acc, i) -> acc + i) assert sum == 45 ``` -Erg is designed to be a natural succinct description of programming with immutable objects. +Erg 被设计为对使用不可变对象进行编程的自然简洁描述。

上一页 | 下一页 diff --git a/doc/zh_CN/syntax/24_module.md b/doc/zh_CN/syntax/24_module.md index 63c58bf3..eee8832e 100644 --- a/doc/zh_CN/syntax/24_module.md +++ b/doc/zh_CN/syntax/24_module.md @@ -8,7 +8,7 @@ Erg allows you to think of the file itself as a single record. This is called a ``` ```python -# 定义ining the foo module is almost the same as defining this record +# 定义 foo 模块与定义这条记录几乎相同 foo = {.i = 1} ``` @@ -19,13 +19,13 @@ print! foo # assert foo.i == 1 ``` -Since module types are also record types, deconstruction assignment is possible. +由于模块类型也是记录类型,因此可以进行解构赋值 ```python {sin; cos; ...} = import "math" ``` -## module visibility +## 模块可见性 ```console └─┬ ./src diff --git a/doc/zh_CN/syntax/25_object_system.md b/doc/zh_CN/syntax/25_object_system.md index bed6a89d..ffb97156 100644 --- a/doc/zh_CN/syntax/25_object_system.md +++ b/doc/zh_CN/syntax/25_object_system.md @@ -1,19 +1,19 @@ -# Object +# 目的 -All data that can be assigned to a variable. The attributes of the `Object` class are as follows. +可以分配给变量的所有数据。 `Object` 类的属性如下。 -* `.__repr__`: Returns a (non-rich) string representation of the object -* `.__sizeof__`: Returns the size of the object (including heap allocation) -* `.__dir__`: Returns a list of object attributes -* `.__hash__`: returns the hash value of the object -* `.__getattribute__`: Get and return an attribute of an object -* `.clone`: Creates and returns a clone of an object (with an independent entity in memory) -* `.copy`: Returns a copy of the object (pointing to the same thing in memory) +* `.__repr__`:返回对象的(非丰富)字符串表示 +* `.__sizeof__`:返回对象的大小(包括堆分配) +* `.__dir__`: 返回对象属性列表 +* `.__hash__`:返回对象的哈希值 +* `.__getattribute__`: 获取并返回对象的属性 +* `.clone`:创建并返回一个对象的克隆(在内存中有一个独立的实体) +* `.copy`:返回对象的副本(指向内存中的同一事物) -## Record +## 记录 -An object generated by a record literal (`{attr = value; ...}`). -This object has basic 方法 such as `.clone` and `.__sizeof__`. +由记录文字(`{attr = value; ...}`)生成的对象。 +这个对象有基本的方法,比如`.clone`和`.__sizeof__`。 ```python obj = {.x = 1} @@ -23,59 +23,59 @@ obj2 = {...x; .y = 2} assert obj2.x == 1 and obj2.y == 2 ``` -## Attribute +## 属性 -An object associated with an object. In particular, a subroutine attribute that takes self (`self`) as its implicit first argument is called a method. +与对象关联的对象。 特别是,将 self (`self`) 作为其隐式第一个参数的子例程属性称为方法。 ```python -# note that there is no `.` in private_attr +# 请注意,private_attr 中没有`.` record = {.public_attr = j; private_attr = 2; .method = self -> self.i + 1} record. public_attr == 2 -record.private_attr # AttributeError: private_attr is private +record.private_attr # AttributeError: private_attr 是私有的 assert record.method() == 3 ``` -## Element +## 元素 -An object belonging to a particular type (e.g. `1` is an element of type `Int`). All objects are at least elements of type `{=}`. -Elements of classes are sometimes called instances. +属于特定类型的对象(例如,“1”是“Int”类型的元素)。所有对象至少是`{=}`类型的元素。 +类的元素有时称为实例。 -## Subroutine +## 子程序 -Indicates an object that is an instance of a function or procedure (including 方法). The class representing a subroutine is `Subroutine`. -An object that implements `.__call__` is more commonly called a `Callable`. +表示作为函数或过程(包括方法)实例的对象。代表子程序的类是“子程序”。 +实现 `.__call__` 的对象通常称为 `Callable`。 -## Callable +## 可调用 -An object that implements `.__call__`. It is also the superclass of `Subroutine`. +一个实现`.__call__`的对象。它也是 `Subroutine` 的超类。 -## Type +## 类型 -An object that defines requirement attributes and commonizes objects. -There are two main types: Polymorphic Type and Monomorphic Type. Typical monomorphic types are `Int`, `Str`, etc., and polymorphic types are `Option Int`, `[Int; 3]`, etc. -Furthermore, a type that defines a method that changes the state of an object is called a Mutable type, and it is necessary to add `!` to the variable attribute (e.g. dynamic array: `[T; !_]`) . +定义需求属性并使对象通用化的对象。 +主要有两种类型:多态类型和单态类型。典型的单态类型有`Int`、`Str`等,多态类型有`Option Int`、`[Int; 3]`等 +此外,定义改变对象状态的方法的类型称为 Mutable 类型,需要在变量属性中添加 `!`(例如动态数组:`[T; !_]`)。 -## Class +## 班级 -A type that has `.__new__`, `.__init__` 方法, etc. Implement class-based object orientation. +具有 `.__new__`、`.__init__` 方法等的类型。实现基于类的面向对象。 -## Function +## 功能 -A subroutine that has read permission for external variables (excluding static variables) but does not have read/write permission for external variables. In other words, it has no external side effects. -Erg functions are defined differently than Python's because they do not allow side effects. +对外部变量(不包括静态变量)有读权限但对外部变量没有读/写权限的子程序。换句话说,它没有外部副作用。 +Erg 函数的定义与 Python 的不同,因为它们不允许副作用。 -## Procedure +## 程序 -It has read and `self` permissions for external variables, read/write permissions for static variables, and is allowed to use all subroutines. It can have external side effects. +它对外部变量具有读取和“自我”权限,对静态变量具有读/写权限,并允许使用所有子例程。它可能有外部副作用。 -## Method +## 方法 -A subroutine that implicitly takes `self` as the first argument. It is a different type than a simple function/procedure. +隐式将“self”作为第一个参数的子例程。它与简单的函数/过程是不同的类型。 -## Entity +## 实体 -Objects that are not subroutines and types. -Monomorphic entities (`1`, `"a"`, etc.) are also called value objects, polymorphic entities (`[1, 2, 3], {"a": 1}`) are also called container objects . +不是子例程和类型的对象。 +单态实体(`1`、`"a"` 等)也称为值对象,多态实体(`[1, 2, 3], {"a": 1}`)也称为容器对象。

上一页 | 下一页