diff options
Diffstat (limited to 'zh-cn')
-rw-r--r-- | zh-cn/c-cn.html.markdown | 4 | ||||
-rw-r--r-- | zh-cn/common-lisp-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/elixir-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/erlang-cn.html.markdown | 259 | ||||
-rw-r--r-- | zh-cn/go-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/haskell-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/javascript-cn.html.markdown | 4 | ||||
-rw-r--r-- | zh-cn/json-cn.html.markdown | 51 | ||||
-rw-r--r-- | zh-cn/julia-cn.html.markdown | 729 | ||||
-rw-r--r-- | zh-cn/livescript-cn.html.markdown | 322 | ||||
-rw-r--r-- | zh-cn/lua-cn.html.markdown | 3 | ||||
-rw-r--r-- | zh-cn/markdown-cn.html.markdown | 240 | ||||
-rw-r--r-- | zh-cn/php-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/r-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/ruby-cn.html.markdown | 2 | ||||
-rw-r--r-- | zh-cn/scala-cn.html.markdown | 4 | ||||
-rw-r--r-- | zh-cn/swift-cn.html.markdown | 227 | ||||
-rw-r--r-- | zh-cn/xml-cn.html.markdown | 127 | ||||
-rw-r--r-- | zh-cn/yaml-cn.html.markdown | 136 |
19 files changed, 2106 insertions, 14 deletions
diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index 223f6e35..1e10416e 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -566,7 +566,7 @@ typedef void (*my_fnp_type)(char *); '\'' // 单引号 '\"' // 双引号 '\xhh' // 十六进制数字. 例子: '\xb' = vertical tab -'\ooo' // 十进制数字. 例子: '\013' = vertical tab +'\ooo' // 八进制数字. 例子: '\013' = vertical tab // 打印格式: "%d" // 整数 @@ -579,7 +579,7 @@ typedef void (*my_fnp_type)(char *); "%c" // 字母 "%p" // 指针 "%x" // 十六进制 -"%o" // 十进制 +"%o" // 八进制 "%%" // 打印 % /////////////////////////////////////// diff --git a/zh-cn/common-lisp-cn.html.markdown b/zh-cn/common-lisp-cn.html.markdown index c4dc3274..b82829a9 100644 --- a/zh-cn/common-lisp-cn.html.markdown +++ b/zh-cn/common-lisp-cn.html.markdown @@ -17,7 +17,7 @@ ANSI Common Lisp 是一个广泛通用于各个工业领域的、支持多种范 另外还有一本热门的近期出版的 [Land of Lisp](http://landoflisp.com/). -```scheme +```common-lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; 0. 语法 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown index 7a1ca084..daee8d3c 100644 --- a/zh-cn/elixir-cn.html.markdown +++ b/zh-cn/elixir-cn.html.markdown @@ -8,7 +8,7 @@ filename: learnelixir-cn.ex lang: zh-cn --- -Elixir 是一门构建在Elang VM 之上的函数式编程语言。Elixir 完全兼容 Eralng, +Elixir 是一门构建在Erlang VM 之上的函数式编程语言。Elixir 完全兼容 Erlang, 另外还提供了更标准的语法,特性。 ```elixir diff --git a/zh-cn/erlang-cn.html.markdown b/zh-cn/erlang-cn.html.markdown new file mode 100644 index 00000000..32e84278 --- /dev/null +++ b/zh-cn/erlang-cn.html.markdown @@ -0,0 +1,259 @@ +--- +language: erlang +lang: zh-cn +contributors: + - ["Giovanni Cappellotto", "http://www.focustheweb.com/"] +translators: + - ["Jakukyo Friel", "http://weakish.github.io"] +filename: erlang-cn.erl +--- + +```erlang +% 百分比符号标明注释的开始。 + +%% 两个符号通常用于注释函数。 + +%%% 三个符号通常用于注释模块。 + +% Erlang 里使用三种标点符号: +% 逗号 (`,`) 分隔函数调用中的参数、数据构建和模式。 +% 句号 (`.`) (后跟空格)分隔函数和 shell 中的表达式。 +% 分号 (`;`) 分隔语句。以下环境中使用语句: +% 函数定义和`case`、`if`、`try..catch`、`receive`表达式。 + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 1. 变量和模式匹配 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +Num = 42. % 变量必须以大写字母开头。 + +% Erlang 的变量只能赋值一次。如果给变量赋不同的值,会导致错误: +Num = 43. % ** exception error: no match of right hand side value 43 + +% 大多数语言中`=`表示赋值语句,在Erlang中,则表示模式匹配。 +% `Lhs = Rhs`实际上意味着: +% 演算右边(Rhs), 将结果与左边的模式匹配。 +Num = 7 * 6. + +% 浮点数 +Pi = 3.14159. + +% Atoms 用于表示非数字的常量。 +% Atom 以小写字母开始,包含字母、数字、`_`和`@`。 +Hello = hello. +OtherNode = example@node. + +% Atom 中如果包含特殊字符,可以用单引号括起。 +AtomWithSpace = 'some atom with space'. + +% Erlang 的元组类似 C 的 struct. +Point = {point, 10, 45}. + +% 使用模式匹配操作符`=`获取元组的值。 +{point, X, Y} = Point. % X = 10, Y = 45 + +% 我们可以使用`_`存放我们不感兴趣的变量。 +% `_`被称为匿名变量。和其他变量不同, +% 同一个模式中的多个`_`变量不必绑定到相同的值。 +Person = {person, {name, {first, joe}, {last, armstrong}}, {footsize, 42}}. +{_, {_, {_, Who}, _}, _} = Person. % Who = joe + +% 列表使用方括号,元素间使用逗号分隔。 +% 列表的元素可以是任意类型。 +% 列表的第一个元素称为列表的 head,其余元素称为列表的 tail。 +ThingsToBuy = [{apples, 10}, {pears, 6}, {milk, 3}]. + +% 若`T`是一个列表,那么`[H|T]`同样是一个列表,head为`H`,tail为`T`. +% `|`分隔列表的 head 和 tail. +% `[]`是空列表。 +% 我们可以使用模式匹配操作来抽取列表中的元素。 +% 如果我们有一个非空的列表`L`,那么`[X|Y] = L`则 +% 抽取 L 的 head 至 X,tail 至 Y (X、Y需为未定义的变量)。 +[FirstThing|OtherThingsToBuy] = ThingsToBuy. +% FirstThing = {apples, 10} +% OtherThingsToBuy = {pears, 6}, {milk, 3} + +% Erlang 中的字符串其实是由整数组成的数组。字符串使用双引号。 +Name = "Hello". +[72, 101, 108, 108, 111] = "Hello". + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 2. 循序编程 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Module 是 Erlang 代码的基本单位。我们编写的所有函数都储存在 module 中。 +% Module 存储在后缀为 `.erl` 的文件中。 +% Module 必须事先编译。编译好的 module 以 `.beam` 结尾。 +-module(geometry). +-export([area/1]). % module 对外暴露的函数列表 + +% `area`函数包含两个分句,分句间以分号相隔。 +% 最后一个分句以句号加换行结尾。 +% 每个分句由头、体两部门组成。 +% 头部包含函数名称和用括号括起的模式, +% 体部包含一系列表达式,如果头部的模式和调用时的参数匹配,这些表达式会被演算。 +% 模式匹配依照定义时的顺序依次进行。 +area({rectangle, Width, Ht}) -> Width * Ht; +area({circle, R}) -> 3.14159 * R * R. + +% 编译文件为 geometry.erl. +c(geometry). % {ok,geometry} + +% 调用函数时必须使用 module 名和函数名。 +geometry:area({rectangle, 10, 5}). % 50 +geometry:area({circle, 1.4}). % 6.15752 + +% 在 Erlang 中,同一模块中,参数数目不同,名字相同的函数是完全不同的函数。 +-module(lib_misc). +-export([sum/1]). % 对外暴露的`sum`函数接受一个参数:由整数组成的列表。 +sum(L) -> sum(L, 0). +sum([], N) -> N; +sum([H|T], N) -> sum(T, H+N). + +% fun 是匿名函数。它们没有名字,不过可以赋值给变量。 +Double = fun(X) -> 2*X end. % `Double` 指向匿名函数 #Fun<erl_eval.6.17052888> +Double(2). % 4 + +% fun 可以作为函数的参数和返回值。 +Mult = fun(Times) -> ( fun(X) -> X * Times end ) end. +Triple = Mult(3). +Triple(5). % 15 + +% 列表解析是创建列表的表达式(不使用fun、map 或 filter)。 +% `[F(X) || X <- L]` 表示 "由 `F(X)` 组成的列表,其中 `X` 取自列表 `L`。 +L = [1,2,3,4,5]. +[2*X || X <- L]. % [2,4,6,8,10] +% 列表解析可以使用生成器,也可以使用过滤器,过滤器用于筛选列表的一部分。 +EvenNumbers = [N || N <- [1, 2, 3, 4], N rem 2 == 0]. % [2, 4] + +% Guard 是用于增强模式匹配的结构。 +% Guard 可用于简单的测试和比较。 +% Guard 可用于函数定义的头部,以`when`关键字开头,或者其他可以使用表达式的地方。 +max(X, Y) when X > Y -> X; +max(X, Y) -> Y. + +% guard 可以由一系列 guard 表达式组成,这些表达式以逗号分隔。 +% `GuardExpr1, GuardExpr2, ..., GuardExprN` 为真,当且仅当每个 guard 表达式均为真。 +is_cat(A) when is_atom(A), A =:= cat -> true; +is_cat(A) -> false. +is_dog(A) when is_atom(A), A =:= dog -> true; +is_dog(A) -> false. + +% guard 序列 `G1; G2; ...; Gn` 为真,当且仅当其中任意一个 guard 表达式为真。 +is_pet(A) when is_dog(A); is_cat(A) -> true; +is_pet(A) -> false. + +% Record 可以将元组中的元素绑定到特定的名称。 +% Record 定义可以包含在 Erlang 源代码中,也可以放在后缀为`.hrl`的文件中(Erlang 源代码中 include 这些文件)。 +-record(todo, { + status = reminder, % Default value + who = joe, + text +}). + +% 在定义某个 record 之前,我们需要在 shell 中导入 record 的定义。 +% 我们可以使用 shell 函数`rr` (read records 的简称)。 +rr("records.hrl"). % [todo] + +% 创建和更新 record。 +X = #todo{}. +% #todo{status = reminder, who = joe, text = undefined} +X1 = #todo{status = urgent, text = "Fix errata in book"}. +% #todo{status = urgent, who = joe, text = "Fix errata in book"} +X2 = X1#todo{status = done}. +% #todo{status = done,who = joe,text = "Fix errata in book"} + +% `case` 表达式。 +% `filter` 返回由列表`L`中所有满足`P(x)`为真的元素`X`组成的列表。 +filter(P, [H|T]) -> + case P(H) of + true -> [H|filter(P, T)]; + false -> filter(P, T) + end; +filter(P, []) -> []. +filter(fun(X) -> X rem 2 == 0 end, [1, 2, 3, 4]). % [2, 4] + +% `if` 表达式。 +max(X, Y) -> + if + X > Y -> X; + X < Y -> Y; + true -> nil; + end. + +% 警告: `if` 表达式里至少有一个 guard 为真,否则会触发异常。 + + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 3. 异常 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% 当遇到内部错误或显式调用时,会触发异常。 +% 显式调用包括 `throw(Exception)`, `exit(Exception)` 和 +% `erlang:error(Exception)`. +generate_exception(1) -> a; +generate_exception(2) -> throw(a); +generate_exception(3) -> exit(a); +generate_exception(4) -> {'EXIT', a}; +generate_exception(5) -> erlang:error(a). + +% Erlang 有两种捕获异常的方法。其一是将调用包裹在`try...catch`表达式中。 +catcher(N) -> + try generate_exception(N) of + Val -> {N, normal, Val} + catch + throw:X -> {N, caught, thrown, X}; + exit:X -> {N, caught, exited, X}; + error:X -> {N, caught, error, X} + end. + +% 另一种方式是将调用包裹在`catch`表达式中。 +% 此时异常会被转化为一个描述错误的元组。 +catcher(N) -> catch generate_exception(N). + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%% 4. 并发 +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Erlang 依赖于 actor并发模型。在 Erlang 编写并发程序的三要素: +% 创建进程,发送消息,接收消息 + +% 启动一个新的进程使用`spawn`函数,接收一个函数作为参数 + +F = fun() -> 2 + 2 end. % #Fun<erl_eval.20.67289768> +spawn(F). % <0.44.0> + +% `spawn` 函数返回一个pid(进程标识符),你可以使用pid向进程发送消息。 +% 使用 `!` 操作符发送消息。 +% 我们需要在进程内接收消息,要用到 `receive` 机制。 + +-module(caculateGeometry). +-compile(export_all). +caculateAera() -> + receive + {rectangle, W, H} -> + W * H; + {circle, R} -> + 3.14 * R * R; + _ -> + io:format("We can only caculate area of rectangles or circles.") + end. + +% 编译这个模块,在 shell 中创建一个进程,并执行 `caculateArea` 函数。 +c(caculateGeometry). +CaculateAera = spawn(caculateGeometry, caculateAera, []). +CaculateAera ! {circle, 2}. % 12.56000000000000049738 + +% shell也是一个进程(process), 你可以使用`self`获取当前 pid + +self(). % <0.41.0> + +``` + +## References + +* ["Learn You Some Erlang for great good!"](http://learnyousomeerlang.com/) +* ["Programming Erlang: Software for a Concurrent World" by Joe Armstrong](http://pragprog.com/book/jaerlang/programming-erlang) +* [Erlang/OTP Reference Documentation](http://www.erlang.org/doc/) +* [Erlang - Programming Rules and Conventions](http://www.erlang.se/doc/programming_rules.shtml) diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 4a87dc21..9f6a8c15 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -68,7 +68,7 @@ func learnTypes() { can include line breaks.` // 同样是String类型 // 非ascii字符。Go使用UTF-8编码。 - g := 'Σ' // rune类型,uint32的别名,使用UTF-8编码 + g := 'Σ' // rune类型,int32的别名,使用UTF-8编码 f := 3.14195 // float64类型,IEEE-754 64位浮点数 c := 3 + 4i // complex128类型,内部使用两个float64表示 diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index 8d51f144..cb7ccdee 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: haskell +language: Haskell filename: learn-haskell-zh.hs contributors: - ["Adit Bhargava", "http://adit.io"] diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 86ad1d07..7dee9cc4 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -363,8 +363,8 @@ var myNumberObj = new Number(12) myNumber == myNumberObj // = true // 但是它们并非严格等价 -typeof(myNumber) // = 'number' -typeof(myNumberObj) // = 'object' +typeof myNumber // = 'number' +typeof myNumberObj // = 'object' myNumber === myNumberObj // = false if (0){ // 这段代码不会执行,因为0代表假 diff --git a/zh-cn/json-cn.html.markdown b/zh-cn/json-cn.html.markdown new file mode 100644 index 00000000..3a8db2cf --- /dev/null +++ b/zh-cn/json-cn.html.markdown @@ -0,0 +1,51 @@ +--- +language: json +contributors: + - ["Anna Harren", "https://github.com/iirelu"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnjson-cn.json +lang: zh-cn +--- + +因为JSON是一个极其简单的数据交换形式,这个最有可能将会是曾经最简单 +的Learn X in Y Minutes。 + +最纯正形式的JSON没有实际的注解,但是大多数解析器将会 +接受C-风格(//, /\* \*/)的注解。为了这个目的,但是, +一切都将会是100%有效的JSON。幸亏,它是不言自明的。 + +```json +{ + "numbers": 0, + "strings": "Hellø, wørld. All unicode is allowed, along with \"escaping\".", + "has bools?": true, + "nothingness": null, + + "big number": 1.2e+100, + + "objects": { + "comment": "Most of your structure will come from objects.", + + "array": [0, 1, 2, 3, "Arrays can have anything in them.", 5], + + "another object": { + "comment": "These things can be nested, very useful." + } + }, + + "silliness": [ + { + "sources of potassium": ["bananas"] + }, + [ + [1, 0, 0, 0], + [0, 1, 0, 0], + [0, 0, 1, "neo"], + [0, 0, 0, 1] + ] + ], + + "that was short": "And, you're done. You now know everything JSON has to offer." +} +``` diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown new file mode 100644 index 00000000..1f91d52c --- /dev/null +++ b/zh-cn/julia-cn.html.markdown @@ -0,0 +1,729 @@ +--- +language: Julia +filename: learn-julia-zh.jl +contributors: + - ["Jichao Ouyang", "http://oyanglul.us"] +translators: + - ["Jichao Ouyang", "http://oyanglul.us"] +lang: zh-cn +--- + +```ruby +# 单行注释只需要一个井号 +#= 多行注释 + 只需要以 '#=' 开始 '=#' 结束 + 还可以嵌套. +=# + +#################################################### +## 1. 原始类型与操作符 +#################################################### + +# Julia 中一切皆是表达式。 + +# 这是一些基本数字类型. +3 # => 3 (Int64) +3.2 # => 3.2 (Float64) +2 + 1im # => 2 + 1im (Complex{Int64}) +2//3 # => 2//3 (Rational{Int64}) + +# 支持所有的普通中缀操作符。 +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 +5 / 2 # => 2.5 # 用 Int 除 Int 永远返回 Float +div(5, 2) # => 2 # 使用 div 截断小数点 +5 \ 35 # => 7.0 +2 ^ 2 # => 4 # 次方, 不是二进制 xor +12 % 10 # => 2 + +# 用括号提高优先级 +(1 + 3) * 2 # => 8 + +# 二进制操作符 +~2 # => -3 # 非 +3 & 5 # => 1 # 与 +2 | 4 # => 6 # 或 +2 $ 4 # => 6 # 异或 +2 >>> 1 # => 1 # 逻辑右移 +2 >> 1 # => 1 # 算术右移 +2 << 1 # => 4 # 逻辑/算术 右移 + +# 可以用函数 bits 查看二进制数。 +bits(12345) +# => "0000000000000000000000000000000000000000000000000011000000111001" +bits(12345.0) +# => "0100000011001000000111001000000000000000000000000000000000000000" + +# 布尔值是原始类型 +true +false + +# 布尔操作符 +!true # => false +!false # => true +1 == 1 # => true +2 == 1 # => false +1 != 1 # => false +2 != 1 # => true +1 < 10 # => true +1 > 10 # => false +2 <= 2 # => true +2 >= 2 # => true +# 比较可以串联 +1 < 2 < 3 # => true +2 < 3 < 2 # => false + +# 字符串可以由 " 创建 +"This is a string." + +# 字符字面量可用 ' 创建 +'a' + +# 可以像取数组取值一样用 index 取出对应字符 +"This is a string"[1] # => 'T' # Julia 的 index 从 1 开始 :( +# 但是对 UTF-8 无效, +# 因此建议使用遍历器 (map, for loops, 等). + +# $ 可用于字符插值: +"2 + 2 = $(2 + 2)" # => "2 + 2 = 4" +# 可以将任何 Julia 表达式放入括号。 + +# 另一种格式化字符串的方式是 printf 宏. +@printf "%d is less than %f" 4.5 5.3 # 5 is less than 5.300000 + +# 打印字符串很容易 +println("I'm Julia. Nice to meet you!") + +#################################################### +## 2. 变量与集合 +#################################################### + +# 给变量赋值就是声明变量 +some_var = 5 # => 5 +some_var # => 5 + +# 访问未声明变量会抛出异常 +try + some_other_var # => ERROR: some_other_var not defined +catch e + println(e) +end + +# 变量名需要以字母开头. +# 之后任何字母,数字,下划线,叹号都是合法的。 +SomeOtherVar123! = 6 # => 6 + +# 甚至可以用 unicode 字符 +☃ = 8 # => 8 +# 用数学符号非常方便 +2 * π # => 6.283185307179586 + +# 注意 Julia 的命名规约: +# +# * 变量名为小写,单词之间以下划线连接('\_')。 +# +# * 类型名以大写字母开头,单词以 CamelCase 方式连接。 +# +# * 函数与宏的名字小写,无下划线。 +# +# * 会改变输入的函数名末位为 !。 +# 这类函数有时被称为 mutating functions 或 in-place functions. + +# 数组存储一列值,index 从 1 开始。 +a = Int64[] # => 0-element Int64 Array + +# 一维数组可以以逗号分隔值的方式声明。 +b = [4, 5, 6] # => 包含 3 个 Int64 类型元素的数组: [4, 5, 6] +b[1] # => 4 +b[end] # => 6 + +# 二维数组以分号分隔维度。 +matrix = [1 2; 3 4] # => 2x2 Int64 数组: [1 2; 3 4] + +# 使用 push! 和 append! 往数组末尾添加元素 +push!(a,1) # => [1] +push!(a,2) # => [1,2] +push!(a,4) # => [1,2,4] +push!(a,3) # => [1,2,4,3] +append!(a,b) # => [1,2,4,3,4,5,6] + +# 用 pop 弹出末尾元素 +pop!(b) # => 6 and b is now [4,5] + +# 可以再放回去 +push!(b,6) # b 又变成了 [4,5,6]. + +a[1] # => 1 # 永远记住 Julia 的 index 从 1 开始! + +# 用 end 可以直接取到最后索引. 可用作任何索引表达式 +a[end] # => 6 + +# 还支持 shift 和 unshift +shift!(a) # => 返回 1,而 a 现在时 [2,4,3,4,5,6] +unshift!(a,7) # => [7,2,4,3,4,5,6] + +# 以叹号结尾的函数名表示它会改变参数的值 +arr = [5,4,6] # => 包含三个 Int64 元素的数组: [5,4,6] +sort(arr) # => [4,5,6]; arr 还是 [5,4,6] +sort!(arr) # => [4,5,6]; arr 现在是 [4,5,6] + +# 越界会抛出 BoundsError 异常 +try + a[0] # => ERROR: BoundsError() in getindex at array.jl:270 + a[end+1] # => ERROR: BoundsError() in getindex at array.jl:270 +catch e + println(e) +end + +# 错误会指出发生的行号,包括标准库 +# 如果你有 Julia 源代码,你可以找到这些地方 + +# 可以用 range 初始化数组 +a = [1:5] # => 5-element Int64 Array: [1,2,3,4,5] + +# 可以切割数组 +a[1:3] # => [1, 2, 3] +a[2:end] # => [2, 3, 4, 5] + +# 用 splice! 切割原数组 +arr = [3,4,5] +splice!(arr,2) # => 4 ; arr 变成了 [3,5] + +# 用 append! 连接数组 +b = [1,2,3] +append!(a,b) # a 变成了 [1, 2, 3, 4, 5, 1, 2, 3] + +# 检查元素是否在数组中 +in(1, a) # => true + +# 用 length 获得数组长度 +length(a) # => 8 + +# Tuples 是 immutable 的 +tup = (1, 2, 3) # => (1,2,3) # an (Int64,Int64,Int64) tuple. +tup[1] # => 1 +try: + tup[1] = 3 # => ERROR: no method setindex!((Int64,Int64,Int64),Int64,Int64) +catch e + println(e) +end + +# 大多数组的函数同样支持 tuples +length(tup) # => 3 +tup[1:2] # => (1,2) +in(2, tup) # => true + +# 可以将 tuples 元素分别赋给变量 +a, b, c = (1, 2, 3) # => (1,2,3) # a is now 1, b is now 2 and c is now 3 + +# 不用括号也可以 +d, e, f = 4, 5, 6 # => (4,5,6) + +# 单元素 tuple 不等于其元素值 +(1,) == 1 # => false +(1) == 1 # => true + +# 交换值 +e, d = d, e # => (5,4) # d is now 5 and e is now 4 + + +# 字典Dictionaries store mappings +empty_dict = Dict() # => Dict{Any,Any}() + +# 也可以用字面量创建字典 +filled_dict = ["one"=> 1, "two"=> 2, "three"=> 3] +# => Dict{ASCIIString,Int64} + +# 用 [] 获得键值 +filled_dict["one"] # => 1 + +# 获得所有键 +keys(filled_dict) +# => KeyIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 注意,键的顺序不是插入时的顺序 + +# 获得所有值 +values(filled_dict) +# => ValueIterator{Dict{ASCIIString,Int64}}(["three"=>3,"one"=>1,"two"=>2]) +# 注意,值的顺序也一样 + +# 用 in 检查键值是否已存在,用 haskey 检查键是否存在 +in(("one", 1), filled_dict) # => true +in(("two", 3), filled_dict) # => false +haskey(filled_dict, "one") # => true +haskey(filled_dict, 1) # => false + +# 获取不存在的键的值会抛出异常 +try + filled_dict["four"] # => ERROR: key not found: four in getindex at dict.jl:489 +catch e + println(e) +end + +# 使用 get 可以提供默认值来避免异常 +# get(dictionary,key,default_value) +get(filled_dict,"one",4) # => 1 +get(filled_dict,"four",4) # => 4 + +# 用 Sets 表示无序不可重复的值的集合 +empty_set = Set() # => Set{Any}() +# 初始化一个 Set 并定义其值 +filled_set = Set(1,2,2,3,4) # => Set{Int64}(1,2,3,4) + +# 添加值 +push!(filled_set,5) # => Set{Int64}(5,4,2,3,1) + +# 检查是否存在某值 +in(2, filled_set) # => true +in(10, filled_set) # => false + +# 交集,并集,差集 +other_set = Set(3, 4, 5, 6) # => Set{Int64}(6,4,5,3) +intersect(filled_set, other_set) # => Set{Int64}(3,4,5) +union(filled_set, other_set) # => Set{Int64}(1,2,3,4,5,6) +setdiff(Set(1,2,3,4),Set(2,3,5)) # => Set{Int64}(1,4) + + +#################################################### +## 3. 控制流 +#################################################### + +# 声明一个变量 +some_var = 5 + +# 这是一个 if 语句,缩进不是必要的 +if some_var > 10 + println("some_var is totally bigger than 10.") +elseif some_var < 10 # elseif 是可选的. + println("some_var is smaller than 10.") +else # else 也是可选的. + println("some_var is indeed 10.") +end +# => prints "some var is smaller than 10" + + +# For 循环遍历 +# Iterable 类型包括 Range, Array, Set, Dict, 以及 String. +for animal=["dog", "cat", "mouse"] + println("$animal is a mammal") + # 可用 $ 将 variables 或 expression 转换为字符串into strings +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# You can use 'in' instead of '='. +for animal in ["dog", "cat", "mouse"] + println("$animal is a mammal") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for a in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$(a[1]) is a $(a[2])") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +for (k,v) in ["dog"=>"mammal","cat"=>"mammal","mouse"=>"mammal"] + println("$k is a $v") +end +# prints: +# dog is a mammal +# cat is a mammal +# mouse is a mammal + +# While 循环 +x = 0 +while x < 4 + println(x) + x += 1 # x = x + 1 +end +# prints: +# 0 +# 1 +# 2 +# 3 + +# 用 try/catch 处理异常 +try + error("help") +catch e + println("caught it $e") +end +# => caught it ErrorException("help") + + +#################################################### +## 4. 函数 +#################################################### + +# 用关键字 'function' 可创建一个新函数 +#function name(arglist) +# body... +#end +function add(x, y) + println("x is $x and y is $y") + + # 最后一行语句的值为返回 + x + y +end + +add(5, 6) # => 在 "x is 5 and y is 6" 后会打印 11 + +# 还可以定义接收可变长参数的函数 +function varargs(args...) + return args + # 关键字 return 可在函数内部任何地方返回 +end +# => varargs (generic function with 1 method) + +varargs(1,2,3) # => (1,2,3) + +# 省略号 ... 被称为 splat. +# 刚刚用在了函数定义中 +# 还可以用在函数的调用 +# Array 或者 Tuple 的内容会变成参数列表 +Set([1,2,3]) # => Set{Array{Int64,1}}([1,2,3]) # 获得一个 Array 的 Set +Set([1,2,3]...) # => Set{Int64}(1,2,3) # 相当于 Set(1,2,3) + +x = (1,2,3) # => (1,2,3) +Set(x) # => Set{(Int64,Int64,Int64)}((1,2,3)) # 一个 Tuple 的 Set +Set(x...) # => Set{Int64}(2,3,1) + + +# 可定义可选参数的函数 +function defaults(a,b,x=5,y=6) + return "$a $b and $x $y" +end + +defaults('h','g') # => "h g and 5 6" +defaults('h','g','j') # => "h g and j 6" +defaults('h','g','j','k') # => "h g and j k" +try + defaults('h') # => ERROR: no method defaults(Char,) + defaults() # => ERROR: no methods defaults() +catch e + println(e) +end + +# 还可以定义键值对的参数 +function keyword_args(;k1=4,name2="hello") # note the ; + return ["k1"=>k1,"name2"=>name2] +end + +keyword_args(name2="ness") # => ["name2"=>"ness","k1"=>4] +keyword_args(k1="mine") # => ["k1"=>"mine","name2"=>"hello"] +keyword_args() # => ["name2"=>"hello","k1"=>4] + +# 可以组合各种类型的参数在同一个函数的参数列表中 +function all_the_args(normal_arg, optional_positional_arg=2; keyword_arg="foo") + println("normal arg: $normal_arg") + println("optional arg: $optional_positional_arg") + println("keyword arg: $keyword_arg") +end + +all_the_args(1, 3, keyword_arg=4) +# prints: +# normal arg: 1 +# optional arg: 3 +# keyword arg: 4 + +# Julia 有一等函数 +function create_adder(x) + adder = function (y) + return x + y + end + return adder +end + +# 这是用 "stabby lambda syntax" 创建的匿名函数 +(x -> x > 2)(3) # => true + +# 这个函数和上面的 create_adder 一模一样 +function create_adder(x) + y -> x + y +end + +# 你也可以给内部函数起个名字 +function create_adder(x) + function adder(y) + x + y + end + adder +end + +add_10 = create_adder(10) +add_10(3) # => 13 + + +# 内置的高阶函数有 +map(add_10, [1,2,3]) # => [11, 12, 13] +filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] + +# 还可以使用 list comprehensions 替代 map +[add_10(i) for i=[1, 2, 3]] # => [11, 12, 13] +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] + +#################################################### +## 5. 类型 +#################################################### + +# Julia 有类型系统 +# 所有的值都有类型;但变量本身没有类型 +# 你可以用 `typeof` 函数获得值的类型 +typeof(5) # => Int64 + +# 类型是一等值 +typeof(Int64) # => DataType +typeof(DataType) # => DataType +# DataType 是代表类型的类型,也代表他自己的类型 + +# 类型可用作文档化,优化,以及调度 +# 并不是静态检查类型 + +# 用户还可以自定义类型 +# 跟其他语言的 records 或 structs 一样 +# 用 `type` 关键字定义新的类型 + +# type Name +# field::OptionalType +# ... +# end +type Tiger + taillength::Float64 + coatcolor # 不附带类型标注的相当于 `::Any` +end + +# 构造函数参数是类型的属性 +tigger = Tiger(3.5,"orange") # => Tiger(3.5,"orange") + +# 用新类型作为构造函数还会创建一个类型 +sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") + +# struct 类似的类型被称为具体类型 +# 他们可被实例化但不能有子类型 +# 另一种类型是抽象类型 + +# abstract Name +abstract Cat # just a name and point in the type hierarchy + +# 抽象类型不能被实例化,但是可以有子类型 +# 例如,Number 就是抽象类型 +subtypes(Number) # => 6-element Array{Any,1}: + # Complex{Float16} + # Complex{Float32} + # Complex{Float64} + # Complex{T<:Real} + # ImaginaryUnit + # Real +subtypes(Cat) # => 0-element Array{Any,1} + +# 所有的类型都有父类型; 可以用函数 `super` 得到父类型. +typeof(5) # => Int64 +super(Int64) # => Signed +super(Signed) # => Real +super(Real) # => Number +super(Number) # => Any +super(super(Signed)) # => Number +super(Any) # => Any +# 所有这些类型,除了 Int64, 都是抽象类型. + +# <: 是类型集成操作符 +type Lion <: Cat # Lion 是 Cat 的子类型 + mane_color + roar::String +end + +# 可以继续为你的类型定义构造函数 +# 只需要定义一个同名的函数 +# 并调用已有的构造函数设置一个固定参数 +Lion(roar::String) = Lion("green",roar) +# 这是一个外部构造函数,因为他再类型定义之外 + +type Panther <: Cat # Panther 也是 Cat 的子类型 + eye_color + Panther() = new("green") + # Panthers 只有这个构造函数,没有默认构造函数 +end +# 使用内置构造函数,如 Panther,可以让你控制 +# 如何构造类型的值 +# 应该尽可能使用外部构造函数而不是内部构造函数 + +#################################################### +## 6. 多分派 +#################################################### + +# 在Julia中, 所有的具名函数都是类属函数 +# 这意味着他们都是有很大小方法组成的 +# 每个 Lion 的构造函数都是类属函数 Lion 的方法 + +# 我们来看一个非构造函数的例子 + +# Lion, Panther, Tiger 的 meow 定义为 +function meow(animal::Lion) + animal.roar # 使用点符号访问属性 +end + +function meow(animal::Panther) + "grrr" +end + +function meow(animal::Tiger) + "rawwwr" +end + +# 试试 meow 函数 +meow(tigger) # => "rawwr" +meow(Lion("brown","ROAAR")) # => "ROAAR" +meow(Panther()) # => "grrr" + +# 再看看层次结构 +issubtype(Tiger,Cat) # => false +issubtype(Lion,Cat) # => true +issubtype(Panther,Cat) # => true + +# 定义一个接收 Cats 的函数 +function pet_cat(cat::Cat) + println("The cat says $(meow(cat))") +end + +pet_cat(Lion("42")) # => prints "The cat says 42" +try + pet_cat(tigger) # => ERROR: no method pet_cat(Tiger,) +catch e + println(e) +end + +# 在面向对象语言中,通常都是单分派 +# 这意味着分派方法是通过第一个参数的类型决定的 +# 在Julia中, 所有参数类型都会被考虑到 + +# 让我们定义有多个参数的函数,好看看区别 +function fight(t::Tiger,c::Cat) + println("The $(t.coatcolor) tiger wins!") +end +# => fight (generic function with 1 method) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The orange tiger wins! + +# 让我们修改一下传入具体为 Lion 类型时的行为 +fight(t::Tiger,l::Lion) = println("The $(l.mane_color)-maned lion wins!") +# => fight (generic function with 2 methods) + +fight(tigger,Panther()) # => prints The orange tiger wins! +fight(tigger,Lion("ROAR")) # => prints The green-maned lion wins! + +# 把 Tiger 去掉 +fight(l::Lion,c::Cat) = println("The victorious cat says $(meow(c))") +# => fight (generic function with 3 methods) + +fight(Lion("balooga!"),Panther()) # => prints The victorious cat says grrr +try + fight(Panther(),Lion("RAWR")) # => ERROR: no method fight(Panther,Lion) +catch +end + +# 在试试让 Cat 在前面 +fight(c::Cat,l::Lion) = println("The cat beats the Lion") +# => Warning: New definition +# fight(Cat,Lion) at none:1 +# is ambiguous with +# fight(Lion,Cat) at none:2. +# Make sure +# fight(Lion,Lion) +# is defined first. +#fight (generic function with 4 methods) + +# 警告说明了无法判断使用哪个 fight 方法 +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The victorious cat says rarrr +# 结果在老版本 Julia 中可能会不一样 + +fight(l::Lion,l2::Lion) = println("The lions come to a tie") +fight(Lion("RAR"),Lion("brown","rarrr")) # => prints The lions come to a tie + + +# Under the hood +# 你还可以看看 llvm 以及生成的汇编代码 + +square_area(l) = l * l # square_area (generic function with 1 method) + +square_area(5) #25 + +# 给 square_area 一个整形时发生什么 +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Prologue + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # Fetch l from memory? + # imul RAX, RAX # Square l and store the result in RAX + # pop RBP # Restore old base pointer + # ret # Result will still be in RAX + +code_native(square_area, (Float32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Scalar single precision multiply (AVX) + # pop RBP + # ret + +code_native(square_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Scalar double precision multiply (AVX) + # pop RBP + # ret + # +# 注意 只要参数中又浮点类型,Julia 就使用浮点指令 +# 让我们计算一下圆的面积 +circle_area(r) = pi * r * r # circle_area (generic function with 1 method) +circle_area(5) # 78.53981633974483 + +code_native(circle_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Load integer (r) from memory + # movabs RAX, 4593140240 # Load pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # + +code_native(circle_area, (Float64,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # +``` diff --git a/zh-cn/livescript-cn.html.markdown b/zh-cn/livescript-cn.html.markdown new file mode 100644 index 00000000..fea00bc1 --- /dev/null +++ b/zh-cn/livescript-cn.html.markdown @@ -0,0 +1,322 @@ +--- +language: LiveScript +filename: learnLivescript.ls +contributors: + - ["Christina Whyte", "http://github.com/kurisuwhyte/"] +translators: + - ["ShengDa Lyu", "http://github.com/SDLyu/"] +lang: zh-cn +--- + +LiveScript 是一种具有函数式特性且编译成 JavaScript 的语言,能对应 JavaScript 的基本语法。 +还有些额外的特性如:柯里化,组合函数,模式匹配,还有借镜于 Haskell,F# 和 Scala 的许多特点。 + +LiveScript 诞生于 [Coco][],而 Coco 诞生于 [CoffeeScript][]。 +LiveScript 目前已释出稳定版本,开发中的新版本将会加入更多特性。 + +[Coco]: http://satyr.github.io/coco/ +[CoffeeScript]: http://coffeescript.org/ + +非常期待您的反馈,你可以通过 +[@kurisuwhyte](https://twitter.com/kurisuwhyte) 与我连系 :) + + +```coffeescript +# 与 CoffeeScript 一样,LiveScript 使用 # 单行注解。 + +/* + 多行注解与 C 相同。使用注解可以避免被当成 JavaScript 输出。 +*/ +``` +```coffeescript +# 语法的部份,LiveScript 使用缩进取代 {} 来定义区块, +# 使用空白取代 () 来执行函数。 + + +######################################################################## +## 1. 值类型 +######################################################################## + +# `void` 取代 `undefined` 表示未定义的值 +void # 与 `undefined` 等价但更安全(不会被覆写) + +# 空值则表示成 Null。 +null + + +# 最基本的值类型数据是罗辑类型: +true +false + +# 罗辑类型的一些别名,等价于前者: +on; off +yes; no + + +# 数字与 JS 一样,使用倍精度浮点数表示。 +10 +0.4 # 开头的 0 是必要的 + + +# 可以使用底线及单位后缀提高可读性,编译器会自动略过底线及单位后缀。 +12_344km + + +# 字串与 JS 一样,是一种不可变的字元序列: +"Christina" # 单引号也可以! +"""Multi-line + strings + are + okay + too.""" + +# 在前面加上 \ 符号也可以表示字串: +\keyword # => 'keyword' + + +# 数组是值的有序集合。 +fruits = + * \apple + * \orange + * \pear + +# 可以用 [] 简洁地表示数组: +fruits = [ \apple, \orange, \pear ] + + +# 你可以更方便地建立字串数组,并使用空白区隔元素。 +fruits = <[ apple orange pear ]> + +# 以 0 为起始值的数组下标获取元素: +fruits[0] # => "apple" + + +# 对象是无序键值对集合(更多给节将在下面章节讨论)。 +person = + name: "Christina" + likes: + * "kittens" + * "and other cute stuff" + +# 你也可以用更简洁的方式表示对象: +person = {name: "Christina", likes: ["kittens", "and other cute stuff"]} + +# 可以通过键值获取值: +person.name # => "Christina" +person["name"] # => "Christina" + + +# 正则表达式的使用跟 JavaScript 一样: +trailing-space = /\s$/ # dashed-words 变成 dashedWords + +# 你也可以用多行描述表达式!(注解和空白会被忽略) +funRE = // + function\s+(.+) # name + \s* \((.*)\) \s* # arguments + { (.*) } # body + // + + +######################################################################## +## 2. 基本运算 +######################################################################## + +# 数值操作符与 JavaScript 一样: +1 + 2 # => 3 +2 - 1 # => 1 +2 * 3 # => 6 +4 / 2 # => 2 +3 % 2 # => 1 + + +# 比较操作符大部份也一样,除了 `==` 等价于 JS 中的 `===`, +# JS 中的 `==` 在 LiveScript 里等价于 `~=`, +# `===` 能进行对象、数组和严格比较。 +2 == 2 # => true +2 == "2" # => false +2 ~= "2" # => true +2 === "2" # => false + +[1,2,3] == [1,2,3] # => false +[1,2,3] === [1,2,3] # => true + ++0 == -0 # => true ++0 === -0 # => false + +# 其它关系操作符包括 <、<=、> 和 >= + +# 罗辑值可以通过 `or`、`and` 和 `not` 结合: +true and false # => false +false or true # => true +not false # => true + + +# 集合也有一些便利的操作符 +[1, 2] ++ [3, 4] # => [1, 2, 3, 4] +'a' in <[ a b c ]> # => true +'name' of { name: 'Chris' } # => true + + +######################################################################## +## 3. 函数 +######################################################################## + +# 因为 LiveScript 是函数式特性的语言,你可以期待函数在语言里被高规格的对待。 +add = (left, right) -> left + right +add 1, 2 # => 3 + +# 加上 ! 防止函数执行后的返回值 +two = -> 2 +two! + +# LiveScript 与 JavaScript 一样使用函式作用域,且一样拥有闭包的特性。 +# 与 JavaScript 不同的地方在于,`=` 变量赋值时,左边的对象永远不用变量宣告。 + +# `:=` 操作符允许*重新賦值*父作用域里的变量。 + + +# 你可以解构函数的参数,从不定长度的参数结构里获取感兴趣的值。 +tail = ([head, ...rest]) -> rest +tail [1, 2, 3] # => [2, 3] + +# 你也可以使用一元或二元操作符转换参数。当然也可以预设传入的参数值。 +foo = (a = 1, b = 2) -> a + b +foo! # => 3 + +# 你可以以拷贝的方式传入参数来避免副作用,例如: +copy = (^^target, source) -> + for k,v of source => target[k] = v + target +a = { a: 1 } +copy a, { b: 2 } # => { a: 1, b: 2 } +a # => { a: 1 } + + +# 使用长箭号取代短箭号来柯里化一个函数: +add = (left, right) --> left + right +add1 = add 1 +add1 2 # => 3 + +# 函式里有一个隐式的 `it` 变量,意谓着你不用宣告它。 +identity = -> it +identity 1 # => 1 + +# 操作符在 LiveScript 里不是一個函数,但你可以简单地将它们转换成函数! +# Enter the operator sectioning: +divide-by-2 = (/ 2) +[2, 4, 8, 16].map(divide-by-2) .reduce (+) + + +# LiveScript 里不只有应用函数,如同其它良好的函数式语言,你可以合并函数获得更多发挥: +double-minus-one = (- 1) . (* 2) + +# 除了普通的数学公式合并 `f . g` 之外,还有 `>>` 和 `<<` 操作符定义函数的合并顺序。 +double-minus-one = (* 2) >> (- 1) +double-minus-one = (- 1) << (* 2) + + +# 说到合并函数的参数, LiveScript 使用 `|>` 和 `<|` 操作符将参数传入: +map = (f, xs) --> xs.map f +[1 2 3] |> map (* 2) # => [2 4 6] + +# 你也可以选择填入值的位置,只需要使用底线 _ 标记: +reduce = (f, xs, initial) --> xs.reduce f, initial +[1 2 3] |> reduce (+), _, 0 # => 6 + + +# 你也能使 _ 让任何函数变成偏函数应用: +div = (left, right) -> left / right +div-by-2 = div _, 2 +div-by-2 4 # => 2 + + +# 最后,也很重要的,LiveScript 拥有後呼叫特性, 可以是基於回调的代码 +# (你可以试试其它函数式特性的解法,比如 Promises): +readFile = (name, f) -> f name +a <- readFile 'foo' +b <- readFile 'bar' +console.log a + b + +# 等同於: +readFile 'foo', (a) -> readFile 'bar', (b) -> console.log a + b + + +######################################################################## +## 4. 模式、判断和流程控制 +######################################################################## + +# 流程控制可以使用 `if...else` 表达式: +x = if n > 0 then \positive else \negative + +# 除了 `then` 你也可以使用 `=>` +x = if n > 0 => \positive + else \negative + +# 过於复杂的流程可以用 `switch` 表达式代替: +y = {} +x = switch + | (typeof y) is \number => \number + | (typeof y) is \string => \string + | 'length' of y => \array + | otherwise => \object # `otherwise` 和 `_` 是等价的。 + +# 函数主体、宣告式和赋值式可以表式成 `switch`,这可以省去一些代码: +take = (n, [x, ...xs]) --> + | n == 0 => [] + | _ => [x] ++ take (n - 1), xs + + +######################################################################## +## 5. 推导式 +######################################################################## + +# 在 JavaScript 的标准函式库里有一些辅助函数能帮助处理列表及对象 +#(LiveScript 则带有一个 prelude.ls ,作为标准函式库的补充 ), +# 推导式能让你使用优雅的语法且快速地处理这些事: +oneToTwenty = [1 to 20] +evens = [x for x in oneToTwenty when x % 2 == 0] + +# 在推导式里 `when` 和 `unless` 可以当成过滤器使用。 + +# 对象推导式在使用上也是同样的方式,差别在于你使用的是对象而不是数组: +copy = { [k, v] for k, v of source } + + +######################################################################## +## 6. OOP +######################################################################## + +# 虽然 LiveScript 是一门函数式语言,但具有一些命令式及面向对象的特性。 +# 像是 class 语法和一些借镜於 CoffeeScript 的类别继承语法糖: +class Animal + (@name, kind) -> + @kind = kind + action: (what) -> "*#{@name} (a #{@kind}) #{what}*" + +class Cat extends Animal + (@name) -> super @name, 'cat' + purr: -> @action 'purrs' + +kitten = new Cat 'Mei' +kitten.purr! # => "*Mei (a cat) purrs*" + +# 除了类别的单一继承模式之外,还提供了像混入 (Mixins) 这种特性。 +# Mixins 在语言里被当成普通对象: +Huggable = + hug: -> @action 'is hugged' + +class SnugglyCat extends Cat implements Huggable + +kitten = new SnugglyCat 'Purr' +kitten.hug! # => "*Mei (a cat) is hugged*" +``` + +## 延伸阅读 + +LiveScript 还有许多强大之处,但这些应该足够启发你写些小型函数式程式了。 +[LiveScript](http://livescript.net/)有更多关于 LiveScript 的资讯 +和线上编译器等着你来试! + +你也可以参考 +[prelude.ls](http://gkz.github.io/prelude-ls/),和一些 `#livescript` +的网络聊天室频道。 diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 95a94c76..53a603a2 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: lua +language: Lua lang: zh-cn contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] @@ -9,6 +9,7 @@ contributors: - ["Amr Tamimi", "https://amrtamimi.com"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] +filename: lua-cn.lua --- ```lua diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown new file mode 100644 index 00000000..eecb8c5b --- /dev/null +++ b/zh-cn/markdown-cn.html.markdown @@ -0,0 +1,240 @@ +--- +language: Markdown +contributors: + - ["Dan Turkel", "http://danturkel.com/"] +translators: + - ["Fangzhou Chen","https://github.com/FZSS"] +filename: learnmarkdown-cn.md +lang: zh-cn +--- + +Markdown 由 John Gruber 于 2004年创立. 它旨在成为一门容易读写的语法结构,并可以便利地转换成 HTML(以及其他很多)格式。 + +欢迎您多多反馈以及分支和请求合并。 + + +```markdown +<!-- Markdown 是 HTML 的父集,所以任何 HTML 文件都是有效的 Markdown。 +这意味着我们可以在 Markdown 里使用任何 HTML 元素,比如注释元素, +且不会被 Markdown 解析器所影响。不过如果你在 Markdown 文件内创建了 HTML 元素, +你将无法在 HTML 元素的内容中使用 Markdown 语法。--> + +<!-- 在不同的解析器中,Markdown 的实现方法有所不同。 +此教程会指出当某功能是否通用及是否只对某一解析器有效。 --> + +<!-- 标头 --> +<!-- 通过在文本前加上不同数量的hash(#), 你可以创建相对应的 <h1> +到 <h6> HTML元素。--> + +# 这是一个 <h1> +## 这是一个 <h2> +### 这是一个 <h3> +#### 这是一个 <h4> +##### 这是一个 <h5> +###### 这是一个 <h6> + +<!-- 对于 <h1> 和 <h2> 元素,Markdown 额外提供了两种添加方式。 --> +这是一个 h1 +============= + +这是一个 h2 +------------- + +<!-- 简易文本样式 --> +<!-- 文本的斜体,粗体,和删除线在 Markdown 中可以轻易地被实现。--> + +*此文本为斜体。* +_此文本也是。_ + +**此文本为粗体。** +__此文本也是__ + +***此文本是斜体加粗体。*** +**_或者这样。_** +*__这个也是!__* + +<!-- 在 Github 采用的 Markdown 中 --> + +~~此文本为删除线效果。~~ + +<!-- 单个段落由一句或多句邻近的句子组成,这些句子由一个或多个空格分隔。--> + +这是第一段落. 这句话在同一个段落里,好玩么? + +现在我是第二段落。 +这句话也在第二段落! + +这句话在第三段落! + +<!-- 如果你插入一个 HTML中的<br />标签,你可以在段末加入两个以上的空格, +然后另起一段。--> + +此段落结尾有两个空格(选中以显示)。 + +上文有一个 <br /> ! + +<!-- 段落引用可由 > 字符轻松实现。--> + +> 这是一个段落引用. 你可以 +> 手动断开你的句子,然后在每句句子前面添加 “>” 字符。或者让你的句子变得很长,以至于他们自动得断开。 +> 只要你的文字以“>” 字符开头,两种方式无异。 + +> 你也对文本进行 +>> 多层引用 +> 这多机智啊! + +<!-- 序列 --> +<!-- 无序序列可由星号,加号或者减号来建立 --> + +* 项目 +* 项目 +* 另一个项目 + +或者 + ++ 项目 ++ 项目 ++ 另一个项目 + +或者 + +- 项目 +- 项目 +- 最后一个项目 + +<!-- 有序序列可由数字加点来实现 --> + +1. 项目一 +2. 项目二 +3. 项目三 + +<!-- 即使你的标签数字有误,Markdown 依旧会呈现出正确的序号, +不过这并不是一个好主意--> + +1. 项目一 +1. 项目二 +1. 项目三 +<!-- (此段与前例一模一样) --> + +<!-- 你也可以使用子序列 --> + +1. 项目一 +2. 项目二 +3. 项目三 + * 子项目 + * 子项目 +4. 项目四 + +<!-- 代码段落 --> +<!-- 代码段落(HTML中 <code>标签)可以由缩进四格(spaces) +或者一个标签页(tab)实现--> + + This is code + So is this + +<!-- 在你的代码中,你仍然使用tab可以进行缩进操作 --> + + my_array.each do |item| + puts item + end + +<!-- 内联代码可由反引号 ` 实现 --> + +John 甚至不知道 `go_to()` 方程是干嘛的! + +<!-- 在Github的 Markdown中,对于代码你可以使用特殊的语法 --> + +\`\`\`ruby <!-- 插入时记得移除反斜线, 仅留```ruby ! --> +def foobar + puts "Hello world!" +end +\`\`\` <!-- 这里也是,移除反斜线,仅留 ``` --> + +<!-- 以上代码不需要缩进,而且 Github 会根据```后表明的语言来进行语法高亮 --> + +<!-- 水平线 (<hr />) --> +<!-- 水平线可由三个或以上的星号或者减号创建,可带可不带空格。 --> + +*** +--- +- - - +**************** + +<!-- 链接 --> +<!-- Markdown 最棒的地方就是简易的链接制作。链接文字放在中括号[]内, +在随后的括弧()内加入url。--> + +[点我点我!](http://test.com/) + +<!-- 你也可以为链接加入一个标题:在括弧内使用引号 --> + +[点我点我!](http://test.com/ "连接到Test.com") + +<!-- 相对路径也可以有 --> + +[去 music](/music/). + +<!-- Markdown同样支持引用样式的链接 --> + +[点此链接][link1]以获取更多信息! +[看一看这个链接][foobar] 如果你愿意的话. + +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" + +<!-- 链接的标题可以处于单引号中,括弧中或是被忽略。引用名可以在文档的任意何处, +并且可以随意命名,只要名称不重复。--> + +<!-- “隐含式命名” 的功能可以让链接文字作为引用名 --> + +[This][] is a link. + +[this]: http://thisisalink.com/ + +<!-- 但这并不常用 --> + +<!-- 图像 --> +<!-- 图像与链接相似,只需在前添加一个感叹号 --> + + + +<!-- 引用样式也同样起作用 --> + +![这是我的悬停文本.][myimage] + +[myimage]: relative/urls/cool/image.jpg "在此输入标题" + +<!-- 杂项 --> +<!-- 自动链接 --> + +<http://testwebsite.com/> 与 +[http://testwebsite.com/](http://testwebsite.com/) 等同 + +<!-- 电子邮件的自动链接 --> + +<foo@bar.com> + +<!-- 转义字符 --> + +我希望 *将这段文字置于星号之间* 但是我不希望它被 +斜体化, 所以我就: \*这段置文字于星号之间\*。 + +<!-- 表格 --> +<!-- 表格只被 Github 的 Markdown 支持,并且有一点笨重,但如果你真的要用的话: --> + +| 第一列 | 第二列 | 第三列 | +| :---------- | :------: | ----------: | +| 左对齐 | 居个中 | 右对齐 | +| 某某某 | 某某某 | 某某某 | + +<!-- 或者, 同样的 --> + +第一列 | 第二列 | 第三列 +:-- | :-: | --: +这太丑了 | 药不能 | 停 + +<!-- 结束! --> + +``` + +更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 diff --git a/zh-cn/php-cn.html.markdown b/zh-cn/php-cn.html.markdown index 24939681..2def7f1c 100644 --- a/zh-cn/php-cn.html.markdown +++ b/zh-cn/php-cn.html.markdown @@ -1,5 +1,5 @@ --- -language: php +language: PHP contributors: - ["Malcolm Fell", "http://emarref.net/"] - ["Trismegiste", "https://github.com/Trismegiste"] diff --git a/zh-cn/r-cn.html.markdown b/zh-cn/r-cn.html.markdown index 19c5f25d..0c46bc22 100644 --- a/zh-cn/r-cn.html.markdown +++ b/zh-cn/r-cn.html.markdown @@ -13,7 +13,7 @@ lang: zh-cn R 是一门统计语言。它有很多数据分析和挖掘程序包。可以用来统计、分析和制图。 你也可以在 LaTeX 文档中运行 `R` 命令。 -```python +```r # 评论以 # 开始 # R 语言原生不支持 多行注释 diff --git a/zh-cn/ruby-cn.html.markdown b/zh-cn/ruby-cn.html.markdown index 3c47f3f9..99250b43 100644 --- a/zh-cn/ruby-cn.html.markdown +++ b/zh-cn/ruby-cn.html.markdown @@ -40,7 +40,7 @@ translators: 1.+(3) #=> 4 10.* 5 #=> 50 -# 特殊的只也是对象 +# 特殊的值也是对象 nil # 空 true # 真 false # 假 diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 24f73bb5..58f5cd47 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -11,7 +11,7 @@ lang: zh-cn Scala - 一门可拓展性的语言 -```cpp +```scala /* 自行设置: @@ -369,7 +369,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // 使用 '=>' 来重命名一个 import -import scala.collection.immutable{ List => ImmutableList } +import scala.collection.immutable.{ List => ImmutableList } // import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类: import scala.collection.immutable.{Map => _, Set => _, _} diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown new file mode 100644 index 00000000..b9696c72 --- /dev/null +++ b/zh-cn/swift-cn.html.markdown @@ -0,0 +1,227 @@ +--- +language: swift +filename: learnswift-cn.swift +contributors: + - ["Grant Timmerman", "http://github.com/grant"] +translators: + - ["Xavier Yao", "http://github.com/xavieryao"] +lang: zh-cn +--- + +Swift 是Apple 开发的用于iOS 和OS X 开发的编程语言。Swift 于2014年Apple WWDC (全球开发者大会)中被引入,用以与Objective-C 共存,同时对错误代码更具弹性。Swift 由Xcode 6 beta 中包含的LLVM编译器编译。 + +参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html) ——一个完整的Swift 教程 + +```swift +// +// 基础 +// + +println("Hello, world") +var myVariable = 42 +let myConstant = 3.1415926 +let explicitDouble: Double = 70 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant)" // String interpolation +var optionalString: String? = "optional" // Can be nil +optionalString = nil + + +// +// 数组与字典(关联数组) +// + +// 数组 +var shoppingList = ["catfish", "water", "lemons"] +shoppingList[1] = "bottle of water" +let emptyArray = String[]() + +// 字典 +var occupations = [ + "Malcolm": "Captain", + "kaylee": "Mechanic" +] +occupations["Jayne"] = "Public Relations" +let emptyDictionary = Dictionary<String, Float>() + + +// +// 控制流 +// + +// 用于数组的for 循环 +let myArray = [1, 1, 2, 3, 5] +for value in myArray { + if value == 1 { + println("One!") + } else { + println("Not one!") + } +} + +// 用于字典的for 循环 +for (key, value) in dict { + println("\(key): \(value)") +} + +// 用于区间的for 循环 +for i in -1...1 { // [-1, 0, 1] + println(i) +} +// 使用 .. 表示的区间不包含最后一个元素 [-1,0,1) + +// while 循环 +var i = 1 +while i < 1000 { + i *= 2 +} + +// do-while 循环 +do { + println("hello") +} while 1 == 2 + +// Switch +let vegetable = "red pepper" +switch vegetable { +case "celery": + let vegetableComment = "Add some raisins and make ants on a log." +case "cucumber", "watercress": + let vegetableComment = "That would make a good tea sandwich." +case let x where x.hasSuffix("pepper"): + let vegetableComment = "Is it a spicy \(x)?" +default: // 必须 (为了覆盖所有可能的输入) + let vegetableComment = "Everything tastes good in soup." +} + + +// +// 函数 +// + +// 函数是一等类型,这意味着可以在函数中构建函数 +// 并且可以被传递 + +// 函数 +func greet(name: String, day: String) -> String { + return "Hello \(name), today is \(day)." +} +greet("Bob", "Tuesday") + +// 使用多元数组返回多返回值的函数 +func getGasPrices() -> (Double, Double, Double) { + return (3.59, 3.69, 3.79) +} + +// 不定参数 +func setup(numbers: Int...) {} + +// 传递、返回函数 +func makeIncrementer() -> (Int -> Int) { + func addOne(number: Int) -> Int { + return 1 + number + } + return addOne +} +var increment = makeIncrementer() +increment(7) + + +// +// 闭包 +// + +// 函数是特殊的闭包({}) + +// 闭包示例. +// `->` 分隔参数和返回类型 +// `in` 分隔闭包头和闭包体 +numbers.map({ + (number: Int) -> Int in + let result = 3 * number + return result + }) + +// 当类型已知时,可以这样做: +var numbers = [1, 2, 6] +numbers = numbers.map({ number in 3 * number }) +print(numbers) // [3, 6, 18] + + +// +// 类 +// + +// 类的全部方法和属性都是public 的 +// 如果你在一个数据结构中只需储存数据, +// 应使用 `struct` + +// 集成自`Shape` 类的简单的类`Square +class Rect: Shape { + var sideLength: Int = 1 + + // Custom getter and setter property + var perimeter: Int { + get { + return 4 * sideLength + } + set { + sideLength = newValue / 4 + } + } + + init(sideLength: Int) { + super.init() + self.sideLength = sideLength + } + + func shrink() { + if sideLength > 0 { + --sideLength + } + } + + override func getArea() -> Int { + return sideLength * sideLength + } +} +var mySquare = new Square(sideLength: 5) +print(mySquare.getArea()) // 25 +mySquare.shrink() +print(mySquare.sideLength) // 4 + +// 如果你不需要自定义getter 和setter, +// 但仍希望在获取或设置一个属性之前或之后运行 +// 一些代码,你可以使用`willSet` 和 `didSet` + + +// +// 枚举类型 +// + +// 枚举类型可以是某种指定的类型,抑或自成一种类型 +// 像类一样,枚举类型可以包含方法 + +enum Suit { + case Spades, Hearts, Diamonds, Clubs + func getIcon() -> String { + switch self { + case .Spades: return "♤" + case .Hearts: return "♡" + case .Diamonds: return "♢" + case .Clubs: return "♧" + } + } +} + + +// +// 其它 +// + +// `协议(protocol)`: 与Java 的接口(Interface) 类似. +// `扩展(extension)`: 为现有类型添加额外特性 +// 泛型: 与Java 相似。使用`where` 关键字指定 +// 泛型的要求. + +``` diff --git a/zh-cn/xml-cn.html.markdown b/zh-cn/xml-cn.html.markdown new file mode 100644 index 00000000..bf0b074f --- /dev/null +++ b/zh-cn/xml-cn.html.markdown @@ -0,0 +1,127 @@ +--- +language: xml +contributors: + - ["João Farias", "https://github.com/JoaoGFarias"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnxml-cn.xml +lang: zh-cn +--- + +XML是一种标记语言,被设计用来存储数据和传输数据。 + +不像HTML, XML不指定怎样显示或格式化数据,只是携带它。 + + +* XML 语法 + +```xml +<!-- XML中的注解像这样 --> + +<?xml version="1.0" encoding="UTF-8"?> +<bookstore> + <book category="COOKING"> + <title lang="en">Everyday Italian</title> + <author>Giada De Laurentiis</author> + <year>2005</year> + <price>30.00</price> + </book> + <book category="CHILDREN"> + <title lang="en">Harry Potter</title> + <author>J K. Rowling</author> + <year>2005</year> + <price>29.99</price> + </book> + <book category="WEB"> + <title lang="en">Learning XML</title> + <author>Erik T. Ray</author> + <year>2003</year> + <price>39.95</price> + </book> +</bookstore> + +<!-- 上面是一个典型的XML文件。 + 它以一个声明开始,通知一些元数据(自选的) + + XML使用一个树的结构。上面的文件中,根节点是'bookstore',它有三个孩子节点, + 所有的'books'。那些节点有更多的孩子节点,等等。。。 + + 节点用开放/关闭标签创建, 并且孩子就是在开发和关闭标签之间的节点。--> + + + +<!-- XML 携带两类信息: + 1 - 属性 -> 那是关于一个元素的元数据。 + 通常,XML解析器使用这些信息去正确地存储数据。 + 它通过在开放标签里出现在插入语中来表示。 + 2 - 元素 -> 那是纯数据。 + 那就是解析器将从XML文件提取的东西。 + 元素出现在开放和关闭标签之间,没插入语。--> + + +<!-- 下面, 一个有两个属性的元素--> +<file type="gif" id="4293">computer.gif</file> + + +``` + +* 良好格式的文件 x 验证 + +一个XML文件是良好格式的如果它是语法正确的。 +但是, 使用文件定义,比如DTD和XML概要,在文件中插入更多的限制是可能的。 + +一个遵守一个文件定义的XML文件被叫做有效的,对于那个文件来说。 + +有了这个工具,你能够在应用逻辑之外检查XML数据。 + +```xml + +<!-- 下面, 你能够看到一个简化版本的增加了DTD定义的bookstore文件。--> + +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE note SYSTEM "Bookstore.dtd"> +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> + +<!-- 这个DTD可能是像这样的:--> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + + +<!-- 这个DTD以一个声明开始。 + 接下来, 根节点被声明, 它需要一个或多个孩子节点'book'。 + 每个 'book' 应该准确包含一个 'title' 和 'price' 和 + 一个被叫做'category'的缺省值为"Literature"的属性。 + 这个'title' 和 'price'节点包含一个解析过的字符数据。--> + +<!-- 这个DTD可以在XML文件中本身被声明。--> + +<?xml version="1.0" encoding="UTF-8"?> + +<!DOCTYPE note +[ +<!ELEMENT bookstore (book+)> +<!ELEMENT book (title,price)> +<!ATTLIST book category CDATA "Literature"> +<!ELEMENT title (#PCDATA)> +<!ELEMENT price (#PCDATA)> +]> + +<bookstore> + <book category="COOKING"> + <title >Everyday Italian</title> + <price>30.00</price> + </book> +</bookstore> +```
\ No newline at end of file diff --git a/zh-cn/yaml-cn.html.markdown b/zh-cn/yaml-cn.html.markdown new file mode 100644 index 00000000..fc510eb5 --- /dev/null +++ b/zh-cn/yaml-cn.html.markdown @@ -0,0 +1,136 @@ +--- +language: yaml +contributors: + - ["Adam Brenecki", "https://github.com/adambrenecki"] +translators: + - ["Zach Zhang", "https://github.com/checkcheckzz"] +filename: learnyaml-cn.yaml +lang: zh-cn +--- + +YAML是一个数据序列化语言,被设计成人类直接可写可读的。 + +它是JSON的严格超集,增加了语法显著换行符和缩进,就像Python。但和Python不一样, +YAML根本不容许文字制表符。 + + +```yaml +# YAML中的注解看起来像这样。 + +################ +# 标量类型 # +################ + +# 我们的根对象 (它们在整个文件里延续) 将会是一个地图, +# 它等价于在别的语言里的一个字典,哈西表或对象。 +key: value +another_key: Another value goes here. +a_number_value: 100 +scientific_notation: 1e+12 +boolean: true +null_value: null +key with spaces: value +# 注意到字符串不需要被引用。但是,它们可以被引用。 +"Keys can be quoted too.": "Useful if you want to put a ':' in your key." + +# 多行字符串既可以写成像一个'文字块'(使用 |), +# 或像一个'折叠块'(使用 '>')。 +literal_block: | + This entire block of text will be the value of the 'literal_block' key, + with line breaks being preserved. + + The literal continues until de-dented, and the leading indentation is + stripped. + + Any lines that are 'more-indented' keep the rest of their indentation - + these lines will be indented by 4 spaces. +folded_style: > + This entire block of text will be the value of 'folded_style', but this + time, all newlines will be replaced with a single space. + + Blank lines, like above, are converted to a newline character. + + 'More-indented' lines keep their newlines, too - + this text will appear over two lines. + +#################### +# 集合类型 # +#################### + +# 嵌套是通过缩进完成的。 +a_nested_map: + key: value + another_key: Another Value + another_nested_map: + hello: hello + +# 地图不用有字符串键值。 +0.25: a float key + +# 键值也可以是多行对象,用?表明键值的开始。 +? | + This is a key + that has multiple lines +: and this is its value + +# YAML也容许键值是集合类型,但是很多语言将会抱怨。 + +# 序列 (等价于表或数组) 看起来像这样: +a_sequence: + - Item 1 + - Item 2 + - 0.5 # 序列可以包含不同类型。 + - Item 4 + - key: value + another_key: another_value + - + - This is a sequence + - inside another sequence + +# 因为YAML是JSON的超集,你也可以写JSON风格的地图和序列: +json_map: {"key": "value"} +json_seq: [3, 2, 1, "takeoff"] + +####################### +# 其余的YAML特点 # +####################### + +# YAML还有一个方便的特点叫'锚',它让你简单地在整个文件里重复内容。 +# 两个键值将会有相同的值: +anchored_content: &anchor_name This string will appear as the value of two keys. +other_anchor: *anchor_name + +# YAML还有标签,你可以用它显示地声明类型。 +explicit_string: !!str 0.5 +# 一些解析器实现特定语言的标签,就像这个为了Python的复数类型。 +python_complex_number: !!python/complex 1+2j + +#################### +# 其余的YAML类型 # +#################### + +# 字符串和数字不是仅有的YAML可以理解的标量。 +# ISO 格式的日期和日期时间文字也是可以被解析的。 +datetime: 2001-12-15T02:59:43.1Z +datetime_with_spaces: 2001-12-14 21:59:43.10 -5 +date: 2002-12-14 + +# 这个!!binary标签表明一个字符串实际上是一个二进制blob的base64编码表示。 +gif_file: !!binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + +# YAML还有一个集合类型,它看起来像这样: +set: + ? item1 + ? item2 + ? item3 + +# 像Python一样,集合仅是有null数值的地图;上面的集合等价于: +set2: + item1: null + item2: null + item3: null +``` |