elixir と phoenixを軽く触ってみる
elixir の wikipedia
Elixir (プログラミング言語) - Wikipedia
Elixir (エリクサー)は並列処理、関数型に対応した、Erlangの仮想環境(BEAM)上で動作する汎用プログラミング言語である。ElixirはErlangで実装されているため、分散システム、耐障害性、ソフトリアルタイムシステム等の機能を使用することができるが、拡張機能として、マクロを使ったメタプログラミング、そしてポリモーフィズムなどのプログラミング・パラダイムもプロトコルを介して実装されている
elixir のインストール
$ brew update
$ brew install elixir
これでok.
iex でインタラクティブシェルが立ち上がる。
$ iex
文字列の連結は + じゃなくて <> を使う。
iex(1)> "hello" + " world" ** (ArithmeticError) bad argument in arithmetic expression :erlang.+("hello", " world") iex(1)> "hello" <> " world" "hello world" iex(2)>
rubyと同様に#{}によって式展開
iex(2)> "10 + 20 = #{10+20}" "10 + 20 = 30"
リストとタプル。
リストは Linked list に対し、タプルは要素を連続したメモリ上に保存している。
リストの更新や追加に比べて、タプルの更新は要素全体をコピーして生成するのでコストが高い。
変更されないようなデータをタプルにした方がよさげ。
iex(4)> %{hoge: 100, huga: 200} %{hoge: 100, huga: 200} iex(5)> nil iex(6)> map = %{hoge: 100, huga: 200} %{hoge: 100, huga: 200} iex(7)> map.hoge 100 iex(8)> %{map | hoge: 300} %{hoge: 300, huga: 200} iex(9)> map.hoge 100 iex(10)> map = %{map | hoge: 300} %{hoge: 300, huga: 200} iex(11)> map.hoge 300 iex(12)>
実際にelixirプロジェクトを作成する。
$ mix new
で空プロジェクトが作成される。
$ mix test
でとりあえずtestが通れば問題無し。
hello world を出力する
defmodule Hello do def world do IO.puts "Hello World" end end Hello.world
defmodule Fib do def fib(0) do 0 end def fib(1) do 1 end def fib(n) do fib(n-1)+fib(n-2) end end IO.puts Fib.fib(10)
Railsライクな web framework の Phoenixもとりあえず動かしてみる。
install
$ mix archive install phoenix
new project
$ mix phoenix.new .
launch
$ mix phoenix.server
これで、localhost:4000 でアクセスできる。
ひな形プロジェクトに対し、/hello ページを追加する。
変更したコードは下記の通り。
https://github.com/kidooom/phoenix_training/commit/801f9039014d4d629dafbf5772826ff73140ebbe
これで、localhost:4000/hello
で動く。簡単。