<%= @title %>
Please, choose a story
Snow white
Read it to me!
Cinderella
Read it to me!
web/routers/application_router.ex
---------------------------------
.. code-block:: elixir
# ....
get "/:file_name" do
normalized_title = String.capitalize(String.replace(conn.params[:file_name], "-", " "))
conn = conn.assign :title, normalized_title
conn = conn.assign :file_name, conn.params[:file_name]
render conn, "story.html"
end
end
web/layouts/story.html.eex
--------------------------
.. code-block:: html
<%= @title %>
<%= @title %>
Play!
web/routers/application_router.ex
---------------------------------
.. code-block:: elixir
# ....
get "/play/:story_name" do
conn = conn.resp_content_type("text/event-stream")
conn = conn.send_chunked(200)
iterator = File.iterator!("#{conn.params[:story_name]}.txt")
Enum.each iterator, fn(line) ->
{ :ok, conn } = conn.chunk "data: #{line}\n"
await conn, 1000, on_wake_up(&1, &2), on_time_out(&1)
end
conn
end
defp on_wake_up(arg1, arg2) do
# Nothing
end
defp on_time_out(arg1) do
# Nothing
end
Now let’s test out code. The curl command is perfec for this
-------------------------------------------------------------
.. code-block:: bash
curl -i http://localhost:4000/play/cinderella
HTTP/1.1 200 OK
transfer-encoding: chunked
connection: keep-alive
server: Cowboy
date: Mon, 29 Apr 2013 15:12:27 GMT
content-type: text/event-stream; charset=utf-8
cache-control: max-age=0, private, must-revalidate
data: Once upon a time... there lived an unhappy young girl.
data: Unhappy she was, for her mother was dead, her father
data: had married another woman, a widow with two daughters,
data: and her stepmother didn't like her one little bit. All
data: the nice things, kind thoughts and loving touches were
data: for her own daughters. And not just the kind thoughts
# ...
/priv/static/storyteller.js
---------------------------
.. code-block:: javascript
$(function(){
$('.play').on('click', function(ev){
ev.preventDefault();
var source = new EventSource(this.href);
source.addEventListener('message', function(e) {
var $line = $('' + e.data + '
');
$line.appendTo('#chat').hide().fadeIn(200, function(){
$("html, body").animate({ scrollTop: $(document).height() }, "slow");
})
}, false);
});
});
`Elixir is for programmers - Pluralsight blog`_
===============================================
.. _Elixir is for programmers - Pluralsight blog: http://blog.pluralsight.com/elixir-is-for-programmers
Smart assert
------------
::
Elixir knows that == is being used in the assertion, and shows you the values on either side of == when the test fails. Now that’s a useful error!
Multi-block control flow
------------------------
::
In Elixir, the relationship between single line functions and multi-line blocks is well thought out.
These two are equivalent:
.. code-block:: elixir
# Single line
if(condition, do: a, else: b)
# Multiple lines
if condition do
a
else
b
end
::
In the single line version, if is a function that takes two arguments: the condition and the clauses. The clauses are do and else.
Consistent use of do
--------------------
::
Elixir is consistent.
Need a module? It’s defmodule...do. Need an if? It also uses do. Same with def.
Built-in TDD
------------
::
With Elixir, it’s built in. Use the mix command to generate a new app and you’re ready to go with a unit test. Run mix test to run the test suite. Done.
::
And it can run your tests concurrently with a single async option.
Mind-blowing metaprogramming: upcase
------------------------------------
.. code-block:: elixir
def upcase("é" <> rest) do
["É"] ++ upcase(rest)
end
::
A few things are going on here. Elixir can match functions on the number, type, and content of its arguments. So it looks for a letter such as é. It knows the upper case version of the letter, then sends the rest of the string to the next letter’s upcase function.
`Elixir Isn't Hipster - alexrp's blog`_
=======================================
.. _Elixir Isn't Hipster - alexrp's blog: http://blog.alexrp.com/2013/02/14/elixir-isnt-hipster/
Performance
-----------
::
It uses the so-called ‘threaded code interpretation’ approach. This is one of the fastest possible ways to interpret bytecode as every instruction is a direct pointer to executable C code.
::
the BEAM offers a full-blown native code compiler these days, called HiPE (High Performance Erlang). HiPE works in a similar fashion to software such as PyPy and IonMonkey with the exception that it compiles ahead-of-time (AOT) instead of just-in-time (JIT).
Reliability
-----------
* Linked processes
* Coordinated restarts
* Failover nodes
* Hot code reloading
Language Design
---------------
* Expression syntax
* Pattern matching
* First-class functions
* Closures
* Records
* Protocols
* Metaprogramming
* Unicode strings
* Immutability
* Variable rebinding
* Erlang interop
Functional Programming
----------------------
::
A general rule of thumb is that you should focus on the data flowing through your program rather than focusing on your program’s high-level behavior.
::
once you stop thinking about objects and methods entirely, it becomes incredibly easy to solve real problems in functional languages.
`The Erlangelist -- Why Elixir?`_
=================================
.. _The Erlangelist -- Why Elixir?: http://www.theerlangelist.com/2014/01/why-elixir.html
The problems of Erlang the language
-----------------------------------
::
The problem I have with Erlang is that the language is somehow too simple, making it very hard to eliminate some frequent cases of boilerplate and structural duplication. Consequently, the resulting code gets a bit messy, being harder to write, analyze, and modify.
What Elixir is (not)
--------------------
::
it is an Erlang-esque language with improved code organization capabilities.
Metaprogramming
---------------
::
Elixir macros are nothing like C/C++ macros. Instead of working on strings, they are something like compile-time Elixir functions that are called in the middle of parsing, and work on the abstract syntax tree (AST), which is a code represented as Elixir data structure. Macro can work on AST, and spit out some alternative AST that represents the generated code. Since macros are executed in compile-time, the performance of a running system will not be affected.
Pipeline operator
-----------------
::
The code can easily be followed by reading it from top to bottom.
::
The pipeline operator works extremely well because the API in Elixir libraries follows the "subject (noun) as the first argument" convention.
Polymorphism via protocols
--------------------------
::
Protocols allow developers to create a generic logic that can be used with any type of data, assuming that some contract is implemented for the given data.
The mix tool
------------
::
With a single command line you can create an OTP application skeleton, that consists of only 7 files (this includes .gitignore and README.md).
Other goodies
-------------
::
there are many other enhancements Elixir provides, such as support for variable rebinding, optional parentheses, implicit statement endings, nullability, short circuits operators, ...
`Introduction to Parallel Computing with Elixir - Reactive.IO`_
===============================================================
.. _Introduction to Parallel Computing with Elixir - Reactive.IO: http://www.reactive.io/tips/2015/02/03/introduction-to-parallel-computing-with-elixir/
Mixing Up a New Project
-----------------------
.. code-block:: bash
mix new fibex
/lib/fibex/fn.ex
~~~~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex.Fn do
def run(n) do
run(n, 1, 0)
end
defp run(0, _, _) do
0
end
defp run(1, a, b) do
a + b
end
defp run(n, a, b) do
run(n - 1, b, a + b)
end
end
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def run(ns) do
ns
|> Enum.map(&(Fibex.Fn.run(&1)))
|> inspect
|> IO.puts
end
end
.. code-block:: bash
$ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])"
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
Going Parallel
--------------
/lib/fibex/fn.ex
~~~~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex.Fn do
def spawn_run(pid, ni) do
spawn __MODULE__, :send_run, [pid, ni]
end
def send_run(pid, {n, i}) do
send pid, {run(n), i}
end
def run(n) do
run(n, 1, 0)
end
defp run(0, _, _) do
0
end
defp run(1, a, b) do
a + b
end
defp run(n, a, b) do
run(n - 1, b, a + b)
end
end
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def run(ns) do
ns
|> Enum.with_index
|> Enum.map fn(ni) ->
Fibex.Fn.spawn_run(self, ni)
end
receive_fibs(length(ns), [])
end
defp receive_fibs(lns, result) do
receive do
fib ->
result = [fib | result]
if lns == 1 do
IO.puts(print_fibs(result))
else
receive_fibs(lns - 1, result)
end
end
end
defp print_fibs(fibs) do
fibs
|> Enum.sort(fn({_, a}, {_, b}) -> a < b end)
|> Enum.map(fn({f, _}) -> f end)
|> inspect
end
end
.. code-block:: bash
$ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])"
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
Building our Escript
--------------------
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def main(argv) do
argv |> Enum.map(&(String.to_integer(&1))) |> run
end
def run(ns) do
ns
|> Enum.with_index
|> Enum.map fn(ni) ->
Fibex.Fn.spawn_run(self, ni)
end
receive_fibs(length(ns), [])
end
defp receive_fibs(lns, result) do
receive do
fib ->
result = [fib | result]
if lns == 1 do
IO.puts(print_fibs(result))
else
receive_fibs(lns - 1, result)
end
end
end
defp print_fibs(fibs) do
fibs
|> Enum.sort(fn({_, a}, {_, b}) -> a < b end)
|> Enum.map(fn({f, _}) -> f end)
|> inspect
end
end
mix.exs
~~~~~~~
.. code-block:: elixir
defmodule Fibex.Mixfile do
use Mix.Project
def project do
[app: :fibex,
version: "0.0.1",
elixir: "~> 1.0",
escript: [main_module: Fibex],
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[]
end
end
.. code-block:: bash
$ ./fibex 20 18 32 28 22 42 55 48
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
`The Oozou Blog - Why we are excited about Elixir`_
===================================================
.. _The Oozou Blog - Why we are excited about Elixir: http://blog.oozou.com/why-we-are-excited-about-elixir/
The platform
------------
::
Erlang is powering projects like Facebook Chat, WhatsApp, and Amazon SimpleDB, which demonstrates both the scalability and stability of the platform. It’s pretty exciting to imagine that Elixir may be able to provide many new developers with easier access to it.
Ruby-like syntax
----------------
::
He also added a certain symmetry that Ruby is lacking (e.g. do keywords for class and module definitions), which allowed for an easier implementation of Elixir’s macro system
::
Elixir offers hygienic macros. While it’s an old saying amongst Lispers that the first rule of macros is to not write macros, they do occasionally come in handy and add powerful meta-programming and DSL capabilities to the language.
Good tooling
------------
mix
~~~~
::
mix clean # Delete generated application files
mix cmd # Executes the given command
mix compile # Compile source files
mix deps # List dependencies and their status
mix deps.clean # Remove the given dependencies' files
mix deps.compile # Compile dependencies
mix deps.get # Get all out of date dependencies
mix deps.unlock # Unlock the given dependencies
mix deps.update # Update the given dependencies
mix new # Create a new Elixir project
mix run # Run the given file or expression
mix test # Run a project's tests
ExUnit
~~~~~~
doc tests
~~~~~~~~~
.. code-block:: elixir
defmodule Oozou do
@doc ~S"""
Adds two numbers
## Examples
iex> Oozou.add(2, 2)
4
"""
def add(a, b), do: a + b
end
.. code-block:: elixir
defmodule OozouTest do
use ExUnit.Case, async: true
doctest Oozou
end
Great documentation
-------------------
.. code-block:: elixir
defmodule Oozou do
@moduledoc """
We handcraft beautiful web apps
"""
@doc """
Be awesome!
"""
def work(), do: :beautiful_web_app
end
Now show me some code
---------------------
.. code-block:: elixir
defmodule FizzBuzz do
def compute(n) do
s = case {rem(n, 3), rem(n, 5)} do
{0, 0} -> :FizzBuzz
{0, _} -> :Fizz
{_, 0} -> :Buzz
_ -> n
end
IO.puts(s)
end
end
Enum.map(1..15, &FizzBuzz.compute/1)
# or as list comprehension:
# for i <- 1..15, do: FizzBuzz.compute(i)
`Lispy Elixir | 8th Light`_
===========================
.. _Lispy Elixir | 8th Light: http://blog.8thlight.com/patrick-gombert/2013/11/26/lispy-elixir.html
Homoiconicity
-------------
::
Elixir, on the surface, is not homoiconic. However, the syntax on the surface is just a facade for the homiconic structure underneath. To peer under the covers we're going to need explore one more of Lisp's ideas.
Quoting
-------
::
In Elixir, all expressions are represented as three element tuples. Let's look at a simple, straightforward example where we are simply adding two numbers.
.. code-block:: elixir
quote do
1 + 1
end # => {:+, [], [1, 1]}
Abstract Syntax Trees
---------------------
::
Abstract syntax trees are simply a way to represent call structures in a tree like fashion.
Macros
------
::
A macro takes quoted forms (abstract syntax trees) and is free to edit the tree as it chooses in order to do any number of interesting things.
Macros (Almost) All The Way Down
--------------------------------
::
def in Elixir is a macro. Upon further inspection we can see what def produces in terms of an abstract syntax tree.
Standing On The Shoulders Of Giants
-----------------------------------
::
Elixir's future looks bright and exciting in part because it's standing on the shoulders of giants.
`How I Start -- Elixir`_
========================
.. _How I Start -- Elixir: https://howistart.org/posts/elixir/1
Portal
------
Installation
------------
Our first project
-----------------
Pattern matching
----------------
Modeling portal doors with Agents
---------------------------------
Inspecting portals with Protocols
---------------------------------
Shooting supervised doors
-------------------------
Distributed transfers
---------------------
Wrapping up
-----------
`Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目`_
===============================================================================================================
.. _Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目: http://gihyo.jp/news/report/01/rubykaigi2013/0002
自己紹介
--------
どうして,いま,並行性(concurrency)なのか
-------------------------------------------
クラスのアクセサにおけるレースコンディション
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
様々な実装の存在するRuby - 実装による違い
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ほかの言語から学ぶこと - Rubyへの提案
-------------------------------------
Javaに目を向けてみる
~~~~~~~~~~~~~~~~~~~~
提案その1:Hash#concurrent_read, Hash#concurrent_write
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その2:AtomicReferenceの導入
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その3:Go言語の紹介と軽量で高機能な新しいQueueの採用
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その4:さらに軽量な,並行プログラミングのための仕組みを組み込みで提供する
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
結論 - concurrentなRubyのための議論をしよう
-------------------------------------------
`Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳`_
================================================================================
.. _Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳: http://yohshiy.blog.fc2.com/blog-entry-235.html
Elixirとは
----------
特徴
----
Hello, world!
~~~~~~~~~~~~~
全てが式
~~~~~~~~
メタプログラミングと DSL
~~~~~~~~~~~~~~~~~~~~~~~~
プロトコル(文脈, 約束)による多様性
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ドキュメントもコードの一部
~~~~~~~~~~~~~~~~~~~~~~~~~~
パターンマッチング
~~~~~~~~~~~~~~~~~~
結局のところ Erlang
~~~~~~~~~~~~~~~~~~~
インストール
------------
使い方
------
対話モード
~~~~~~~~~~
コンパイル
~~~~~~~~~~
スクリプト
~~~~~~~~~~
Emacs モードの設定
------------------
感想
----
参考
----
`elixir はプログラマの万能薬になるか - Fat Old Sun`_
====================================================
.. _elixir はプログラマの万能薬になるか - Fat Old Sun: http://d.hatena.ne.jp/k-1/20120310/p1
特徴
----
::
ひとことでまとめると、erlangの並列/高信頼フレームワークが利用できるrubyライクの構文を持つlispといえる。
ビルド
------
Hello, world.
-------------
`Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp`_
===========================================================
.. _Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp: http://m.igrs.jp/blog/2012/03/12/why-rubyists-should-try-elixir/
パターンマッチング (Pattern matching)
-------------------------------------
単一代入変数と不変性 (Single assignment variables and immutability)
-------------------------------------------------------------------
プロセス間通信 (Communication between processes)
------------------------------------------------
異なるオブジェクトモデル (A different Object Model)
---------------------------------------------------
学ぶ (Just learn)
-----------------
結論 (Wrapping up)
------------------
`The Excitement of Elixir - Hacking Devin Torres`_
==================================================
.. _The Excitement of Elixir - Hacking Devin Torres: http://devintorr.es/blog/2013/01/22/the-excitement-of-elixir/
Syntax
------
::
Elixir syntax is like a marriage of DSL friendly Ruby and the powerful hygenic macros of Clojure.
Expressions
-----------
::
Elixir if expressions, like most everything else in the language, are implemented using a macro.
Strings
-------
::
Elixir strings are UTF8 binaries, with all the raw speed and memory savings that brings. Elixir has a String module with Unicode functionality built-in and is a great example of writing code that writes code. String.Unicode reads various Unicode database dumps such as UnicodeData.txt to dynamically generate Unicode functions for the String module built straight from that data!
Single assignment
-----------------
::
There is no context dependent expression separators and when you rebind a name all you’re doing is rebinding a new value to the name. Elixir is still immutable, it’s just not trying to pass off single assignment as immutability.
Records
-------
::
Elixir records are real records, and provide compile time pattern matching and a much more dynamic nature.
Standard library
----------------
::
While you can’t escape using the Erlang standard library from time to time, Elixir’s standard library is trying to normalize zero-based access and noun-first argument ordering, along with a more consistent API.
Code organization
-----------------
::
Elixir modules provide a great way to encapsulate functionality. As many modules as you desire can be declared within the same file including private functionality (functions, macros, records, exceptions, fuzzybunnies, whatever).
`Learn elixir in Y Minutes - Learn X in Y Minutes`_
===================================================
.. _Learn elixir in Y Minutes - Learn X in Y Minutes: http://learnxinyminutes.com/docs/elixir/
`Two days with Elixir - Neo | Ideas`_
=====================================
.. _Two days with Elixir - Neo | Ideas: http://www.neo.com/2013/08/27/two-days-with-elixir
The pipe operator |> is fantastic.
----------------------------------
The function capture notation & is cool as long as you keep the definitions short.
----------------------------------------------------------------------------------
Pattern matching makes recursive definitions easy
-------------------------------------------------
Guard clauses are nice but the syntax feels verbose
---------------------------------------------------
When a guard clauses prevents a function match, I feel like the error message you get could be more helpful
-----------------------------------------------------------------------------------------------------------
Elixir's functional nature means there is less syntactic sugar than I'm used to
-------------------------------------------------------------------------------
ExUnit feels pretty unfinished
------------------------------
Building concurrent, distributed, fault-tolerant systems is baked right in
--------------------------------------------------------------------------
Summing Up
----------
`Build and test a blazing fast JSON API with Phoenix, an Elixir framework`_
===========================================================================
.. _Build and test a blazing fast JSON API with Phoenix, an Elixir framework: https://robots.thoughtbot.com/testing-a-phoenix-elixir-json-api
Why Elixir and Phoenix?
-----------------------
Writing the test
----------------
Creating our databases
----------------------
Adding the Contact model
------------------------
Adding the routes and controller
--------------------------------
Rendering our JSON with a view
------------------------------
Cleanup
-------
That’s a wrap
--------------
`超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう`_
==========================================================================
.. _超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう: http://postd.cc/testing-a-phoenix-elixir-json-api/
なぜElixirとPhoenixなのか
-------------------------
テストを書く
------------
データベースを構築する
----------------------
連絡先モデルを追加する
----------------------
ルートとコントローラを追加する
------------------------------
viewでJSONをレンダリングする
----------------------------
クリーンアップ
--------------
まとめ
------
`Elixir - The next big language for the web`_
=============================================
.. _Elixir - The next big language for the web: http://www.creativedeletion.com/2015/04/19/elixir_next_language.html
From obscurity to the default choice
------------------------------------
Erlang
------
Elixir
------
Immutability and functional programming
---------------------------------------
Concurrency
-----------
Web framework
-------------
Programmer happiness and beautiful code
---------------------------------------
Déjà vu
---------
`Why I’m betting on Elixir — Medium`_
=====================================
.. _Why I’m betting on Elixir — Medium: https://medium.com/@kenmazaika/why-im-betting-on-elixir-7c8f847b58
Ruby Crushed It!
----------------
But every so often, artifacts of ruby’s humble beginnings arise
---------------------------------------------------------------
Run-away memory!
~~~~~~~~~~~~~~~~
Concurrency!
~~~~~~~~~~~~
Speed!
~~~~~~
Scala
~~~~~
The Elixir Ecosystem
--------------------
Package Management with Mix
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Erlang Virtual Machine
~~~~~~~~~~~~~~~~~~~~~~~~~~
The Phoenix Web Framework
~~~~~~~~~~~~~~~~~~~~~~~~~
Strong Leadership
~~~~~~~~~~~~~~~~~
Friends, the web is about to under-go a transformational change
---------------------------------------------------------------
`Unlimited Novelty -- Why I'm stopping work on Reia`_
=====================================================
.. _Unlimited Novelty -- Why I'm stopping work on Reia: http://www.unlimitednovelty.com/2011/06/why-im-stopping-work-on-reia.html
Please, choose a story
Snow white
Read it to me!
Cinderella
Read it to me!
Snow white
Read it to me!Cinderella
Read it to me!<%= @title %>
Play!
web/routers/application_router.ex
---------------------------------
.. code-block:: elixir
# ....
get "/play/:story_name" do
conn = conn.resp_content_type("text/event-stream")
conn = conn.send_chunked(200)
iterator = File.iterator!("#{conn.params[:story_name]}.txt")
Enum.each iterator, fn(line) ->
{ :ok, conn } = conn.chunk "data: #{line}\n"
await conn, 1000, on_wake_up(&1, &2), on_time_out(&1)
end
conn
end
defp on_wake_up(arg1, arg2) do
# Nothing
end
defp on_time_out(arg1) do
# Nothing
end
Now let’s test out code. The curl command is perfec for this
-------------------------------------------------------------
.. code-block:: bash
curl -i http://localhost:4000/play/cinderella
HTTP/1.1 200 OK
transfer-encoding: chunked
connection: keep-alive
server: Cowboy
date: Mon, 29 Apr 2013 15:12:27 GMT
content-type: text/event-stream; charset=utf-8
cache-control: max-age=0, private, must-revalidate
data: Once upon a time... there lived an unhappy young girl.
data: Unhappy she was, for her mother was dead, her father
data: had married another woman, a widow with two daughters,
data: and her stepmother didn't like her one little bit. All
data: the nice things, kind thoughts and loving touches were
data: for her own daughters. And not just the kind thoughts
# ...
/priv/static/storyteller.js
---------------------------
.. code-block:: javascript
$(function(){
$('.play').on('click', function(ev){
ev.preventDefault();
var source = new EventSource(this.href);
source.addEventListener('message', function(e) {
var $line = $('' + e.data + '
');
$line.appendTo('#chat').hide().fadeIn(200, function(){
$("html, body").animate({ scrollTop: $(document).height() }, "slow");
})
}, false);
});
});
`Elixir is for programmers - Pluralsight blog`_
===============================================
.. _Elixir is for programmers - Pluralsight blog: http://blog.pluralsight.com/elixir-is-for-programmers
Smart assert
------------
::
Elixir knows that == is being used in the assertion, and shows you the values on either side of == when the test fails. Now that’s a useful error!
Multi-block control flow
------------------------
::
In Elixir, the relationship between single line functions and multi-line blocks is well thought out.
These two are equivalent:
.. code-block:: elixir
# Single line
if(condition, do: a, else: b)
# Multiple lines
if condition do
a
else
b
end
::
In the single line version, if is a function that takes two arguments: the condition and the clauses. The clauses are do and else.
Consistent use of do
--------------------
::
Elixir is consistent.
Need a module? It’s defmodule...do. Need an if? It also uses do. Same with def.
Built-in TDD
------------
::
With Elixir, it’s built in. Use the mix command to generate a new app and you’re ready to go with a unit test. Run mix test to run the test suite. Done.
::
And it can run your tests concurrently with a single async option.
Mind-blowing metaprogramming: upcase
------------------------------------
.. code-block:: elixir
def upcase("é" <> rest) do
["É"] ++ upcase(rest)
end
::
A few things are going on here. Elixir can match functions on the number, type, and content of its arguments. So it looks for a letter such as é. It knows the upper case version of the letter, then sends the rest of the string to the next letter’s upcase function.
`Elixir Isn't Hipster - alexrp's blog`_
=======================================
.. _Elixir Isn't Hipster - alexrp's blog: http://blog.alexrp.com/2013/02/14/elixir-isnt-hipster/
Performance
-----------
::
It uses the so-called ‘threaded code interpretation’ approach. This is one of the fastest possible ways to interpret bytecode as every instruction is a direct pointer to executable C code.
::
the BEAM offers a full-blown native code compiler these days, called HiPE (High Performance Erlang). HiPE works in a similar fashion to software such as PyPy and IonMonkey with the exception that it compiles ahead-of-time (AOT) instead of just-in-time (JIT).
Reliability
-----------
* Linked processes
* Coordinated restarts
* Failover nodes
* Hot code reloading
Language Design
---------------
* Expression syntax
* Pattern matching
* First-class functions
* Closures
* Records
* Protocols
* Metaprogramming
* Unicode strings
* Immutability
* Variable rebinding
* Erlang interop
Functional Programming
----------------------
::
A general rule of thumb is that you should focus on the data flowing through your program rather than focusing on your program’s high-level behavior.
::
once you stop thinking about objects and methods entirely, it becomes incredibly easy to solve real problems in functional languages.
`The Erlangelist -- Why Elixir?`_
=================================
.. _The Erlangelist -- Why Elixir?: http://www.theerlangelist.com/2014/01/why-elixir.html
The problems of Erlang the language
-----------------------------------
::
The problem I have with Erlang is that the language is somehow too simple, making it very hard to eliminate some frequent cases of boilerplate and structural duplication. Consequently, the resulting code gets a bit messy, being harder to write, analyze, and modify.
What Elixir is (not)
--------------------
::
it is an Erlang-esque language with improved code organization capabilities.
Metaprogramming
---------------
::
Elixir macros are nothing like C/C++ macros. Instead of working on strings, they are something like compile-time Elixir functions that are called in the middle of parsing, and work on the abstract syntax tree (AST), which is a code represented as Elixir data structure. Macro can work on AST, and spit out some alternative AST that represents the generated code. Since macros are executed in compile-time, the performance of a running system will not be affected.
Pipeline operator
-----------------
::
The code can easily be followed by reading it from top to bottom.
::
The pipeline operator works extremely well because the API in Elixir libraries follows the "subject (noun) as the first argument" convention.
Polymorphism via protocols
--------------------------
::
Protocols allow developers to create a generic logic that can be used with any type of data, assuming that some contract is implemented for the given data.
The mix tool
------------
::
With a single command line you can create an OTP application skeleton, that consists of only 7 files (this includes .gitignore and README.md).
Other goodies
-------------
::
there are many other enhancements Elixir provides, such as support for variable rebinding, optional parentheses, implicit statement endings, nullability, short circuits operators, ...
`Introduction to Parallel Computing with Elixir - Reactive.IO`_
===============================================================
.. _Introduction to Parallel Computing with Elixir - Reactive.IO: http://www.reactive.io/tips/2015/02/03/introduction-to-parallel-computing-with-elixir/
Mixing Up a New Project
-----------------------
.. code-block:: bash
mix new fibex
/lib/fibex/fn.ex
~~~~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex.Fn do
def run(n) do
run(n, 1, 0)
end
defp run(0, _, _) do
0
end
defp run(1, a, b) do
a + b
end
defp run(n, a, b) do
run(n - 1, b, a + b)
end
end
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def run(ns) do
ns
|> Enum.map(&(Fibex.Fn.run(&1)))
|> inspect
|> IO.puts
end
end
.. code-block:: bash
$ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])"
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
Going Parallel
--------------
/lib/fibex/fn.ex
~~~~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex.Fn do
def spawn_run(pid, ni) do
spawn __MODULE__, :send_run, [pid, ni]
end
def send_run(pid, {n, i}) do
send pid, {run(n), i}
end
def run(n) do
run(n, 1, 0)
end
defp run(0, _, _) do
0
end
defp run(1, a, b) do
a + b
end
defp run(n, a, b) do
run(n - 1, b, a + b)
end
end
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def run(ns) do
ns
|> Enum.with_index
|> Enum.map fn(ni) ->
Fibex.Fn.spawn_run(self, ni)
end
receive_fibs(length(ns), [])
end
defp receive_fibs(lns, result) do
receive do
fib ->
result = [fib | result]
if lns == 1 do
IO.puts(print_fibs(result))
else
receive_fibs(lns - 1, result)
end
end
end
defp print_fibs(fibs) do
fibs
|> Enum.sort(fn({_, a}, {_, b}) -> a < b end)
|> Enum.map(fn({f, _}) -> f end)
|> inspect
end
end
.. code-block:: bash
$ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])"
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
Building our Escript
--------------------
/lib/fibex.ex
~~~~~~~~~~~~~
.. code-block:: elixir
defmodule Fibex do
def main(argv) do
argv |> Enum.map(&(String.to_integer(&1))) |> run
end
def run(ns) do
ns
|> Enum.with_index
|> Enum.map fn(ni) ->
Fibex.Fn.spawn_run(self, ni)
end
receive_fibs(length(ns), [])
end
defp receive_fibs(lns, result) do
receive do
fib ->
result = [fib | result]
if lns == 1 do
IO.puts(print_fibs(result))
else
receive_fibs(lns - 1, result)
end
end
end
defp print_fibs(fibs) do
fibs
|> Enum.sort(fn({_, a}, {_, b}) -> a < b end)
|> Enum.map(fn({f, _}) -> f end)
|> inspect
end
end
mix.exs
~~~~~~~
.. code-block:: elixir
defmodule Fibex.Mixfile do
use Mix.Project
def project do
[app: :fibex,
version: "0.0.1",
elixir: "~> 1.0",
escript: [main_module: Fibex],
deps: deps]
end
# Configuration for the OTP application
#
# Type `mix help compile.app` for more information
def application do
[applications: [:logger]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type `mix help deps` for more examples and options
defp deps do
[]
end
end
.. code-block:: bash
$ ./fibex 20 18 32 28 22 42 55 48
[6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976]
`The Oozou Blog - Why we are excited about Elixir`_
===================================================
.. _The Oozou Blog - Why we are excited about Elixir: http://blog.oozou.com/why-we-are-excited-about-elixir/
The platform
------------
::
Erlang is powering projects like Facebook Chat, WhatsApp, and Amazon SimpleDB, which demonstrates both the scalability and stability of the platform. It’s pretty exciting to imagine that Elixir may be able to provide many new developers with easier access to it.
Ruby-like syntax
----------------
::
He also added a certain symmetry that Ruby is lacking (e.g. do keywords for class and module definitions), which allowed for an easier implementation of Elixir’s macro system
::
Elixir offers hygienic macros. While it’s an old saying amongst Lispers that the first rule of macros is to not write macros, they do occasionally come in handy and add powerful meta-programming and DSL capabilities to the language.
Good tooling
------------
mix
~~~~
::
mix clean # Delete generated application files
mix cmd # Executes the given command
mix compile # Compile source files
mix deps # List dependencies and their status
mix deps.clean # Remove the given dependencies' files
mix deps.compile # Compile dependencies
mix deps.get # Get all out of date dependencies
mix deps.unlock # Unlock the given dependencies
mix deps.update # Update the given dependencies
mix new # Create a new Elixir project
mix run # Run the given file or expression
mix test # Run a project's tests
ExUnit
~~~~~~
doc tests
~~~~~~~~~
.. code-block:: elixir
defmodule Oozou do
@doc ~S"""
Adds two numbers
## Examples
iex> Oozou.add(2, 2)
4
"""
def add(a, b), do: a + b
end
.. code-block:: elixir
defmodule OozouTest do
use ExUnit.Case, async: true
doctest Oozou
end
Great documentation
-------------------
.. code-block:: elixir
defmodule Oozou do
@moduledoc """
We handcraft beautiful web apps
"""
@doc """
Be awesome!
"""
def work(), do: :beautiful_web_app
end
Now show me some code
---------------------
.. code-block:: elixir
defmodule FizzBuzz do
def compute(n) do
s = case {rem(n, 3), rem(n, 5)} do
{0, 0} -> :FizzBuzz
{0, _} -> :Fizz
{_, 0} -> :Buzz
_ -> n
end
IO.puts(s)
end
end
Enum.map(1..15, &FizzBuzz.compute/1)
# or as list comprehension:
# for i <- 1..15, do: FizzBuzz.compute(i)
`Lispy Elixir | 8th Light`_
===========================
.. _Lispy Elixir | 8th Light: http://blog.8thlight.com/patrick-gombert/2013/11/26/lispy-elixir.html
Homoiconicity
-------------
::
Elixir, on the surface, is not homoiconic. However, the syntax on the surface is just a facade for the homiconic structure underneath. To peer under the covers we're going to need explore one more of Lisp's ideas.
Quoting
-------
::
In Elixir, all expressions are represented as three element tuples. Let's look at a simple, straightforward example where we are simply adding two numbers.
.. code-block:: elixir
quote do
1 + 1
end # => {:+, [], [1, 1]}
Abstract Syntax Trees
---------------------
::
Abstract syntax trees are simply a way to represent call structures in a tree like fashion.
Macros
------
::
A macro takes quoted forms (abstract syntax trees) and is free to edit the tree as it chooses in order to do any number of interesting things.
Macros (Almost) All The Way Down
--------------------------------
::
def in Elixir is a macro. Upon further inspection we can see what def produces in terms of an abstract syntax tree.
Standing On The Shoulders Of Giants
-----------------------------------
::
Elixir's future looks bright and exciting in part because it's standing on the shoulders of giants.
`How I Start -- Elixir`_
========================
.. _How I Start -- Elixir: https://howistart.org/posts/elixir/1
Portal
------
Installation
------------
Our first project
-----------------
Pattern matching
----------------
Modeling portal doors with Agents
---------------------------------
Inspecting portals with Protocols
---------------------------------
Shooting supervised doors
-------------------------
Distributed transfers
---------------------
Wrapping up
-----------
`Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目`_
===============================================================================================================
.. _Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目: http://gihyo.jp/news/report/01/rubykaigi2013/0002
自己紹介
--------
どうして,いま,並行性(concurrency)なのか
-------------------------------------------
クラスのアクセサにおけるレースコンディション
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
様々な実装の存在するRuby - 実装による違い
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ほかの言語から学ぶこと - Rubyへの提案
-------------------------------------
Javaに目を向けてみる
~~~~~~~~~~~~~~~~~~~~
提案その1:Hash#concurrent_read, Hash#concurrent_write
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その2:AtomicReferenceの導入
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その3:Go言語の紹介と軽量で高機能な新しいQueueの採用
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
提案その4:さらに軽量な,並行プログラミングのための仕組みを組み込みで提供する
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
結論 - concurrentなRubyのための議論をしよう
-------------------------------------------
`Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳`_
================================================================================
.. _Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳: http://yohshiy.blog.fc2.com/blog-entry-235.html
Elixirとは
----------
特徴
----
Hello, world!
~~~~~~~~~~~~~
全てが式
~~~~~~~~
メタプログラミングと DSL
~~~~~~~~~~~~~~~~~~~~~~~~
プロトコル(文脈, 約束)による多様性
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ドキュメントもコードの一部
~~~~~~~~~~~~~~~~~~~~~~~~~~
パターンマッチング
~~~~~~~~~~~~~~~~~~
結局のところ Erlang
~~~~~~~~~~~~~~~~~~~
インストール
------------
使い方
------
対話モード
~~~~~~~~~~
コンパイル
~~~~~~~~~~
スクリプト
~~~~~~~~~~
Emacs モードの設定
------------------
感想
----
参考
----
`elixir はプログラマの万能薬になるか - Fat Old Sun`_
====================================================
.. _elixir はプログラマの万能薬になるか - Fat Old Sun: http://d.hatena.ne.jp/k-1/20120310/p1
特徴
----
::
ひとことでまとめると、erlangの並列/高信頼フレームワークが利用できるrubyライクの構文を持つlispといえる。
ビルド
------
Hello, world.
-------------
`Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp`_
===========================================================
.. _Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp: http://m.igrs.jp/blog/2012/03/12/why-rubyists-should-try-elixir/
パターンマッチング (Pattern matching)
-------------------------------------
単一代入変数と不変性 (Single assignment variables and immutability)
-------------------------------------------------------------------
プロセス間通信 (Communication between processes)
------------------------------------------------
異なるオブジェクトモデル (A different Object Model)
---------------------------------------------------
学ぶ (Just learn)
-----------------
結論 (Wrapping up)
------------------
`The Excitement of Elixir - Hacking Devin Torres`_
==================================================
.. _The Excitement of Elixir - Hacking Devin Torres: http://devintorr.es/blog/2013/01/22/the-excitement-of-elixir/
Syntax
------
::
Elixir syntax is like a marriage of DSL friendly Ruby and the powerful hygenic macros of Clojure.
Expressions
-----------
::
Elixir if expressions, like most everything else in the language, are implemented using a macro.
Strings
-------
::
Elixir strings are UTF8 binaries, with all the raw speed and memory savings that brings. Elixir has a String module with Unicode functionality built-in and is a great example of writing code that writes code. String.Unicode reads various Unicode database dumps such as UnicodeData.txt to dynamically generate Unicode functions for the String module built straight from that data!
Single assignment
-----------------
::
There is no context dependent expression separators and when you rebind a name all you’re doing is rebinding a new value to the name. Elixir is still immutable, it’s just not trying to pass off single assignment as immutability.
Records
-------
::
Elixir records are real records, and provide compile time pattern matching and a much more dynamic nature.
Standard library
----------------
::
While you can’t escape using the Erlang standard library from time to time, Elixir’s standard library is trying to normalize zero-based access and noun-first argument ordering, along with a more consistent API.
Code organization
-----------------
::
Elixir modules provide a great way to encapsulate functionality. As many modules as you desire can be declared within the same file including private functionality (functions, macros, records, exceptions, fuzzybunnies, whatever).
`Learn elixir in Y Minutes - Learn X in Y Minutes`_
===================================================
.. _Learn elixir in Y Minutes - Learn X in Y Minutes: http://learnxinyminutes.com/docs/elixir/
`Two days with Elixir - Neo | Ideas`_
=====================================
.. _Two days with Elixir - Neo | Ideas: http://www.neo.com/2013/08/27/two-days-with-elixir
The pipe operator |> is fantastic.
----------------------------------
The function capture notation & is cool as long as you keep the definitions short.
----------------------------------------------------------------------------------
Pattern matching makes recursive definitions easy
-------------------------------------------------
Guard clauses are nice but the syntax feels verbose
---------------------------------------------------
When a guard clauses prevents a function match, I feel like the error message you get could be more helpful
-----------------------------------------------------------------------------------------------------------
Elixir's functional nature means there is less syntactic sugar than I'm used to
-------------------------------------------------------------------------------
ExUnit feels pretty unfinished
------------------------------
Building concurrent, distributed, fault-tolerant systems is baked right in
--------------------------------------------------------------------------
Summing Up
----------
`Build and test a blazing fast JSON API with Phoenix, an Elixir framework`_
===========================================================================
.. _Build and test a blazing fast JSON API with Phoenix, an Elixir framework: https://robots.thoughtbot.com/testing-a-phoenix-elixir-json-api
Why Elixir and Phoenix?
-----------------------
Writing the test
----------------
Creating our databases
----------------------
Adding the Contact model
------------------------
Adding the routes and controller
--------------------------------
Rendering our JSON with a view
------------------------------
Cleanup
-------
That’s a wrap
--------------
`超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう`_
==========================================================================
.. _超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう: http://postd.cc/testing-a-phoenix-elixir-json-api/
なぜElixirとPhoenixなのか
-------------------------
テストを書く
------------
データベースを構築する
----------------------
連絡先モデルを追加する
----------------------
ルートとコントローラを追加する
------------------------------
viewでJSONをレンダリングする
----------------------------
クリーンアップ
--------------
まとめ
------
`Elixir - The next big language for the web`_
=============================================
.. _Elixir - The next big language for the web: http://www.creativedeletion.com/2015/04/19/elixir_next_language.html
From obscurity to the default choice
------------------------------------
Erlang
------
Elixir
------
Immutability and functional programming
---------------------------------------
Concurrency
-----------
Web framework
-------------
Programmer happiness and beautiful code
---------------------------------------
Déjà vu
---------
`Why I’m betting on Elixir — Medium`_
=====================================
.. _Why I’m betting on Elixir — Medium: https://medium.com/@kenmazaika/why-im-betting-on-elixir-7c8f847b58
Ruby Crushed It!
----------------
But every so often, artifacts of ruby’s humble beginnings arise
---------------------------------------------------------------
Run-away memory!
~~~~~~~~~~~~~~~~
Concurrency!
~~~~~~~~~~~~
Speed!
~~~~~~
Scala
~~~~~
The Elixir Ecosystem
--------------------
Package Management with Mix
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Erlang Virtual Machine
~~~~~~~~~~~~~~~~~~~~~~~~~~
The Phoenix Web Framework
~~~~~~~~~~~~~~~~~~~~~~~~~
Strong Leadership
~~~~~~~~~~~~~~~~~
Friends, the web is about to under-go a transformational change
---------------------------------------------------------------
`Unlimited Novelty -- Why I'm stopping work on Reia`_
=====================================================
.. _Unlimited Novelty -- Why I'm stopping work on Reia: http://www.unlimitednovelty.com/2011/06/why-im-stopping-work-on-reia.html
' + e.data + '
'); $line.appendTo('#chat').hide().fadeIn(200, function(){ $("html, body").animate({ scrollTop: $(document).height() }, "slow"); }) }, false); }); }); `Elixir is for programmers - Pluralsight blog`_ =============================================== .. _Elixir is for programmers - Pluralsight blog: http://blog.pluralsight.com/elixir-is-for-programmers Smart assert ------------ :: Elixir knows that == is being used in the assertion, and shows you the values on either side of == when the test fails. Now that’s a useful error! Multi-block control flow ------------------------ :: In Elixir, the relationship between single line functions and multi-line blocks is well thought out. These two are equivalent: .. code-block:: elixir # Single line if(condition, do: a, else: b) # Multiple lines if condition do a else b end :: In the single line version, if is a function that takes two arguments: the condition and the clauses. The clauses are do and else. Consistent use of do -------------------- :: Elixir is consistent. Need a module? It’s defmodule...do. Need an if? It also uses do. Same with def. Built-in TDD ------------ :: With Elixir, it’s built in. Use the mix command to generate a new app and you’re ready to go with a unit test. Run mix test to run the test suite. Done. :: And it can run your tests concurrently with a single async option. Mind-blowing metaprogramming: upcase ------------------------------------ .. code-block:: elixir def upcase("é" <> rest) do ["É"] ++ upcase(rest) end :: A few things are going on here. Elixir can match functions on the number, type, and content of its arguments. So it looks for a letter such as é. It knows the upper case version of the letter, then sends the rest of the string to the next letter’s upcase function. `Elixir Isn't Hipster - alexrp's blog`_ ======================================= .. _Elixir Isn't Hipster - alexrp's blog: http://blog.alexrp.com/2013/02/14/elixir-isnt-hipster/ Performance ----------- :: It uses the so-called ‘threaded code interpretation’ approach. This is one of the fastest possible ways to interpret bytecode as every instruction is a direct pointer to executable C code. :: the BEAM offers a full-blown native code compiler these days, called HiPE (High Performance Erlang). HiPE works in a similar fashion to software such as PyPy and IonMonkey with the exception that it compiles ahead-of-time (AOT) instead of just-in-time (JIT). Reliability ----------- * Linked processes * Coordinated restarts * Failover nodes * Hot code reloading Language Design --------------- * Expression syntax * Pattern matching * First-class functions * Closures * Records * Protocols * Metaprogramming * Unicode strings * Immutability * Variable rebinding * Erlang interop Functional Programming ---------------------- :: A general rule of thumb is that you should focus on the data flowing through your program rather than focusing on your program’s high-level behavior. :: once you stop thinking about objects and methods entirely, it becomes incredibly easy to solve real problems in functional languages. `The Erlangelist -- Why Elixir?`_ ================================= .. _The Erlangelist -- Why Elixir?: http://www.theerlangelist.com/2014/01/why-elixir.html The problems of Erlang the language ----------------------------------- :: The problem I have with Erlang is that the language is somehow too simple, making it very hard to eliminate some frequent cases of boilerplate and structural duplication. Consequently, the resulting code gets a bit messy, being harder to write, analyze, and modify. What Elixir is (not) -------------------- :: it is an Erlang-esque language with improved code organization capabilities. Metaprogramming --------------- :: Elixir macros are nothing like C/C++ macros. Instead of working on strings, they are something like compile-time Elixir functions that are called in the middle of parsing, and work on the abstract syntax tree (AST), which is a code represented as Elixir data structure. Macro can work on AST, and spit out some alternative AST that represents the generated code. Since macros are executed in compile-time, the performance of a running system will not be affected. Pipeline operator ----------------- :: The code can easily be followed by reading it from top to bottom. :: The pipeline operator works extremely well because the API in Elixir libraries follows the "subject (noun) as the first argument" convention. Polymorphism via protocols -------------------------- :: Protocols allow developers to create a generic logic that can be used with any type of data, assuming that some contract is implemented for the given data. The mix tool ------------ :: With a single command line you can create an OTP application skeleton, that consists of only 7 files (this includes .gitignore and README.md). Other goodies ------------- :: there are many other enhancements Elixir provides, such as support for variable rebinding, optional parentheses, implicit statement endings, nullability, short circuits operators, ... `Introduction to Parallel Computing with Elixir - Reactive.IO`_ =============================================================== .. _Introduction to Parallel Computing with Elixir - Reactive.IO: http://www.reactive.io/tips/2015/02/03/introduction-to-parallel-computing-with-elixir/ Mixing Up a New Project ----------------------- .. code-block:: bash mix new fibex /lib/fibex/fn.ex ~~~~~~~~~~~~~~~~ .. code-block:: elixir defmodule Fibex.Fn do def run(n) do run(n, 1, 0) end defp run(0, _, _) do 0 end defp run(1, a, b) do a + b end defp run(n, a, b) do run(n - 1, b, a + b) end end /lib/fibex.ex ~~~~~~~~~~~~~ .. code-block:: elixir defmodule Fibex do def run(ns) do ns |> Enum.map(&(Fibex.Fn.run(&1))) |> inspect |> IO.puts end end .. code-block:: bash $ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])" [6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976] Going Parallel -------------- /lib/fibex/fn.ex ~~~~~~~~~~~~~~~~ .. code-block:: elixir defmodule Fibex.Fn do def spawn_run(pid, ni) do spawn __MODULE__, :send_run, [pid, ni] end def send_run(pid, {n, i}) do send pid, {run(n), i} end def run(n) do run(n, 1, 0) end defp run(0, _, _) do 0 end defp run(1, a, b) do a + b end defp run(n, a, b) do run(n - 1, b, a + b) end end /lib/fibex.ex ~~~~~~~~~~~~~ .. code-block:: elixir defmodule Fibex do def run(ns) do ns |> Enum.with_index |> Enum.map fn(ni) -> Fibex.Fn.spawn_run(self, ni) end receive_fibs(length(ns), []) end defp receive_fibs(lns, result) do receive do fib -> result = [fib | result] if lns == 1 do IO.puts(print_fibs(result)) else receive_fibs(lns - 1, result) end end end defp print_fibs(fibs) do fibs |> Enum.sort(fn({_, a}, {_, b}) -> a < b end) |> Enum.map(fn({f, _}) -> f end) |> inspect end end .. code-block:: bash $ mix run -e "Fibex.run([20, 18, 32, 28, 22, 42, 55, 48])" [6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976] Building our Escript -------------------- /lib/fibex.ex ~~~~~~~~~~~~~ .. code-block:: elixir defmodule Fibex do def main(argv) do argv |> Enum.map(&(String.to_integer(&1))) |> run end def run(ns) do ns |> Enum.with_index |> Enum.map fn(ni) -> Fibex.Fn.spawn_run(self, ni) end receive_fibs(length(ns), []) end defp receive_fibs(lns, result) do receive do fib -> result = [fib | result] if lns == 1 do IO.puts(print_fibs(result)) else receive_fibs(lns - 1, result) end end end defp print_fibs(fibs) do fibs |> Enum.sort(fn({_, a}, {_, b}) -> a < b end) |> Enum.map(fn({f, _}) -> f end) |> inspect end end mix.exs ~~~~~~~ .. code-block:: elixir defmodule Fibex.Mixfile do use Mix.Project def project do [app: :fibex, version: "0.0.1", elixir: "~> 1.0", escript: [main_module: Fibex], deps: deps] end # Configuration for the OTP application # # Type `mix help compile.app` for more information def application do [applications: [:logger]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type `mix help deps` for more examples and options defp deps do [] end end .. code-block:: bash $ ./fibex 20 18 32 28 22 42 55 48 [6765, 2584, 2178309, 317811, 17711, 267914296, 139583862445, 4807526976] `The Oozou Blog - Why we are excited about Elixir`_ =================================================== .. _The Oozou Blog - Why we are excited about Elixir: http://blog.oozou.com/why-we-are-excited-about-elixir/ The platform ------------ :: Erlang is powering projects like Facebook Chat, WhatsApp, and Amazon SimpleDB, which demonstrates both the scalability and stability of the platform. It’s pretty exciting to imagine that Elixir may be able to provide many new developers with easier access to it. Ruby-like syntax ---------------- :: He also added a certain symmetry that Ruby is lacking (e.g. do keywords for class and module definitions), which allowed for an easier implementation of Elixir’s macro system :: Elixir offers hygienic macros. While it’s an old saying amongst Lispers that the first rule of macros is to not write macros, they do occasionally come in handy and add powerful meta-programming and DSL capabilities to the language. Good tooling ------------ mix ~~~~ :: mix clean # Delete generated application files mix cmd # Executes the given command mix compile # Compile source files mix deps # List dependencies and their status mix deps.clean # Remove the given dependencies' files mix deps.compile # Compile dependencies mix deps.get # Get all out of date dependencies mix deps.unlock # Unlock the given dependencies mix deps.update # Update the given dependencies mix new # Create a new Elixir project mix run # Run the given file or expression mix test # Run a project's tests ExUnit ~~~~~~ doc tests ~~~~~~~~~ .. code-block:: elixir defmodule Oozou do @doc ~S""" Adds two numbers ## Examples iex> Oozou.add(2, 2) 4 """ def add(a, b), do: a + b end .. code-block:: elixir defmodule OozouTest do use ExUnit.Case, async: true doctest Oozou end Great documentation ------------------- .. code-block:: elixir defmodule Oozou do @moduledoc """ We handcraft beautiful web apps """ @doc """ Be awesome! """ def work(), do: :beautiful_web_app end Now show me some code --------------------- .. code-block:: elixir defmodule FizzBuzz do def compute(n) do s = case {rem(n, 3), rem(n, 5)} do {0, 0} -> :FizzBuzz {0, _} -> :Fizz {_, 0} -> :Buzz _ -> n end IO.puts(s) end end Enum.map(1..15, &FizzBuzz.compute/1) # or as list comprehension: # for i <- 1..15, do: FizzBuzz.compute(i) `Lispy Elixir | 8th Light`_ =========================== .. _Lispy Elixir | 8th Light: http://blog.8thlight.com/patrick-gombert/2013/11/26/lispy-elixir.html Homoiconicity ------------- :: Elixir, on the surface, is not homoiconic. However, the syntax on the surface is just a facade for the homiconic structure underneath. To peer under the covers we're going to need explore one more of Lisp's ideas. Quoting ------- :: In Elixir, all expressions are represented as three element tuples. Let's look at a simple, straightforward example where we are simply adding two numbers. .. code-block:: elixir quote do 1 + 1 end # => {:+, [], [1, 1]} Abstract Syntax Trees --------------------- :: Abstract syntax trees are simply a way to represent call structures in a tree like fashion. Macros ------ :: A macro takes quoted forms (abstract syntax trees) and is free to edit the tree as it chooses in order to do any number of interesting things. Macros (Almost) All The Way Down -------------------------------- :: def in Elixir is a macro. Upon further inspection we can see what def produces in terms of an abstract syntax tree. Standing On The Shoulders Of Giants ----------------------------------- :: Elixir's future looks bright and exciting in part because it's standing on the shoulders of giants. `How I Start -- Elixir`_ ======================== .. _How I Start -- Elixir: https://howistart.org/posts/elixir/1 Portal ------ Installation ------------ Our first project ----------------- Pattern matching ---------------- Modeling portal doors with Agents --------------------------------- Inspecting portals with Protocols --------------------------------- Shooting supervised doors ------------------------- Distributed transfers --------------------- Wrapping up ----------- `Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目`_ =============================================================================================================== .. _Jose Valim,Rubyにおける並行プログラミングのためのいくつかのアイデアを提案。~ RubyKaigi 2013 基調講演 2日目: http://gihyo.jp/news/report/01/rubykaigi2013/0002 自己紹介 -------- どうして,いま,並行性(concurrency)なのか ------------------------------------------- クラスのアクセサにおけるレースコンディション ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 様々な実装の存在するRuby - 実装による違い ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ほかの言語から学ぶこと - Rubyへの提案 ------------------------------------- Javaに目を向けてみる ~~~~~~~~~~~~~~~~~~~~ 提案その1:Hash#concurrent_read, Hash#concurrent_write ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 提案その2:AtomicReferenceの導入 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 提案その3:Go言語の紹介と軽量で高機能な新しいQueueの採用 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 提案その4:さらに軽量な,並行プログラミングのための仕組みを組み込みで提供する ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 結論 - concurrentなRubyのための議論をしよう ------------------------------------------- `Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳`_ ================================================================================ .. _Elixir : Erlang VM 上で動作する Ruby 風味の関数型言語 - プログラマーズ雑記帳: http://yohshiy.blog.fc2.com/blog-entry-235.html Elixirとは ---------- 特徴 ---- Hello, world! ~~~~~~~~~~~~~ 全てが式 ~~~~~~~~ メタプログラミングと DSL ~~~~~~~~~~~~~~~~~~~~~~~~ プロトコル(文脈, 約束)による多様性 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ドキュメントもコードの一部 ~~~~~~~~~~~~~~~~~~~~~~~~~~ パターンマッチング ~~~~~~~~~~~~~~~~~~ 結局のところ Erlang ~~~~~~~~~~~~~~~~~~~ インストール ------------ 使い方 ------ 対話モード ~~~~~~~~~~ コンパイル ~~~~~~~~~~ スクリプト ~~~~~~~~~~ Emacs モードの設定 ------------------ 感想 ---- 参考 ---- `elixir はプログラマの万能薬になるか - Fat Old Sun`_ ==================================================== .. _elixir はプログラマの万能薬になるか - Fat Old Sun: http://d.hatena.ne.jp/k-1/20120310/p1 特徴 ---- :: ひとことでまとめると、erlangの並列/高信頼フレームワークが利用できるrubyライクの構文を持つlispといえる。 ビルド ------ Hello, world. ------------- `Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp`_ =========================================================== .. _Rubyist が今すぐ Elixir を使ってみるべき理由 - m.igrs.jp: http://m.igrs.jp/blog/2012/03/12/why-rubyists-should-try-elixir/ パターンマッチング (Pattern matching) ------------------------------------- 単一代入変数と不変性 (Single assignment variables and immutability) ------------------------------------------------------------------- プロセス間通信 (Communication between processes) ------------------------------------------------ 異なるオブジェクトモデル (A different Object Model) --------------------------------------------------- 学ぶ (Just learn) ----------------- 結論 (Wrapping up) ------------------ `The Excitement of Elixir - Hacking Devin Torres`_ ================================================== .. _The Excitement of Elixir - Hacking Devin Torres: http://devintorr.es/blog/2013/01/22/the-excitement-of-elixir/ Syntax ------ :: Elixir syntax is like a marriage of DSL friendly Ruby and the powerful hygenic macros of Clojure. Expressions ----------- :: Elixir if expressions, like most everything else in the language, are implemented using a macro. Strings ------- :: Elixir strings are UTF8 binaries, with all the raw speed and memory savings that brings. Elixir has a String module with Unicode functionality built-in and is a great example of writing code that writes code. String.Unicode reads various Unicode database dumps such as UnicodeData.txt to dynamically generate Unicode functions for the String module built straight from that data! Single assignment ----------------- :: There is no context dependent expression separators and when you rebind a name all you’re doing is rebinding a new value to the name. Elixir is still immutable, it’s just not trying to pass off single assignment as immutability. Records ------- :: Elixir records are real records, and provide compile time pattern matching and a much more dynamic nature. Standard library ---------------- :: While you can’t escape using the Erlang standard library from time to time, Elixir’s standard library is trying to normalize zero-based access and noun-first argument ordering, along with a more consistent API. Code organization ----------------- :: Elixir modules provide a great way to encapsulate functionality. As many modules as you desire can be declared within the same file including private functionality (functions, macros, records, exceptions, fuzzybunnies, whatever). `Learn elixir in Y Minutes - Learn X in Y Minutes`_ =================================================== .. _Learn elixir in Y Minutes - Learn X in Y Minutes: http://learnxinyminutes.com/docs/elixir/ `Two days with Elixir - Neo | Ideas`_ ===================================== .. _Two days with Elixir - Neo | Ideas: http://www.neo.com/2013/08/27/two-days-with-elixir The pipe operator |> is fantastic. ---------------------------------- The function capture notation & is cool as long as you keep the definitions short. ---------------------------------------------------------------------------------- Pattern matching makes recursive definitions easy ------------------------------------------------- Guard clauses are nice but the syntax feels verbose --------------------------------------------------- When a guard clauses prevents a function match, I feel like the error message you get could be more helpful ----------------------------------------------------------------------------------------------------------- Elixir's functional nature means there is less syntactic sugar than I'm used to ------------------------------------------------------------------------------- ExUnit feels pretty unfinished ------------------------------ Building concurrent, distributed, fault-tolerant systems is baked right in -------------------------------------------------------------------------- Summing Up ---------- `Build and test a blazing fast JSON API with Phoenix, an Elixir framework`_ =========================================================================== .. _Build and test a blazing fast JSON API with Phoenix, an Elixir framework: https://robots.thoughtbot.com/testing-a-phoenix-elixir-json-api Why Elixir and Phoenix? ----------------------- Writing the test ---------------- Creating our databases ---------------------- Adding the Contact model ------------------------ Adding the routes and controller -------------------------------- Rendering our JSON with a view ------------------------------ Cleanup ------- That’s a wrap -------------- `超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう`_ ========================================================================== .. _超高速なJSON APIをElixirフレームワークのPhoenixでビルドしてテストしよう: http://postd.cc/testing-a-phoenix-elixir-json-api/ なぜElixirとPhoenixなのか ------------------------- テストを書く ------------ データベースを構築する ---------------------- 連絡先モデルを追加する ---------------------- ルートとコントローラを追加する ------------------------------ viewでJSONをレンダリングする ---------------------------- クリーンアップ -------------- まとめ ------ `Elixir - The next big language for the web`_ ============================================= .. _Elixir - The next big language for the web: http://www.creativedeletion.com/2015/04/19/elixir_next_language.html From obscurity to the default choice ------------------------------------ Erlang ------ Elixir ------ Immutability and functional programming --------------------------------------- Concurrency ----------- Web framework ------------- Programmer happiness and beautiful code --------------------------------------- Déjà vu --------- `Why I’m betting on Elixir — Medium`_ ===================================== .. _Why I’m betting on Elixir — Medium: https://medium.com/@kenmazaika/why-im-betting-on-elixir-7c8f847b58 Ruby Crushed It! ---------------- But every so often, artifacts of ruby’s humble beginnings arise --------------------------------------------------------------- Run-away memory! ~~~~~~~~~~~~~~~~ Concurrency! ~~~~~~~~~~~~ Speed! ~~~~~~ Scala ~~~~~ The Elixir Ecosystem -------------------- Package Management with Mix ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The Erlang Virtual Machine ~~~~~~~~~~~~~~~~~~~~~~~~~~ The Phoenix Web Framework ~~~~~~~~~~~~~~~~~~~~~~~~~ Strong Leadership ~~~~~~~~~~~~~~~~~ Friends, the web is about to under-go a transformational change --------------------------------------------------------------- `Unlimited Novelty -- Why I'm stopping work on Reia`_ ===================================================== .. _Unlimited Novelty -- Why I'm stopping work on Reia: http://www.unlimitednovelty.com/2011/06/why-im-stopping-work-on-reia.html