Elixir

本頁使用了標題或全文手工轉換
維基百科,自由的百科全書
Elixir
編程範型多範式函數式並列式面向行程同像性
面市時間2012年,​12年前​(2012
目前版本
  • 1.16.2 (2024年3月10日;穩定版本)[1]
編輯維基數據鏈結
型態系統動態型別強型別
許可證Apache License
副檔名.ex、.exs
網站elixir-lang.org
啟發語言
ClojureErlangRuby

Elixir是一個基於Erlang虛擬機器函數式、面向並列的通用程式語言。Elixir以Erlang為基礎,支援分散式、高容錯、即時應用程式的開發,亦可通過巨集實現元程式設計對其進行擴充,並通過協定支援多型[2]

歷史[編輯]

José Valim是Elixir語言的設計者。他創造該語言的目標是在維持與現有Erlang工具鏈及生態環境相容性的同時,讓人們可以在Erlang虛擬機器上進行擴充性更好的、高生產率的開發。[3]

特性[編輯]

範例[編輯]

以下範例可以在iex shell中執行或儲存在檔案中,並通過命令列鍵入命令執行 elixir <filename>.

經典的 Hello world 例子:

iex> IO.puts("Hello World!")
Hello World!

Enumerable 推導

iex> for n <- [1,2,3,4,5], rem(n, 2) == 1, do: n*n
[1, 9, 25]

模式匹配(解構)

iex> [1, a] = [1, 2]
iex> a
2

iex> {:ok, [hello: a]} = {:ok, [hello: "world"]}
iex> a
"world"

模式匹配(多子句)

iex> case File.read("path/to/file") do
iex>   {:ok, contents} -> IO.puts("found file: #{contents}")
iex>   {:error, reason} -> IO.puts("missing file: #{reason}")
iex> end

管道運算子

iex> "1" |> String.to_integer() |> Kernel.*(2)
2

模組

defmodule Fun do
  def fib(0), do: 0
  def fib(1), do: 1
  def fib(n), do: fib(n-2) + fib(n-1)  
end

順序產生1000個行程

for num <- 1..1000, do: spawn fn -> IO.puts("#{num * 2}") end

執行非同步任務

task = Task.async fn -> perform_complex_action() end
other_time_consuming_action()
Task.await task

參考資料[編輯]

  1. ^ 1.0 1.1 Release 1.16.2. 2024年3月10日 [2024年3月22日]. 
  2. ^ Elixir. José Valim. [2013-02-17]. (原始內容存檔於2017-09-30). 
  3. ^ Elixir - A modern approach to programming for the Erlang VM. [2013-02-17]. (原始內容存檔於2012-11-29). 

外部連結[編輯]