[Erlang 0108] Elixir 入门

简介:

  Erlang Resources里面关于Elixir的资料越来越多,加上Joe Armstrong的这篇文章,对Elixir的兴趣也越来越浓厚,投入零散时间学习了一下.零零散散,测试代码写了一些,Evernote中笔记更是混乱,还是逐步整理出来.

   Elixir is a functional, meta-programming aware language built on top of the Erlang VM. It is a dynamic language with flexible syntax and macro support that leverages Erlang's abilities to build concurrent, distributed and fault-tolerant applications with hot code upgrades.

 

Git首页 https://github.com/elixir-lang/elixir
Elixir官网 http://elixir-lang.org/

 

各种环境安装Elixir

需要Erlang R16B或更新版本,安装Elixir参考下面的列表.之前有人问是否可以在windows中使用Elixir,下面列表中包含了Chocolatey安装的方案:

Homebrew for Mac OS X

 Update your homebrew to latest with brew update
 Install Elixir: brew install elixir

Fedora 17+ and Fedora Rawhide

 sudo yum -y install elixir

Arch Linux (on AUR)

 yaourt -S elixir

openSUSE (and SLES 11 SP3+)

 Add Erlang devel repo with zypper ar -f obs://devel:languages:erlang/ erlang
 Install Elixir: zypper in elixir

 Gentoo

 emerge --ask dev-lang/elixir

 Chocolatey for Windows

 cinst elixir

 

源码编译

如果是从Git获取源代码编译使用

$ git clone https://github.com/elixir-lang/elixir.git
$ cd elixir
$ make test

 

 

好吧,Windows

 虽然不建议在Windows中搞Erlang相关的东西,但考虑到还是有很多小伙伴习惯在Windows中做开发,还是尝试一下在Windows环境中安装Elixir.我们使用的工具是Chocolatey,它依附于Windows PowerShell的软件库工具,官网有一键安装的批处理命令.安装Chocolatey之后,直接执行cinst elixir即可完成elixir及其依赖库的安装以及环境变量的配置,安装目录在C:\tools\Elixir ,不过进入bin目录执行脚本会闪退,把错误重定向出来如下

复制代码
c:\tools\Elixir\bin>iex
'ETLOCAL' is not recognized as an internal or external command,
operable program or batch file.
'et' is not recognized as an internal or external command,
operable program or batch file.
'or' is not recognized as an internal or external command,
operable program or batch file.
'f' is not recognized as an internal or external command,
operable program or batch file.
Usage: elixir.bat [options] [.exs file] [data]
'cho.' is not recognized as an internal or external command,
复制代码

 

   这是因为脚本解析错误,解决方法很简单:打开elixir.bat脚本用正则在每行的头添加个空格即可.修改后运行:

Interactive Elixir (0.10.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)>

 

我后续的测试都将在Centos中完成,不再考虑Windows环境的情况.

 

开发环境

还用说,Sublime Text通过Package Control安装Elixir插件即可,看截图

 

iex


 在Erlang学习过程中有一个强大的REPL工具EShell,绝大部分的测试和调试都可以在EShell中完成.Elixir同样提供了一个这样的工具iex,而且更为强大(比如可以在Shell中可以定义module).

熟悉一下iex,h()可以看到一些快捷的方法,比如查看一个方法的文档,清屏什么的,看下面的例子

复制代码
iex(5)> h()
# IEx.Helpers

Welcome to Interactive Elixir. You are currently
seeing the documentation for the module `IEx.Helpers`
which provides many helpers to make Elixir's shell
more joyful to work with.

This message was triggered by invoking the helper
`h()`, usually referred to as `h/0` (since it expects 0
arguments).

There are many other helpers available:

* `c/2` — compiles a file at the given path
* `cd/1` — changes the current directory
* `clear/0` — clears the screen
* `flush/0` — flushes all messages sent to the shell
* `h/0` — prints this help message
* `h/1` — prints help for the given module, function or macro
* `l/1` — loads the given module's beam code and purges the current version
* `ls/0` — lists the contents of the current directory
* `ls/1` — lists the contents of the specified directory
* `m/0` — prints loaded modules
* `pwd/0` — prints the current working directory
* `r/0` — recompile and reload all modules that were previously reloaded
* `r/1` — recompiles and reloads the given module's source file
* `s/1` — prints spec information
* `t/1` — prints type information
* `v/0` — prints the history of commands evaluated in the session
* `v/1` — retrieves the nth value from the history
* `import_file/1`
— evaluates the given file in the shell's context

Help for functions in this module can be consulted
directly from the command line, as an example, try:

h(c/2)

You can also retrieve the documentation for any module
or function. Try these:

h(Enum)
h(Enum.reverse/1)

To learn more about IEx as a whole, just type `h(IEx)`.
iex(6)> h(size)
* def size(arg)

Returns the size of the given argument, which must be a tuple
or a binary. If possible, please use `tuple_size` or `byte_size`.

iex(7)> h(length)
* def length(list)

Returns the length of `list`.

Allowed in guard tests.

## Examples

iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
9

iex(8)>
复制代码

 如何退出iex? Ctrl+c 然后 a  

基本数据类型

复制代码
iex> 1 # integer
iex> 0x1F # integer
iex> 1.0 # float
iex> :atom # atom / symbol
iex> {1,2,3} # tuple
iex> [1,2,3] # list
iex> <<1,2,3>> # bitstring
复制代码

 

注意上面:atom这种风格和Ruby是一致的,且在Ruby中这种数据类型就是 symbol.作为一种为了取悦开发者而生的开发语言,Ruby提供了很多让开发者爽到的便利,Elixir从Ruby偷师不少,后续讨论中可以看到.

复制代码
iex(22)> 0x1F
31
iex(23)> 
iex(24)> size {1,2,3}
3
iex(25)> length [12,34,56,66]
4
复制代码

 

字符串!字符串!

先看一个取长度的测试:

复制代码
iex(11)> length("hello")
** (ArgumentError) argument error
:erlang.length("hello")
erl_eval.erl:569: :erl_eval.do_apply/6
src/elixir.erl:138: :elixir.eval_forms/3

iex(11)> size("hello") 
5
iex(12)>
复制代码

 

细心的你一定发现了上面列举基本数据类型的时候没有提到string.上面用到了length和size,两者的区别是什么?length适用于需要遍历计算才能得到长度的场景,Size用于长度已经预计算的情况.换句话说,"hello"是长度是预计算出来的,没有遍历,换句话说,"hello"在Erlang中是list在Elixir中不是!那string到底是什么呢?Elixir还有单引号形式的字符串,这两种又有什么区别?抓狂了吧,其实string只不过是一堆排列在一起的字节而已,而二进制数据只不过是一串数据位而已.看测试:

复制代码
iex(48)> is_binary('zen')
false
iex(49)> is_list('zen') 
true
iex(50)>
nil
iex(51)> is_binary("zen")
true
iex(52)> is_list("zen") 
false
iex(53)> <<"zen">> == "zen"
true
iex(54)> <<'zen'>> == "zen"
true
iex(55)> <<'zen'>> == 'zen'
false
iex(56)> <<122,101,110>> == "zen"
true
复制代码

 

深究一下size和length,我们打开elixir-master\lib\elixir\lib \kernel.ex文件,可以找到下面的代码

复制代码
@doc """
  Returns the size of the given argument, which must be a tuple
  or a binary. If possible, please use `tuple_size` or `byte_size`.
  """
  @spec size(tuple|binary) :: non_neg_integer
  def size(arg) do
    :erlang.size(arg)
  end

  @doc """
  Returns the length of `list`.

  Allowed in guard tests.

  ## Examples

      iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
      9
  """
  @spec length(list) :: non_neg_integer
  def length(list) do
    :erlang.length(list)
  end
复制代码

 

 

在Elixir中双引号和单引号表示的字符串是不同的,看上面的例子, "zen", <<"zen">>,<<'zen'>>都是 <<122,101,110>>数据的语法糖;而'zen'本质上是char list,看下面的代码:

iex(59)> [122,101,110] == "zen" 
false
iex(60)> [122,101,110] == 'zen'
true
iex(61)>

 

提到string就不可避免提到对unicode的支持,Elixir的基础是Erlang R16B01,所以支持unicode不费力,我们先从一
在Erlang中取ASCII的快捷运算符 $a 在Elixir中使用的是"?",不过这个是增强版的,它可以字符的Codepoint

复制代码
iex(29)> ?a
97
iex(30)> [?a,?b,?c]
'abc'
iex(31)> [?a,?b,?c,1]
[97, 98, 99, 1]
iex(53)> ?24320
iex(54)> ?24515

iex(51)> String.codepoints "a我b们c开心"
["a", "", "b", "", "c", "", ""]

iex(59)> <<content::utf8,restcontent::binary >>="我们很开心abc"
"我们很开心abc"
iex(60)> content
25105
iex(61)> ?25105
iex(62)> restcontent
"们很开心abc"


iex(43)> is_bitstring("hello开心")
true
iex(44)> bit_size("hello开心") 
88
iex(45)> bit_size("开心") 
48
iex(47)> size("wo们")
5
复制代码

 

之前我们分析过Erlang字符串截断的例子,里面提到了"开心"这两个汉字都是三字节模板,所以这里的bit_size是48,"wo们"是两个单字节加上一个三字节所以是5.

继续看Elixir字符串处理还有哪些特色:

字符串连接:

iex(74)> "foo" <> "bar"
"foobar"

 

字符串占位符:

iex(37)> name="zen"
"zen"
iex(38)> "hello,I am #{name}"
"hello,I am zen"
iex(39)>

 

Ruby里面把上面占位替换成为表达式替换"Expression Substitution",看Ruby的例子

x, y, z = 12, 36, 72
puts "The value of x is #{ x }.
puts "The sum of x and y is #{ x + y }.
puts "The average was #{ (x + y + z)/3 }."

 

更多字符串操作 http://elixir-lang.org/docs/stable/String.html

 

先到这里,小图一张 小黄人 最近它们很火:

目录
相关文章
|
7月前
|
Java
开发语言漫谈-erlang
erlang又是一个应用邻域狭窄的语言
|
6月前
|
Linux Windows
一篇文章讲明白Erlang打包工具rebar安装使用
一篇文章讲明白Erlang打包工具rebar安装使用
80 0
|
开发框架 物联网 开发者
Ruby vs Elixir | 2022 该选哪个?
Ruby vs Elixir | 2022 该选哪个?
Ruby vs Elixir | 2022 该选哪个?
|
开发工具 git
|
C#
[Erlang 0112] Elixir Protocols
Why Elixir        为什么要学习Elixir?答案很简单,为了更好的学习Erlang.这么无厘头的理由?      Erlang语法设计几乎没有考虑过取悦开发者,所以学习之初的门槛略高.
1223 0
|
JavaScript 前端开发 Shell
|
IDE 开发工具 Android开发