diff --git a/1-intro.md b/1-intro.md deleted file mode 100644 index 3ce439e..0000000 --- a/1-intro.md +++ /dev/null @@ -1,134 +0,0 @@ -1-简介 -====== - -欢迎! - -> -本章是主要讲了各个平台上如何安装使用Elixir。由于本文主要关注Elixir的语言学习, -因此这个章节所讲的步骤或工具可能不是最新,请大家自行网上搜索。 - -本章将涵盖如何安装Elixir,并且学习使用交互式的Elixir Shell(称为IEx)。 - -使用本教程的需求: - - Erlang - version 17.0 或更高 - - Elixir - 1.0.0 或更高 - -现在开始吧! - ->如果你发现本手册有错误,请帮忙开_issue_讨论或发_pull request_。 - -## 1.1-安装包 -在各个平台上最方便的安装方式是相应平台的安装包。 -如果没有,推荐使用precompiled package或者用源码编译安装。 - -注意Elixir需要Erlang 17.0或更高。下面介绍的方法基本上都会自动为你安装Erlang。 -假如没有,请阅读下面安装Erlang的说明。 - -### Mac OS X -- Homebrew - - 升级Homebrew到最新 - - 执行:```brew install elixir``` -- Macports - - 执行:```sudo port install elixir``` - -### Unix(或者类Unix) - - Fedora 17或更新 - - 执行:```yum install elixir``` - - Fedora 22或更新 - - 执行:```dnf install elixir``` - - Arch Linux (社区repo) - - 执行:```pacman -S elixir``` - - openSUSE (and SLES 11 SP3+) - - 添加Erlang devel repo: ```zypper ar -f obs://devel:languages:erlang/ erlang``` - - 执行:```zypper in elixir``` - - Gentoo - - 执行:```emerge --ask dev-lang/elixir``` - - FreeBSD - - 使用ports: ```cd /usr/ports/lang/elixir && make install clean``` - - 或使用pkg: ```pkg install elixir``` - - Ubuntu 12.04和14.04,或Debian 7 - - 添加Erlang Solutions repo: ```wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb``` - - 执行:```sudo apt-get update``` - - 安装Erlang/OTP平台及相关程序:```sudo apt-get install esl-erlang``` - - 安装Elixir:```sudo apt-get install elixir``` - -### Windows - - Web installer - - [下载installer](https://s3.amazonaws.com/s3.hex.pm/elixir-websetup.exe) - - 点下一步,下一步...直到完成 - - Chocolatey - - ```cinst elixir ``` - -## 1.3-使用预编译包 -Elixir为每一个release提供了预编译包(编译好并打包的程序,开箱即用)。 -首先[安装Erlang](http://elixir-lang.org/install.html#installing-erlang), -然后在[这里](https://github.com/elixir-lang/elixir/releases/)下载最新的 -预编译包(Precompiled.zip)。unzip,即可使用elixir程序和iex程序了。 -当然为了方便起见,需要将一些路径加入环境变量。 - -## 1.4-从源码编译安装(Unix和MinGW) -首先[安装Erlang](http://elixir-lang.org/install.html#installing-erlang), -然后在[这里](https://github.com/elixir-lang/elixir/releases/)下载最新的源码, -自己使用make工具编译安装。 - ->在Windows上编译安装请参考https://github.com/elixir-lang/elixir/wiki/Windows - ->附上加环境变量的命令 -```sh -$ export PATH="$PATH:/path/to/elixir/bin" -``` - -如果你十分激进,可以直接选择编译安装github上的master分支: -```sh -$ git clone https://github.com/elixir-lang/elixir.git -$ cd elixir -$ make clean test -``` -如果测试无法通过,可在[repo](https://github.com/elixir-lang/elixir)里开issue汇报。 - -## 1.5-安装Erlang -安装Elixir唯一的要求就是Erlang(V17.0+), -它可以很容易地使用 -[预编译包](https://www.erlang-solutions.com/downloads/download-erlang-otp)安装。 -如果你想从源码安装,可以去[Erlang网站](http://www.erlang.org/download.html)找找, -参考[Riak文档](http://docs.basho.com/riak/1.3.0/tutorials/installation/Installing-Erlang/)。 -安装好Erlang后,打开命令行(或命令窗口),输入```erl```,可以输出Erlang的版本信息: -``` -Erlang/OTP 17 (erts-6) [64-bit] [smp:2:2] [async-threads:0] [hipe] [kernel-poll:false] -``` ->安装好Erlang后,你需要手动添加环境变量或$PATH。 -关于环境变量,参考[这里](http://en.wikipedia.org/wiki/Environment_variable)。 - - -## 1.6-交互模式 -安装好Elixir之后,你有了三个可执行文件:```iex```,```elixir```和```elixirc```。 -如果你是用预编译包方式安装的,可以在解压后的bin目录下找到它们。 - -现在我们可以从```iex```开始了(或者是```iex.bat```,如果在Windows上)。 -交互模式,就是可以向其中输入任何Elixir表达式或命令,然后直接看到表达式或命令的结果。 -如以下所示: -```elixir -Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help) - -iex> 40 + 2 -42 -iex> "hello" <> " world" -"hello world" -``` -对这种交互式命令行,相信熟悉ruby,python等动态语言的程序员一定不会陌生。 - ->如果你用的是Windows,你可以使用```iex.bat --werl```,可以根据你的console获得更好的使用体验。 - -## 1.7-执行脚本 -把表达式写进脚本文件,可以用```elixir```命令执行它。如: -```sh -$ cat simple.exs -IO.puts "Hello world -from Elixir" - -$ elixir simple.exs -Hello world -from Elixir -``` - -在以后的章节中,我们还会介绍如何编译Elixir程序,以及使用Mix这样的构建工具。 diff --git a/10-enum-stream.md b/10-enum-stream.md deleted file mode 100644 index 1b90a5e..0000000 --- a/10-enum-stream.md +++ /dev/null @@ -1,110 +0,0 @@ -10-枚举类型和流 -================== -[枚举对象](#101-%E6%9E%9A%E4%B8%BE%E7%B1%BB%E5%9E%8B)
-[积极vs懒惰](#102-%E7%A7%AF%E6%9E%81vs%E6%87%92%E6%83%B0)
-[流](#103-%E6%B5%81)
- -## 10.1-枚举类型 -Elixir提供了枚举类型(enumerables)的概念,使用[Enum模块]()操作它们。我们已经介绍过两种枚举类型:列表和图。 -``` -iex> Enum.map([1, 2, 3], fn x -> x * 2 end) -[2, 4, 6] -iex> Enum.map(%{1 => 2, 3 => 4}, fn {k, v} -> k * v end) -[2, 12] -``` - -Enum模块为枚举类型提供了大量函数来变化,排序,分组,过滤和读取元素。 -Enum模块是开发者最常用的模块之一。 -
- -Elixir还提供了范围(range): -``` -iex> Enum.map(1..3, fn x -> x * 2 end) -[2, 4, 6] -iex> Enum.reduce(1..3, 0, &+/2) -6 -``` - -因为Enum模块在设计时为了适用于不同的数据类型,所以它的API被限制为多数据类型适用的函数。 -为了实现某些操作,你可能需要针对某类型使用某特定的模块。 -比如,如果你要在列表中某特定位置插入一个元素,要用[List模块](http://elixir-lang.org/docs/stable/elixir/List.html)中的List.insert_at/3函数。而向某些类型内插入数据是没意义的,比如范围。 - -Enum中的函数是多态的,因为它们能处理不同的数据类型。 -尤其是,模块中可以适用于不同数据类型的函数,它们是遵循了[Enumerable协议](http://elixir-lang.org/docs/stable/elixir/Enumerable.html)。 -我们在后面章节中将讨论这个协议。下面将介绍一种特殊的枚举类型:流。 - -## 10.2-积极vs懒惰 -Enum模块中的所有函数都是**积极**的。多数函数接受一个枚举类型,并返回一个列表: -``` -iex> odd? = &(rem(&1, 2) != 0) -#Function<6.80484245/1 in :erl_eval.expr/5> -iex> Enum.filter(1..3, odd?) -[1, 3] -``` - -这意味着当使用Enum进行多种操作时,每次操作都生成一个中间列表,直到得出最终结果: -``` -iex> 1..100_000 |> Enum.map(&(&1 * 3)) |> Enum.filter(odd?) |> Enum.sum -7500000000 -``` - -上面例子是一个含有多个操作的管道。从一个范围开始,然后给每个元素乘以3。 -该操作将会生成的中间结果是含有100000个元素的列表。 -然后我们过滤掉所有偶数,产生又一个新中间结果:一个50000元素的列表。 -最后求和,返回结果。 ->这个符号的用法似乎和F#中的不一样啊... - -作为一个替代,[流模块](http://elixir-lang.org/docs/stable/elixir/Stream.html)提供了懒惰的实现: -``` -iex> 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) |> Enum.sum -7500000000 -``` - -与之前Enum的处理不同,流先创建了一系列的计算操作。然后仅当我们把它传递给Enum模块,它才会被调用。流这种方式适用于处理大量的(甚至是无限的)数据集合。 - -## 10.3-流 -流是懒惰的,比起Enum来说。 -分步分析一下上面的例子,你会发现流与Enum的区别: -``` -iex> 1..100_000 |> Stream.map(&(&1 * 3)) -#Stream<[enum: 1..100000, funs: [#Function<34.16982430/1 in Stream.map/2>]]> -``` -流操作返回的不是结果列表,而是一个数据类型---流,一个表示要对范围1..100000使用map操作的动作。 - -另外,当我们用管道连接多个流操作时: -``` -iex> 1..100_000 |> Stream.map(&(&1 * 3)) |> Stream.filter(odd?) -#Stream<[enum: 1..100000, funs: [...]]> -``` - -流模块中的函数接受任何枚举类型为参数,返回一个流。 -流模块还提供了创建流(甚至是无限操作的流)的函数。 -例如,```Stream.cycle/1```可以用来创建一个流,它能无限周期性枚举所提供的参数(小心使用): -``` -iex> stream = Stream.cycle([1, 2, 3]) -#Function<15.16982430/2 in Stream.cycle/1> -iex> Enum.take(stream, 10) -[1, 2, 3, 1, 2, 3, 1, 2, 3, 1] -``` - -另一方面,```Stream.unfold/2```函数可以生成给定的有限值: -``` -iex> stream = Stream.unfold("hełło", &String.next_codepoint/1) -#Function<39.75994740/2 in Stream.unfold/2> -iex> Enum.take(stream, 3) -["h", "e", "ł"] -``` - -另一个有趣的函数是```Stream.resource/3```,它可以用来包裹某资源,确保该资源在使用前打开,在用完后关闭(即使中途出现错误)。--类似C#中的use{}关键字。 -比如,我们可以stream一个文件: -``` -iex> stream = File.stream!("path/to/file") -#Function<18.16982430/2 in Stream.resource/3> -iex> Enum.take(stream, 10) -``` - -这个例子读取了文件的前10行内容。流在处理大文件,或者慢速资源(如网络)时非常有用。 -
- -一开始Enum和流模块中函数的数量多到让人气馁。但你会慢慢地熟悉它们。 -建议先熟悉Enum模块,然后因为应用而转去流模块中那些相应的,懒惰版的函数。 diff --git a/11-process.md b/11-process.md deleted file mode 100644 index 9c631ce..0000000 --- a/11-process.md +++ /dev/null @@ -1,280 +0,0 @@ -11-进程 -======= - -Elixir里所有代码都在进程中执行。进程彼此独立,并发执行,通过传递消息(message)进行沟通。 -进程不仅仅是Elixir并发编程的基础,也是Elixir创建分布式、高容错程序的本质。 - -Elixir的进程和传统操作系统中的进程不可混为一谈。 -Elixir的进程在CPU和内存使用上,是极度轻量级的(但不同于其它语言中的线程)。 -正因如此,同时运行着数十万、百万个进程也并不是罕见的事。 - -本章将讲解如何派生新进程,以及在不同进程间发送和接受消息等基本知识。 - -## 进程派生(spawning) - -派生(spawning)一个新进程的方法是使用自动导入(kernel模块)的```spawn/1```函数: - -```elixir -iex> spawn fn -> 1 + 2 end -#PID<0.43.0> -``` - -函数```spawn/1```接收一个_函数_作为参数,在其派生出的进程中执行这个函数。 - -注意,```spawn/1```返回一个PID(进程标识)。在这个时候,这个派生的进程很可能已经结束。 - -派生的进程执行完函数后便会结束: - -```elixir -iex> pid = spawn fn -> 1 + 2 end -#PID<0.44.0> -iex> Process.alive?(pid) -false -``` - ->你可能会得到与例子中不一样的PID - -用```self/0```函数获取当前进程的PID: -```elixir -iex> self() -#PID<0.41.0> -iex> Process.alive?(self()) -true -``` - ->注:上文调用```self/0```加了括号。 -但是如前文所说,在不引起误解的情况下,可以省略括号而只写```self``` - -可以发送和接收消息,让进程变得越来越有趣。 - -## 发送和接收(消息) - -使用```send/2```函数发送消息,用```receive/1```接收消息: - -```elixir -iex> send self(), {:hello, "world"} -{:hello, "world"} -iex> receive do -...> {:hello, msg} -> msg -...> {:world, msg} -> "won't match" -...> end -"world" -``` - -当有消息被发给某进程,该消息就被存储在该进程的“邮箱”里。 -语句块```receive/1```检查当前进程的邮箱,寻找匹配给定模式的消息。 -函数```receive/1```支持卫兵语句(guards)及分支子句(clause)如```case/2```。 - -如果找不到匹配的消息,当前进程将一直等待,直到下一条信息到达。 - -可以给等待设置一个超时时间: -```elixir -iex> receive do -...> {:hello, msg} -> msg -...> after -...> 1_000 -> "nothing after 1s" -...> end -"nothing after 1s" -``` - -超时时间设为0表示你知道当前邮箱内肯定有邮件存在,很自信,因此设了这个极短的超时时间。 - -把以上概念综合起来,演示进程间发送消息: -```elixir -iex> parent = self() -#PID<0.41.0> -iex> spawn fn -> send(parent, {:hello, self()}) end -#PID<0.48.0> -iex> receive do -...> {:hello, pid} -> "Got hello from #{inspect pid}" -...> end -"Got hello from #PID<0.48.0>" -``` - -在shell中执行程序时,辅助函数```flush/0```很有用。它清空并打印进程邮箱中的所有消息: -```elixir -iex> send self(), :hello -:hello -iex> flush() -:hello -:ok -``` - -## 链接(links) - -Elixir中最常用的进程派生方式是通过调用函数```spawn_link/1```。 - -在举例子讲解```spawn_link/1```之前,来看看如果一个进程挂掉会发生什么: -```elixir -iex> spawn fn -> raise "oops" end -#PID<0.58.0> - -[error] Process #PID<0.58.00> raised an exception -** (RuntimeError) oops - :erlang.apply/2 -``` - -...仅仅是打印了一些文字信息,而派生这个倒霉进程的父进程仍然全无知觉地继续运行。 -这是因为进程是互不干扰的。 -如果我们希望一个进程发生异常挂掉可以被另一个进程感知,我们需要链接它们。 - -这需要使用```spawn_link/1```函数来派生进程,例子: -```elixir -iex> spawn_link fn -> raise "oops" end -#PID<0.60.0> -** (EXIT from #PID<0.41.0>) an exception was raised: - ** (RuntimeError) oops - :erlang.apply/2 -``` - -当这个失败发生在shell中,shell会自动捕获这个异常并显示格式优雅的异常信息。 -为了弄明白失败时真正会发生什么,让我们在一个脚本文件中使用```spawn_link/1```: - -```elixir -# spawn.exs -spawn_link fn -> raise "oops" end - -receive do - :hello -> "let's wait until the process fails" -end -``` - -执行: -```elixir -$ elixir spawn.exs - -** (EXIT from #PID<0.47.0>) an exception was raised: - ** (RuntimeError) oops - spawn.exs:1: anonymous fn/0 in :elixir_compiler_0.__FILE__/1 -``` - -这次,该进程在失败时把它的父进程也弄停止了,因为它们是链接的。 - -使用函数```spawn_link/1```是在派生时对父子进程进行链接, -你还可以手动对两个进程进行链接:使用函数```Process.link/1```。 -我们推荐可以多看看[Process模块](http://elixir-lang.org/docs/stable/elixir/Process.html),里面包含很多常用的进程操作函数。 - -进程和链接在创建能高容错系统时扮演重要角色。 -在Elixir程序中,我们经常把进程链接到“管理者(supervisors)”上。 -由这个角色负责检测失败进程,并且创建新进程取代之。这是唯一可行的方式。 -因为进程间独立,默认情况下不共享任何东西。一个进程失败了,不会影响其它进程的状态。 - -其它语言通常需要我们抛出/捕获异常,而在Elixir中我们可以放任进程挂掉, -因为我们希望“管理者”会以更合适的方式重启系统。 -“死快一点(failing fast)”是Elixir软件开发中的一个常见哲学。 - -`spawn/1`和`spawn_link/1`是Elixir中创建进程的基本方式。 -尽管我们到目前为止都是专门调用它们,实际上大部分时间我们会使用基于它们功能的一些抽象操作。 -比如常见的:“任务(Tasks)”。 - -## 任务(Task) - -任务建立在进程派生函数之上,提供了更好的错误报告和内省。 - -```elixir -iex(1)> Task.start fn -> raise "oops" end -{:ok, #PID<0.55.0>} - -15:22:33.046 [error] Task #PID<0.55.0> started from #PID<0.53.0> terminating -** (RuntimeError) oops - (elixir) lib/task/supervised.ex:74: Task.Supervised.do_apply/2 - (stdlib) proc_lib.erl:239: :proc_lib.init_p_do_apply/3 -Function: #Function<20.90072148/0 in :erl_eval.expr/5> - Args: [] -``` - -我们使用```Task.start/1```和```Task.start_link/1```代替```spawn/1```和```spawn_link/1```, -返回```{:ok pid}```而不仅仅是子进程的PID。这使得任务可以在监督者树中使用。 -另外,任务提供了许多便利的函数,比如```Task.async/1```和```Task.await/1```等, -以及其它一些易于构建分布式接结构的函数。 - -我们将在《高级》篇中介绍关于任务更多的函数功能。现在我们只需要知道,使用任务有更好的错误报告。 - -## 状态(state) - -目前为止我们还没有怎么谈到状态。但是如果你需要构建一个程序它需要状态,比如保存程序的配置信息, -或者解析一个文件先把它保存在内存里,你在哪儿存储? - -_进程_就是(最常见的一个)答案。我们可以写个进程执行无限循环,保存若干状态, -通过收发消息维护和改变这些状态值。 -举个例子,我们写一个程序模块,创建一个提供键值对存储服务的进程: - -```elixir -defmodule KV do - def start_link do - Task.start_link(fn -> loop(%{}) end) - end - - defp loop(map) do - receive do - {:get, key, caller} -> - send caller, Map.get(map, key) - loop(map) - {:put, key, value} -> - loop(Map.put(map, key, value)) - end - end -end - -``` - -注意```start_link```函数启动一个新的进程。这个进程以一个空的图(map)为参数,执行```loop/1```函数。 -启动后,```loop/1```函数等待消息,并且针对每个消息执行合适的操作。 -如果收到```:get```消息,它会把消息发回给调用者,然后再次调用自身```loop/1```,等待新消息。 -如果收到```:put```消息,它便用一个新版本的图变量(里面保存了新的键/值)再次调用```loop/1```。 - -执行一下```iex kv.exs```: -```elixir -iex> {:ok, pid} = KV.start_link -#PID<0.62.0> -iex> send pid, {:get, :hello, self()} -{:get, :hello, #PID<0.41.0>} -iex> flush -nil -``` - -一开始进程内的图变量是没有键值的,所以发送一个```:get```消息并且刷新当前进程的收件箱,返回nil。 -下面发送一个```:put```消息再试一次: - -```elixir -iex> send pid, {:put, :hello, :world} -#PID<0.62.0> -iex> send pid, {:get, :hello, self()} -{:get, :hello, #PID<0.41.0>} -iex> flush -:world -``` - -注意这个进程是怎么保持状态信息的:我们通过向该进程发送消息来获取和更新状态。 -事实上,其它任何进程只要知道这个进程的PID,都能读取和修改状态。 - -还可以注册这个PID,给它一个名称。这使得我们可以通过名字来向它发送消息: -```elixir -iex> Process.register(pid, :kv) -true -iex> send :kv, {:get, :hello, self()} -{:get, :hello, #PID<0.41.0>} -iex> flush -:world -``` - -使用进程维护状态、进程名称注册都是构建Elixir应用的常见模式。 -但是大多数时间我们不会自己实现这样的模式,而是使用Elixir已经提供的抽象实现。 - -例如,Elixir提供的[agent](http://elixir-lang.org/docs/stable/elixir/Agent.html)就是一个状态维护进程的简单实现: - -```elixir -iex> {:ok, pid} = Agent.start_link(fn -> %{} end) -{:ok, #PID<0.72.0>} -iex> Agent.update(pid, fn map -> Map.put(map, :hello, :world) end) -:ok -iex> Agent.get(pid, fn map -> Map.get(map, :hello) end) -:world -``` - -给```Agent.start_link/2```方法加上```:name```选项,可以自动为其注册一个名字。 - -除了agents,Elixir还提供了一套API来创建通用服务器(generic servers,称作GenServer),任务等。 -这些都是建立在进程概念之上的实现。其它概念,包括“管理者”树,都可以在《高级》篇里找到更详细的说明。 - -下一章将介绍Elixir语言的I/O世界。 diff --git a/12-io.md b/12-io.md deleted file mode 100644 index 666019f..0000000 --- a/12-io.md +++ /dev/null @@ -1,228 +0,0 @@ -12-IO和文件系统 -====== - -本章简单介绍Elixir的输入、输出机制,文件系统相关的任务, -以及涉及到的模块,如[`IO`](http://elixir-lang.org/docs/stable/elixir/IO.html), -[`File`](http://elixir-lang.org/docs/stable/elixir/File.html) -和[`Path`](http://elixir-lang.org/docs/stable/elixir/Path.html)。 - -我们曾经在早期的文章中说现在介绍IO似乎有点早。 -但是,我们注意到IO系统其实提供了一窥Elixir和虚拟机的设计哲学和精妙的绝佳机会。 - ->“早期的文章”:现在介绍I/O似乎有点早,但是I/O系统可以让我们一窥Elixir哲学,满足我们对该语言以及VM的好奇心。 - -## `IO`模块 - -模块`IO`提供了Elixir语言中读写标准输入/输出(`:stdio`)、 -标准错误(`:stderr`)、文件和其他IO设备的主要机制。 - -该模块的使用方法颇为直白: - -```elixir -iex> IO.puts "hello world" -"hello world" -:ok -iex> IO.gets "yes or no? " -yes or no? yes -"yes\n" -``` - -默认情况下,IO模块中的函数从标准输入中读取,向标准输出中写入。 -我们可以传递参数,比如```:stderr```,来指示将信息写到标准错误上: - -```elixir -iex> IO.puts :stderr, "hello world" -"hello world" -:ok -``` - -## `File`模块 - -`File`模块包含的函数可以让我们打开文件作为IO设备。 -默认情况下文件是以二进制模式打开, -它要求程序员使用特定的```IO.binread/2```和```IO.binwrite/2```函数来读写文件: - -```elixir -iex> {:ok, file} = File.open "hello", [:write] -{:ok, #PID<0.47.0>} -iex> IO.binwrite file, "world" -:ok -iex> File.close file -:ok -iex> File.read "hello" -{:ok, "world"} -``` - -文件可以使用`:utf8`编码方式打开,这让`File`模块以UTF-8编码方式解析文件中读取的字节: - -```elixir -iex> {:ok, file} = File.open "another", [:write, :utf8] -{:ok, #PID<0.48.0>} -``` - -除了打开、读写文件的函数,文件模块还提供了许多函数来操作文件系统。 -这些函数根据Unix平台上功能相对应的命令来命名。 -如`File.rm/1`用来删除文件,`File.mkdir/1`用来创建目录, -`File.mkdir_p/1`创建目录并保证其父目录一并创建。 -甚至还有`File.cp_r/2`和`File.rm_rf/1`用来递归地复制或删除整个目录。 - -你会注意到`File`模块的函数有两种变体,一个普通的和一个名称末尾有`!`(bang)的。 -例如在上面的例子里,我们在读取“hello”文件时,用的是不带`!`的版本。 -相对地,我们也可以使用`File.read!/1`: - -```elixir -iex> File.read "hello" -{:ok, "world"} -iex> File.read! "hello" -"world" -iex> File.read "unknown" -{:error, :enoent} -iex> File.read! "unknown" -** (File.Error) could not read file unknown: no such file or directory -``` - -注意看,当文件不存在时,带!号的版本会抛出一个错误。 -而不带!号的版本适用于你对不同结果进行模式匹配的情形: - -```elixir -case File.read(file) do - {:ok, body} -> # do something with the `body` - {:error, reason} -> # handle the error caused by `reason` -end -``` - -但有的时候,你就是希望文件在那儿,!号变体更加适用,因为它能报出有意义的错误。 -例如,如果这么写: - -```elixir -{:ok, body} = File.read(file) -``` - -当遇到文件不存在的情况时,函数返回`{:error, reason}`,然后导致在跟左侧元组做模式匹配时失败。 -失败依然会抛出一个异常,但是该异常的错误信息是描述一次模式匹配失败,而不是文件的什么错误。 -从而在一定程度上掩盖了真正的失败原因。 - -可以这么写: - -```elixir -case File.read(file) do - {:ok, body} -> # handle ok - {:error, r} -> # handle error -end -``` - -当然,更推荐的写法: - -```elixir -File.read!(file) -``` - -## ```Path```模块 - -模块`File`中的绝大多数函数都以各种路径作为参数。 -通常,这些路径都是二进制串(binaries)。 -模块`Path`提供了操作这些路径的函数: - -```elixir -iex> Path.join("foo", "bar") -"foo/bar" -iex> Path.expand("~/hello") -"/Users/jose/hello" -``` - -推荐使用`Path`模块提供的函数而不是直接手动操作代表路径的二进制串。 -因为`Path`模块考虑了不同操作系统的区别,使得各种处理是对“操作系统”透明的。 -最后,记住在Windows平台上处理文件操作时,Elixir会自动将斜杠(/)转换成反斜杠(\)。 - -有了上面介绍的模块和函数,我们已经能对文件系统进行基本的操作。 -下面将讨论有关IO的一些高级话题。这部分并不是写Elixir程序必须掌握的,可以跳过不看。 -但是如果你浏览一下,可以大致了解IO是如何在VM上实现的,以及其它一些有趣的内容。 - -## 进程(Processes)和组长(group leaders) - -你可能已经注意到`File.open/2`函数返回类似`{:ok, pid}`的元组: - -```elixir -iex> {:ok, file} = File.open "hello", [:write] -{:ok, #PID<0.47.0>} -``` - -模块`IO`实际上是和进程(Process)一起协同工作的。 -当你调用`IO.write(pid, binary)`时,`IO`模块将发送一条消息给`pid`标示的进程, -附上所期望进行的操作。 - -如果我们自己用进程来描述这个过程: - -```elixir -iex> pid = spawn fn -> -...> receive do: (msg -> IO.inspect msg) -...> end -#PID<0.57.0> -iex> IO.write(pid, "hello") -{:io_request, #PID<0.41.0>, #Reference<0.0.8.91>, {:put_chars, :unicode, "hello"}} -** (ErlangError) erlang error: :terminated -``` - -调用`IO.write/2`之后,可以看到`IO`模块发出的请求(四个元素的元组)被打印了出来。 -不久后,因为我们并未提供`IO`模块期待的某种结果,这个请求失败了。 - -[`StringIO`模块](http://elixir-lang.org/docs/stable/elixir/StringIO.html) -提供了基于字符串的`IO`设备消息处理功能(将字符串看做IO设备): - -```elixir -iex> {:ok, pid} = StringIO.open("hello") -{:ok, #PID<0.43.0>} -iex> IO.read(pid, 2) -"he" -``` - -Erlang虚拟机通过利用进程给IO设备建模,使得同一个网络中的不同节点可以通过交换文件进程, -实现跨节点的文件读写。而在所有IO设备之中,有一个特殊的进程,称作*组长(group leader)*。 - -当你写东西到标准输入输出(`:stdio`),实际上是发送了一条消息给进程组长, -它把内容写给标准输出的文件描述符: - -```elixir -iex> IO.puts :stdio, "hello" -hello -:ok -iex> IO.puts Process.group_leader, "hello" -hello -:ok -``` - -在不同的应用场景下,让哪个进程作为组长是可以配置的。 -例如,当在远程终端执行代码时,通过配置组长,可以使得远程节点上打印的消息可以被重定向到发起操作(你)的终端上。 - -## `iodata`和`chardata` - -在以上所有例子中,我们都用的是二进制串格式写入文件。 -在“二进制串、字符串和字符列表”那章里,我们提到过字符串(string)就是普通的bytes, -而字符列表(char list)就是字符编码(code point,如“Uxxxx”、“049”)的列表。 - -`IO`模块和`File`模块中的函数还可以接受列表作为参数。 -不光如此,它们还接受混合类型的列表,里面内容可以是列表(如`'ab c'`)、 -整形(如`49`,`?A` --- 返回65)和二进制串(如`"ab c"`): - -```elixir -iex> IO.puts 'hello world' -hello world -:ok -iex> IO.puts ['hello', ?\s, "world"] -hello world -:ok -``` - ->`?`返回后面字符的编码(code point),如`?A`默认情况下返回65。 - -尽管如此,有些地方还是要注意。一个列表可能表示一串byte,或者一串字符。 -用哪一种需要看IO设备是怎么编码的。 -如果不指明编码,文件就以raw模式打开, -这时候只能用`IO`模块里`bin*`开头(二进制版本)的函数对其进行操作。 -这些函数接受`iodata`作为参数。也就是说,它们期待一个整数值的列表,用来表示bytes或二进制串。 - -另一边,使用`:utf8`打开的`:stdio`和文件使用`IO`模块里剩下来其它的函数。 -这些函数期待`char_data`作为参数,即一串字符或字符串的列表。 - -尽管差别比较精妙,但只是当你想要传递列表给那些函数的时候,才用担心一下细节问题。 -而二进制串(binaries)表示了底层的bytes字节列表,这种表示已经是raw的了。 diff --git a/13-alias-req-imp.md b/13-alias-req-imp.md deleted file mode 100644 index b44c0d3..0000000 --- a/13-alias-req-imp.md +++ /dev/null @@ -1,268 +0,0 @@ -13-alias,require和import -================= - -为了实现软件重用,Elixir提供了三种指令(`alias`,`require`和`import`), -外加一个宏命令`use`,如下: - -```elixir -# 给模块起别名,让它可以用 Bar 调用而非 Foo.Bar -alias Foo.Bar, as: Bar - -# 确保模块已被编译且可用(通常为了宏) -require Foo - -# 从 Foo 中导入函数,使之调用时不用加`Foo`前缀 -import Foo - -# 执行定义在 Foo 拓展点内的代码 -use Foo -``` - -下面我们将深入细节。记住前三个之所以称之为“指令”, -是因为它们的作用域是*词法作用域(lexicla scope)*, -而`use`是一个普通拓展点(common extension point),可以将宏展开。 - -## alias - -指令`alias`可以为任何模块设置别名。 -想象一下之前使用过的`Math`模块,它针对特殊的数学运算提供了特殊的列表(list)实现: - -```elixir -defmodule Math do - alias Math.List, as: List -end -``` - -现在,任何对`List`的引用将被自动变成对`Math.List`的引用。 -如果还想访问原来的`List`,可以加上它的模块名前缀'Elixir': - -```elixir -List.flatten #=> uses Math.List.flatten -Elixir.List.flatten #=> uses List.flatten -Elixir.Math.List.flatten #=> uses Math.List.flatten -``` - ->注意:Elixir中定义的所有模块都被定义在Elixir命名空间内。 -但为方便起见,在引用它们时,你可以省略它们的前缀‘Elixir’。 - -别名常被使用于定义快捷方式。实际应用中,不带`:as`选项调用`alias`会 -自动将别名设置为该模块名称的最后一部分: - -```elixir -alias Math.List -``` - -就相当于: - -```elixir -alias Math.List, as: List -``` - -注意,`alias`是**词法作用域**。也就是说,当你在某个函数中设置别名: - -```elixir -defmodule Math do - def plus(a, b) do - alias Math.List - # ... - end - - def minus(a, b) do - # ... - end -end -``` - -例子中`alias`指令设置的别名只在函数`plus/2`中有效,函数`minus/2`则不受影响。 - -## require - -Elixir提供了许多宏用于元编程(可以编写生成代码的代码)。 - -宏是在编译时被执行和展开的代码。 -也就是说为了使用宏,你需要确保定义这个宏的模块及实现在你的代码的编译时可用(即被加载)。 -这使用`require`指令实现: - -```elixir -iex> Integer.odd?(3) -** (CompileError) iex:1: you must require Integer before invoking the macro Integer.odd?/1 -iex> require Integer -nil -iex> Integer.odd?(3) -true -``` - -Elixir中,`Integer.odd?/1`函数被定义为一个宏,因此它可以被当作卫兵表达式(guards)使用。 -为了调用这个宏,首先需要使用`require`引用`Integer`模块。 - -总的来说,一个模块在被用到之前不需要早早地require,除非我们需要用到这个模块中定义的宏的时候。 -尝试调用一个没有加载的宏时,会报出一个异常。 -注意,像`alias`指令一样,`require`指令也是词法作用域的。 -在后面章节我们会进一步讨论宏。 - -## import - -当想轻松地访问模块中的函数和宏时,可以使用`import`指令避免输入模块的完整名字。 -例如,如果我们想多次使用`List`模块中的`duplicate/2`函数,我们可以import它: - -```elixir -iex> import List, only: [duplicate: 2] -List -iex> duplicate :ok, 3 -[:ok, :ok, :ok] -``` - -这个例子中,我们只从List模块导入了函数`duplicate`(元数是2的那个)。 -尽管`:only`选项是可选的,但是仍推荐使用,以避免向当前命名空间内导入这个模块内定义的所有函数。 -还有`:except`选项,可以*排除*一些函数而导入其余的。 - -还有选项`:only`,传递给它`:macros`或`:functions`,来导入该模块的所有宏或函数。 -如下面例子,程序仅导入`Integer`模块中定义的所有的宏: - -```elixir -import Integer, only: :macros -``` - -或者,仅导入所有的函数: - -```elixir -import Integer, only: :functions -``` - -注意,`import`也遵循**词法作用域**,意味着我们可以在某特定函数定义内导入宏或方法: - -```elixir -defmodule Math do - def some_function do - import List, only: [duplicate: 2] - duplicate(:ok, 10) - end -end -``` - -在这个例子中,导入的函数`List.duplicate/2`只在函数`some_function`中可见, -在该模块的其它函数中都不可用(自然,别的模块也不受影响)。 - -注意,若`import`一个模块,将自动`require`它。 - -## use - -尽管不是一条指令,`use`是一个宏,与帮助你在当前上下文中使用模块的`require`指令联系紧密。 -`use`宏常被用来引入外部的功能到当前的词法作用域---通常是模块。 - -例如,在编写测试时,我们使用ExUnit框架。开发者需要使用`ExUnit.Case` 模块: - -```elixir -defmodule AssertionTest do - use ExUnit.Case, async: true - - test "always pass" do - assert true - end -end -``` - -在代码背后,`use`宏先是`require`所给的模块,然后在模块上调用`__using__/1`回调函数, -从而允许这个模块在当前上下文中注入某些代码。 - -比如下面这个模块: - -```exlixir -defmodule Example do - use Feature, option: :value -end -``` - -会被编译成(即宏`use`扩展) - -```exlixir -defmodule Example do - require Feature - Feature.__using__(option: :value) -end -``` - -到这里,关于Elixir的模块基本上讲得差不多了。后面会讲解模块的属性(Attribute)。 - -## 别名机制 - -讲到这里你会问,Elixir的别名到底是什么,它是怎么实现的? - -Elixir中的别名是以大写字母开头的标识符(像`String`, `Keyword`),在编译时会被转换为原子。 -例如,别名‘String’默认情况下会被转换为原子`:"Elixir.String"`: - -```elixir -iex> is_atom(String) -true -iex> to_string(String) -"Elixir.String" -iex> :"Elixir.String" == String -true -``` - -使用`alias/2`指令,其实只是简单地改变了这个别名将要转换的结果。 - -别名会被转换为原子,是因为在Erlang虚拟机(以及上面的Elixir)中,模块是由原子表述。 -例如,我们调用一个Erlang模块函数的机制是: - -```elixir -iex> :lists.flatten([1,[2],3]) -[1, 2, 3] -``` - -这也是允许我们动态调用模块函数的机制: - -```elixir -iex> mod = :lists -:lists -iex> mod.flatten([1,[2],3]) -[1,2,3] -``` - -我们只是简单地在原子`:lists`上调用了函数`flatten`。 - -## 模块嵌套 - -我们已经介绍了别名,现在可以讲讲嵌套(nesting)以及它在Elixir中是如何工作的。 -考虑下面的例子: - -```elixir -defmodule Foo do - defmodule Bar do - end -end -``` - -该例子定义了两个模块:`Foo`和`Foo.Bar`。 -后者在`Foo`中可以用`Bar`为名来访问,因为它们在同一个词法作用域中。 -上面的代码等同于: - -```elixir -defmodule Elixir.Foo do - defmodule Elixir.Foo.Bar do - end - alias Elixir.Foo.Bar, as: Bar -end -``` - -如果之后开发者决定把`Bar`模块定义挪出`Foo`模块的定义,但是在`Foo`中仍然使用`Bar`来引用, -那它就需要以全名(Foo.Bar)来命名,或者向上文提到的,在`Foo`中设置个别名来指代。 - -**注意:** 在Elixir中,你并不是必须在定义`Foo.Bar`模块之前定义`Foo`模块, -因为编程语言会将所有模块名翻译成原子。 -你可以定义任意嵌套的模块而不需要注意其名称链上的先后顺序 -(比如,在定义`Foo.Bar.Baz`前不需要提前定义`foo`或者`Foo.Bar`)。 - -在后面几章我们会看到,别名在宏里面也扮演着重要角色,来保证它们是“干净”(hygienic)的。 - -## 一次、多个 - -从Elixir v1.2版本开始,可以一次性使用alias,import,require操作多个模块。 -这在定义和使用嵌套模块的时候非常有用,这也是在构建Elixir程序的常见情形。 - -例如,假设你的程序所有模块都嵌套在`MyApp`下, -你可以一次同时给三个模块:`MyApp.Foo`,`MyApp.Bar`和`MyApp.Baz`提供别名: - -```elixir -alias MyApp.{Foo, Bar, Baz} -``` diff --git a/14-mod-attr.md b/14-mod-attr.md deleted file mode 100644 index 354d5a2..0000000 --- a/14-mod-attr.md +++ /dev/null @@ -1,179 +0,0 @@ -14-模块属性 -=========== - -在Elixir中,模块属性(module attributes)主要服务于三个目的: - 1. 作为一个模块的注解(annotations),通常附加上用户或虚拟机会用到的信息 - 2. 作为常量 - 3. 在编译时作为一个临时的模块存储机制 - -下面让我们来一一讲解。 - -## 作为注解(annotations) - -Elixir从Erlang带来了模块属性的概念。如: - -```elixir -defmodule MyServer do - @vsn 2 -end -``` - -这个例子中,我们显式地为该模块设置了 _版本(vsn即version)_ 属性。 -`@vsn`是一个系统保留的属性名称,它被Erlang虚拟机的代码装载机制使用,以检查该模块是否被更新过。 -如果不注明版本号,该属性的值会自动设置为模块函数的md5 checksum。 - -Elixir还有好多系统保留的预定义注解。下面是一些比较常用的: - - * `@moduledoc` - 为当前模块提供文档说明 - * `@doc` - 为该属性标注的函数或宏提供文档说明 - * `@behaviour` - (注意这个单词是英式拼法)用来注明一个OTP或用户自定义行为 - * `@before_compile` - 提供一个每当模块被编译之前执行的钩子。这使得我们可以在模块被编译之前往里面注入函数 - -`@moduledoc`和`@doc`是目前最常用的注解属性,我们也希望你能够多使用它们。 -Elixir视文档为一等公民,而且提供了很多方法来访问这些文档。 -你可以拓展阅读文章[《用我们官方的方式写Elixir程序文档》](http://elixir-lang.org/docs/stable/elixir/writing-documentation.html)。 - -让我们回到上几章定义的`Math`模块,为它添加文档,然后依然保存在math.ex文件中: - -```elixir -defmodule Math do - @moduledoc """ - Provides math-related functions. - - ## Examples - - iex> Math.sum(1, 2) - 3 - - """ - - @doc """ - Calculates the sum of two numbers. - """ - def sum(a, b), do: a + b -end -``` - -Elixir推荐使用markdown语法和多行文本(heredocs)书写容易阅读的文档。 -heredocs是多行的字符串,用三个双引号包裹,它会保持里面内容的格式不变。 -我们可以在IEx中读取任何编译的模块的文档: - -```elixir -$ elixirc math.ex -$ iex -``` - -``` -iex> h Math # Access the docs for the module Math -... -iex> h Math.sum # Access the docs for the sum function -... -``` - -Elixir还提供了[ExDoc工具](https://github.com/elixir-lang/ex_doc), -利用注释生成HTML页文档。 - -你可以看看[模块](http://elixir-lang.org/docs/stable/elixir/Module.html) -里面列出的完整的模块注解列表,Elixir还利用注解来定义[typespecs](../20-typespecs-behaviors.md)。 - -本节讲了一些内置的注解。当然,注解可以被开发者和类库扩展使用,来支持自定义的行为。 - -## 作为常量 - -Elixir开发者经常会将模块属性当作常量使用: - -```elixir -defmodule MyServer do - @initial_state %{host: "147.0.0.1", port: 3456} - IO.inspect @initial_state -end -``` - ->不同于Erlang,默认情况下用户定义的属性不会被存储在模块里。属性值仅在编译时存在。 -开发者可以通过调用`Module.register_attribute/3`来使这种属性的行为更接近Erlang。 - -访问一个未定义的属性会报警告: - -```elixir -defmodule MyServer do - @unknown -end -warning: undefined module attribute @unknown, please remove access to @unknown or explicitly set it to nil before access -``` - -最后,属性也可以在函数中被读取: - -```elixir -defmodule MyServer do - @my_data 14 - def first_data, do: @my_data - @my_data 13 - def second_data, do: @my_data -end - -MyServer.first_data #=> 14 -MyServer.second_data #=> 13 -``` - -注意,在函数内读取某属性,读取的是该属性值的一份快照。换句话说,读取的是编译时的值,而非运行时。 -后面我们将看到,这个特点使得属性可以作为模块在编译时的临时存储,十分有用。 - -## 作为临时存储 - -Elixir组织中有一个项目,叫做[Plug](https://github.com/elixir-lang/plug), -这个项目的目标是创建一个通用的Web库和框架。 - ->注:我想功能应该类似于ruby的rack。你可以定义各种plug,这这些plug会像链条一样, -按顺序各自对http请求进行加工处理,最后返回。这类似给rails或sinatra定义各种rack中间件, -也有些类似Java filter的概念。最终,Plug框架会组织和执行它们。 - -Plug库允许开发者定义它们自己的plug,运行在web服务器上: - -```elixir -defmodule MyPlug do - use Plug.Builder - - plug :set_header - plug :send_ok - - def set_header(conn, _opts) do - put_resp_header(conn, "x-header", "set") - end - - def send_ok(conn, _opts) do - send(conn, 200, "ok") - end -end - -IO.puts "Running MyPlug with Cowboy on http://localhost:4000" -Plug.Adapters.Cowboy.http MyPlug, [] -``` - -上面例子中,我们用了`plug/1`宏来连接处理请求时会被调用的函数。 -在代码背后,每次调用宏`plug/1`时,Plug库把提供的参数(即plug的名字)存储在`@plugs`属性里。 -就在模块被编译之前,Plug会执行一个回调函数,该回调函数定义一个函数(`call/2`)来处理http请求。 -这个函数将按顺序执行所有保存在`@plugs`属性里的plugs。 - -要理解底层的代码,我们还需要了解宏,因此我们将在后期《元编程》章节中回顾这个模式。 -这里的重点是怎样使用属性来存储数据,让开发者可以创建DSL(领域特定语言)。 - -另一个例子来自[ExUnit框架](http://elixir-lang.org/docs/stable/ex_unit/), -它使用模块属性作为注解和存储: - -```elixir -defmodule MyTest do - use ExUnit.Case - - @tag :external - test "contacts external service" do - # ... - end -end -``` - -ExUnit中,标签(Tag)被用来注解该测试用例。在标记之后,这些标签可以用来过滤测试用例。 -例如,你可以避免执行那些被标记成`:external`的测试,因为它们执行起来很慢而且可以依赖外部的东西。 -但是它们依然在你的工程之内。 - -本章带你一窥Elixir元编程的冰山一角,讲解了模块属性在开发中是如何扮演关键角色的。 -下一章将讲解结构体(structs)和协议(protocols),在前进到其它更远的知识点(诸如异常处理等)之前。 diff --git a/15-structs.md b/15-structs.md deleted file mode 100644 index 066d485..0000000 --- a/15-structs.md +++ /dev/null @@ -1,113 +0,0 @@ -15-结构体 -========= - -在之前的某章中,我们学习了图(Map): - -```elixir -iex> map = %{a: 1, b: 2} -%{a: 1, b: 2} -iex> map[:a] -1 -iex> %{map | a: 3} -%{a: 3, b: 2} -``` - -结构体是基于图的一个扩展。它引入了默认值、编译期验证。 - -定义一个结构体,只需调用`defstruct/1`: - -```elixir -iex> defmodule User do -...> defstruct name: "john", age: 27 -...> end - -``` - -`defstruct/1`的参数(一个键值列表)定义了结构体的字段和默认值。结构体使用了定义它的模块的名字。 -像上面这个例子,我们定义的结构体叫做`User`。 - -现在可以用类似创建图的语法来创建结构体`User`: - -```elixir -iex> %User{} -%User{age: 27, name: "John"} -iex> %User{name: "Meg"} -%User{age: 27, name: "Meg"} -``` - -结构体提供*编译期验证*,在代码在编译时会检查结构体内仅有之前定义的字段(而且一个字段也不少): - -```elixir -iex> %User{ oops: :field } -** (CompileError) iex:3: unknown key :oops for struct User -``` - -## 访问和修改结构体 - -当讨论图的时候,我们演示了如何访问和修改图的字段。 -访问和修改结构体的技术(以及语法)也是一样的: - -```elixir -iex> john = %User{} -%User{age: 27, name: "John"} -iex> john.name -"John" -iex> meg = %{john | name: "Meg"} -%User{age: 27, name: "Meg"} -iex> %{meg | oops: :field} -** (KeyError) key :oops not found in: %User{age: 27, name: "Meg"} -``` - -当使用语法标记(`|`)的时候,虚拟机知道并没有增加新的字段,这使得底层的图可以共享内存中得结构。 -像上文的例子,`john`和`meg`在内存中使用相同的键值结构。 - -结构体也能用在模式匹配中,这不但可以保证结构体的字段名称的值相同,也可以确保对应的字段值的类型也相同: - -```elixir -iex> %User{name: name} = john -%User{age: 27, name: "John"} -iex> name -"John" -iex> %User{} = %{} -** (MatchError) no match of right hand side value: %{} -``` - -## 结构体和底层的图 - -在上面的例子里,之所以可以用模式匹配,是因为结构体底层不过是拥有固定字段的图。 -而作为图,结构体还存储了一个名叫`__struct__`的特殊字段,来存储结构体的名字: - -```elixir -iex> is_map(john) -true -iex> john.__struct__ -User -``` - -简单说,结构体就是个被扒光的图外加一个默认字段。 -为啥说是被扒光的图?因为,所有为图实现的协议(protocols)都不能用于结构体。 -例如,你不能像对图那样枚举或直接访问一个结构体: - -```elixir -iex> john = %User{} -%User{age: 27, name: "John"} -iex> john[:name] -** (UndefinedFunctionError) undefined function: User.fetch/2 -iex> Enum.each john, fn({field, value}) -> IO.puts(value) end -** (Protocol.UndefinedError) protocol Enumerable not implemented for %User{age: 27, name: "John"} -``` - -尽管如此,因为结构体说到底还是图,对图有效的函数也可以作用于结构体: - -```elixir -iex> kurt = Map.put(%User{}, :name, "Kurt") -%User{age: 27, name: "Kurt"} -iex> Map.merge(kurt, %User{name: "Takashi"}) -%User{age: 27, name: "Takashi"} -iex> Map.keys(john) -[:__struct__, :age, :name] -``` - -结构体和协议(protocols),为Elixir程序员提供了一个最重要的特性:数据多态。我们会在下一章解释和学习。 - -下一章我们将介绍结构体是如何同协议进行交互的。 diff --git a/16-proto.md b/16-proto.md deleted file mode 100644 index 7ff268b..0000000 --- a/16-proto.md +++ /dev/null @@ -1,264 +0,0 @@ -16-协议(protocols) -======== - -协议是实现Elixir多态性的重要机制。任何数据类型只要实现了某协议, -那么基于该协议的(函数调用)消息分发就是可用的。 - ->先简单解释一下上面“分发(dispatching)”的意思:对于许多编程语言, -特别是支持“duck-typing”的语言来说,对象调用方法,相当于以该对象为目的, -对其发送消息(函数/方法名),希望它支持该方法调用。 -这里的“协议”二字对于熟悉ruby等具有“duck-typing”特性的语言的人来说会比较容易理解。 - -让我们看个例子。 - -在Elixir中,只有`false`和`nil`被认为是“false”的。其它的值都被认为是“true”。 -根据程序需要,有时需要一个`blank?`协议(注意,我们此处称之为“协议”), -返回一个布尔值,以说明该参数是否为空。 -举例来说,一个空列表或者空二进制可以被认为是空的。 - -我们可以如下定义协议: -```elixir -defprotocol Blank do - @doc "Returns true if data is considered blank/empty" - def blank?(data) -end -``` - -从上面代码的语法上看,这个协议`Blank`声明了一个函数`blank?`,接受一个参数。 -我们可以为不同的数据类型实现这个协议: - -```elixir -# 整型永远不为空 -defimpl Blank, for: Integer do - def blank?(_), do: false -end - -# 只有空列表是“空”的 -defimpl Blank, for: List do - def blank?([]), do: true - def blank?(_), do: false -end - -# 只有空map是“空” -defimpl Blank, for: Map do - # 一定要记住,我们不能匹配 %{} ,因为它能match所有的map。 - # 但是我们能检查它的size是不是0 - # 检查size是很快速的操作 - def blank?(map), do: map_size(map) == 0 -end - -# 只有false和nil这两个原子被认为是“空” -defimpl Blank, for: Atom do - def blank?(false), do: true - def blank?(nil), do: true - def blank?(_), do: false -end -``` - -我们可以为所有内建数据类型实现协议: - - 原子 - - 比特串 - - 浮点型 - - 函数 - - 整型 - - 列表 - - 图 - - PID - - Port - - 引用 - - 元组 - -现在手上有了一个协议的定义以及其实现,可如此使用之: - -```elixir -iex> Blank.blank?(0) -false -iex> Blank.blank?([]) -true -iex> Blank.blank?([1, 2, 3]) -false -``` - -给它传递一个并没有实现该协议的数据类型,会导致报错: - -```elixir -iex> Blank.blank?("hello") -** (Protocol.UndefinedError) protocol Blank not implemented for "hello" -``` - -## 协议和结构体 - -Elixir的可扩展性(extensiblility)来源于将协议和结构体一同使用。 - -在前面几章中我们知道,尽管结构体本质上就是图(map),但是它和图并不共享各自协议的实现。 -像那章一样,我们先定义一个名为`User`的结构体: - -```elixir -iex> defmodule User do -...> defstruct name: "john", age: 27 -...> end -{:module, User, <<70, 79, 82, ...>>, {:__struct__, 0}} -``` - -然后看看能不能用刚才定义的协议: - -```elixir -iex> Blank.blank?(%{}) -true -iex> Blank.blank?(%User{}) -** (Protocol.UndefinedError) protocol Blank not implemented for %User{age: 27, name: "john"} -``` - -果然,结构体没有使用这个协议针对图的实现。 -因此,对于这个结构体,需要定义它的协议实现: - -```elixir -defimpl Blank, for: User do - def blank?(_), do: false -end -``` - -如果愿意,你可以定义你自己的语法来检查一个user是否为空。 -不光如此,你还可以使用结构体创建更强健的数据类型(比如队列),然后实现所有相关的协议, -比如`Enumerable`,或者是`Blank`等等。 - -## 实现`Any` - -手动给所有类型实现某些协议实现很快就会变得犹如重复性劳动般枯燥无味。 -在这种情况下,Elixir给出两种选择:一是显式让我们的类型继承某些已有的实现; -二是,自动给所有类型提供实现。这两种情况,我们都需要为`Any`类型写实现代码。 - -### 继承 - -Elixir允许我们继承某些有基于`Any`类型的实现。比如,我们先为`Any`实现某个协议: - -```Elixir -defimpl Blank, for: Any do - def blank?(_), do: false -end -``` - -OK我们现在有个协议通用的实现了。在定义结构体时,可以显式标注其继承了`Blank`协议的实现: - -```Elixir -defmodule DeriveUser do - @derive Blank - defstruct name: "john", age: 27 -end -``` - -继承的时候,Elixir会为`DeriveUser`实现`Blank`协议(基于`Blank`在`Any`上的实现)。 -这种方式是可选择的:结构体只会跟它们自己显式实现或继承实现的协议一起工作。 - -### 退化至`Any` - -`@derive`注解的一个替代物是显式地告诉协议,如果没有找到(在某个类型上得)实现的时候, -使用其`Any`的实现(如果有)。在定义协议的时候设置`@fallback_to_any`为`true`即可: - -```elixir -defprotocol Blank do - @fallback_to_any true - def blank?(data) -end -``` - -假使我们在前一小节已经完成了对`Any`的实现: - -```elixir -defimpl Blank, for: Any do - def blank?(_), do: false -end -``` - -现在,所有没有实现`blank`协议的数据类型(包括结构体)都会被认为是非空的。 -对比`@derive`,退化至`Any`是必然的:只有没有显式提供某个实现的实现,所有类型对于某个协议,都会有默认的行为。 -这项技术提供了很大的灵活性,也支持了Elixir程序员“显式先于隐式”的编码哲学。 -你可以在很多库中看到`@derive`的身影。 - -## 内建协议 - -Elixir内建了一些协议。在前面几章中我们讨论过`Enum`模块,它提供了许多方法。 -只要任何一种数据结构它实现了`Enumerable`协议,就能使用这些方法: - -```elixir -iex> Enum.map [1, 2, 3], fn(x) -> x * 2 end -[2,4,6] -iex> Enum.reduce 1..3, 0, fn(x, acc) -> x + acc end -6 -``` - -另一个例子是`String.Chars`协议,它规定了如何将包含字符的数据结构转换为字符串类型。 -它暴露为函数```to_string```: - -```elixir -iex> to_string :hello -"hello" -``` - -注意,在Elixir中,字符串插值操作背后就调用了```to_string```函数: - -```elixir -iex> "age: #{25}" -"age: 25" -``` - -上面代码能工作,是因为25这个数字类型实现了`String.Chars`协议。 -而如果传进去的是元组就会报错: - -```elixir -iex> tuple = {1, 2, 3} -{1, 2, 3} -iex> "tuple: #{tuple}" -** (Protocol.UndefinedError) protocol String.Chars not implemented for {1, 2, 3} -``` - -当想要打印一个比较复杂的数据结构时,可以使用`inspect`函数。该函数基于协议`Inspect`: - -```elixir -iex> "tuple: #{inspect tuple}" -"tuple: {1, 2, 3}" -``` - -`Inspect`协议用来将任意数据类型转换为可读的文字表述。IEx用来打印表达式结果用的就是它: - -```elixir -iex> {1, 2, 3} -{1,2,3} -iex> %User{} -%User{name: "john", age: 27} -``` - ->```inspect```是ruby中非常常用的方法。 -这也能看出Elixir的作者们真是绞尽脑汁把Elixir的语法尽量往ruby上靠。 - -记住,被执行`inspect`函数后的结果,是头顶着`#`符号的Elixir的类型描述文本,本身并不是合法的Elixir语法。 -在转换为可读的文本后,数值丢失了信息,因此别指望还能从该字符串取回原来的那个东西: - -```elixir -iex> inspect &(&1+2) -"#Function<6.71889879/1 in :erl_eval.expr/5>" -``` - -Elixir中还有些其它协议,但本章就讲这几个比较常用的。 - -## 协议压实(consolidation) - -当使用Mix构建工具的时候,你可能会看到如下输出: - -``` -Consolidated String.Chars -Consolidated Collectable -Consolidated List.Chars -Consolidated IEx.Info -Consolidated Enumerable -Consolidated Inspect -``` - -这些都是Elixir内建的协议,它们正在被“压实”(压紧、夯实;还有更好的翻译么?)。 -因为协议可以被分发给所有的数据类型,在每一次调用时,协议必须检查是否对某数据类型提供了实现。 -这消耗大量资源。 - -但是,如果使用构建工具Mix,我们会知道所有的模块已被定义,包括协议和实现。 -这样,协议可以被优化到一个简单的易于快速分发的模块中。 - -从Elixir v1.2开始,这种优化是自动进行的。后面的《Mix和OTP教程》中会讲到。 diff --git a/17-try-catch.md b/17-try-catch.md deleted file mode 100644 index c7bfe23..0000000 --- a/17-try-catch.md +++ /dev/null @@ -1,258 +0,0 @@ -17-异常处理 -=========== - -Elixir有三种错误处理机制:errors,throws和exits。 -本章我们将逐个讲解它们,包括应该在何时使用哪一个。 - -## Errors - -错误(errors,或者叫它异常)用在代码中出现意外的地方。 -举个例子,尝试让原子加上一个数字,就会返回一个错误: - -```elixir -iex> :foo + 1 -** (ArithmeticError) bad argument in arithmetic expression - :erlang.+(:foo, 1) -``` - -`raise/1`可以在任何时候激发一个运行时错误: - -```elixir -iex> raise "oops" -** (RuntimeError) oops -``` - -也可以调用`raise/2`抛出错误,并且附上错误名称和一个键值列表: - -```elixir -iex> raise ArgumentError, message: "invalid argument foo" -** (ArgumentError) invalid argument foo -``` - -你可以定义一个模块,在里面使用`defexception/2`定义你自己的错误。 -这种方式,你创建的错误和模块同名。最常见的是定义一个有详细错误信息字段的错误: - -```elixir -iex> defmodule MyError do -iex> defexception message: "default message" -iex> end -iex> raise MyError -** (MyError) default message -iex> raise MyError, message: "custom message" -** (MyError) custom message -``` - -错误可以用`try/catch`结构 **拯救(rescued)** : - -```elixir -iex> try do -...> raise "oops" -...> rescue -...> e in RuntimeError -> e -...> end -%RuntimeError{message: "oops"} -``` - -这个例子处理了一个运行时异常,返回该错误本身(被显示在`:iex`回话中)。 - -如果你不需要使用错误对象,你可以不提供它: - -```elixir -iex> try do -...> raise "oops" -...> rescue -...> RuntimeError -> "Error!" -...> end -"Error!" -``` - -在实际应用中,Elixir程序员极少使用`try/rescue`结构。 -例如,当文件打开失败,很多编程语言会强制你去处理异常。 -而Elixir提供的`File.read/1`函数不管文件打开成功与否,都会返回包含结果信息的元组: - -```elixir -iex> File.read "hello" -{:error, :enoent} -iex> File.write "hello", "world" -:ok -iex> File.read "hello" -{:ok, "world"} -``` - -这个例子中没有用到`try/rescue`。 -如果你想处理打开文件可能发生的不同结果,你可以使用`case`结构来做模式匹配: - -```elixir -iex> case File.read "hello" do -...> {:ok, body} -> IO.puts "Success: #{body}" -...> {:error, reason} -> IO.puts "Error: #{reason}" -...> end -``` - -使用这种匹配处理,你就可以自己决定打开文件异常是不是一种错误。 -这也是为什么Elixir不让`File.read/1`等函数自己抛出异常。 -它把决定权留给程序员,让他们寻找最合适的处理方法。 - -如果你真的期待文件存在(_打开文件时文件不存在_ 确实是一个 **错误**), -你可以简单地使用`File.read!/1`: - -```elixir -iex> File.read! "unknown" -** (File.Error) could not read file unknown: no such file or directory - (elixir) lib/file.ex:305: File.read!/1 -``` - -但是标准库中的许多函数都遵循这样的模式:不返回元组来模式匹配,而是抛出异常。 -具体说,这种约定是在定义名字不带感叹号后缀的函数时,返回结果信息的元组; -定义带有感叹号后缀的相同函数时,使用触发异常的机制。 -可以阅读`File`模块的代码,有很多关于这种约定的好例子。 - -总之在Elixir中,我们避免使用`try/rescue`是因为我们**不通过错误处理机制来控制程序执行流程**。 -我们视错误为其字面意思:它们只不过是用来处理意外时用到的信息。 -如果你真的希望异常机制改变程序执行流程,可以使用`throws`。 - -## Throws - -在Elixir中,你可以抛出(throw)一个值(不一定是一个错误/异常对象)做后续处理并终止当前其它操作。 -(前方文字高能=>)`throw`和`catch`就被保留用来处理这样有值被抛出、但是不用`try/catch`就取不到的情况。 - ->译注:这句话原文也差不多。仔细读读感觉逻辑类似于“X被用来描述不用X就无法描述的东西”。 - -这中情况很不多,非要找得话,比如当一个库的接口没有提供合适的API时。 -举个例子,`Enum`模块没有提供现成的API来做这个奇葩的事情:寻找若干数字里第一个13的倍数。 -你可以利用`throw`机制,在刚找到第一个符合条件的数时,抛出这个数字,并终止执行流程: - -```elixir -iex> try do -...> Enum.each -50..50, fn(x) -> -...> if rem(x, 13) == 0, do: throw(x) -...> end -...> "Got nothing" -...> catch -...> x -> "Got #{x}" -...> end -"Got -39" -``` - ->但实际上`Enum`提供了这样的API---使用`Enum.find/2`: - ->```elixir -iex> Enum.find -50..50, &(rem(&1, 13) == 0) --39 -``` - -## Exits - -Elixir代码都在各种进程中运行,彼此间相互通信。当一个进程因为自然原因死亡了(如“未处理的异常), -它会发出`exit`信号。一个进程可以通过显式地发出`exit`信号来终止: - -```elixir -iex> spawn_link fn -> exit(1) end -#PID<0.56.0> -** (EXIT from #PID<0.56.0>) 1 -``` - -上面的例子中,被链接的进程通过发送`exit`信号(带有参数1)而终止。 -Elixir shell自动处理这个消息并把它们显示在终端上。 - ->打比方,在某进程中执行的Elixir代码,突遇故障难以处理,便大喊一声“要死”后死亡; -或者它主动喊出一声“要死”而死亡。是该进程发送消息(即,调用函数)。 - -`exit`可以被`try/catch`块捕获处理: - -```elixir -iex> try do -...> exit "I am exiting" -...> catch -...> :exit, _ -> "not really" -...> end -"not really" -``` - -`try/catch`已经很少使用了,用它们捕获`exit`信号就更少见了。 - -`exit`信号是Erlang虚拟机提供的高容错性的重要部分。 -进程通常都在*监督树(supervision trees)*下运行。 -监督树本身也是进程,它任务就是一直等待下面被监督进程的`exit`信号。 -一旦监听到退出信号,监督策略就开始工作,发送了死亡信号的被监督进程会被重启。 - -就是这种监督机制使得`try/catch`和`try/rescue`代码块很少用到。 -与其拯救一个错误,不如让它*快速失败*。 -因为在程序发生失败后,监督树会保证这个程序恢复到一个已知的初始状态去。 - -## After - -有时候我们有必要确保某资源在执行可能会发生错误的操作后被正确地关闭或清理。 -使用`try/after`结构来做这个。 -例如打开一个文件,使用`after`子句来确保它在使用后被关闭,即使发生了错误: - -```elixir -iex> {:ok, file} = File.open "sample", [:utf8, :write] -iex> try do -...> IO.write file, "olá" -...> raise "oops, something went wrong" -...> after -...> File.close(file) -...> end -** (RuntimeError) oops, something went wrong -``` - -`after`块中的代码,无论`try`代码块中是否出现错误,其都会执行。 -但是,也有例外。如果一个链接进程整个终止了,它代码中的`after`块可能还没有执行。 -因此,我们说`after`只是个“软”保障。 -幸运的是,在Elixir语言中,打开的文件永远是链接到当前进程的。如果当前进程挂了,文件也会跟着关闭。 -不管执没执行`after`块。 -其它一些资源,如ETS表,套接字,端口等也是这样。 - -有时候你想将整个函数体用`try`结构包起来,是某些代码在某情况下会后续执行。 -这时,Elixir允许你不写`try`那行: - -```elixir -iex> defmodule RunAfter do -...> def without_even_trying do -...> raise "oops" -...> after -...> IO.puts "cleaning up!" -...> end -...> end -iex> RunAfter.without_even_trying -cleaning up! -** (RuntimeError) oops -``` - -这时,Elixir会将整个函数体的代码用`try`块包裹,不管后面是`after`,`rescue`还是`catch`。 - -## 变量的作用域 - -定义在`try/catch/rescue/after`代码块中的变量,不会泄露到外面去。 -这是因为`try`代码块有可能会失败,而这些变量此时并没有正常绑定数值: - -换句话说,下面这份代码是错误的: - -```elixir -iex> try do -...> raise "fail" -...> what_happened = :did_not_raise -...> rescue -...> _ -> what_happened = :rescued -...> end -iex> what_happened -** (RuntimeError) undefined function: what_happened/0 -``` - -相反,你可以保存`try`表达式的返回值: - -```elixir -iex> what_happened = -...> try do -...> raise "fail" -...> :did_not_raise -...> rescue -...> _ -> :rescued -...> end -iex> what_happened -:rescued -``` - -至此我们结束了对`try/catch/rescue`的介绍。 -你会发现Elixir语言中的这些概念的使用频率比其他语言小,尽管的确有时使用起来也挺顺手。 diff --git a/18-comprehensions.md b/18-comprehensions.md deleted file mode 100644 index 6f97da6..0000000 --- a/18-comprehensions.md +++ /dev/null @@ -1,166 +0,0 @@ -18-速构(Comprehension) -======== - -> *Comprehensions* 翻译成“速构”是参照了《Erlang/OTP in Action》译者的用辞。 -国内一些Python书(是的,Python也有这个概念)中翻译为“推导式”、“递推式”。 -这里不用纠结它的翻译,更重要的是需要弄明白它是什么。 - ->“速构”是函数式语言中常见的概念,指的是定义规则来生成一系列元素填充新的数据集合。 -这个概念我们在中学的数学课上其实就已经接触过,在大学高数中更为常见: -如`{ x | x ∈ N }`这个表达式,字面上意思是:这是一个集合, -这个集合里每个元素x符合“x属于自然数N”这个条件。即,用自然数集合的所有元素来构成这个集合。 -相关知识可参考[WIKI](http://en.wikipedia.org/wiki/List_comprehension)。 - -Elixir中,使用枚举类型(Enumerable,如列表)来做循环操作是很常见的, -通常还搭配过滤(filtering)和映射(mapping)行为。 -速构(comprehensions)就是为此目的诞生的语法糖:把这些常见任务分组,放到特殊的`for`指令中表达出来。 - -例如,我们可以这样,生成原列表中每个元素的平方: - -```elixir -iex> for n <- [1, 2, 3, 4], do: n * n -[1, 4, 9, 16] -``` - ->注意看,`<-`符号其实是模拟符号`∈ `的形象。 -这个例子用熟悉(当然,如果你高数课没怎么听那就另当别论)的数学符号表示就是: - -``` -S = { X^2 | X ∈ [1,4], X ∈ N } -``` - -速构由三部分组成:生成器,过滤器和收集式。 - -## 生成器和过滤器 - -在上面的例子中,`n <- [1, 2, 3, 4]`就是生成器。 -它字面意思上生成了即将要在速构中使用的数值。任何枚举类型(Enumerable)都可以传递给生成器表达式的右端: - -```elixir -iex> for n <- 1..4, do: n * n -[1, 4, 9, 16] -``` - -生成器表达式左操作数支持模式匹配,它会**忽略**所有不匹配的模式。 -想象一下如果不用范围而是用一个键值列表作为生成器的数据源,它的键只有`:good`和`:bad`两种, -我们仅要计算键为‘:good’的元素值的平方: - -```elixir -iex> values = [good: 1, good: 2, bad: 3, good: 4] -iex> for {:good, n} <- values, do: n * n -[1, 4, 16] -``` - -除了使用模式匹配,过滤器也可以用来选择某些特定数值。 -例如我们可以只选择3的倍数,而丢弃其它数值: - -```elixir -iex> multiple_of_3? = fn(n) -> rem(n, 3) == 0 end -iex> for n <- 0..5, multiple_of_3?.(n), do: n * n -[0, 9] -``` - -速构过程会丢弃过滤器表达式结果为`false`或`nil`的值;其它值都会被保留。 - -总的来说,速构提供了比直接使用`Enum`或`Stream`模块的函数更精确的表达。 -不但如此,速构还可以接受多个生成器和过滤器。下面就是一个例子,代码接受目录列表, -删除这些目录下的所有文件: - -```elixir -for dir <- dirs, - file <- File.ls!(dir), - path = Path.join(dir, file), - File.regular?(path) do - File.stat!(path).size -end -``` - -多生成器还可以用来生成两个列表的笛卡尔积: - -```elixir -iex> for i <- [:a, :b, :c], j <- [1, 2], do: {i, j} -[a: 1, a: 2, b: 1, b: 2, c: 1, c: 2] -``` - -关于多生成器、过滤器的更高级些的例子:计算毕达哥拉斯三元数(Pythagorean triples)。 -毕氏三元数一组正整数满足`a * a + b * b = c * c`,让我们在文件`triples.exs`里写这个速构: - -```elixir -defmodule Triple do - def pythagorean(n) when n > 0 do - for a <- 1..n, - b <- 1..n, - c <- 1..n, - a + b + c <= n, - a*a + b*b == c*c, - do: {a, b, c} - end -end -``` - -然后,在终端里: - -``` -iex triple.exs -``` - -```elixir -iex> Triple.pythagorean(5) -[] -iex> Triple.pythagorean(12) -[{3, 4, 5}, {4, 3, 5}] -iex> Triple.pythagorean(48) -[{3, 4, 5}, {4, 3, 5}, {5, 12, 13}, {6, 8, 10}, {8, 6, 10}, {8, 15, 17}, - {9, 12, 15}, {12, 5, 13}, {12, 9, 15}, {12, 16, 20}, {15, 8, 17}, {16, 12, 20}] -``` - -Finally, keep in mind that variable assignments inside the comprehension, be it in generators, filters or inside the block, are not reflected outside of the comprehension. - -需要记住的是,在生成器、过滤器或者代码块中赋值的变量,不会暴露到速构外面去。 - -## 比特串生成器 - -速构也支持比特串作为生成器,这种生成器在处理比特流时非常有用。 -下面的例子中,程序接收一个表示像素颜色的比特串(格式为<<像素1的R值,像素1的G值,像素1的B值, -像素2的R值,像素2的G...>>),把它转换为三元元组的列表: - -```elixir -iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>> -iex> for <>, do: {r, g, b} -[{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}] -``` - -比特串生成器可以和“普通的”枚举类型生成器混合使用,过滤器也是。 - -## `:into`选项 - -在上面的例子中,速构返回列表作为结果。 -但是,通过使用```:into```选项,速构的结果可以插入到不同的数据结构中。 -例如,你可以使用比特串生成器加上```:into```来轻松地移除字符串中的空格: - -```elixir -iex> for <>, c != ?\s, into: "", do: <> -"helloworld" -``` - -集合、图、其他字典类型都可以传递给`:into`选项。总的来说,`:into`接受任何实现了_Collectable_协议的数据结构。 - -`:into`选项一个常见的作用是,不用操作键,而改变图中元素的值: - -```elixir -iex> for {key, val} <- %{"a" => 1, "b" => 2}, into: %{}, do: {key, val * val} -%{"a" => 1, "b" => 4} -``` - -再来一个使用流的例子。因为`IO`模块提供了流(既是Enumerable也是Collectable)。 -你可以使用速构实现一个回声终端,让其返回任何输入的字母的大写形式: - -```elixir -iex> stream = IO.stream(:stdio, :line) -iex> for line <- stream, into: stream do -...> String.upcase(line) <> "\n" -...> end -``` - -现在在终端中输入任意字符串,你会看到同样的内容以大写形式被打印出来。 -不幸的是,这个例子会让你的shell陷入到该速构代码中,只能用Ctrl+C两次来退出:-)。 diff --git a/19-sigils.md b/19-sigils.md deleted file mode 100644 index 547f43b..0000000 --- a/19-sigils.md +++ /dev/null @@ -1,200 +0,0 @@ -19-魔法印(Sigils) -========== - ->看看标题,这个“魔法印”是什么奇葩翻译? -Sigil原意是“魔符,图章,印记”, -如古代西方魔幻传说中的巫女、魔法师画的封印或者召唤魔鬼的六芒星, -中国道士画的咒符,火影里面召唤守护兽的血印等。 -在计算机编程领域,Sigil指的是在变量名称上做的标记,用来标明它的作用域或者类型什么的。 -例如某语言里面`$var`中的`$`就是这样的东西,表示其为全局变量。 -不同的魔法印赋予变量不同的属性,这么看,翻译成“魔法印”还挺带感呢。 -本章(或者本文)所有的*sigil*都会翻译成“魔法印”或是采用英文原文。 - -我们已经学习了Elixir提供的字符串(双引号包裹)和字符列表(单引号包裹)。 -但是对于Elixir中所有的*文本描述型数据类型*来说,这些只是冰山一角。其它的, -例如*原子*也是一种文本描述型数据类型。 - -Elixir的一个特点就是高可扩展性:开发者能够为特定的领域来扩展语言。 -计算机科学的领域已是如此广阔。几乎无法设计一门语言来涵盖所有范围。 -我们的打算是,与其创造出一种万能的语言,不如创造一种可扩展的语言, -让开发者可以根据所从事的领域来对语言进行扩展。 - -本章将讲述“魔法印(sigils)”,它是Elixir提供的处理文本描述型数据的一种机制。 - -## 19.1-正则表达式 -魔法印以波浪号(~)起头,后面跟着一个字母,然后是分隔符。最常用的魔法印是~r, -代表[正则表达式](https://en.wikipedia.org/wiki/Regular_Expressions): - -```elixir -# A regular expression that returns true if the text has foo or bar -iex> regex = ~r/foo|bar/ -~r/foo|bar/ -iex> "foo" =~ regex -true -iex> "bat" =~ regex -false -``` - -Elixir提供了Perl兼容的正则表达式(regex),由[PCRE库](http://www.pcre.org/)实现。 - -正则表达式支持修饰符(modifiers),例如```i```修饰符使该正则表达式无视大小写: - -```elixir -iex> "HELLO" =~ ~r/hello/ -false -iex> "HELLO" =~ ~r/hello/i -true -``` - -阅读[Regex模块](http://elixir-lang.org/docs/stable/elixir/Regex.html)获取关于其它修饰符的及其所支持的操作的更多信息。 - -目前为止,所有的例子都用了```/```界定正则表达式。事实上魔法印支持8种不同的分隔符: - -```elixir -~r/hello/ -~r|hello| -~r"hello" -~r'hello' -~r(hello) -~r[hello] -~r{hello} -~r -``` - -支持多种分隔符是因为在处理不同的魔法印的时候更加方便。 -比如,使用括号作为正则表达式的分隔符会让人困惑,分不清括号是正则模式的一部分还是别的什么。 -但是,括号对某些魔法印来说就很方便。 - -## 19.2-字符串、字符列表和单词魔法印 -除了正则表达式,Elixir还提供了三种魔法印。 - -魔法印```~s``` 用来生成字符串,类似双引号的作用: - -```elixir -iex> ~s(this is a string with "quotes") -"this is a string with \"quotes\"" -``` -通过这个例子可以看出,如果文本中有双引号,又不想逐个转义,可以用这种魔法印来包裹字符串。 - -魔法印```~c``` 用来生成字符列表: - -```elixir -iex> ~c(this is a string with "quotes") -'this is a string with "quotes"' -``` - -魔法印```~w``` 用来生成单词,以空格分隔开: - -```elixir -iex> ~w(foo bar bat) -["foo", "bar", "bat"] -``` - -魔法印```~w``` 还接受```c```,```s```和```a```修饰符(分别代表字符列表,字符串和原子) -来选择结果的类型: - -```elixir -iex> ~w(foo bar bat)a -[:foo, :bar, :bat] -``` - -除了小写的魔法印,Elixir还支持大写的魔法印。如,```~s```和```~S```都返回字符串, -前者会解释转义字符而后者不会: - -```elixir -iex> ~s(String with escape codes \x26 interpolation) -"String with escape codes & interpolation" -iex> ~S(String without escape codes and without #{interpolation}) -"String without escape codes and without \#{interpolation}" -``` - -字符串和字符列表支持以下转义字符: - - \" 表示一个双引号 - - \' 表示一个单引号 - - \\\ 表示一个反斜杠 - - \a 响铃 - - \b 退格 - - \d 删除 - - \e 退出 - - \f 换页 - - \n 新行 - - \r 换行 - - \s 空格 - - \t 水平制表符 - - \v 垂直制表符 - - \DDD, \DD, \D 八进制数字(如\377) - - \xDD 十六进制数字(如\x13) - - \x{D...} 多个十六进制字符的十六进制数(如\x{abc13} - - -魔法印还支持多行文本(heredocs),使用的是三个双引号或单引号: - -```elixir -iex> ~s""" -...> this is -...> a heredoc string -...> """ -``` - -最常见的有多行文本的魔法印就是写注释文档了。 -例如,如果你要在注释里写一些转义字符,这有可能会报错。 - -```elixir -@doc """ -Converts double-quotes to single-quotes. - -## Examples - - iex> convert("\\\"foo\\\"") - "'foo'" - -""" -def convert(...) -``` - -使用```~S```,我们就可以避免问题: - -```elixir -@doc ~S""" -Converts double-quotes to single-quotes. - -## Examples - - iex> convert("\"foo\"") - "'foo'" - -""" -def convert(...) -``` - -### 19.3-自定义魔法印 -本章开头提到过,魔法印是可扩展的。事实上,魔法印```~r/foo/i```等于是 -用两个参数调用了函数```sigil_r```: - -```elixir -iex> sigil_r(<<"foo">>, 'i') -~r"foo"i -``` - -就是说,我们可以通过该函数阅读魔法印```~r```的文档: - -```elixir -iex> h sigil_r -... -``` - -我们也可以通过实现相应的函数来提供我们自己的魔法印。例如,我们来实现一个```~i(N)```魔法印, -返回整数: - -```elixir -iex> defmodule MySigils do -...> def sigil_i(string, []), do: String.to_integer(string) -...> end -iex> import MySigils -iex> ~i("13") -13 -``` - -魔法印通过宏,可以用来做一些发生在*编译时*的工作。例如,正则表达式在编译时会被编译, -而在执行的时候就不必再被编译了。 -如果你对此主题感兴趣,可以多阅读关于宏的资料,并且阅读Kernel模块中那些魔法印的实现。 diff --git a/2-basic-types.md b/2-basic-types.md deleted file mode 100644 index eef430f..0000000 --- a/2-basic-types.md +++ /dev/null @@ -1,355 +0,0 @@ -2-基本类型 -========== - -本章介绍Elixir的基本类型。Elixir主要的基本类型有: -整型(integer),浮点(float),布尔(boolean),原子(atom,又称symbol符号), -字符串(string),列表(list)和元组(tuple)等。 - -它们在iex中显示如下: -```elixir -iex> 1 # integer -iex> 0x1F # integer -iex> 1.0 # float -iex> true # boolean -iex> :atom # atom / symbol -iex> "elixir" # string -iex> [1, 2, 3] # list -iex> {1, 2, 3} # tuple -``` - -## 2.1-基本算数运算 -打开```iex```,输入以下表达式: -```elixir -iex> 1 + 2 -3 -iex> 5 * 5 -25 -iex> 10 / 2 -5.0 -``` - ->```10 / 2```返回了一个浮点型的5.0而非整型的5,这是预期的。 -在Elixir中,```/```运算符总是返回浮点型数值。 - -如果你想进行整型除法,或者求余数,可以使用函数```div```和```rem```。 -(rem的意思是division remainder,余数): -```elixir -iex> div(10, 2) -5 -iex> div 10, 2 -5 -iex> rem 10, 3 -1 -``` ->在写函数参数时,括号是可选的。(ruby程序员会心一笑) - -Elixir支持用 **捷径(shortcut)** 书写二进制、八进制、十六进制整数。如: -```elixir -iex> 0b1010 -10 -iex> 0o777 -511 -iex> 0x1F -31 -``` ->揉揉眼,八进制是```0o```,数字0 + 小写o。 - -输入浮点型数字需要一个小数点,且在其后至少有一位数字。 -Elixir支持使用```e```来表示指数: -```elixir -iex> 1.0 -1.0 -iex> 1.0e-10 -1.0e-10 -``` -Elixir中浮点型都是64位双精度。 - -## 2.2-布尔 -Elixir使用```true```和```false```两个布尔值。 -```elixir -iex> true -true -iex> true == false -false -``` -Elixir提供了许多用以判断类型的函数,如```is_boolean/1```函数可以用来检查参数是不是布尔型。 - ->在Elixir中,函数通过名称和参数个数(又称元数,arity)来识别。 -如```is_boolean/1```表示名为```is_boolean```,接受一个参数的函数; -而```is_boolean/2```表示与其同名、但接受2个参数的**不同**函数。(只是打个比方,这样的is_boolean实际上不存在) -另外,```<函数名>/<元数>```这样的表述是为了在讲述函数时方便,在实际程序中如果调用函数, -是不用注明```/1```或```/2```的。 - -```elixir -iex> is_boolean(true) -true -iex> is_boolean(1) -false -``` - -类似的函数还有```is_integer/1```,```is_float/1```,```is_number/1```, -分别测试参数是否是整型、浮点型或者两者其一。 - ->可以在交互式命令行中使用```h```命令来打印函数或运算符的帮助信息。 -如```h is_boolean/1```或```h ==/2```。 -注意此处提及某个函数时,不但要给出名称,还要加上元数```/```。 - -## 2.3-原子 -原子(atom)是一种常量,名字就是它的值。 -有些语言中称其为 **符号(symbol)**(如ruby): -```elixir -iex> :hello -:hello -iex> :hello == :world -false -``` - -布尔值```true```和```false```实际上就是原子: -```elixir -iex> true == :true -true -iex> is_atom(false) -true -``` - -## 2.4-字符串 -在Elixir中,字符串以 **双括号** 包裹,采用UTF-8编码: -```elixir -iex> "hellö" -"hellö" -``` - -Elixir支持字符串插值(和ruby一样使用```#{ ... }```): -```elixir -iex> "hellö #{:world}" -"hellö world" -``` - -字符串可以直接包含换行符,或者其转义字符: -```elixir -iex> "hello -...> world" -"hello\nworld" -iex> "hello\nworld" -"hello\nworld" -``` - -你可以使用```IO```模块(module)里的```IO.puts/1```方法打印字符串: -```elixir -iex> IO.puts "hello\nworld" -hello -world -:ok -``` -函数```IO.puts/1```打印完字符串后,返回原子值```:ok```。 - -字符串在Elixir内部被表示为二进制数值(binaries),也就是一连串的字节(bytes): -```elixir -iex> is_binary("hellö") -true -``` ->注意,二进制数值(binary)是Elixir内部的存储结构之一。 -字符串、列表等类型在语言内部就表示为二进制数值,因此它们也可以被专门操作二进制数值的函数修改。 - -你可以查看字符串包含的字节数量: -```elixir -iex> byte_size("hellö") -6 -``` ->为啥是6?不是5个字符么?注意里面有一个非ASCII字符```ö```,在UTF-8下被编码为2个字节。 - -我们可以使用专门的函数来返回字符串中的字符数量: -```elixir -iex> String.length("hellö") -5 -``` - -[String模块](http://elixir-lang.org/docs/stable/elixir/String.html)中提供了 -很多符合Unicode标准的函数来操作字符串。如: -```elixir -iex> String.upcase("hellö") -"HELLÖ" -``` - -记住,单引号和双引号包裹的字符串在Elixir中是两种不同的数据类型: -```elixir -iex> 'hellö' == "hellö" -false -``` -我们将在之后关于“二进制、字符串与字符列表”章节中详细讲述它们的区别。 - -## 2.5-匿名函数 -在Elixir中,使用关键字```fn```和```end```来界定函数。如: -```elixir -iex> add = fn a, b -> a + b end -#Function<12.71889879/2 in :erl_eval.expr/5> -iex> is_function(add) -true -iex> is_function(add, 2) -true -iex> is_function(add, 1) -false -iex> add.(1, 2) -3 -``` -在Elixir中,函数是 **一等公民**。你可以将函数作为参数传递给其他函数,就像整型和浮点型一样。 -在上面的例子中,我们向函数```is_function/1```传递了由变量```add```表示的匿名函数, -结果返回```true```。 -我们还可以调用函数```is_function/2```来判断该参数函数的元数(参数个数)。 - -注意,在调用一个匿名函数时,在变量名和写参数的括号之间要有个 **点号(.)**。 - -匿名函数是闭包,意味着它们可以保留其定义的作用域(scope)内的其它变量值: -```elixir -iex> add_two = fn a -> add.(a, 2) end -#Function<6.71889879/1 in :erl_eval.expr/5> -iex> add_two.(2) -4 -``` -这个例子定义的匿名函数```add_two```它内部使用了之前在同一个iex内定义好的```add```变量。 -但要注意,在匿名函数内修改了所引用的外部变量的值,并不实际反映到该变量上: -```elixir -iex> x = 42 -42 -iex> (fn -> x = 0 end).() -0 -iex> x -42 -``` -这个例子中匿名函数把引用了外部变量x,并修改它的值为0。这时函数执行后,外部的x没有被影响。 - -## 2.6-(链式)列表 -Elixir使用方括号标识列表。列表可以包含任意类型的值: -```elixir -iex> [1, 2, true, 3] -[1, 2, true, 3] -iex> length [1, 2, 3] -3 -``` - -两个列表可以使用```++/2```拼接,使用```--/2```做“减法”: -```elixir -iex> [1, 2, 3] ++ [4, 5, 6] -[1, 2, 3, 4, 5, 6] -iex> [1, true, 2, false, 3, true] -- [true, false] -[1, 2, 3, true] -``` - -本教程将多次涉及列表头(head)和尾(tail)的概念。 -列表的头指的是第一个元素,而尾指的是除了第一个元素以外,其它元素组成的列表。 -它们分别可以用函数```hd/1```和```tl/1```从原列表中取出: -```elixir -iex> list = [1,2,3] -iex> hd(list) -1 -iex> tl(list) -[2, 3] -``` - -尝试从一个空列表中取出头或尾将会报错: -```elixir -iex> hd [] -** (ArgumentError) argument error -``` - -## 2.7-元组 -Elixir使用大括号(花括号)定义元组(tuples)。类似列表,元组也可以承载任意类型的数据: -```elixir -iex> {:ok, "hello"} -{:ok, "hello"} -iex> tuple_size {:ok, "hello"} -2 -``` -元组使用 ***连续的内存空间*** 存储数据。 -这意味着可以很方便地使用索引访问元组数据,以及获取元组大小(索引从0开始): -```elixir -iex> tuple = {:ok, "hello"} -{:ok, "hello"} -iex> elem(tuple, 1) -"hello" -iex> tuple_size(tuple) -2 -``` - -也可以很方便地使用函数```put_elem/3```设置某个位置的元素值: -```elixir -iex> tuple = {:ok, "hello"} -{:ok, "hello"} -iex> put_elem(tuple, 1, "world") -{:ok, "world"} -iex> tuple -{:ok, "hello"} -``` - -注意函数```put_elem/3```返回一个新元组。原来那个由变量tuple标识的元组没有被改变。 -这是因为Elixir的数据类型是 **不可变的**。 -这种不可变性使你永远不用担心你的数据会在某处被某些代码改变。 -在处理并发程序时,这种不可变性有利于减少多个程序实体同时修改一个数据结构时引起的竞争以及其他麻烦。 - -## 2.8-列表还是元组? -列表与元组的区别:列表在内存中是以链表的形式存储的,一个元素指向下一个元素, -然后再下一个...直到到达列表末尾。 -我们称这样的一对数据(元素值 和 指向下一个元素的指针)为列表的一个单元(cons cell)。 - -用Elixir语法表示这种模式: -```elixir -iex> list = [1|[2|[3|[]]]] -[1, 2, 3] -``` ->列表方括号中的竖线(|)表示列表头与尾的分界。 - -这个原理意味着获取列表的长度是一个线性操作:我们必须遍历完整个列表才能知道它的长度。 -但是列表的前置拼接操作很快捷: -```elixir -iex> [0] ++ list -[0, 1, 2, 3] -iex> list ++ [4] -[1, 2, 3, 4] -``` - -上面例子中第一条语句是 __前置__ 拼接操作,执行起来很快。 -因为它只是简单地添加了一个新列表单元,它的尾指针指向原先列表头部。而原先的列表没有任何变化。 - -第二条语句是 __后缀__ 拼接操作,执行速度较慢。 -这是因为它 **重建** 了原先的列表,让原先列表的末尾元素指向那个新元素。 - -另一方面,元组在内存中是连续存储的。 -这意味着获取元组大小,或者使用索引访问元组元素的操作十分快速。 -但是元组在修改或添加元素时开销很大,因为这些操作会在内存中对元组的进行整体复制。 - -这些讨论告诉我们当如何在不同的情况下选择使用不同的数据结构。 - -函数常用元组来返回多个信息。如```File.read/1```,它读取文件内容,返回一个元组: -```elixir -iex> File.read("path/to/existing/file") -{:ok, "... contents ..."} -iex> File.read("path/to/unknown/file") -{:error, :enoent} -``` - -如果传递给函数```File.read/1```的文件路径有效,那么函数返回一个元组, -其首元素是原子```:ok```,第二个元素是文件内容。 -如果路径无效,函数也将返回一个元组,其首元素是原子```:error```,第二个元素是错误信息。 - -大多数情况下,Elixir会引导你做正确的事。 -比如有个叫```elem/2```的函数,它使用索引来访问一个元组元素。 -这个函数没有相应的列表版本,因为根据存储机制,列表不适用通过索引来访问: -```elixir -iex> tuple = {:ok, "hello"} -{:ok, "hello"} -iex> elem(tuple, 1) -"hello" -``` - -当需要计算某数据结构包含的元素个数时,Elixir遵循一个简单的规则: -如果操作在常数时间内完成(答案是提前算好的),这样的函数通常被命名为 ```*size```。 -而如果操作需要显式计数,那么该函数通常命名为 ```*length```。 - -例如,目前讲到过的4个计数函数:```byte_size/1```(用来计算字符串有多少字节),```tuple_size/1``` -(用来计算元组大小),```length/1```(计算列表长度) -以及```String.length/1```(计算字符串中的字符数)。 - -按照命名规则,当我们用```byte_size```获取字符串所占字节数时,开销较小。 -但是当我们用```String.length```获取字符串unicode字符个数时,需要遍历整个字符串,开销较大。 - -除了本章介绍的数据类型,Elixir还提供了 **Port**,**Reference** 和 **PID** 三个数据类型(它们常用于进程交互)。这些数据类型将在讲解进程时详细介绍。 diff --git a/20-typespecs-behaviors.md b/20-typespecs-behaviors.md deleted file mode 100644 index 15f837f..0000000 --- a/20-typespecs-behaviors.md +++ /dev/null @@ -1,163 +0,0 @@ -20-Typespecs和behaviors -======================= - -## 类型(type)和规格说明(spec) - -Elixir是一门动态类型语言,Elixir中所有数据类型都是在运行时动态推定的。 -然而,Elixir还提供了 **typespecs** 标记,用来: - - 1. 声明自定义数据类型 - 2. 声明含有显式类型说明的函数签名(即函数的规格说明) - -### 函数的规格说明(spec) - -默认地,Elixir提供了一些基础数据类型,表示为 `integer` 或者 `pid`。 -还有一些复杂情形:如函数`round/1`为例,它对一个float类型的数值四舍五入。 -它以一个`number`(一个`integer`或`float`)作为参数,返回一个`integer`。 - -那么,它在[round函数的文档](http://elixir-lang.org/docs/stable/elixir/Kernel.html#round/1) -里面记载的函数签名为: - -``` -round(number) :: integer -``` - -`::` 表示其左边的函数 *返回* 一个其右面声明的类型的值。函数名后面括号中是参数类型的列表。 - -如果想特别注明某个函数的参数类型及返回值类型,那么可以在定义函数的时候, -在函数前面使用`@spec`指令附加上函数的规格说明(spec)。 - -比如,在函数库源码中,函数`round/1`是这么写的: - -```elixir -@spec round(number) :: integer -def round(number), do: # 具体实现 ... -``` - -Elixir还支持组合类型。例如,整数的列表,它的类型表示为`[integer]`。 -可以阅读[typespecs的文档](http://elixir-lang.org/docs/stable/elixir/typespecs.html) -查看Elixir提供的所有内建类型的表示方法。 - -### 定义自定义类型 - -Elixir提供了许多有用的内建类型,而且也方便创建自定义类型应用于特定场景。 -方法是在定义的时候,加上`@type`指令。 - -比如我们有个模块叫做`LuosyCalculator`,可以执行常见的算术计算(如求和、计算乘积等)。 -但是,它的函数不是返回结果数值,而是返回一个元組, -该元組第一个元素是计算结果,第二个是随机的文字记号。 - -```elixir -defmodule LousyCalculator do - @spec add(number, number) :: {number, String.t} - def add(x, y), do: { x + y, "你用计算器算这个?!" } - - @spec multiply(number, number) :: {number, String.t} - def multiply(x, y), do: { x * y, "老天,不是吧?!" } -end -``` - -从例子中可以看出,元组是复合类型。每个元组都定义了其具体元素类型。 -至于为何是`String.t`而不是`string`的原因,可以参考 -[这篇文章](http://elixir-lang.org/docs/stable/elixir/typespecs.html#Notes), -此处不多说明。 - -像这样定义函数规格说明是没问题,但是一次次重复写这种复合类型的 -表示方法`{number, String.t}`,很快会厌烦的吧。 -我们可以使用`@type`指令来声明我们自定义的类型: - -```elixir -defmodule LousyCalculator do - @typedoc """ - Just a number followed by a string. - """ - @type number_with_remark :: {number, String.t} - - @spec add(number, number) :: number_with_remark - def add(x, y), do: {x + y, "You need a calculator to do that?"} - - @spec multiply(number, number) :: number_with_remark - def multiply(x, y), do: {x * y, "It is like addition on steroids."} -end -``` - -指令`@typedoc`,和`@doc`或`@moduledoc`指令类似,用来解释说明自定义的类型,放在`@type`前面。 - -另外,通过`@type`定义的自定义类型,实际上也是模块的成员,可以被外界访问: - -```elixir -defmodule QuietCalculator do - @spec add(number, number) :: number - def add(x, y), do: make_quiet(LousyCalculator.add(x, y)) - - @spec make_quiet(LousyCalculator.number_with_remark) :: number - defp make_quiet({num, _remark}), do: num -end -``` - -如果想要将某个自定义类型保持私有,可以使用 `@typep` 指令代替 `@type` 。 - -### 静态代码分析 - -给函数等元素标记类型或者签名的作用,不仅仅是被用来作为程序文档说明。举个例子, -Erlang工具[Dialyzer][Dialyzer](http://www.erlang.org/doc/man/dialyzer.html) -通过这些类型或者签名标记,进行代码静态分析。 -这就是为什么我们在 `QuiteCalculator` 例子中, -即使 `make_quite/1` 是个私有函数,也写了函数规格说明。 - -## 行为(behavior) - -许多模块公用相同的公共API。可以参考下[Plug](https://github.com/elixir-lang/plug), -正如它的描述所言,是一个用于互联网应用的、可编辑的模块的**规格声明**。 -每个所谓*plug*就是一个**必须**实现至少两个公共函数:`init/1`和`call/2`的模块。 - -行为提供了一种方法,用来: - -* 定义一系列必须实现的函数 -* 确保模块实现所有这些函数 - -你也可以把这些行为想象为面向对象语言里的接口:模块必须实现的一系列函数签名。 - -### 定义行为(Defining behaviors) - -假如说我们希望实现一系列parser,每个parser解析结构化的数据:比如,一个JSON parser或是YAML parser。 -这两个parser的*行为*几近相同: -它们都提供一个`parse/1`函数和一个`extensions/0`函数。`parse/1`函数返回一个数据对应的Elixir表达。 -而`extensions/0`函数返回一个可被其解析的文件的扩展名列表(如,JSON文件是`.json`)。 - -我们可以创建一个名为`Parser`的行为: - -```elixir -defmodule Parser do - @callback parse(String.t) :: any - @callback extensions() :: [String.t] -end -``` - -那么,采用`Parser`这个行为的模块,必须实现所有被`@callback`指令标记的函数。正如你所看到的, -`@callback`指令不但可以接受一个函数名,还可以接受一个函数规格定义(我们在本文开头讲述的,函数的spec)。 - - -### 采用行为(adopting behavior) - -模块采用一个行为的语法非常直白: - -```elixir -defmodule JSONParser do - @behaviour Parser - - def parse(str), do: # ... parse JSON - def extensions, do: ["json"] -end -``` - -```elixir -defmodule YAMLParser do - @behaviour Parser - - def parse(str), do: # ... parse YAML - def extensions, do: ["yml"] -end -``` - -如果一个模块采用了一个尚未完全实现其所需回调方法的**行为(behavior)**,这将生成一个编译时错误。 diff --git a/21-erlang-lib.md b/21-erlang-lib.md deleted file mode 100644 index ce20182..0000000 --- a/21-erlang-lib.md +++ /dev/null @@ -1,210 +0,0 @@ -21-Erlang库 -============ - -正如前文所言,Elixir是基于Erlang实现的编程语言。 -对于Erlang语言库,Elixir提供了完善的交互能力。 -而且,实际上,Elixir不只是简单地对Erlang库功能进行语言上的包装(是的,没有Elixir版本的对应Erlang库函数), -而是直接连接Erlang代码(因为同源,Elixir以特定语法来直接调用Erlang库函数)。 -本章将展示一些Elixir中没有,但是常用(常见+有用)的Erlang功能函数。 - ->随着对Elixir更加深入的学习和使用,你可能会更多地阅读参考Erlang的 -[标准库手册](http://erlang.org/doc/apps/stdlib/index.html)。 - -## 二进制串模块 - -内建的Elixir字符串模块用来处理UTF-8编码过的二进制串(binaries)。 -而Erlang的[二进制串模块](http://erlang.org/doc/man/binary.html)可能对你更加有用, -因为它可以处理的二进制串不一定非要是UTF-8编码的: - -```iex -iex> String.to_char_list "Ø" -[216] -iex> :binary.bin_to_list "Ø" -[195, 152] -``` - -从上面的例子你就能看出一些区别来了;`String`模块返回UTF-8的字符码, -而`:binary`是原始的数据字节。 - ->Elixir引用Erlang的库函数十分简单。正如这个例子所示,在Erlang库模块名称前面加上冒号, -就可以直接调用Erlang的库函数了。 - -## 格式化的字符串输出 - -Elixir中并没有类似于C中的`printf`函数。作为一个可选项,你可以使用字符串插值来完成同样的功能: - -```iex -iex> f = Float.to_string(:math.pi, decimals: 3) |> String.rjust(10) -iex> str = "Pi is approximately given by: #{f}" -"Pi is approximately given by: 3.142" -``` - -另外,还可以用Erlang标准库中的`:io.format/2`和`:io_lib.format/2`函数。 -第一个格式化后输出到终端,而第二个输出到一个iolist。具体格式化的语法和`pringf`略有区别, -详见[Erlang文档](http://erlang.org/doc/man/io.html#format-1): - -```iex -iex> :io.format("Pi is approximately given by:~10.3f~n", [:math.pi]) -Pi is approximately given by: 3.142 -:ok -iex> to_string :io_lib.format("Pi is approximately given by:~10.3f~n", [:math.pi]) -"Pi is approximately given by: 3.142\n" -``` - -另外需要注意的是Erlang的格式化函数中对Unicode的处理。 - -## 日历模块 - -[日历模块](http://erlang.org/doc/man/calendar.html) 包含本地时间和标准时间的转换函数, -以及其它一些时间函数。 - -```iex -iex> :calendar.day_of_the_week(1980, 6, 28) -6 -iex> {date, time} = :calendar.now_to_local_time(:erlang.timestamp) -iex> date -{2016, 2, 17} -iex> time -{22, 4, 55} -``` - -## 加密模块 - -[加密模块](http://erlang.org/doc/man/crypto.html) 包含哈希方法,数字签名, -加密等功能函数: - -```iex -iex> Base.encode16(:crypto.hash(:sha256, "Elixir")) -"3315715A7A3AD57428298676C5AE465DADA38D951BDFAC9348A8A31E9C7401CB" -``` - -`:crypto` 模块不是Erlang的标准库,但是包含在了Erlang发行包中。 -这要求你必须在项目的配置文件中列出`:crypto`模块作为依赖项。 -通过修改`mix.exs`来加载该模块: - -```elixir - def application do - [applications: [:crypto]] - end -``` - -## 有向图模块 - -[有向图模块](http://erlang.org/doc/man/digraph.html) (以及 -[有向图模块工具](http://erlang.org/doc/man/digraph_utils.html)) -包含了处理有向图(有丁点和边构成)的函数。 -创建了一个图实例之后,模块的算法即可帮助找寻顶点最短路径、图中的环等。 - -给出三个顶点,找寻从第一个到最后一个顶点的最短路径: - -```iex -iex> digraph = :digraph.new() -iex> coords = [{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}] -iex> [v0, v1, v2] = (for c <- coords, do: :digraph.add_vertex(digraph, c)) -iex> :digraph.add_edge(digraph, v0, v1) -iex> :digraph.add_edge(digraph, v1, v2) -iex> :digraph.get_short_path(digraph, v0, v2) -[{0.0, 0.0}, {1.0, 0.0}, {1.0, 1.0}] -``` - -## ETS(Erlang Term Storage):Erlang的“Term存储”机制 - -模块[`ets`](http://erlang.org/doc/man/ets.html)以及 -[`dets`](http://erlang.org/doc/man/dets.html) -分别处理在内存中、磁盘上存储大型数据结构。 - -ETS创建一个表来存储元祖。默认情况下,ETS表是受保护的:只有owner进程才能写表, -其它进程只可以读。ETS提供了一些功能,可被当做简单的数据库、键值存储或cache机制使用。 - -作为副作用,`ets`模块中的函数会修改表的状态。 - -```iex -iex> table = :ets.new(:ets_test, []) -# Store as tuples with {name, population} -iex> :ets.insert(table, {"China", 1_374_000_000}) -iex> :ets.insert(table, {"India", 1_284_000_000}) -iex> :ets.insert(table, {"USA", 322_000_000}) -iex> :ets.i(table) -<1 > {"USA", 322000000} -<2 > {"China", 1_374_000_000} -<3 > {"India", 1_284_000_000} -``` - -## 数学模块 - -[数学模块](http://erlang.org/doc/man/math.html) 包含了常用数学操作, -如三角函数、指数或底数函数等等。 - -```iex -iex> angle_45_deg = :math.pi() * 45.0 / 180.0 -iex> :math.sin(angle_45_deg) -0.7071067811865475 -iex> :math.exp(55.0) -7.694785265142018e23 -iex> :math.log(7.694785265142018e23) -55.0 -``` - -## 队列(queue)模块 - -[队列 `queue` 是一种数据结构](http://erlang.org/doc/man/queue.html) -实现了双向先进先出的高效率队列: - -```iex -iex> q = :queue.new -iex> q = :queue.in("A", q) -iex> q = :queue.in("B", q) -iex> {value, q} = :queue.out(q) -iex> value -{:value, "A"} -iex> {value, q} = :queue.out(q) -iex> value -{:value, "B"} -iex> {value, q} = :queue.out(q) -iex> value -:empty -``` - -## 随机值(rand)模块 - -[`rand`模块函数](http://erlang.org/doc/man/rand.html) 可以返回随机值或是设置随机seed: - -```iex -iex> :rand.uniform() -0.8175669086010815 -iex> _ = :rand.seed(:exs1024, {123, 123534, 345345}) -iex> :rand.uniform() -0.5820506340260994 -iex> :rand.uniform(6) -6 -``` - -## zip和zlib模块 - -[`zip`模块](http://erlang.org/doc/man/zip.html) 可以让你读写磁盘或内存中的zip文件, -以及提取其文件信息等。 - -以下代码计算了zip压缩包中的文件数量: - -```iex -iex> :zip.foldl(fn _, _, _, acc -> acc + 1 end, 0, :binary.bin_to_list("file.zip")) -{:ok, 633} -``` - -[`zlib`模块](http://erlang.org/doc/man/zlib.html) 处理zlib格式的数据压缩 -(如gzip中用的): - -```iex -iex> song = " -...> Mary had a little lamb, -...> His fleece was white as snow, -...> And everywhere that Mary went, -...> The lamb was sure to go." -iex> compressed = :zlib.compress(song) -iex> byte_size song -110 -iex> byte_size compressed -99 -iex> :zlib.uncompress(compressed) -"\nMary had a little lamb,\nHis fleece was white as snow,\nAnd everywhere that Mary went,\nThe lamb was sure to go." -``` diff --git a/22-next.md b/22-next.md deleted file mode 100644 index a12ab68..0000000 --- a/22-next.md +++ /dev/null @@ -1,59 +0,0 @@ -20-下一步 -========== - -还想学习更多?继续阅读吧! - -## 构建第一个Elixir工程 - -Elixir提供了一个构建工具叫做Mix。你可以简单地执行以下命令来开始构建项目: - -``` -mix new path/to/new/project -``` - -这里已经写好了一份手册,讲述了如何构建一个Elixir应用程序,包括它自己的监督树,配置,测试等等。 -这个应用程序是一个分布式的键-值对存储程序。它以键-值对的形式将数据存储在“桶”里, -并且把这些“桶”分发到不同的节点: - - - [Advanced Elixir](https://github.com/straightdave/advanced_elixir) - -## 元编程 - -感谢语言上的元编程支持,Elixir具有可扩展性和高度定制性。 -Elixir的元编程主要是由“宏”实现。在许多情景,特别是开发DSL特别有用。 -这里也有一份手册文档,讲述了宏背后的基础原理,以及如何利用宏实现元编程来创建DSL: - - - [Elixir元编程](https://github.com/straightdave/elixir_meta_programming) - -## 社区和其它资源 - -社区内的[“学习”部分](http://elixir-lang.org/learning.html) -推荐了一些书籍、视频等资源来学习Elixir,探索其生态系统。 -还有一些,如程序大会的演讲、开源项目等由社区创建的学习资料在那里。 - -记住如果遇到困难,可以访问 __#elixir-lang__ 频道(__irc.freenode.net__), -或是向邮件列表中发信。可以肯定那里会有人愿意提供帮助。收藏博客或是 -[订阅邮件列表](https://groups.google.com/group/elixir-lang-core) -以接收最新的新闻和声明。 - -别忘记还可以阅读Elixir的源码,其大部分使用Elixir写的(主要是lib那个目录下)。 -或是[阅读Elixir的文档](http://elixir-lang.org/docs.html)。 - -## 来点Erlang - -Elixir运行于Erlang虚拟机。不久之后,Elixir的开发者会完成对所有Erlang库的连接。 -以下这些在线资源包含了Erlang的基础知识及高级特性: - - - [Erlang语法速成](http://elixir-lang.org/crash-course.html) - 提供了Erlang语法的简要介绍。每个代码片段都附有对等的Elixir代码。 - 这不但有助于你一窥Erlang的语法,还可以复习你在本指导书里学到的知识。 - - - Erlang的官方站点有份简短的 - [图文教程](http://www.erlang.org/course/concurrent_programming.html) - 简要描述了Erlang并行编程的原语。 - - - [为你好学点Erlang吧](http://learnyousomeerlang.com/) - 是极好的Erlang介绍:它的设计原则、标准库、最佳实践等等等等。 - 只要阅读上述速成,你就可以安全地忽略一些Erlang教课书前面介绍基础语法的几章。当阅读到 - [并发指南](http://learnyousomeerlang.com/the-hitchhikers-guide-to-concurrency) - 时,真正的愉悦开始了。 diff --git a/3-basic-ops.md b/3-basic-ops.md deleted file mode 100644 index 1f34746..0000000 --- a/3-basic-ops.md +++ /dev/null @@ -1,103 +0,0 @@ -3-基本运算符 -============ - -通过前几章的学习,我们知道Elixir提供了 ```+,-,*,/``` 4个算术运算符,外加整数除法函数```div/2```和 -取余函数```rem/2```。 -Elixir还提供了```++```和```--```运算符来操作列表: -```elixir -iex> [1,2,3] ++ [4,5,6] -[1,2,3,4,5,6] -iex> [1,2,3] -- [2] -[1,3] -``` - -使用```<>```进行字符串拼接: -```elixir -iex> "foo" <> "bar" -"foobar" -``` - -Elixir还提供了三个布尔运算符:```or,and,not```。这三个运算符只接受布尔值作为 *第一个* 参数: -```elixir -iex> true and true -true -iex> false or is_atom(:example) -true -``` - -如果提供了非布尔值作为第一个参数,会报异常: -```elixir -iex> 1 and true -** (ArgumentError) argument error -``` - -运算符```or```和```and```可短路,即它们仅在第一个参数无法决定整体结果的情况下才执行第二个参数: -```elixir -iex> false and error("This error will never be raised") -false - -iex> true or error("This error will never be raised") -true -``` - ->如果你是Erlang程序员,Elixir中的```and```和```or```其实就是```andalso```和```orelse```运算符。 - -除了这几个布尔运算符,Elixir还提供```||```,```&&```和```!```运算符。它们可以接受任意类型的参数值。 -在使用这些运算符时,除了 false 和 nil 的值都被视作 true: - -```elixir -# or -iex> 1 || true -1 -iex> false || 11 -11 - -# and -iex> nil && 13 -nil -iex> true && 17 -17 - -# ! -iex> !true -false -iex> !1 -false -iex> !nil -true -``` - -根据经验,当参数确定是布尔时,使用```and```,```or```和```not```; -如果非布尔值(或不确定是不是),用```&&```,```||```和```!```。 - -Elixir还提供了 ```==,!=,===,!==,<=,>=,<,>``` 这些比较运算符: - -```elixir -iex> 1 == 1 -true -iex> 1 != 2 -true -iex> 1 < 2 -true -``` - -其中```==```和```===```的不同之处是后者在判断数字时更严格: - -```elixir -iex> 1 == 1.0 -true -iex> 1 === 1.0 -false -``` - -在Elixir中,可以判断不同类型数据的大小: -```elixir -iex> 1 < :atom -true -``` - -这很实用。排序算法不必担心如何处理不同类型的数据。总体上,不同类型的排序顺序是: -``` -number < atom < reference < functions < port < pid < tuple < maps < list < bitstring -``` -不用强记,只要知道有这么回事儿就可以。 diff --git a/4-pattern-matching.md b/4-pattern-matching.md deleted file mode 100644 index 4a9d101..0000000 --- a/4-pattern-matching.md +++ /dev/null @@ -1,180 +0,0 @@ -4-模式匹配 -========== - -本章起教程进入 _不那么基础的_ 阶段,开始涉及函数式编程概念。 -对之前没有函数式编程经验的人来说,这一章是一个基础,需要好好学习和理解。 - -在Elixir中,```=```运算符实际上叫做 *匹配运算符*。 -本章将讲解如何使用```=```运算符来对各种数据结构进行模式匹配。 -最后本章还会讲解pin运算符(```^```),用来访问某变量之前绑定的值。 - -## 4.1-匹配运算符 - -我们已经多次使用```=```符号进行变量的赋值操作: -```elixir -iex> x = 1 -1 -iex> x -1 -``` - -在Elixir中,```=```作为 *匹配运算符*。下面来学习这样的概念: -```elixir -iex> 1 = x -1 -iex> 2 = x -** (MatchError) no match of right hand side value: 1 -``` - -注意```1 = x```是一个合法的表达式。 -由于前面的例子给x赋值为1,因此在匹配时左右相同,所以它匹配成功了。而两侧不匹配的时候,MatchError将被抛出。 - -变量只有在匹配操作符```=```的左侧时才被赋值: -```elixir -iex> 1 = unknown -** (RuntimeError) undefined function: unknown/0 -``` -错误原因是unknown变量没有被赋过值,Elixir猜你想调用一个名叫```unknown/0```的函数, -但是找不到这样的函数。 - -> -变量名在等号左边,Elixir认为是赋值表达式;变量名放在右边,Elixir认为是拿该变量的值和左边的值做匹配。 - -## 4.2-模式匹配 -匹配运算符不光可以匹配简单数值,还能用来 *解构* 复杂的数据类型。例如,我们在元组上使用模式匹配: -```elixir -iex> {a, b, c} = {:hello, "world", 42} -{:hello, "world", 42} -iex> a -:hello -iex> b -"world" -``` - -在两端不匹配的情况下,模式匹配会失败。比方说,匹配的两端的元组不一样长: -```elixir -iex> {a, b, c} = {:hello, "world"} -** (MatchError) no match of right hand side value: {:hello, "world"} -``` - -或者两端模式有区别(比如两端数据类型不同): -```elixir -iex> {a, b, c} = [:hello, "world", "!"] -** (MatchError) no match of right hand side value: [:hello, "world", "!"] -``` - -利用“匹配”的这个概念,我们可以匹配特定值;或者在匹配成功时,为某些变量赋值。 - -下面例子中先写好了匹配的左端,它要求右端必须是个元组,且第一个元素是原子```:ok```。 -```elixir -iex> {:ok, result} = {:ok, 13} -{:ok, 13} -iex> result -13 - -iex> {:ok, result} = {:error, :oops} -** (MatchError) no match of right hand side value: {:error, :oops} -``` - -用在列表上: -```elixir -iex> [a, 2, 3] = [1, 2, 3] -[1, 2, 3] -iex> a -1 -``` - -列表支持匹配自己的```head```和```tail``` -(这相当于同时调用```hd/1```和```tl/1```,给```head```和```tail```赋值): -```elixir -iex> [head | tail] = [1, 2, 3] -[1, 2, 3] -iex> head -1 -iex> tail -[2, 3] -``` - -同```hd/1```和```tl/1```函数一样,以上代码不能对空列表使用: -```elixir -iex> [h|t] = [] -** (MatchError) no match of right hand side value: [] -``` - -> -[head|tail]这种形式不光在模式匹配时可以用,还可以用作向列表插入前置数值: -```elixir -iex> list = [1, 2, 3] -[1, 2, 3] -iex> [0|list] -[0, 1, 2, 3] -``` - -模式匹配使得程序员可以容易地解构数据结构(如元组和列表)。 -在后面我们还会看到,它是Elixir的一个基础,对其它数据结构同样适用,比如图和二进制。 - -小结: -* 模式匹配使用```=```符号 -* 匹配中等号左右的“模式”必须相同 -* 变量在等号左侧才会被赋值 -* 变量在右侧时必须有值,Elixir拿这个值和左侧相应位置的元素做匹配 - - -## 4.3-pin运算符 -在Elixir中,变量可以被重新绑定: -```elixir -iex> x = 1 -1 -iex> x = 2 -2 -``` ->Elixir可以给变量重新绑定(赋值)。 -它带来一个问题,就是对一个单独变量(而且是放在左端)做匹配时, -Elixir会认为这是一个重新绑定(赋值)操作,而不会当成匹配,执行匹配逻辑。 -这里就要用到pin运算符。 - -如果你不想这样,可以使用pin运算符(^)。 -加上了pin运算符的变量,在匹配时使用的值是本次匹配前就赋予的值: -```elixir -iex> x = 1 -1 -iex> ^x = 2 -** (MatchError) no match of right hand side value: 2 -iex> {x, ^x} = {2, 1} -{2, 1} -iex> x -2 -``` - -注意如果一个变量在匹配中被引用超过一次,所有的引用都应该绑定同一个模式: -```elixir -iex> {x, x} = {1, 1} -1 -iex> {x, x} = {1, 2} -** (MatchError) no match of right hand side value: {1, 2} -``` - -有些时候,你并不在意模式匹配中的一些值。 -可以把它们绑定到特殊的变量 “ _ ” (underscore)上。 -例如,如果你只想要某列表的head,而不要tail值。你可以这么做: -```elixir -iex> [h | _ ] = [1, 2, 3] -[1, 2, 3] -iex> h -1 -``` - -变量“ _ ”特殊之处在于它不能被读,尝试读取它会报“未绑定的变量”错误: -```elixir -iex> _ -** (CompileError) iex:1: unbound variable _ -``` - -尽管模式匹配看起来如此牛逼,但是语言还是对它的作用做了一些限制。 -比如,你不能让函数调用作为模式匹配的左端。下面例子就是非法的: -```elixir -iex> length([1,[2],3]) = 3 -** (CompileError) iex:1: illegal pattern -``` - -模式匹配介绍完了。 在以后的章节中,模式匹配是常用的语法结构。 diff --git a/5-case-cond-if.md b/5-case-cond-if.md deleted file mode 100644 index cfe3761..0000000 --- a/5-case-cond-if.md +++ /dev/null @@ -1,248 +0,0 @@ -5-流程控制 -========== -[case](#51-case) -[卫兵子句中的表达式](#52-%E5%8D%AB%E5%85%B5%E5%AD%90%E5%8F%A5%E4%B8%AD%E7%9A%84%E8%A1%A8%E8%BE%BE%E5%BC%8F) -[cond](#53-cond) -[if和unless](#54-if%E5%92%8Cunless) -[do语句块](#55-do%E8%AF%AD%E5%8F%A5%E5%9D%97) - -本章讲解case,cond和if的流程控制结构。 - -## 5.1-case -case将一个值与许多模式进行匹配,直到找到一个匹配成功的: -```elixir -iex> case {1, 2, 3} do -...> {4, 5, 6} -> -...> "This clause won't match" -...> {1, x, 3} -> -...> "This clause will match and bind x to 2 in this clause" -...> _ -> -...> "This clause would match any value" -...> end -``` - -如果与一个已赋值的变量做比较,要用pin运算符(^)标记该变量: -```elixir -iex> x = 1 -1 -iex> case 10 do -...> ^x -> "Won't match" -...> _ -> "Will match" -...> end -``` - -可以加上卫兵子句(guard clauses)提供额外的条件: -```elixir -iex> case {1, 2, 3} do -...> {1, x, 3} when x > 0 -> -...> "Will match" -...> _ -> -...> "Won't match" -...> end -``` -于是上面例子中,第一个待比较的模式多了一个条件:x必须是正数。 - -## 5.2-卫兵子句中的表达式 -Erlang中只允许以下表达式出现在卫兵子句中: - - 比较运算符(==,!=,===,!==,>,<,<=,>=) - - 布尔运算符(and,or)以及否定运算符(not,!) - - 算数运算符(+,-,*,/) - - <>和++如果左端是字面值 - - in运算符 - - 以下类型判断函数: - - is_atom/1 - - is_binary/1 - - is_bitstring/1 - - is_boolean/1 - - is_float/1 - - is_function/1 - - is_function/2 - - is_integer/1 - - is_list/1 - - is_map/1 - - is_number/1 - - is_pid/1 - - is_reference/1 - - is_tuple/1 - - 外加以下函数: - - abs(number) - - bit_size(bitstring) - - byte_size(bitstring) - - div(integer, integer) - - elem(tuple, n) - - hd(list) - - length(list) - - map_size(map) - - node() - - node(pid | ref | port) - - rem(integer, integer) - - round(number) - - self() - - tl(list) - - trunc(number) - - tuple_size(tuple) - -记住,卫兵子句中出现的错误不会漏出,只会简单地让卫兵条件失败: -```elixir -iex> hd(1) -** (ArgumentError) argument error - :erlang.hd(1) -iex> case 1 do -...> x when hd(x) -> "Won't match" -...> x -> "Got: #{x}" -...> end -"Got 1" -``` - -如果case中没有一条模式能匹配,会报错: -```elixir -iex> case :ok do -...> :error -> "Won't match" -...> end -** (CaseClauseError) no case clause matching: :ok -``` - -匿名函数也可以像下面这样,用多个模式或卫兵条件来灵活地匹配该函数的参数: -```elixir -iex> f = fn -...> x, y when x > 0 -> x + y -...> x, y -> x * y -...> end -#Function<12.71889879/2 in :erl_eval.expr/5> -iex> f.(1, 3) -4 -iex> f.(-1, 3) --3 -``` -需要注意的是,所有case模式中表示的参数个数必须一致,否则会报错。 -上面的例子两个待匹配模式都是x,y。如果再有一个模式表示的参数是x,y,z,那就不行: -```elixir -iex(5)> f2 = fn -...(5)> x,y -> x+y -...(5)> x,y,z -> x+y+z -...(5)> end -** (CompileError) iex:5: cannot mix clauses with different arities in function definition - (elixir) src/elixir_translator.erl:17: :elixir_translator.translate/2 -``` - -## 5.3-cond -case是拿一个值去同多个值或模式进行匹配,匹配了就执行那个分支的语句。 -然而,许多情况下我们要检查不同的条件,找到第一个结果为true的,执行它的分支。 -这时我们用cond: -```elixir -iex> cond do -...> 2 + 2 == 5 -> -...> "This will not be true" -...> 2 * 2 == 3 -> -...> "Nor this" -...> 1 + 1 == 2 -> -...> "But this will" -...> end -"But this will" -``` -这样的写法和命令式语言里的```else if```差不多一个意思(尽管很少这么写)。 - -如果没有一个条件结果为true,会报错。因此,实际应用中通常会使用true作为最后一个条件。 -因为即使上面的条件没有一个是true,那么该cond表达式至少还可以执行这最后一个分支: -```elixir -iex> cond do -...> 2 + 2 == 5 -> -...> "This is never true" -...> 2 * 2 == 3 -> -...> "Nor this" -...> true -> -...> "This is always true (equivalent to else)" -...> end -``` -用法就好像许多语言中,switch语句中的default一样。 - -最后需要注意的是,cond视所有非false和nil的值为true: -```elixir -iex> cond do -...> hd([1,2,3]) -> -...> "1 is considered as true" -...> end -"1 is considered as true" -``` - -## 5.4 if和unless -除了case和cond,Elixir还提供了两很常用的宏:```if/2```和```unless/2```, -用它们检查单个条件: -```elixir -iex> if true do -...> "This works!" -...> end -"This works!" -iex> unless true do -...> "This will never be seen" -...> end -nil -``` - -如果给```if/2```的条件结果为false或者nil,那么它在do/end间的语句块就不会执行, -该表达式返回nil。```unless/2```相反。 - -它们都支持else语句块: -```elixir -iex> if nil do -...> "This won't be seen" -...> else -...> "This will" -...> end -"This will" -``` - ->有趣的是,```if/2```和```unless/2```是以宏的形式提供的,而不像在很多语言中那样是语句。 -可以阅读文档或```if/2```的源码 -([Kernel模块](http://elixir-lang.org/docs/stable/elixir/Kernel.html))。 -_Kernel_ 模块还定义了诸如```+/2```运算符和```is_function/2```函数。 -它们默认被导入,因而在你的代码中可用。 - -## 5.5-```do```语句块 -以上讲解的4种流程控制结构:case,cond,if和unless,它们都被包裹在do/end语句块中。 -即使我们把if语句写成这样: -```elixir -iex> if true, do: 1 + 2 -3 -``` - -在Elixir中,do/end语句块方便地将一组表达式传递给```do:```。以下是等同的: -```elixir -iex> if true do -...> a = 1 + 2 -...> a + 10 -...> end -13 -iex> if true, do: ( -...> a = 1 + 2 -...> a + 10 -...> ) -13 -``` -我们称第二种语法使用了 **关键字列表(keyword lists)**。我们可以这样传递```else```: -```elixir -iex> if false, do: :this, else: :that -:that -``` - -注意一点,do/end语句块永远是被绑定在最外层的函数调用上。例如: -```elixir -iex> is_number if true do -...> 1 + 2 -...> end -``` -将被解析为: -```elixir -iex> is_number(if true) do -...> 1 + 2 -...> end -``` -这使得Elixir认为你是要调用函数```is_number/2```(第一个参数是if true,第二个是语句块)。 -这时就需要加上括号解决二义性: -```elixir -iex> is_number(if true do -...> 1 + 2 -...> end) -true -``` -关键字列表在Elixir语言中占有重要地位,在许多函数和宏中都有使用。后文中还会对其进行详解。 diff --git a/6-bin-str-charlist.md b/6-bin-str-charlist.md deleted file mode 100644 index bdbb95b..0000000 --- a/6-bin-str-charlist.md +++ /dev/null @@ -1,215 +0,0 @@ -6-二进制串、字符串和字符列表 -======================== - -在“基本类型”一章中,介绍了字符串,以及使用`is_binary/1`函数检查它: - -```elixir -iex> string = "hello" -"hello" -iex> is_binary string -true -``` - -本章将学习理解:二进制串(binaries)是个啥,它怎么和字符串(strings)扯上关系的; -以及用单引号包裹的值`'like this'`是啥意思。 - -## UTF-8和Unicode - -字符串是UTF-8编码的二进制串。 -为了弄清这句话的准确含义,我们要先理解两个概念:字节(bytes)和字符编码(code point)的区别。 -Unicode标准为我们已知的大部分字母分配了字符编码。 -比如,字母`a`的字符编码是`97`,而字母`ł`的字符编码是`322`。 -当把字符串`"hełło"`写到硬盘上的时候,需要将字符编码转化为字节。 -如果我们遵循一个字节表示一个字符编码这个,那是写不了`"hełło"`的。 -因为字母`ł`的编码是`322`,而一个字节所能存储的数值范围是`0`到`255`。 -但是如你所见,确实能够在屏幕上显示`"hełło"`,说明还是有*某种*解决方法的,于是*编码*便出现了。 - -要用字节表示字符编码,我们需要用某种方式对其进行编码。 -Elixir选择UTF-8为主要并且默认的编码方式。 -当我们说某个字符串是UTF-8编码的二进制串,指的是该字符串是一串字节, -这些字节以某种方式(即UTF-8编码)组织起来,表示特定的字符编码。 - -因为给字母`ł`分配的字符编码是`322`,因此在实际上需要一个以上的字节来表示。 -这就是为什么我们会看到,调用函数`byte_size/1`和`String.length/1`的结果不一样: - -```elixir -iex> string = "hełło" -"hełło" -iex> byte_size string -7 -iex> String.length string -5 -``` - ->注意:如果你使用Windows,你的终端有可能不是默认使用UTF-8编码方式。你需要在进入`iex(iex.bat)`之前, -首先执行`chcp 65001`命令来修改当前Session的编码方式。 - -UTF-8需要1个字节来表示`h`,`e`,`o`的字符编码,用2个字节表示`ł`。 -在Elixir中可以使用`?`运算符获取字符的编码: - -```elixir -iex> ?a -97 -iex> ?ł -322 -``` - -你还可以使用 -[String](http://elixir-lang.org/docs/stable/elixir/String.html)模块里的函数 -将字符串切成单独的字符编码: - -```elixir -iex> String.codepoints("hełło") -["h", "e", "ł", "ł", "o"] -``` - -Elixir为字符串操作提供了强大的支持,它支持Unicode的许多操作。实际上,Elixir通过了文章 -[“字符串类型崩坏了”](http://mortoray.com/2013/11/27/the-string-type-is-broken/) -记录的所有测试。 - -然而,字符串只是故事的一小部分。如果字符串正如所言是二进制串,那我们使用`is_binaries/1`函数时, -Elixir必须一个底层类型来支持字符串。事实亦如此,下面就来介绍这个底层类型---二进制串。 - -## 二进制串(以及比特串`bitstring`) - -在Elixir中可以用`<<>>`定义一个二进制串: - -```elixir -iex> <<0, 1, 2, 3>> -<<0, 1, 2, 3>> -iex> byte_size(<<0, 1, 2, 3>>) -4 -``` - -一个二进制串只是一连串的字节而已。这些字节可以以任何方式组织,即使凑不成一个合法的字符串: - -```elixir -iex> String.valid?(<<239, 191, 191>>) -false -``` - -而字符串的拼接操作实际上就是二进制串的拼接操作: - -```elixir -iex> <<0, 1>> <> <<2, 3>> -<<0, 1, 2, 3>> -``` - -一个常见技巧是,通过给一个字符串尾部拼接一个空(null)字节`<<0>>`, -可以看到该字符串内部二进制串的样子: - -```elixir -iex> "hełło" <> <<0>> -<<104, 101, 197, 130, 197, 130, 111, 0>> -``` - -二进制串中的每个数值都表示一个字节,其数值最大范围是255。 -二进制允许使用修改器显式标注一下那个数值的存储空间大小,使其可以存储超过255的数值; -或者将一个字符编码转换为utf8编码后的形式(变成多个字节的二进制串): - -```elixir -iex> <<255>> -<<255>> -iex> <<256>> # 被截断(truncated) -<<0>> -iex> <<256 :: size(16)>> # 使用16比特(bits)即2个字节来保存 -<<1, 0>> -iex> <<256 :: utf8>> # 这个数字是一个字符的编码,将其使用utf8方式编码为字节 -"Ā" # 注意,在iex交互窗口中,所有可以作为合法字符串的二进制串,都会显示为字符串 -iex> <<256 :: utf8, 0>> # 尾部拼接个空字节,查看上一条命令结果内部实际的二进制串 -<<196, 128, 0>> -``` - -如果一个字节是8个比特,那如果我们给一个大小是1比特的修改器会怎样?: - -```elixir -iex> <<1 :: size(1)>> -<<1::size(1)>> -iex> <<2 :: size(1)>> # 被截断(truncated) -<<0::size(1)>> -iex> is_binary(<< 1 :: size(1)>>) # 二进制串失格 -false -iex> is_bitstring(<< 1 :: size(1)>>) -true -iex> bit_size(<< 1 :: size(1)>>) -1 -``` - -这样(每个元素长度是1比特)就不再是二进制串(人家每个元素是一个字节,起码8比特), -退化成为比特串(bitstring),意思就是一串比特! -所以,所以,二进制串就是一特殊的比特串,比特总数是8的倍数。 - -也可以对二进制串或比特串做模式匹配: - -```elixir -iex> <<0, 1, x>> = <<0, 1, 2>> -<<0, 1, 2>> -iex> x -2 -iex> <<0, 1, x>> = <<0, 1, 2, 3>> -** (MatchError) no match of right hand side value: <<0, 1, 2, 3>> -``` - -注意,在没有修改器标识的情况下,二进制串中的每个元素都应该匹配8个比特长度。 -因此上面最后的例子,匹配的左右两端不具有相同容量,因此出现错误。 - -下面是使用了修改器标识的匹配例子: - -```elixir -iex> <<0, 1, x :: binary>> = <<0, 1, 2, 3>> -<<0, 1, 2, 3>> -iex> x -<<2, 3>> -``` - -上面例子使用了`binary`修改器,指示`x`是个二进制串。(为啥不用单词的复数形式`binaries`搞不懂啊。) -这个修改器仅仅可以用在被匹配的串的*末尾元素*上。 - -跟上面例子同样的原理,使用字符串的连接操作符`<>`,效果相似: - -```elixir -iex> "he" <> rest = "hello" -"hello" -iex> rest -"llo" -``` - -关于二进制串/比特串的构造器`<< >>`完整的参考, -请见[Elixir的文档](http://elixir-lang.org/docs/stable/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1)。 - -总之,记住字符串是UTF-8编码后的二进制串,而二进制串是特殊的、元素数量是8的倍数的比特串。 -尽管这种机制增加了Elixir在处理比特或字节时的灵活性, -而现实中99%的时候你只会用到`is_binary/1`和`byte_size/1`函数跟二进制串打交道。 - -## 字符列表(char lists) - -字符列表就是字符的列表。 - -```elixir -iex> 'hełło' -[104, 101, 322, 322, 111] -iex> is_list 'hełło' -true -iex> 'hello' -'hello' -``` - -可以看出,比起包含字节,一个字符列表包含的是单引号所引用的一串字符各自的字符编码。 -注意IEx遇到超出ASCII值范围的字符编码时,显示其字符编码的值,而不是字符。 -双引号引用的是字符串(即二进制串),单引号表示的是字符列表(即,一个列表)。 - -实际应用中,字符列表常被用来做为同一些Erlang库交互的参数,因为这些老库不接受二进制串作为参数。 -要将字符列表和字符串之间相互转换,可以使用函数`to_string/1`和`to_char_list/1`: - -```elixir -iex> to_char_list "hełło" -[104, 101, 322, 322, 111] -iex> to_string 'hełło' -"hełło" -iex> to_string :hello -"hello" -iex> to_string 1 -"1" -``` - -注意这些函数是多态的。它们不但可以将字符列表转化为字符串,还能转化整数、原子等为字符串。 diff --git a/7-keywords-map-dict.md b/7-keywords-map-dict.md deleted file mode 100644 index b8dbbdc..0000000 --- a/7-keywords-map-dict.md +++ /dev/null @@ -1,190 +0,0 @@ -7-键值列表-图-字典 -================ -[键值列表](#71) -[图](#72-%E5%9B%BEmaps) -[字典](#73-%E5%AD%97%E5%85%B8dicts) - -到目前还没有讲到任何关联性数据结构,即那种可以将一个或几个值关联到一个key上。 -不同语言有不同的叫法,如字典,哈希,关联数组,图,等等。 - -Elixir中有两种主要的关联性结构:键值列表(keyword list)和图(map)。 - -## 7.1-键值列表 -在很多函数式语言中,常用二元元组的列表来表示关联性数据结构。在Elixir中也是这样。 -当我们有了一个元组(不一定仅有两个元素的元组)的列表,并且每个元组的第一个元素是个 **原子**, -那就称之为键值列表: -```elixir -iex> list = [{:a, 1}, {:b, 2}] -[a: 1, b: 2] -iex> list == [a: 1, b: 2] -true -iex> list[:a] -1 -``` - ->当原子key和关联的值之间没有逗号分隔时,可以把原子的冒号拿到字母的后面。这时,原子与后面的数值之间要有一个空格。 - -如你所见,Elixir使用比较特殊的语法来定义这样的列表,但实际上它们会映射到一个元组列表。 -因为它们是简单的列表而已,所有针对列表的操作,键值列表也可以用。 - -比如,可以用```++```运算符为列表添加元素: -```elixir -iex> list ++ [c: 3] -[a: 1, b: 2, c: 3] -iex> [a: 0] ++ list -[a: 0, a: 1, b: 2] -``` -上面例子中重复出现了```:a```这个key,这是允许的。 -以这个key取值时,取回来的是第一个找到的(因为有序): -```elixir -iex> new_list = [a: 0] ++ list -[a: 0, a: 1, b: 2] -iex> new_list[:a] -0 -``` - -键值列表十分重要,它有两大特点: -- 有序 -- key可以重复(!仔细看上面两个示例) - -例如,[Ecto库](https://github.com/elixir-lang/ecto)使用这两个特点 -写出了精巧的DSL(用来写数据库query): -```elixir -query = from w in Weather, - where: w.prcp > 0, - where: w.temp < 20, - select: w -``` - -这些特性使得键值列表成了Elixir中为函数提供额外选项的默认手段。 -在第5章我们讨论了```if/2```宏,提到了下方的语法: -```elixir -iex> if false, do: :this, else: :that -:that -``` - -do: 和else: 就是键值列表!事实上代码等同于: -```elixir -iex> if(false, [do: :this, else: :that]) -:that -``` - -当键值列表是函数最后一个参数时,方括号就成了可选的。 - -为了操作关键字列表,Elixir提供了 -[键值(keyword)模块](http://elixir-lang.org/docs/stable/elixir/Keyword.html)。 -记住,键值列表就是简单的列表,和列表一样提供了线性的性能。 -列表越长,获取长度或找到一个键值的速度越慢。 -因此,关键字列表在Elixir中一般就作为函数调用的可选项。 -如果你要存储大量数据,并且保证一个键只对应最多一个值,那就使用图。 - -对键值列表做模式匹配: -```elixir -iex> [a: a] = [a: 1] -[a: 1] -iex> a -1 -iex> [a: a] = [a: 1, b: 2] -** (MatchError) no match of right hand side value: [a: 1, b: 2] -iex> [b: b, a: a] = [a: 1, b: 2] -** (MatchError) no match of right hand side value: [a: 1, b: 2] -``` -尽管如此,对列表使用模式匹配很少用到。因为不但要元素个数相等,顺序还要匹配。 - -## 7.2-图(maps) -无论何时想用键-值结构,图都应该是你的第一选择。Elixir中,用```%{}```定义图: -```elixir -iex> map = %{:a => 1, 2 => :b} -%{2 => :b, :a => 1} -iex> map[:a] -1 -iex> map[2] -:b -``` - -和键值列表对比,图有两主要区别: -- 图允许任何类型值作为键 -- 图的键没有顺序 - -如果你向图添加一个已有的键,将会覆盖之前的键-值对: -```elixir -iex> %{1 => 1, 1 => 2} -%{1 => 2} -``` - -如果图中的键都是原子,那么你也可以用键值列表中的一些语法: -```elixir -iex> map = %{a: 1, b: 2} -%{a: 1, b: 2} -``` - -对比键值列表,图的模式匹配很是有用: -```elixir -iex> %{} = %{:a => 1, 2 => :b} -%{:a => 1, 2 => :b} -iex> %{:a => a} = %{:a => 1, 2 => :b} -%{:a => 1, 2 => :b} -iex> a -1 -iex> %{:c => c} = %{:a => 1, 2 => :b} -** (MatchError) no match of right hand side value: %{2 => :b, :a => 1} -``` -如上所示,图A与另一个图B做匹配。 -图B中只要包含有图A的键,那么两个图就能匹配上。若图A是个空的,那么任意图B都能匹配上。 -但是如果图B里不包含图A的键,那就匹配失败了。 - -图还有个有趣的功能:它提供了特殊的语法来修改和访问原子键: -```elixir -iex> map = %{:a => 1, 2 => :b} -%{:a => 1, 2 => :b} -iex> map.a -1 -iex> %{map | :a => 2} -%{:a => 2, 2 => :b} -iex> %{map | :c => 3} -** (ArgumentError) argument error -``` - -使用上面两种语法要求的前提是所给的键是切实存在的。最后一条语句错误的原因就是键```:c```不存在。 - -未来几章中我们还将讨论结构体(structs)。结构体提供了编译时的保证,它是Elixir多态的基础。 -结构体是基于图的,上面例子提到的修改键值的前提就变得十分重要。 - -[图模块](http://elixir-lang.org/docs/stable/elixir/Map.html)提供了许多关于图的操作。 -它提供了与键值列表许多相似的API,因为这两个数据结构都实现了字典的行为。 - ->图是最近连同[EEP 43](http://www.erlang.org/eeps/eep-0043.html)被引入Erlang虚拟机的。 -Erlang 17提供了EEP的部分实现,只支持_一小部分_图功能。 -这意味着图仅在存储不多的键时,图的性能还行。 -为了解决这个问题,Elixir还提供了 -[HashDict模块](http://elixir-lang.org/docs/stable/elixir/HashDict.html)。 -该模块提供了一个字典来支持大量的键,并且性能不错。 - -## 7.3-字典(Dicts) -Elixir中,键值列表和图都被称作字典。 -换句话说,一个字典就像一个接口(在Elixir中称之为行为behaviour)。 -键值列表和图模块实现了该接口。 - -这个接口定义于[Dict模块](http://elixir-lang.org/docs/stable/elixir/Dict.html), -该模块还提供了底层实现的一个API: -```elixir -iex> keyword = [] -[] -iex> map = %{} -%{} -iex> Dict.put(keyword, :a, 1) -[a: 1] -iex> Dict.put(map, :a, 1) -%{a: 1} -``` - -字典模块允许开发者实现自己的字典形式,提供一些特殊的功能。 -字典模块还提供了所有字典类型都可以使用的函数。 -如,```Dicr.equal?/2```可以比较两个字典类型(可以是不同的实现)。 - -你会疑惑些程序时用keyword,Map还是Dict模块呢?答案是:看情况。 - -如果你的代码期望接受一个关键字作为参数,那么使用简直列表模块。 -如果你想操作一个图,那就使用图模块。 -如果你想你的API对所有字典类型的实现都有用, -那就使用字典模块(确保以不同的实现作为参数测试一下)。 diff --git a/8-modules.md b/8-modules.md deleted file mode 100644 index 67657bf..0000000 --- a/8-modules.md +++ /dev/null @@ -1,248 +0,0 @@ -8-模块 -====== - -[编译](#81-%E7%BC%96%E8%AF%91) -[脚本模式](#82-%E8%84%9A%E6%9C%AC%E6%A8%A1%E5%BC%8F) -[命名函数](#83-%E5%91%BD%E5%90%8D%E5%87%BD%E6%95%B0) -[函数捕捉](#84-%E5%87%BD%E6%95%B0%E6%8D%95%E6%8D%89) -[默认参数](#85-%E9%BB%98%E8%AE%A4%E5%8F%82%E6%95%B0) - -Elixir中我们把许多函数组织成一个模块。我们在前几章已经提到了许多模块, -如[String模块](http://elixir-lang.org/docs/stable/elixir/String.html): -```elixir -iex> String.length "hello" -5 -``` - -创建自己的模块,用```defmodule```宏。用```def```宏在其中定义函数: -```elixir -iex> defmodule Math do -...> def sum(a, b) do -...> a + b -...> end -...> end - -iex> Math.sum(1, 2) -3 -``` ->像ruby一样,模块名大写起头 - -## 8.1-编译 -通常把模块写进文件,这样可以编译和重用。假如文件```math.ex```有如下内容: -```elixir -defmodule Math do - def sum(a, b) do - a + b - end -end -``` - -这个文件可以用```elixirc```进行编译: -```elixir -$ elixirc math.ex -``` - -这将生成名为```Elixir.Math.beam```的bytecode文件。 -如果这时再启动iex,那么这个模块就已经可以用了(假如在含有该编译文件的目录启动iex): -```elixir -iex> Math.sum(1, 2) -3 -``` - -Elixir工程通常组织在三个文件夹里: -- ebin,包括编译后的字节码 -- lib,包括Elixir代码(.ex文件) -- test,测试代码(.exs文件) - -实际项目中,构建工具Mix会负责编译,并且设置好正确的路径。 -而为了学习方便,Elixir也提供了脚本模式,可以更灵活而不用编译。 - -## 8.2-脚本模式 -除了.ex文件,Elixir还支持.exs脚本文件。 -Elixir对两种文件一视同仁,唯一区别是.ex文件会保留编译执行后产出的比特码文件, -而.exs文件用来作脚本执行,不会留下比特码文件。例如,如下创建名为math.exs的文件: -```elixir -defmodule Math do - def sum(a, b) do - a + b - end -end - -IO.puts Math.sum(1, 2) -``` - -执行之: -```sh -$ elixir math.exs -``` -像这样执行脚本文件时,将在内存中编译和执行,打印出“3”作为结果。没有比特码文件生成。 -后文中(为了学习和练习方便),推荐使用脚本模式执行学到的代码。 - -## 8.3-命名函数 -在某模块中,我们可以用```def/2```宏定义函数,用```defp/2```定义私有函数。 -用```def/2```定义的函数可以被其它模块中的代码使用,而私有函数仅在定义它的模块内使用。 -```elixir -defmodule Math do - def sum(a, b) do - do_sum(a, b) - end - - defp do_sum(a, b) do - a + b - end -end - -Math.sum(1, 2) #=> 3 -Math.do_sum(1, 2) #=> ** (UndefinedFunctionError) -``` - -函数声明也支持使用卫兵或多个子句。 -如果一个函数有好多子句,Elixir会匹配每一个子句直到找到一个匹配的。 -下面例子检查参数是否是数字: -```elixir -defmodule Math do - def zero?(0) do - true - end - - def zero?(x) when is_number(x) do - false - end -end - -Math.zero?(0) #=> true -Math.zero?(1) #=> false - -Math.zero?([1,2,3]) -#=> ** (FunctionClauseError) -``` -如果没有一个子句能匹配参数,会报错。 - -## 8.4-函数捕捉 -本教程中提到函数,都是用```name/arity```的形式描述。 -这种表示方法可以被用来获取一个命名函数(赋给一个函数型变量)。 -下面用iex执行一下上文定义的math.exs文件: -```elixir -$ iex math.exs -``` - -```elixir -iex> Math.zero?(0) -true -iex> fun = &Math.zero?/1 -&Math.zero?/1 -iex> is_function fun -true -iex> fun.(0) -true -``` -用```&```通过函数名捕捉一个函数,它本身代表该函数值(函数类型的值)。 -它可以不必赋给一个变量,直接用括号来使用该函数。 - -本地定义的,或者已导入的函数,比如```is_function/1```,可以不用前缀模模块名: -```elixir -iex> &is_function/1 -&:erlang.is_function/1 -iex> (&is_function/1).(fun) -true -``` - -这种语法还可以作为快捷方式来创建和使用函数: -```elixir -iex> fun = &(&1 + 1) -#Function<6.71889879/1 in :erl_eval.expr/5> -iex> fun.(1) -2 -``` - -代码中```&1``` 表示传给该函数的第一个参数。 -因此,```&(&1+1)```其实等同于```fn x->x+1 end```。在创建短小函数时,这个很方便。 -想要了解更多关于```&```捕捉操作符,参考[Kernel.SpecialForms文档](http://elixir-lang.org/docs/stable/elixir/Kernel.SpecialForms.html)。 - -## 8.5-默认参数 -Elixir中,命名函数也支持默认参数: -```elixir -defmodule Concat do - def join(a, b, sep \\ " ") do - a <> sep <> b - end -end - -IO.puts Concat.join("Hello", "world") #=> Hello world -IO.puts Concat.join("Hello", "world", "_") #=> Hello_world -``` - -任何表达式都可以作为默认参数,但是只在函数调用时 **用到了** 才被执行。 -(函数定义时,那些表达式只是存在那儿,不执行;函数调用时,没有用到默认值,也不执行)。 -```elixir -defmodule DefaultTest do - def dowork(x \\ IO.puts "hello") do - x - end -end -``` - -```elixir -iex> DefaultTest.dowork 123 -123 -iex> DefaultTest.dowork -hello -:ok -``` - -如果有默认参数值的函数有了多条子句,推荐先定义一个函数头(无具体函数体)声明默认参数: -```elixir -defmodule Concat do - def join(a, b \\ nil, sep \\ " ") - - def join(a, b, _sep) when is_nil(b) do - a - end - - def join(a, b, sep) do - a <> sep <> b - end -end - -IO.puts Concat.join("Hello", "world") #=> Hello world -IO.puts Concat.join("Hello", "world", "_") #=> Hello_world -IO.puts Concat.join("Hello") #=> Hello -``` - -使用默认值时,注意对函数重载会有一定影响。考虑下面例子: -```elixir -defmodule Concat do - def join(a, b) do - IO.puts "***First join" - a <> b - end - - def join(a, b, sep \\ " ") do - IO.puts "***Second join" - a <> sep <> b - end -end -``` - -如果将以上代码保存在文件“concat.ex”中并编译,Elixir会报出以下警告: -```elixir -concat.ex:7: this clause cannot match because a previous clause at line 2 always matches -``` - -编译器是在警告我们,在使用两个参数调用```join```函数时,总使用第一个函数定义。 -只有使用三个参数调用时,才会使用第二个定义: - -```elixir -$ iex concat.exs -``` - -```elixir -iex> Concat.join "Hello", "world" -***First join -"Helloworld" -iex> Concat.join "Hello", "world", "_" -***Second join -"Hello_world" -``` - -后面几章将介绍使用命名函数来做循环,如何从别的模块中导入函数,以及模块的属性等。 diff --git a/9-recursion.md b/9-recursion.md deleted file mode 100644 index 32ba520..0000000 --- a/9-recursion.md +++ /dev/null @@ -1,143 +0,0 @@ -9-递归 -====== -因为在Elixir中(或所有函数式语言中),数据有不变性(immutability),因此在写循环时与传统的命令式(imperative)语言有所不同。 -例如某命令式语言的循环可以这么写: -``` -for(i = 0; i < array.length; i++) { - array[i] = array[i] * 2 -} -``` - -上面例子中,我们改变了```array```,以及辅助变量```i```的值。这在Elixir中是不可能的。 -尽管如此,函数式语言却依赖于某种形式的循环---递归:一个函数可以不断地被递归调用,直到某条件满足才停止。 -考虑下面的例子:打印一个字符串若干次: -``` -defmodule Recursion do - def print_multiple_times(msg, n) when n <= 1 do - IO.puts msg - end - - def print_multiple_times(msg, n) do - IO.puts msg - print_multiple_times(msg, n - 1) - end -end - -Recursion.print_multiple_times("Hello!", 3) -# Hello! -# Hello! -# Hello! -``` - -一个函数可以有许多子句(上面看起来定义了两个函数,但卫兵条件不同,可以看作同一个函数的两个子句)。 -当参数匹配该子句的模式,且该子句的卫兵表达式返回true,才会执行该子句内容。 -上面例子中,当```print_multiple_times/2```第一次调用时,n的值是3。 - -第一个子句有卫兵表达式要求n必须小于等于1。因为不满足此条件,代码找该函数的下一条子句。 - -参数匹配第二个子句,且该子句也没有卫兵表达式,因此得以执行。 -首先打印```msg```,然后调用自身并传递第二个参数```n-1```(=2)。 -这样```msg```又被打印一次,之后调用自身并传递参数```n-1```(=1)。 - -这个时候,n满足第一个函数子句条件。遂执行该子句,打印```msg```,然后就此结束。 - -我们称例子中第一个函数子句这种子句为“基本情形”。 -基本情形总是最后被执行,因为起初通常都不匹配执行条件,程序而转去执行其它子句。 -但是,每执行一次其它子句,条件都向这基本情形靠拢一点,直到最终回到基本情形处执行代码。 - -下面我们使用递归的威力来计算列表元素求和: -``` -defmodule Math do - def sum_list([head|tail], accumulator) do - sum_list(tail, head + accumulator) - end - - def sum_list([], accumulator) do - accumulator - end -end - -Math.sum_list([1, 2, 3], 0) #=> 6 -``` - -我们首先用列表[1,2,3]和初值0作为参数调用函数,程序将逐个匹配各子句的条件,执行第一个符合要求的子句。 -于是,参数首先满足例子中定义的第一个子句。参数匹配使得head = 1,tail = [2,3],accumulator = 0。 - -然后执行该字据内容,把head + accumulator作为第二个参数,连带去掉了head的列表做第一个参数,再次调用函数本身。 -如此循环,每次都把新传入的列表的head加到accumulator上,传递去掉了head的列表。 -最终传递的列表为空,符合第二个子句的条件,执行该子句,返回accumulator的值6。 - -几次函数调用情况如下: -``` -sum_list [1, 2, 3], 0 -sum_list [2, 3], 1 -sum_list [3], 3 -sum_list [], 6 -``` - -这种使用列表做参数,每次削减一点列表的递归方式,称为“递减”算法,是函数式编程的核心。 -
-如果我们想给每个列表元素加倍呢?: -``` -defmodule Math do - def double_each([head|tail]) do - [head * 2| double_each(tail)] - end - - def double_each([]) do - [] - end -end - -Math.double_each([1, 2, 3]) #=> [2, 4, 6] -``` - -此处使用了递归来遍历列表元素,使它们加倍,然后返回新的列表。 -这样以列表为参数,递归处理其每个元素的方式,称为“映射(map)”算法。 -
- -递归和列尾调用优化(tail call optimization)是Elixir中重要的部分,通常用来创建循环。 -尽管如此,在Elixir中你很少会使用以上方式来递归地处理列表。 - -下一章要介绍的[Enum模块](http://elixir-lang.org/docs/stable/elixir/Enum.html)为操作列表提供了诸多方便。 -比如,下面例子: -``` -iex> Enum.reduce([1, 2, 3], 0, fn(x, acc) -> x + acc end) -6 -iex> Enum.map([1, 2, 3], fn(x) -> x * 2 end) -[2, 4, 6] -``` - -或者,使用捕捉的语法: -``` -iex> Enum.reduce([1, 2, 3], 0, &+/2) -6 -iex> Enum.map([1, 2, 3], &(&1 * 2)) -[2, 4, 6] -``` - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/README.md b/README.md deleted file mode 100644 index dfd59d6..0000000 --- a/README.md +++ /dev/null @@ -1,53 +0,0 @@ -Elixir编程入门 -============= - -Elixir,[ɪ'lɪksər],意为灵丹妙药、圣水,其logo是一枚紫色水滴: - -![logo](http://elixir-lang.org/images/logo/logo.png) - -Elixir是一门建立在Erlang虚拟机上的[**函数式**](http://baike.baidu.com/view/3476448.htm?fr=aladdin)系统编程语言,支持元编程。 -创始人[José Valim](https://github.com/josevalim)是ruby界的知名人士。 -可以把Elixir看作函数式的ruby语言,或者是语法类似ruby的Erlang。 -Elixir受瞩目的主要原因,是因为它较好地结合了Erlang编程语言的各种优点,以及ruby那样简单易懂的语法(Erlang语法比较晦涩)。 - -Elixir还是一门初出茅庐的语言: - - 2014年9月1日临晨,1.0.0rc1发布 - - 2014年9月7日晚,1.0.0rc2发布 - - 2014年9月18日,[v1.0正式发布](http://elixir-lang.org/blog/2014/09/18/elixir-v1-0-0-released/) - - 2015年9月28日,[v1.1发布](http://elixir-lang.org/blog/2015/09/28/elixir-v1-1-0-released/) - - 2016年1月1日,[v1.2发布](http://elixir-lang.org/blog/2016/01/03/elixir-v1-2-0-released/) - - 2016年6月2日,[v1.3发布](http://elixir-lang.org/blog/2016/06/21/elixir-v1-3-0-released/) - -本文主要框架为Elixir官方的入门教程,辅以网上其它Elixir资源的内容,以及花钱:sob:购买的原版书籍(Dave Thomas的《Programming Elixir》,Progmatic) - ->请帮助更新文档(发个pr)。讨论问题可发issue。 - -**基本教程** - -[1-简介](../master/1-intro.md)
-[2-基本数据类型](../master/2-basic-types.md)
-[3-基本运算符](../master/3-basic-ops.md)
-[4-模式匹配](../master/4-pattern-matching.md)
-[5-流程控制](../master/5-case-cond-if.md)
-[6-二进制串-字符串-字符列表](../master/6-bin-str-charlist.md)
-[7-键值-图-字典](../master/7-keywords-map-dict.md)
-[8-模块](../master/8-modules.md)
-[9-递归](../master/9-recursion.md)
-[10-枚举类型和流](../master/10-enum-stream.md)
-[11-进程](../master/11-process.md)
-[12-IO和文件系统](../master/12-io.md)
-[13-别名和程序导入](../master/13-alias-req-imp.md)
-[14-模块属性](../master/14-mod-attr.md)
-[15-结构体](../master/15-structs.md)
-[16-协议](../master/16-proto.md)
-[17-异常处理](../master/17-try-catch.md)
-[18-列表速构](../master/18-comprehensions.md)
-[19-魔法印](../master/19-sigils.md)
-[20-Typespecs和behaviors](../master/20-typespecs-behaviors.md)
-[21-Erlang库](../master/21-erlang-lib.md)
-[22-下一步](../master/22-next.md)
- - - -**偷偷写在后面的话**   -Elixir处于蓬勃发展中,现在学习的ROI比较高;请谨慎、小规模用于生产环境。 diff --git a/cheat.ex b/cheat.ex deleted file mode 100644 index dd87849..0000000 --- a/cheat.ex +++ /dev/null @@ -1 +0,0 @@ -# Github会以为本repo是elixir 100% diff --git a/images/code.png b/images/code.png new file mode 100644 index 0000000..b414519 Binary files /dev/null and b/images/code.png differ diff --git a/images/pattern.png b/images/pattern.png new file mode 100644 index 0000000..2357903 Binary files /dev/null and b/images/pattern.png differ diff --git a/images/tar.png b/images/tar.png new file mode 100644 index 0000000..1abbdf1 Binary files /dev/null and b/images/tar.png differ diff --git a/images/top.png b/images/top.png new file mode 100644 index 0000000..9acb7f5 Binary files /dev/null and b/images/top.png differ diff --git a/images/zip.png b/images/zip.png new file mode 100644 index 0000000..6499b00 Binary files /dev/null and b/images/zip.png differ diff --git a/index.html b/index.html new file mode 100644 index 0000000..380f4b7 --- /dev/null +++ b/index.html @@ -0,0 +1,82 @@ + + + + + + Elixir编程 by straightdave + + + + + + + +
+
+

Elixir编程

+

Elixir语言入门

+ +

View the Project on GitHub straightdave/programming_elixir

+ + + +
+
+

+Elixir编程入门

+ +

Elixir,[ɪ'lɪksər],意为灵丹妙药、圣水,logo是一枚紫色水滴:
+logo +
+Elixir是一门建立在Erlang虚拟机上的函数式语言,支持元编程,创始人Valim是ruby界的知名人士。私以为,可以把Elixir看作函数式的ruby语言,或者语法改良的Erlang。Elixir受瞩目的原因,是因为它结合了Erlang作为系统编程语言的各种优秀特点,以及类似ruby的语法(Erlang语法比较晦涩)。 +

+ +

Elixir还是一门初出茅庐的语言:
+2014年8月31日,1.0.0发布
+2014年9月1日临晨,1.0.0rc1发布
+2014年9月7日晚,1.0.0rc2发布
+2014年9月10日,1.0.0正式发布
+2015年9月28日,1.1发布

+ +

翻译互联网上诸多Elixir资源,以期能够促进自己和大家学习和推广Elixir编程
+主要资料来源于Elixir网站
+如有问题,请联系我

+ +

基本教程

+ +

1-简介
+2-基本数据类型
+3-基本运算符
+4-模式匹配
+5-流程控制
+6-二进制-字符串-字符列表
+7-键值-图-字典
+8-模块
+9-递归
+10-枚举类型和流
+11-进程
+12-IO
+13-别名和程序导入
+14-模块属性
+15-结构体
+16-协议
+17-异常处理
+18-列表速构
+19-魔法印
+20-下一步

+
+ +
+ + + + diff --git a/javascripts/scale.fix.js b/javascripts/scale.fix.js new file mode 100644 index 0000000..87a40ca --- /dev/null +++ b/javascripts/scale.fix.js @@ -0,0 +1,17 @@ +var metas = document.getElementsByTagName('meta'); +var i; +if (navigator.userAgent.match(/iPhone/i)) { + for (i=0; i" + lines.join("\n") + ""); + }); + + var headings = []; + + var collectHeaders = function(){ + headings.push({"top":$(this).offset().top - 15,"text":$(this).text()}); + } + + if($(".markdown-body h1").length > 1) $(".markdown-body h1").each(collectHeaders) + else if($(".markdown-body h2").length > 1) $(".markdown-body h2").each(collectHeaders) + else if($(".markdown-body h3").length > 1) $(".markdown-body h3").each(collectHeaders) + + $(window).scroll(function(){ + if(headings.length==0) return true; + var scrolltop = $(window).scrollTop() || 0; + if(headings[0] && scrolltop < headings[0].top) { + $(".current-section").css({"opacity":0,"visibility":"hidden"}); + return false; + } + $(".current-section").css({"opacity":1,"visibility":"visible"}); + for(var i in headings) { + if(scrolltop >= headings[i].top) { + $(".current-section .name").text(headings[i].text); + } + } + }); + + $(".current-section a").click(function(){ + $(window).scrollTop(0); + return false; + }) +}); +})(jQuery) \ No newline at end of file diff --git a/params.json b/params.json new file mode 100644 index 0000000..6c98f45 --- /dev/null +++ b/params.json @@ -0,0 +1 @@ +{"name":"Elixir编程","tagline":"Elixir语言入门","body":"Elixir编程入门\r\n=============\r\n\r\nElixir,[ɪ'lɪksər],意为灵丹妙药、圣水,logo是一枚紫色水滴:
\r\n![logo](http://elixir-lang.org/images/logo/logo.png)\r\n
\r\nElixir是一门建立在Erlang虚拟机上的[**函数式语言**](http://baike.baidu.com/view/3476448.htm?fr=aladdin),支持元编程,创始人Valim是ruby界的知名人士。私以为,可以把Elixir看作函数式的ruby语言,或者语法改良的Erlang。Elixir受瞩目的原因,是因为它结合了Erlang作为系统编程语言的各种优秀特点,以及类似ruby的语法(Erlang语法比较晦涩)。\r\n
\r\n\r\nElixir还是一门初出茅庐的语言:
\r\n2014年8月31日,1.0.0发布
\r\n2014年9月1日临晨,1.0.0rc1发布
\r\n2014年9月7日晚,1.0.0rc2发布
\r\n2014年9月10日,1.0.0正式发布
\r\n2015年9月28日,[1.1发布](http://elixir-lang.org/blog/2015/09/28/elixir-v1-1-0-released/)\r\n\r\n翻译互联网上诸多Elixir资源,以期能够促进自己和大家学习和推广Elixir编程 \r\n主要资料来源于[Elixir网站](http://elixir-lang.com) \r\n如有问题,请[联系我](mailto:eyaswoo@163.com)
\r\n\r\n**基本教程**\r\n\r\n[1-简介](../master/1-intro.md)
\r\n[2-基本数据类型](../master/2-basic-types.md)
\r\n[3-基本运算符](../master/3-basic-ops.md)
\r\n[4-模式匹配](../master/4-pattern-matching.md)
\r\n[5-流程控制](../master/5-case-cond-if.md)
\r\n[6-二进制-字符串-字符列表](../master/6-bin-str-charlist.md)
\r\n[7-键值-图-字典](../master/7-keywords-map-dict.md)
\r\n[8-模块](../master/8-modules.md)
\r\n[9-递归](../master/9-recursion.md)
\r\n[10-枚举类型和流](../master/10-enum-stream.md)
\r\n[11-进程](../master/11-process.md)
\r\n[12-IO](../master/12-io.md)
\r\n[13-别名和程序导入](../master/13-alias-req-imp.md)
\r\n[14-模块属性](../master/14-mod-attr.md)
\r\n[15-结构体](../master/15-structs.md)
\r\n[16-协议](../master/16-proto.md)
\r\n[17-异常处理](../master/17-try-catch.md)
\r\n[18-列表速构](../master/18-comprehensions.md)
\r\n[19-魔法印](../master/19-sigils.md)
\r\n[20-下一步](../master/20-next.md)
\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."} \ No newline at end of file diff --git a/stylesheets/github-light.css b/stylesheets/github-light.css new file mode 100644 index 0000000..872a6f4 --- /dev/null +++ b/stylesheets/github-light.css @@ -0,0 +1,116 @@ +/* + Copyright 2014 GitHub Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +.pl-c /* comment */ { + color: #969896; +} + +.pl-c1 /* constant, markup.raw, meta.diff.header, meta.module-reference, meta.property-name, support, support.constant, support.variable, variable.other.constant */, +.pl-s .pl-v /* string variable */ { + color: #0086b3; +} + +.pl-e /* entity */, +.pl-en /* entity.name */ { + color: #795da3; +} + +.pl-s .pl-s1 /* string source */, +.pl-smi /* storage.modifier.import, storage.modifier.package, storage.type.java, variable.other, variable.parameter.function */ { + color: #333; +} + +.pl-ent /* entity.name.tag */ { + color: #63a35c; +} + +.pl-k /* keyword, storage, storage.type */ { + color: #a71d5d; +} + +.pl-pds /* punctuation.definition.string, string.regexp.character-class */, +.pl-s /* string */, +.pl-s .pl-pse .pl-s1 /* string punctuation.section.embedded source */, +.pl-sr /* string.regexp */, +.pl-sr .pl-cce /* string.regexp constant.character.escape */, +.pl-sr .pl-sra /* string.regexp string.regexp.arbitrary-repitition */, +.pl-sr .pl-sre /* string.regexp source.ruby.embedded */ { + color: #183691; +} + +.pl-v /* variable */ { + color: #ed6a43; +} + +.pl-id /* invalid.deprecated */ { + color: #b52a1d; +} + +.pl-ii /* invalid.illegal */ { + background-color: #b52a1d; + color: #f8f8f8; +} + +.pl-sr .pl-cce /* string.regexp constant.character.escape */ { + color: #63a35c; + font-weight: bold; +} + +.pl-ml /* markup.list */ { + color: #693a17; +} + +.pl-mh /* markup.heading */, +.pl-mh .pl-en /* markup.heading entity.name */, +.pl-ms /* meta.separator */ { + color: #1d3e81; + font-weight: bold; +} + +.pl-mq /* markup.quote */ { + color: #008080; +} + +.pl-mi /* markup.italic */ { + color: #333; + font-style: italic; +} + +.pl-mb /* markup.bold */ { + color: #333; + font-weight: bold; +} + +.pl-md /* markup.deleted, meta.diff.header.from-file */ { + background-color: #ffecec; + color: #bd2c00; +} + +.pl-mi1 /* markup.inserted, meta.diff.header.to-file */ { + background-color: #eaffea; + color: #55a532; +} + +.pl-mdr /* meta.diff.range */ { + color: #795da3; + font-weight: bold; +} + +.pl-mo /* meta.output */ { + color: #1d3e81; +} + diff --git a/stylesheets/pygment_trac.css b/stylesheets/pygment_trac.css new file mode 100644 index 0000000..c6a6452 --- /dev/null +++ b/stylesheets/pygment_trac.css @@ -0,0 +1,69 @@ +.highlight { background: #ffffff; } +.highlight .c { color: #999988; font-style: italic } /* Comment */ +.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ +.highlight .k { font-weight: bold } /* Keyword */ +.highlight .o { font-weight: bold } /* Operator */ +.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ +.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ +.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #aa0000 } /* Generic.Error */ +.highlight .gh { color: #999999 } /* Generic.Heading */ +.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ +.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #555555 } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold; } /* Generic.Subheading */ +.highlight .gt { color: #aa0000 } /* Generic.Traceback */ +.highlight .kc { font-weight: bold } /* Keyword.Constant */ +.highlight .kd { font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ +.highlight .kr { font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ +.highlight .m { color: #009999 } /* Literal.Number */ +.highlight .s { color: #d14 } /* Literal.String */ +.highlight .na { color: #008080 } /* Name.Attribute */ +.highlight .nb { color: #0086B3 } /* Name.Builtin */ +.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ +.highlight .no { color: #008080 } /* Name.Constant */ +.highlight .ni { color: #800080 } /* Name.Entity */ +.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ +.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ +.highlight .nn { color: #555555 } /* Name.Namespace */ +.highlight .nt { color: #000080 } /* Name.Tag */ +.highlight .nv { color: #008080 } /* Name.Variable */ +.highlight .ow { font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mf { color: #009999 } /* Literal.Number.Float */ +.highlight .mh { color: #009999 } /* Literal.Number.Hex */ +.highlight .mi { color: #009999 } /* Literal.Number.Integer */ +.highlight .mo { color: #009999 } /* Literal.Number.Oct */ +.highlight .sb { color: #d14 } /* Literal.String.Backtick */ +.highlight .sc { color: #d14 } /* Literal.String.Char */ +.highlight .sd { color: #d14 } /* Literal.String.Doc */ +.highlight .s2 { color: #d14 } /* Literal.String.Double */ +.highlight .se { color: #d14 } /* Literal.String.Escape */ +.highlight .sh { color: #d14 } /* Literal.String.Heredoc */ +.highlight .si { color: #d14 } /* Literal.String.Interpol */ +.highlight .sx { color: #d14 } /* Literal.String.Other */ +.highlight .sr { color: #009926 } /* Literal.String.Regex */ +.highlight .s1 { color: #d14 } /* Literal.String.Single */ +.highlight .ss { color: #990073 } /* Literal.String.Symbol */ +.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ +.highlight .vc { color: #008080 } /* Name.Variable.Class */ +.highlight .vg { color: #008080 } /* Name.Variable.Global */ +.highlight .vi { color: #008080 } /* Name.Variable.Instance */ +.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ + +.type-csharp .highlight .k { color: #0000FF } +.type-csharp .highlight .kt { color: #0000FF } +.type-csharp .highlight .nf { color: #000000; font-weight: normal } +.type-csharp .highlight .nc { color: #2B91AF } +.type-csharp .highlight .nn { color: #000000 } +.type-csharp .highlight .s { color: #A31515 } +.type-csharp .highlight .sc { color: #A31515 } diff --git a/stylesheets/styles.css b/stylesheets/styles.css new file mode 100644 index 0000000..2e1768e --- /dev/null +++ b/stylesheets/styles.css @@ -0,0 +1,324 @@ +@font-face { + font-family: 'Noto Sans'; + font-weight: 400; + font-style: normal; + src: url('../fonts/Noto-Sans-regular/Noto-Sans-regular.eot'); + src: url('../fonts/Noto-Sans-regular/Noto-Sans-regular.eot?#iefix') format('embedded-opentype'), + local('Noto Sans'), + local('Noto-Sans-regular'), + url('../fonts/Noto-Sans-regular/Noto-Sans-regular.woff2') format('woff2'), + url('../fonts/Noto-Sans-regular/Noto-Sans-regular.woff') format('woff'), + url('../fonts/Noto-Sans-regular/Noto-Sans-regular.ttf') format('truetype'), + url('../fonts/Noto-Sans-regular/Noto-Sans-regular.svg#NotoSans') format('svg'); +} + +@font-face { + font-family: 'Noto Sans'; + font-weight: 700; + font-style: normal; + src: url('../fonts/Noto-Sans-700/Noto-Sans-700.eot'); + src: url('../fonts/Noto-Sans-700/Noto-Sans-700.eot?#iefix') format('embedded-opentype'), + local('Noto Sans Bold'), + local('Noto-Sans-700'), + url('../fonts/Noto-Sans-700/Noto-Sans-700.woff2') format('woff2'), + url('../fonts/Noto-Sans-700/Noto-Sans-700.woff') format('woff'), + url('../fonts/Noto-Sans-700/Noto-Sans-700.ttf') format('truetype'), + url('../fonts/Noto-Sans-700/Noto-Sans-700.svg#NotoSans') format('svg'); +} + +@font-face { + font-family: 'Noto Sans'; + font-weight: 400; + font-style: italic; + src: url('../fonts/Noto-Sans-italic/Noto-Sans-italic.eot'); + src: url('../fonts/Noto-Sans-italic/Noto-Sans-italic.eot?#iefix') format('embedded-opentype'), + local('Noto Sans Italic'), + local('Noto-Sans-italic'), + url('../fonts/Noto-Sans-italic/Noto-Sans-italic.woff2') format('woff2'), + url('../fonts/Noto-Sans-italic/Noto-Sans-italic.woff') format('woff'), + url('../fonts/Noto-Sans-italic/Noto-Sans-italic.ttf') format('truetype'), + url('../fonts/Noto-Sans-italic/Noto-Sans-italic.svg#NotoSans') format('svg'); +} + +@font-face { + font-family: 'Noto Sans'; + font-weight: 700; + font-style: italic; + src: url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.eot'); + src: url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.eot?#iefix') format('embedded-opentype'), + local('Noto Sans Bold Italic'), + local('Noto-Sans-700italic'), + url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.woff2') format('woff2'), + url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.woff') format('woff'), + url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.ttf') format('truetype'), + url('../fonts/Noto-Sans-700italic/Noto-Sans-700italic.svg#NotoSans') format('svg'); +} + +body { + background-color: #fff; + padding:50px; + font: 14px/1.5 "Noto Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + color:#727272; + font-weight:400; +} + +h1, h2, h3, h4, h5, h6 { + color:#222; + margin:0 0 20px; +} + +p, ul, ol, table, pre, dl { + margin:0 0 20px; +} + +h1, h2, h3 { + line-height:1.1; +} + +h1 { + font-size:28px; +} + +h2 { + color:#393939; +} + +h3, h4, h5, h6 { + color:#494949; +} + +a { + color:#39c; + text-decoration:none; +} + +a:hover { + color:#069; +} + +a small { + font-size:11px; + color:#777; + margin-top:-0.3em; + display:block; +} + +a:hover small { + color:#777; +} + +.wrapper { + width:860px; + margin:0 auto; +} + +blockquote { + border-left:1px solid #e5e5e5; + margin:0; + padding:0 0 0 20px; + font-style:italic; +} + +code, pre { + font-family:Monaco, Bitstream Vera Sans Mono, Lucida Console, Terminal, Consolas, Liberation Mono, DejaVu Sans Mono, Courier New, monospace; + color:#333; + font-size:12px; +} + +pre { + padding:8px 15px; + background: #f8f8f8; + border-radius:5px; + border:1px solid #e5e5e5; + overflow-x: auto; +} + +table { + width:100%; + border-collapse:collapse; +} + +th, td { + text-align:left; + padding:5px 10px; + border-bottom:1px solid #e5e5e5; +} + +dt { + color:#444; + font-weight:700; +} + +th { + color:#444; +} + +img { + max-width:100%; +} + +header { + width:270px; + float:left; + position:fixed; + -webkit-font-smoothing:subpixel-antialiased; +} + +header ul { + list-style:none; + height:40px; + padding:0; + background: #f4f4f4; + border-radius:5px; + border:1px solid #e0e0e0; + width:270px; +} + +header li { + width:89px; + float:left; + border-right:1px solid #e0e0e0; + height:40px; +} + +header li:first-child a { + border-radius:5px 0 0 5px; +} + +header li:last-child a { + border-radius:0 5px 5px 0; +} + +header ul a { + line-height:1; + font-size:11px; + color:#999; + display:block; + text-align:center; + padding-top:6px; + height:34px; +} + +header ul a:hover { + color:#999; +} + +header ul a:active { + background-color:#f0f0f0; +} + +strong { + color:#222; + font-weight:700; +} + +header ul li + li + li { + border-right:none; + width:89px; +} + +header ul a strong { + font-size:14px; + display:block; + color:#222; +} + +section { + width:500px; + float:right; + padding-bottom:50px; +} + +small { + font-size:11px; +} + +hr { + border:0; + background:#e5e5e5; + height:1px; + margin:0 0 20px; +} + +footer { + width:270px; + float:left; + position:fixed; + bottom:50px; + -webkit-font-smoothing:subpixel-antialiased; +} + +@media print, screen and (max-width: 960px) { + + div.wrapper { + width:auto; + margin:0; + } + + header, section, footer { + float:none; + position:static; + width:auto; + } + + header { + padding-right:320px; + } + + section { + border:1px solid #e5e5e5; + border-width:1px 0; + padding:20px 0; + margin:0 0 20px; + } + + header a small { + display:inline; + } + + header ul { + position:absolute; + right:50px; + top:52px; + } +} + +@media print, screen and (max-width: 720px) { + body { + word-wrap:break-word; + } + + header { + padding:0; + } + + header ul, header p.view { + position:static; + } + + pre, code { + word-wrap:normal; + } +} + +@media print, screen and (max-width: 480px) { + body { + padding:15px; + } + + header ul { + width:99%; + } + + header li, header ul li + li + li { + width:33%; + } +} + +@media print { + body { + padding:0.4in; + font-size:12pt; + color:#444; + } +} diff --git a/stylesheets/stylesheet.css b/stylesheets/stylesheet.css new file mode 100644 index 0000000..abf2d27 --- /dev/null +++ b/stylesheets/stylesheet.css @@ -0,0 +1,966 @@ +/*! normalize.css v3.0.0 | MIT License | git.io/normalize */ + +/** + * 1. Set default font family to sans-serif. + * 2. Prevent iOS text size adjust after orientation change, without disabling + * user zoom. + */ + +html { + font-family: sans-serif; /* 1 */ + -ms-text-size-adjust: 100%; /* 2 */ + -webkit-text-size-adjust: 100%; /* 2 */ +} + +/** + * Remove default margin. + */ + +body { + margin: 0; +} + +/* HTML5 display definitions + ========================================================================== */ + +/** + * Correct `block` display not defined for any HTML5 element in IE 8/9. + * Correct `block` display not defined for `details` or `summary` in IE 10/11 and Firefox. + * Correct `block` display not defined for `main` in IE 11. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +main, +nav, +section, +summary { + display: block; +} + +/** + * 1. Correct `inline-block` display not defined in IE 8/9. + * 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera. + */ + +audio, +canvas, +progress, +video { + display: inline-block; /* 1 */ + vertical-align: baseline; /* 2 */ +} + +/** + * Prevent modern browsers from displaying `audio` without controls. + * Remove excess height in iOS 5 devices. + */ + +audio:not([controls]) { + display: none; + height: 0; +} + +/** + * Address `[hidden]` styling not present in IE 8/9/10. + * Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22. + */ + +[hidden], +template { + display: none; +} + +/* Links + ========================================================================== */ + +/** + * Remove the gray background color from active links in IE 10. + */ + +a { + background: transparent; +} + +/** + * Improve readability when focused and also mouse hovered in all browsers. + */ + +a:active, +a:hover { + outline: 0; +} + +/* Text-level semantics + ========================================================================== */ + +/** + * Address styling not present in IE 8/9/10/11, Safari, and Chrome. + */ + +abbr[title] { + border-bottom: 1px dotted; +} + +/** + * Address style set to `bolder` in Firefox 4+, Safari, and Chrome. + */ + +b, +strong { + font-weight: bold; +} + +/** + * Address styling not present in Safari and Chrome. + */ + +dfn { + font-style: italic; +} + +/** + * Address variable `h1` font-size and margin within `section` and `article` + * contexts in Firefox 4+, Safari, and Chrome. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +/** + * Address styling not present in IE 8/9. + */ + +mark { + background: #ff0; + color: #000; +} + +/** + * Address inconsistent and variable font size in all browsers. + */ + +small { + font-size: 80%; +} + +/** + * Prevent `sub` and `sup` affecting `line-height` in all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +/* Embedded content + ========================================================================== */ + +/** + * Remove border when inside `a` element in IE 8/9/10. + */ + +img { + border: 0; +} + +/** + * Correct overflow not hidden in IE 9/10/11. + */ + +svg:not(:root) { + overflow: hidden; +} + +/* Grouping content + ========================================================================== */ + +/** + * Address margin not present in IE 8/9 and Safari. + */ + +figure { + margin: 1em 40px; +} + +/** + * Address differences between Firefox and other browsers. + */ + +hr { + -moz-box-sizing: content-box; + box-sizing: content-box; + height: 0; +} + +/** + * Contain overflow in all browsers. + */ + +pre { + overflow: auto; +} + +/** + * Address odd `em`-unit font size rendering in all browsers. + */ + +code, +kbd, +pre, +samp { + font-family: monospace, monospace; + font-size: 1em; +} + +/* Forms + ========================================================================== */ + +/** + * Known limitation: by default, Chrome and Safari on OS X allow very limited + * styling of `select`, unless a `border` property is set. + */ + +/** + * 1. Correct color not being inherited. + * Known issue: affects color of disabled elements. + * 2. Correct font properties not being inherited. + * 3. Address margins set differently in Firefox 4+, Safari, and Chrome. + */ + +button, +input, +optgroup, +select, +textarea { + color: inherit; /* 1 */ + font: inherit; /* 2 */ + margin: 0; /* 3 */ +} + +/** + * Address `overflow` set to `hidden` in IE 8/9/10/11. + */ + +button { + overflow: visible; +} + +/** + * Address inconsistent `text-transform` inheritance for `button` and `select`. + * All other form control elements do not inherit `text-transform` values. + * Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera. + * Correct `select` style inheritance in Firefox. + */ + +button, +select { + text-transform: none; +} + +/** + * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` + * and `video` controls. + * 2. Correct inability to style clickable `input` types in iOS. + * 3. Improve usability and consistency of cursor style between image-type + * `input` and others. + */ + +button, +html input[type="button"], /* 1 */ +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; /* 2 */ + cursor: pointer; /* 3 */ +} + +/** + * Re-set default cursor for disabled elements. + */ + +button[disabled], +html input[disabled] { + cursor: default; +} + +/** + * Remove inner padding and border in Firefox 4+. + */ + +button::-moz-focus-inner, +input::-moz-focus-inner { + border: 0; + padding: 0; +} + +/** + * Address Firefox 4+ setting `line-height` on `input` using `!important` in + * the UA stylesheet. + */ + +input { + line-height: normal; +} + +/** + * It's recommended that you don't attempt to style these elements. + * Firefox's implementation doesn't respect box-sizing, padding, or width. + * + * 1. Address box sizing set to `content-box` in IE 8/9/10. + * 2. Remove excess padding in IE 8/9/10. + */ + +input[type="checkbox"], +input[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Fix the cursor style for Chrome's increment/decrement buttons. For certain + * `font-size` values of the `input`, it causes the cursor style of the + * decrement button to change from `default` to `text`. + */ + +input[type="number"]::-webkit-inner-spin-button, +input[type="number"]::-webkit-outer-spin-button { + height: auto; +} + +/** + * 1. Address `appearance` set to `searchfield` in Safari and Chrome. + * 2. Address `box-sizing` set to `border-box` in Safari and Chrome + * (include `-moz` to future-proof). + */ + +input[type="search"] { + -webkit-appearance: textfield; /* 1 */ + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; /* 2 */ + box-sizing: content-box; +} + +/** + * Remove inner padding and search cancel button in Safari and Chrome on OS X. + * Safari (but not Chrome) clips the cancel button when the search input has + * padding (and `textfield` appearance). + */ + +input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} + +/** + * Define consistent border, margin, and padding. + */ + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +/** + * 1. Correct `color` not being inherited in IE 8/9/10/11. + * 2. Remove padding so people aren't caught out if they zero out fieldsets. + */ + +legend { + border: 0; /* 1 */ + padding: 0; /* 2 */ +} + +/** + * Remove default vertical scrollbar in IE 8/9/10/11. + */ + +textarea { + overflow: auto; +} + +/** + * Don't inherit the `font-weight` (applied by a rule above). + * NOTE: the default cannot safely be changed in Chrome and Safari on OS X. + */ + +optgroup { + font-weight: bold; +} + +/* Tables + ========================================================================== */ + +/** + * Remove most spacing between table cells. + */ + +table { + border-collapse: collapse; + border-spacing: 0; +} + +td, +th { + padding: 0; +} + + +/* Style */ + +body { + font-size: 15px; + font-family: Arial, Arial, Helvetica, sans-serif; + line-height: 1.5; + background: #D1D1D1; +} + +a { + color: #63a52a; + text-decoration: none; + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +a:hover { + text-decoration: underline; + color: #90D355; +} + +h1.title { + margin: 30px 20px 10px; + font-size: 60px; + font-weight: bold; + font-style: italic; + font-family:Georgia, serif; + text-align: center; +} + +.wrapper { + width: 675px; + margin: 0 auto; +} + +#container { + border: 1px solid #2a2a2a; + background: #ddd url(../images/pattern.png); + box-shadow: 0 0 5px #b1b1b1; +} + +p.tagline { + padding: 20px 20px 0; + color: #fff; + font-size: 17px; +} + +#main { + margin-top: 20px; + padding: 0 20px 90px; + background-color: #fff; +} + +.download-bar { + background: #222; + border: 5px solid #444; + padding: 10px; + margin: 0 -35px 20px; + position: relative; +} + +.download-bar .inner { + overflow: hidden; +} + +.download-bar .watch-fork iframe { + display: block; + float: left; + border-right: 1px solid #ddd; + padding-right: 5px; +} +.download-bar .watch-fork iframe.last { + border-right: 0 none; + padding-right: 0; + padding-left: 5px; + border-left: 1px solid #fff; +} +.download-bar .watch-fork { + overflow: hidden; + float: right; + background-color: #eee; + padding: 5px; + border-radius: 3px; +} + +.download-bar .blc { + border: 10px solid black; + border-color: transparent transparent black; + width: 0; + height: 0; + display: block; + position: absolute; + bottom: -15px; + left: 0; + transform: rotate(45deg); + -ms-transform: rotate(45deg); /* IE9 */ + -webkit-transform: rotate(45deg); /* 2014 current */ +} + +.download-bar .trc { + border: 10px solid black; + border-color: black transparent transparent; + width: 0; + height: 0; + display: block; + position: absolute; + top: -15px; + right: 0; + transform: rotate(45deg); + -ms-transform: rotate(45deg); /* IE9 */ + -webkit-transform: rotate(45deg); /* 2014 current */ +} + +.download-bar .avatar { + border: 1px solid black; + display: block; + padding: 4px; + float: left; +} + +.download-bar .avatar img { + display: block; +} + +.download-bar a.code { + background: transparent url(../images/code.png) no-repeat 0 2px; + padding-left: 35px; + margin-top: 8px; + display: block; + float: left; + text-indent: 0; + width: auto; + height: auto; + opacity: 1; + filter:alpha(opacity=100); /* IE 5-7 */ +} + +.current-section { + position: fixed; + top: 0; + left: 50%; + width: 693px; + margin-left: -352px; + background: #222; + border: 5px solid #444; + color: #fff; + opacity: 0; + visibility: hidden; + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +.current-section p { + padding: 5px 27px; + font-size: 24px; + font-weight: bold; +} + +.current-section a { + float: right; + text-indent: -10000px; + background: transparent url(../images/top.png) no-repeat 0 0; + width: 20px; + height: 20px; + opacity: 0.8; + margin-right: 12px; + margin-top: 12px; + opacity: 0.8; + filter:alpha(opacity=80); /* IE 5-7 */ + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +.current-section a:hover { + opacity: 1; + filter:alpha(opacity=100); /* IE 5-7 */ +} + +.current-section a.zip { + margin-right: 8px; +} + +a.zip, +a.zip span { + background: transparent url(../images/zip.png) no-repeat 0 0; + width: 30px; + height: 21px; + display: inline-block; + text-indent: -10000px; + opacity: 0.8; + filter:alpha(opacity=80); /* IE 5-7 */ + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +a.tar, +a.tar span { + background: transparent url(../images/tar.png) no-repeat 0 0; + width: 30px; + height: 21px; + display: inline-block; + text-indent: -10000px; + opacity: 0.8; + filter:alpha(opacity=80); /* IE 5-7 */ + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +a.code { + background: transparent url(../images/code.png) no-repeat 0 2px; + width: 30px; + height: 21px; + display: block; + display: inline-block; + text-indent: -10000px; + opacity: 0.8; + filter:alpha(opacity=80); /* IE 5-7 */ + transition: opacity ease-in-out 0.3s; + -webkit-transition: opacity ease-in-out 0.3s; /* Safari <=6.1, Android <= 4.3 */ +} + +a.zip:hover, +a.tar:hover, +a.code:hover { + opacity: 1; + filter:alpha(opacity=100); +} + +a.download-button { + border: 1px solid black; + border-radius: 3px; + display: inline-block; + text-indent: 0!important; + width: auto; + float: right; + background: #999; /* for non-css3 browsers */ + filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#37ADD4', endColorstr='#1B657E'); /* IE <= 9 */ + background: -webkit-gradient(linear, left top, left bottom, from(#37ADD4), to(#1B657E)); /* ancient webkit browsers */ + background: -webkit-linear-gradient(top, #37ADD4, #1B657E); /* Safari <=6.1, Android <= 4.3 */ + background: linear-gradient(to bottom, #37ADD4, #1B657E); + height: auto; + margin-left: 10px; +} + +a.download-button span { + background-position: 10px 5px; + width: auto; + height: auto; + padding: 5px 10px; + padding-left: 45px; + display: inline-block; + text-indent: 0!important; + color: #fff; +} + +footer { + margin-bottom: 60px; + padding-bottom: 60px; +} + +footer .owner { + background: #222; + border: 5px solid #444; + padding: 5px 15px; + margin: -67px -10px 35px; + color: #d6d6d6; +} + +footer .creds small { + float: right; + font-size: 10px; + text-align: right; + margin-left: 15px; +} + +footer .owner .avatar { + background-color: #666; + display: block; + margin: -19px 10px 0 0; + width: 60px; + float: left; +} + +footer .owner img { + display: block; + border: 1px solid #2a2a2a; + margin: 5px; +} + +footer .owner p { + font-family:Georgia, serif; +} + +footer .owner p a { + font-size: 16px; + font-style: italic; +} + +/* Markdown */ +.markdown-body h1, +.markdown-body h2, +.markdown-body h3, +.markdown-body h4, +.markdown-body h5, +.markdown-body h6, +.markdown-body p, +.markdown-body pre, +.markdown-body ul, +.markdown-body ol, +.markdown-body dl, +.markdown-body table, +.markdown-body blockquote { + margin-bottom: 20px; +} + +.markdown-body h1, +.markdown-body h2, +.markdown-body h3, +.markdown-body h4, +.markdown-body h5, +.markdown-body h6 { + font-weight: bold; +} + +.markdown-body h1 { + font-size: 28px; +} + +.markdown-body h2 { + font-size: 24px; + color: #557398; +} + +.markdown-body h3 { + font-size: 20px; +} + +.markdown-body h4 { + font-size: 18px; +} + +.markdown-body h5 { + font-size: 16px; +} + +.markdown-body pre { + padding: 10px 70px 10px 0; + margin-left: -20px; + margin-right: -20px; + font-family: 'Monaco', 'Lucida Console', monospace; + font-size: 13px; + line-height: 20px; + box-shadow: inset 0 0 5px #000; + word-wrap: break-word; + background-color:#3b3b3b; + color: #d6d6d6; +} + +.markdown-body pre.lines { + font-size: 12px; + margin:0 10px 0 -20px; + padding: 10px; + float: left; + display: block; + text-align: right; + box-shadow: none; + background-color:#2a2a2a; + color: #d6d6d6; +} + +.markdown-body ul, +.markdown-body ol { + padding-left: 30px; +} + +.markdown-body ul { + list-style-type: disc; +} + +.markdown-body ol { + list-style-type: decimal; +} + +.markdown-body li, +.markdown-body li p, +.markdown-body dd, +.markdown-body dd p { + margin-bottom: 10px; +} + +.markdown-body li pre, +.markdown-body li pre.lines, +.markdown-body dd pre, +.markdown-body dd pre.lines { + margin-left: -35px; +} + +.markdown-body dt { + font-weight: bold; + font-style: italic; +} + +.markdown-body dd { + margin-left: 15px; +} + +.markdown-body table { + width: 673px; + margin-left: -20px; + margin-right: -20px; +} + +.markdown-body tbody { + border-top: 2px solid #557398; + border-bottom: 2px solid #557398; + background-color: #EBEFF4; +} + +.markdown-body table td * { + margin: 0; +} + +.markdown-body td { + border-right: 1px solid #557398; + border-bottom: 1px solid #557398; + padding: 5px; +} + +.markdown-body td:first-child, +.markdown-body th:first-child { + width: 30%; + padding-left: 20px; +} + +.markdown-body td:last-child { + border-right: 0 none; +} + +.markdown-body th { + font-size: 18px; + font-weight: bold; + text-align: left; + padding: 5px; +} + +.markdown-body tt { + background-color:#3b3b3b; + color: #d6d6d6; + padding: 2px 3px; +} + +.markdown-body blockquote { + font-style: italic; + font-family:Georgia, serif; + font-size: 17px; + border-top: 3px solid #333; + border-bottom: 3px solid #333; + padding: 10px 20px; + padding-left: 50px; +} + +.markdown-body blockquote:before { + font-style: italic; + font-family: Georgia, serif; + font-size: 90px; + height: 90px; + margin-left: -60px; + margin-top: -25px; + content: "‟"; + display: block; + float: left; +} + +.markdown-body img { + max-width: 100%; + box-sizing: border-box; +} + +.highlight { background: #ffffff; } +.highlight .c { color: #999988; font-style: italic } /* Comment */ +.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ +.highlight .k { font-weight: bold } /* Keyword */ +.highlight .o { font-weight: bold } /* Operator */ +.highlight .cm { color: #999988; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #999999; font-weight: bold } /* Comment.Preproc */ +.highlight .c1 { color: #999988; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #999999; font-weight: bold; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ +.highlight .gd .x { color: #000000; background-color: #ffaaaa } /* Generic.Deleted.Specific */ +.highlight .ge { font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #aa0000 } /* Generic.Error */ +.highlight .gh { color: #999999 } /* Generic.Heading */ +.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ +.highlight .gi .x { color: #000000; background-color: #aaffaa } /* Generic.Inserted.Specific */ +.highlight .go { color: #888888 } /* Generic.Output */ +.highlight .gp { color: #555555 } /* Generic.Prompt */ +.highlight .gs { font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #800080; font-weight: bold; } /* Generic.Subheading */ +.highlight .gt { color: #aa0000 } /* Generic.Traceback */ +.highlight .kc { font-weight: bold } /* Keyword.Constant */ +.highlight .kd { font-weight: bold } /* Keyword.Declaration */ +.highlight .kn { font-weight: bold } /* Keyword.Namespace */ +.highlight .kp { font-weight: bold } /* Keyword.Pseudo */ +.highlight .kr { font-weight: bold } /* Keyword.Reserved */ +.highlight .kt { color: #445588; font-weight: bold } /* Keyword.Type */ +.highlight .m { color: #009999 } /* Literal.Number */ +.highlight .s { color: #d14 } /* Literal.String */ +.highlight .na { color: #008080 } /* Name.Attribute */ +.highlight .nb { color: #0086B3 } /* Name.Builtin */ +.highlight .nc { color: #445588; font-weight: bold } /* Name.Class */ +.highlight .no { color: #008080 } /* Name.Constant */ +.highlight .ni { color: #800080 } /* Name.Entity */ +.highlight .ne { color: #990000; font-weight: bold } /* Name.Exception */ +.highlight .nf { color: #990000; font-weight: bold } /* Name.Function */ +.highlight .nn { color: #555555 } /* Name.Namespace */ +.highlight .nt { color: #000080 } /* Name.Tag */ +.highlight .nv { color: #008080 } /* Name.Variable */ +.highlight .ow { font-weight: bold } /* Operator.Word */ +.highlight .w { color: #bbbbbb } /* Text.Whitespace */ +.highlight .mf { color: #009999 } /* Literal.Number.Float */ +.highlight .mh { color: #009999 } /* Literal.Number.Hex */ +.highlight .mi { color: #009999 } /* Literal.Number.Integer */ +.highlight .mo { color: #009999 } /* Literal.Number.Oct */ +.highlight .sb { color: #d14 } /* Literal.String.Backtick */ +.highlight .sc { color: #d14 } /* Literal.String.Char */ +.highlight .sd { color: #d14 } /* Literal.String.Doc */ +.highlight .s2 { color: #d14 } /* Literal.String.Double */ +.highlight .se { color: #d14 } /* Literal.String.Escape */ +.highlight .sh { color: #d14 } /* Literal.String.Heredoc */ +.highlight .si { color: #d14 } /* Literal.String.Interpol */ +.highlight .sx { color: #d14 } /* Literal.String.Other */ +.highlight .sr { color: #009926 } /* Literal.String.Regex */ +.highlight .s1 { color: #d14 } /* Literal.String.Single */ +.highlight .ss { color: #990073 } /* Literal.String.Symbol */ +.highlight .bp { color: #999999 } /* Name.Builtin.Pseudo */ +.highlight .vc { color: #008080 } /* Name.Variable.Class */ +.highlight .vg { color: #008080 } /* Name.Variable.Global */ +.highlight .vi { color: #008080 } /* Name.Variable.Instance */ +.highlight .il { color: #009999 } /* Literal.Number.Integer.Long */ \ No newline at end of file