Skip to main content

Long post to test postprocessing

Elixir (programming language)

Appearance

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

(Opens in a new window)

This article relies excessively on references (Opens in a new window) to primary sources (Opens in a new window). Please improve this article by adding secondary or tertiary sources (Opens in a new window).
Find sources: "Elixir" programming language (Opens in a new window) – news (Opens in a new window) · newspapers (Opens in a new window) · books (Opens in a new window) · scholar (Opens in a new window) · JSTOR (Opens in a new window) (June 2023) (Learn how and when to remove this message (Opens in a new window))

Elixir

elixir programming language (Opens in a new window)

Elixir

Paradigms (Opens in a new window)multi-paradigm (Opens in a new window): functional (Opens in a new window), concurrent (Opens in a new window), distributed (Opens in a new window), process-oriented (Opens in a new window)Designed by (Opens in a new window)José ValimFirst appeared2012; 13 years agoStable release (Opens in a new window)

1.18.4[1] (Opens in a new window) 

Edit this on Wikidata (Opens in a new window)

/ 21 May 2025; 4 days ago

Typing disciplinedynamic (Opens in a new window), strong (Opens in a new window)Platform (Opens in a new window)Erlang (Opens in a new window)License (Opens in a new window)Apache License 2.0 (Opens in a new window)[2] (Opens in a new window)Filename extensions (Opens in a new window).ex, .exsWebsiteelixir-lang.org (Opens in a new window)Influenced byClojure (Opens in a new window), Erlang (Opens in a new window), Ruby (Opens in a new window)InfluencedGleam (Opens in a new window), LFE (Opens in a new window)

Elixir is a functional (Opens in a new window), concurrent (Opens in a new window), high-level (Opens in a new window) general-purpose (Opens in a new window) programming language (Opens in a new window) that runs on the BEAM (Opens in a new window) virtual machine (Opens in a new window), which is also used to implement the Erlang (Opens in a new window) programming language.[3] (Opens in a new window) Elixir builds on top of Erlang and shares the same abstractions for building distributed (Opens in a new window), fault-tolerant (Opens in a new window) applications. Elixir also provides tooling and an extensible (Opens in a new window) design. The latter is supported by compile-time metaprogramming (Opens in a new window) with macros (Opens in a new window) and polymorphism (Opens in a new window) via protocols.[4] (Opens in a new window)

The community organizes yearly events in the United States,[5] (Opens in a new window) Europe,[6] (Opens in a new window) and Japan,[7] (Opens in a new window) as well as minor local events and conferences.[8] (Opens in a new window)[9] (Opens in a new window)

History

José Valim created the Elixir programming language as a research and development (Opens in a new window) project at Plataformatec. His goals were to enable higher extensibility and productivity in the Erlang VM while maintaining compatibility with Erlang's ecosystem.[10] (Opens in a new window)[11] (Opens in a new window)

Elixir is aimed at large-scale sites and apps. It uses features of Ruby (Opens in a new window), Erlang, and Clojure (Opens in a new window) to develop a high-concurrency and low-latency language. It was designed to handle large data volumes. Elixir is also used in telecommunications, e-commerce, and finance.[12] (Opens in a new window)

In 2021, the Numerical Elixir effort was announced with the goal of bringing machine learning, neural networks, GPU compilation, data processing, and computational notebooks to the Elixir ecosystem.[13] (Opens in a new window)

Versioning

Each of the minor versions supports a specific range of Erlang/OTP (Opens in a new window) versions.[14] (Opens in a new window) The current stable release version is 1.18.4[1] (Opens in a new window) .

Features

Examples

The following examples can be run in an iex shell (Opens in a new window) or saved in a file and run from the command line (Opens in a new window) by typing elixir <filename>.

Classic Hello world (Opens in a new window) example:

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

Pipe operator:

iex> "Elixir" |> String.graphemes() |> Enum.frequencies()
%{"E" => 1, "i" => 2, "l" => 1, "r" => 1, "x" => 1}

iex> %{values: 1..5} |> Map.get(:values) |> Enum.map(& &1 * 2)
[2, 4, 6, 8, 10]

iex> %{values: 1..5} |> Map.get(:values) |> Enum.map(& &1 * 2) |> Enum.sum()
30

Pattern matching (Opens in a new window) (a.k.a. destructuring):

iex> %{left: x} = %{left: 5, right: 8}
iex> x
5

iex> {:ok, [_ | rest]} = {:ok, [1, 2, 3]}
iex> rest
[2, 3]

Pattern matching with multiple clauses:

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

List comprehension (Opens in a new window):

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

Asynchronously reading files with streams:

1..5
|> Task.async_stream(&File.read!("#{&1}.txt"))
|> Stream.filter(fn {:ok, contents} -> String.trim(contents) != "" end)
|> Enum.join("\n")

Multiple function bodies with guards (Opens in a new window):

def fib(n) when n in [0, 1], do: n
def fib(n), do: fib(n-2) + fib(n-1)

Relational databases with the Ecto library:

schema "weather" do
  field :city     # Defaults to type :string
  field :temp_lo, :integer
  field :temp_hi, :integer
  field :prcp,    :float, default: 0.0
end

Weather |> where(city: "Kraków") |> order_by(:temp_lo) |> limit(10) |> Repo.all

Sequentially spawning a thousand processes:

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

Asynchronously (Opens in a new window) performing a task:

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

[citation needed (Opens in a new window)]

See also

References

  1. Wlaschin, Scott (May 2013). "Railway Oriented Programming" (Opens in a new window). F# for Fun and Profit. Archived (Opens in a new window) from the original on 30 January 2021. Retrieved 28 February 2021.

Further reading

Programming languages (Opens in a new window)

Authority control databases (Opens in a new window): National

Edit this at Wikidata (Opens in a new window)

Categories (Opens in a new window):

Elm (programming language)

Tools

Appearance

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

(Opens in a new window)

This article relies excessively on references (Opens in a new window) to primary sources (Opens in a new window). Please improve this article by adding secondary or tertiary sources (Opens in a new window).
Find sources: "Elm" programming language (Opens in a new window) – news (Opens in a new window) · newspapers (Opens in a new window) · books (Opens in a new window) · scholar (Opens in a new window) · JSTOR (Opens in a new window) (May 2019) (Learn how and when to remove this message (Opens in a new window))

Elm

(Opens in a new window)

The Elm tangram

Paradigm (Opens in a new window)functional (Opens in a new window)FamilyHaskell (Opens in a new window)Designed by (Opens in a new window)Evan CzaplickiFirst appearedMarch 30, 2012; 13 years ago[1] (Opens in a new window)Stable release (Opens in a new window)

0.19.1 / October 21, 2019; 5 years ago[2] (Opens in a new window)

Typing discipline (Opens in a new window)static (Opens in a new window), strong (Opens in a new window), inferred (Opens in a new window)Platform (Opens in a new window)x86-64 (Opens in a new window)OS (Opens in a new window)macOS (Opens in a new window), Windows (Opens in a new window)License (Opens in a new window)Permissive (Opens in a new window) (Revised BSD (Opens in a new window))[3] (Opens in a new window)Filename extensions (Opens in a new window).elmWebsiteelm-lang.org (Opens in a new window)

Edit this at Wikidata (Opens in a new window)

Influenced byHaskell (Opens in a new window), Standard ML (Opens in a new window), OCaml (Opens in a new window), F# (Opens in a new window)InfluencedRedux (Opens in a new window),[4] (Opens in a new window) Rust (Opens in a new window),[5] (Opens in a new window) Vue (Opens in a new window),[6] (Opens in a new window) Roc,[7] (Opens in a new window) Derw,[8] (Opens in a new window) Gren[9] (Opens in a new window)

Elm is a domain-specific (Opens in a new window) programming language (Opens in a new window) for declaratively (Opens in a new window) creating web browser (Opens in a new window)-based graphical user interfaces (Opens in a new window). Elm is purely functional (Opens in a new window), and is developed with emphasis on usability (Opens in a new window), performance, and robustness (Opens in a new window). It advertises "no runtime (Opens in a new window) exceptions (Opens in a new window) in practice",[10] (Opens in a new window) made possible by the Elm compiler's static type checking (Opens in a new window).

History

Elm was initially designed by Evan Czaplicki as his thesis in 2012.[11] (Opens in a new window) The first release of Elm came with many examples and an online editor that made it easy to try out in a web browser (Opens in a new window).[12] (Opens in a new window) Czaplicki joined Prezi (Opens in a new window) in 2013 to work on Elm,[13] (Opens in a new window) and in 2016 moved to NoRedInk (Opens in a new window) as an Open Source Engineer, also starting the Elm Software Foundation.[14] (Opens in a new window)

The initial implementation of the Elm compiler targets HyperText Markup Language (HTML (Opens in a new window)), Cascading Style Sheets (Opens in a new window) (CSS), and JavaScript (Opens in a new window).[15] (Opens in a new window) The set of core tools has continued to expand, now including a read–eval–print loop (Opens in a new window) (REPL),[16] (Opens in a new window) package manager (Opens in a new window),[17] (Opens in a new window) time-travelling debugger,[18] (Opens in a new window) and installers for macOS (Opens in a new window) and Windows (Opens in a new window).[19] (Opens in a new window) Elm also has an ecosystem of community created libraries (Opens in a new window),[20] (Opens in a new window) and Ellie, an advanced online editor that allows saved work and including community libraries.[21] (Opens in a new window)

Features

Elm has a small set of language constructs, including traditional if-expressions, let-expressions for storing local values, and case-expressions for pattern matching (Opens in a new window).[22] (Opens in a new window) As a functional language, it supports anonymous functions (Opens in a new window), functions as arguments, and functions can return functions, the latter often by partial application of curried (Opens in a new window) functions. Functions are called by value. Its semantics include immutable values, stateless functions (Opens in a new window), and static typing with type inference. Elm programs render HTML through a virtual DOM, and may interoperate with other code by using "JavaScript as a service".

Immutability

All values in Elm are immutable (Opens in a new window), meaning that a value cannot be modified after it is created. Elm uses persistent data structures (Opens in a new window) to implement its arrays, sets, and dictionaries in the standard library.[23] (Opens in a new window)

Static types

Elm is statically typed. Type annotations are optional (due to type inference) but strongly encouraged. Annotations exist on the line above the definition (unlike C-family languages where types and names are interspersed). Elm uses a single colon to mean "has type".

Types include primitives like integers and strings, and basic data structures such as lists, tuples, and records. Functions have types written with arrows, for example round : Float -> Int. Custom types (Opens in a new window) allow the programmer to create custom types to represent data in a way that matches the problem domain.[24] (Opens in a new window)

Types can refer to other types, for example a List Int. Types are always capitalized; lowercase names are type variables. For example, a List a is a list of values of unknown type. It is the type of the empty list and of the argument to List.length, which is agnostic to the list's elements. There are a few special types that programmers create to interact with the Elm runtime. For example, Html Msg represents a (virtual) DOM tree whose event handlers all produce messages of type Msg.

Rather than allow any value to be implicitly nullable (such as JavaScript's undefined or a null pointer (Opens in a new window)), Elm's standard library defines a Maybe a type. Code that produces or handles an optional value does so explicitly using this type, and all other code is guaranteed a value of the claimed type is actually present.

Elm provides a limited number of built-in type classes (Opens in a new window): number which includes Int and Float to facilitate the use of numeric operators such as (+) or (*), comparable which includes numbers, characters, strings, lists of comparable things, and tuples of comparable things to facilitate the use of comparison operators, and appendable which includes strings and lists to facilitate concatenation with (++). Elm does not provide a mechanism to include custom types into these type classes or create new type classes (see Limits (Opens in a new window)).

Module system

Elm has a module system (Opens in a new window) that allows users to break their code into smaller parts called modules. Modules can hide implementation details such as helper functions, and group related code together. Modules serve as a namespace for imported code, such as Bitwise.and. Third party libraries (or packages) consist of one or more modules, and are available from the Elm Public Library (Opens in a new window). All libraries are versioned according to semver (Opens in a new window), which is enforced by the compiler and other tools. That is, removing a function or changing its type can only be done in a major release.

Interoperability with HTML, CSS, and JavaScript

Elm uses an abstraction called ports to communicate with JavaScript (Opens in a new window).[25] (Opens in a new window) It allows values to flow in and out of Elm programs, making it possible to communicate between Elm and JavaScript.

Elm has a library called elm/html that a programmer can use to write HTML and CSS within Elm.[26] (Opens in a new window) It uses a virtual DOM (Opens in a new window) approach to make updates efficient.[27] (Opens in a new window)

Backend

Elm does not officially support server-side development. Czaplicki does consider it a primary goal at this point, but public progress on this front has been slow. Nevertheless, there are several independent projects which attempt to explore Elm on the backend.

The primary production-ready full-stack Elm platform is Lamdera, an open-core "unfork" of Elm.[28] (Opens in a new window)[29] (Opens in a new window)[30] (Opens in a new window) Czaplicki has also teased Elm Studio, a potential alternative to Lamdera, but it isn't available to the public yet.[31] (Opens in a new window) Current speculation is that Elm Studio will use a future version of Elm that targets C, uses Emscripten to compile to WASM, and supports type-safe Postgres (Opens in a new window) table generation.[32] (Opens in a new window)[33] (Opens in a new window)

For full-stack frameworks, as opposed to BaaS (Opens in a new window) products, elm-pages is perhaps the most popular fully open-source option.[34] (Opens in a new window) It does not extend the Elm language, but just runs the compiled JS on Node.js (Opens in a new window). It also supports scripting. There is also Pine, an Elm to .NET compiler, which allows safe interop with C#, F#, and other CLR (Opens in a new window) languages.[35] (Opens in a new window)

There were also some attempts in Elm versions prior to 0.19.0 to use the BEAM (Erlang virtual machine) (Opens in a new window) to run Elm, but they are stuck due to the removal of native code in 0.19.0 and changes to the package manager. One of the projects executed Elm directly on the environment,[36] (Opens in a new window) while another one compiled it to Elixir.[37] (Opens in a new window)

Finally, the Gren programming language started out a fork of Elm primarily focused on backend support, although its goals have since shifted.

The Elm Architecture (TEA pattern)

The Elm Architecture is a software design pattern (Opens in a new window) and as a TLA (Opens in a new window) called TEA pattern for building interactive web applications. Elm applications are naturally constructed in that way, but other projects may find the concept useful.

An Elm program is always split into three parts:

  • Model - the state of the application

  • View - a function that turns the model into HTML

  • Update - a function that updates the model based on messages

Those are the core of the Elm Architecture.

For example, imagine an application that displays a number and a button that increments the number when pressed.[38] (Opens in a new window) In this case, all we need to store is one number, so our model can be as simple as type alias Model = Int. The view function would be defined with the Html library and display the number and button. For the number to be updated, we need to be able to send a message to the update function, which is done through a custom type such as type Msg = Increase. The Increase value is attached to the button defined in the view function such that when the button is clicked by a user, Increase is passed on to the update function, which can update the model by increasing the number.

In the Elm Architecture, sending messages to update is the only way to change the state. In more sophisticated applications, messages may come from various sources: user interaction, initialization of the model, internal calls from update, subscriptions to external events (window resize, system clock, JavaScript interop...) and URL changes and requests.

Limits

Elm does not support higher-kinded polymorphism (Opens in a new window),[39] (Opens in a new window) which related languages Haskell (Opens in a new window), Scala (Opens in a new window) and PureScript (Opens in a new window) offer, nor does Elm support the creation of type classes (Opens in a new window).

This means that, for example, Elm does not have a generic map function which works across multiple data structures such as List and Set. In Elm, such functions are typically invoked qualified by their module name, for example calling List.map and Set.map. In Haskell or PureScript, there would be only one function map. This is a known feature request that is on Czaplicki's rough roadmap since at least 2015.[40] (Opens in a new window) On the other hand, implementations of TEA pattern in advanced languages like Scala (Opens in a new window) does not suffer from such limitations and can benefit from Scala (Opens in a new window)'s type classes, type-level (Opens in a new window) and kind-level (Opens in a new window) programming constructs.[41] (Opens in a new window)

Another outcome is a large amount of boilerplate code (Opens in a new window) in medium to large size projects as illustrated by the author of "Elm in Action," a former Elm core team member, in his single page application example[42] (Opens in a new window) with almost identical fragments being repeated in update, view, subscriptions, route parsing and building functions.

Example code

-- This is a single line comment.

{-
This is a multi-line comment.
It is {- nestable. -}
-}

-- Here we define a value named `greeting`. The type is inferred as a `String`.
greeting =
    "Hello World!"

-- It is best to add type annotations to top-level declarations.
hello : String
hello =
    "Hi there."

-- Functions are declared the same way, with arguments following the function name.
add x y =
    x + y

-- Again, it is best to add type annotations.
hypotenuse : Float -> Float -> Float
hypotenuse a b =
    sqrt (a^2 + b^2)

-- We can create lambda functions with the `\[arg] -> [expression]` syntax.
hello : String -> String
hello = \s -> "Hi, " ++ s

-- Function declarations may have the anonymous parameter names denoted by `_`, 
-- which are matched but not used in the body. 
const : a -> b -> a
const k _ = k

-- Functions are also curried; here we've curried the multiplication 
-- infix operator with a `2`
multiplyBy2 : number -> number
multiplyBy2 =
    (*) 2

-- If-expressions are used to branch on `Bool` values
absoluteValue : number -> number
absoluteValue number =
    if number < 0 then negate number else number

-- Records are used to hold values with named fields
book : { title : String, author : String, pages : Int }
book =
    { title = "Steppenwolf"
    , author = "Hesse"
    , pages = 237 
    }

-- Record access is done with `.`
title : String
title =
    book.title

-- Record access `.` can also be used as a function
author : String
author =
    .author book

-- We can create tagged unions with the `type` keyword.
-- The following value represents a binary tree.
type Tree a
    = Empty
    | Node a (Tree a) (Tree a)

-- It is possible to inspect these types with case-expressions.
depth : Tree a -> Int
depth tree =
    case tree of
        Empty -> 0
        Node _ left right ->
            1 + max (depth left) (depth right)

See also

References

  1. "Main.elm" (Opens in a new window). github.com/rtfeldman/elm-spa-example. Retrieved 30 June 2020.

External links

Haskell (Opens in a new window) programming

Programming languages (Opens in a new window)

Categories (Opens in a new window):

Gleam (programming language)

Tools

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

The topic of this article may not meet Wikipedia's general notability guideline (Opens in a new window). Please help to demonstrate the notability of the topic by citing reliable secondary sources (Opens in a new window) that are independent (Opens in a new window) of the topic and provide significant coverage of it beyond a mere trivial mention. If notability cannot be shown, the article is likely to be merged (Opens in a new window), redirected (Opens in a new window), or deleted (Opens in a new window).
Find sources: "Gleam" programming language (Opens in a new window) – news (Opens in a new window) · newspapers (Opens in a new window) · books (Opens in a new window) · scholar (Opens in a new window) · JSTOR (Opens in a new window) (March 2024) (Learn how and when to remove this message (Opens in a new window))

Gleam

(Opens in a new window)

Lucy, the starfish mascot for Gleam[1] (Opens in a new window)

Paradigm (Opens in a new window)Multi-paradigm (Opens in a new window): functional (Opens in a new window), concurrent (Opens in a new window)[2] (Opens in a new window)Designed by (Opens in a new window)Louis PilfoldDeveloper (Opens in a new window)Louis PilfoldFirst appearedJune 13, 2016; 8 years agoStable release (Opens in a new window)

1.10.0[3] (Opens in a new window) 

Edit this on Wikidata (Opens in a new window)

/ 14 April 2025

Typing discipline (Opens in a new window)Type-safe (Opens in a new window), static (Opens in a new window), inferred (Opens in a new window)[2] (Opens in a new window)Memory management (Opens in a new window)Garbage collected (Opens in a new window)Implementation languageRust (Opens in a new window)OS (Opens in a new window)FreeBSD (Opens in a new window), Linux (Opens in a new window), macOS (Opens in a new window), OpenBSD (Opens in a new window), Windows (Opens in a new window)[4] (Opens in a new window)License (Opens in a new window)Apache License 2.0 (Opens in a new window)[5] (Opens in a new window)Filename extensions (Opens in a new window).gleamWebsitegleam.run (Opens in a new window)Influenced by

[6] (Opens in a new window)

Gleam is a general-purpose (Opens in a new window), concurrent (Opens in a new window), functional (Opens in a new window) high-level (Opens in a new window) programming language (Opens in a new window) that compiles to Erlang (Opens in a new window) or JavaScript (Opens in a new window) source code.[2] (Opens in a new window)[7] (Opens in a new window)[8] (Opens in a new window)

Gleam is a statically-typed language,[9] (Opens in a new window) which is different from the most popular languages that run on Erlang’s virtual machine BEAM (Opens in a new window), Erlang (Opens in a new window) and Elixir (Opens in a new window). Gleam has its own type-safe implementation of OTP, Erlang's actor framework.[10] (Opens in a new window) Packages are provided using the Hex package manager, and an index for finding packages written for Gleam is available.[11] (Opens in a new window)

History

The first numbered version of Gleam was released on April 15, 2019.[12] (Opens in a new window) Compiling to JavaScript was introduced with version v0.16.[13] (Opens in a new window)

In 2023 the Erlang Ecosystem Foundation funded the creation of a course for learning Gleam on the learning platform Exercism (Opens in a new window).[14] (Opens in a new window)

Version v1.0.0 was released on March 4, 2024.[15] (Opens in a new window)

Features

Gleam includes the following features, many common to other functional programming languages:[8] (Opens in a new window)

Example

A "Hello, World!" (Opens in a new window) example:

import gleam/io

pub fn main() {
  io.println("hello, world!")
}

Gleam supports tail call (Opens in a new window) optimization:[16] (Opens in a new window)

pub fn factorial(x: Int) -> Int {
  // The public function calls the private tail recursive function
  factorial_loop(x, 1)
}

fn factorial_loop(x: Int, accumulator: Int) -> Int {
  case x {
    1 -> accumulator

    // The last thing this function does is call itself
    _ -> factorial_loop(x - 1, accumulator * x)
  }
}

Implementation

Gleam's toolchain is implemented in the Rust programming language (Opens in a new window).[17] (Opens in a new window) The toolchain is a single native binary executable which contains the compiler, build tool, package manager, source code formatter, and language server (Opens in a new window). A WebAssembly (Opens in a new window) binary containing the Gleam compiler is also available, enabling Gleam code to be compiled within a web browser.

References

  1. "gleam-lang/gleam" (Opens in a new window). Gleam. May 6, 2024. Retrieved May 6, 2024.

External links

Stub icon (Opens in a new window)

This programming-language (Opens in a new window)-related article is a stub (Opens in a new window). You can help Wikipedia by expanding it (Opens in a new window).

Categories (Opens in a new window):

Erlang (programming language)

Tools

Text

  • Small

    Standard

    Large

Width

  • Standard

    Wide

Color (beta)

  • Automatic

    Light

    Dark

From Wikipedia, the free encyclopedia

Erlang

(Opens in a new window)

Paradigms (Opens in a new window)Multi-paradigm (Opens in a new window): concurrent (Opens in a new window), functional (Opens in a new window)Designed by (Opens in a new window)

Developer (Opens in a new window)Ericsson (Opens in a new window)First appeared1986; 39 years agoStable release (Opens in a new window)

27.3.4[1] (Opens in a new window) 

Edit this on Wikidata (Opens in a new window)

/ 8 May 2025; 9 days ago

Typing disciplineDynamic (Opens in a new window), strong (Opens in a new window)License (Opens in a new window)Apache License 2.0 (Opens in a new window)Filename extensions (Opens in a new window).erl, .hrlWebsitewww.erlang.org (Opens in a new window)Major implementations (Opens in a new window)ErlangInfluenced byLisp (Opens in a new window), PLEX (Opens in a new window),[2] (Opens in a new window) Prolog (Opens in a new window), Smalltalk (Opens in a new window)InfluencedAkka (Opens in a new window), Clojure (Opens in a new window),[3] (Opens in a new window) Dart (Opens in a new window), Elixir (Opens in a new window), F# (Opens in a new window), Opa (Opens in a new window), Oz (Opens in a new window), Reia (Opens in a new window), Rust (Opens in a new window),[4] (Opens in a new window) Scala (Opens in a new window), Go (Opens in a new window)

Erlang (/ˈɜːrlæŋ/ (Opens in a new window) UR-lang (Opens in a new window)) is a general-purpose (Opens in a new window), concurrent (Opens in a new window), functional (Opens in a new window) high-level (Opens in a new window) programming language (Opens in a new window), and a garbage-collected (Opens in a new window) runtime system (Opens in a new window). The term Erlang is used interchangeably with Erlang/OTP, or Open Telecom Platform (Opens in a new window) (OTP), which consists of the Erlang runtime system (Opens in a new window), several ready-to-use components (OTP) mainly written in Erlang, and a set of design principles (Opens in a new window) for Erlang programs.[5] (Opens in a new window)

The Erlang runtime system (Opens in a new window) is designed for systems with these traits:

The Erlang programming language (Opens in a new window) has immutable (Opens in a new window) data, pattern matching (Opens in a new window), and functional programming (Opens in a new window).[7] (Opens in a new window) The sequential subset of the Erlang language supports eager evaluation (Opens in a new window), single assignment (Opens in a new window), and dynamic typing (Opens in a new window).

A normal Erlang application is built out of hundreds of small Erlang processes.

It was originally proprietary software (Opens in a new window) within Ericsson (Opens in a new window), developed by Joe Armstrong (Opens in a new window), Robert Virding, and Mike Williams in 1986,[8] (Opens in a new window) but was released as free and open-source software (Opens in a new window) in 1998.[9] (Opens in a new window)[10] (Opens in a new window) Erlang/OTP is supported and maintained by the Open Telecom Platform (OTP) product unit at Ericsson (Opens in a new window).

History

The name Erlang, attributed to Bjarne Däcker, has been presumed by those working on the telephony switches (for whom the language was designed) to be a reference to Danish mathematician and engineer Agner Krarup Erlang (Opens in a new window) and a syllabic abbreviation (Opens in a new window) of "Ericsson Language".[8] (Opens in a new window)[11] (Opens in a new window)[12] (Opens in a new window) Erlang was designed with the aim of improving the development of telephony applications.[13] (Opens in a new window) The initial version of Erlang was implemented in Prolog (Opens in a new window) and was influenced by the programming language PLEX (Opens in a new window) used in earlier Ericsson exchanges. By 1988 Erlang had proven that it was suitable for prototyping telephone exchanges, but the Prolog interpreter was far too slow. One group within Ericsson estimated that it would need to be 40 times faster to be suitable for production use. In 1992, work began on the BEAM (Opens in a new window) virtual machine (VM), which compiles Erlang to C using a mix of natively compiled code and threaded code (Opens in a new window) to strike a balance between performance and disk space.[14] (Opens in a new window) According to co-inventor Joe Armstrong, the language went from laboratory product to real applications following the collapse of the next-generation AXE telephone exchange (Opens in a new window) named AXE-N (Opens in a new window) in 1995. As a result, Erlang was chosen for the next Asynchronous Transfer Mode (Opens in a new window) (ATM) exchange AXD.[8] (Opens in a new window)

(Opens in a new window)
Robert Virding and Joe Armstrong, 2013

In February 1998, Ericsson Radio Systems banned the in-house use of Erlang for new products, citing a preference for non-proprietary languages.[15] (Opens in a new window) The ban caused Armstrong and others to make plans to leave Ericsson.[16] (Opens in a new window) In March 1998 Ericsson announced the AXD301 switch,[8] (Opens in a new window) containing over a million lines of Erlang and reported to achieve a high availability (Opens in a new window) of nine "9"s (Opens in a new window).[17] (Opens in a new window) In December 1998, the implementation of Erlang was open-sourced and most of the Erlang team resigned to form a new company, Bluetail AB.[8] (Opens in a new window) Ericsson eventually relaxed the ban and re-hired Armstrong in 2004.[16] (Opens in a new window)

In 2006, native symmetric multiprocessing (Opens in a new window) support was added to the runtime system and VM.[8] (Opens in a new window)

Processes

Erlang applications are built of very lightweight Erlang processes in the Erlang runtime system. Erlang processes can be seen as "living" objects (object-oriented programming (Opens in a new window)), with data encapsulation and message passing (Opens in a new window), but capable of changing behavior during runtime. The Erlang runtime system provides strict process isolation (Opens in a new window) between Erlang processes (this includes data and garbage collection, separated individually by each Erlang process) and transparent communication between processes (see Location transparency (Opens in a new window)) on different Erlang nodes (on different hosts).

Joe Armstrong, co-inventor of Erlang, summarized the principles of processes in his PhD (Opens in a new window) thesis (Opens in a new window):[18] (Opens in a new window)

  • Everything is a process.

  • Processes are strongly isolated.

  • Process creation and destruction is a lightweight operation.

  • Message passing is the only way for processes to interact.

  • Processes have unique names.

  • If you know the name of a process you can send it a message.

  • Processes share no resources.

  • Error handling is non-local.

  • Processes do what they are supposed to do or fail.

Joe Armstrong remarked in an interview with Rackspace in 2013: "If Java (Opens in a new window) is 'write once, run anywhere (Opens in a new window)', then Erlang is 'write once, run forever'."[19] (Opens in a new window)

Usage

In 2014, Ericsson (Opens in a new window) reported Erlang was being used in its support nodes, and in GPRS (Opens in a new window), 3G (Opens in a new window) and LTE (Opens in a new window) mobile networks worldwide and also by Nortel (Opens in a new window) and Deutsche Telekom (Opens in a new window).[20] (Opens in a new window)

Erlang is used in RabbitMQ (Opens in a new window). As Tim Bray (Opens in a new window), director of Web Technologies at Sun Microsystems (Opens in a new window), expressed in his keynote at O'Reilly Open Source Convention (Opens in a new window) (OSCON) in July 2008:

If somebody came to me and wanted to pay me a lot of money to build a large scale message handling system that really had to be up all the time, could never afford to go down for years at a time, I would unhesitatingly choose Erlang to build it in.

Erlang is the programming language used to code WhatsApp (Opens in a new window).[21] (Opens in a new window)

It is also the language of choice for Ejabberd (Opens in a new window) – an XMPP (Opens in a new window) messaging server.

Elixir (Opens in a new window) is a programming language that compiles into BEAM byte code (via Erlang Abstract Format).[22] (Opens in a new window)

Since being released as open source, Erlang has been spreading beyond telecoms, establishing itself in other vertical markets such as FinTech, gaming, healthcare, automotive, Internet of Things and blockchain. Apart from WhatsApp, there are other companies listed as Erlang's success stories, including Vocalink (Opens in a new window) (a MasterCard company), Goldman Sachs (Opens in a new window), Nintendo (Opens in a new window), AdRoll, Grindr (Opens in a new window), BT Mobile (Opens in a new window), Samsung (Opens in a new window), OpenX (Opens in a new window), and SITA (Opens in a new window).[23] (Opens in a new window)[24] (Opens in a new window)

Functional programming examples

Factorial

A factorial (Opens in a new window) algorithm implemented in Erlang:

-module(fact). % This is the file 'fact.erl', the module and the filename must match
-export([fac/1]). % This exports the function 'fac' of arity 1 (1 parameter, no type, no name)

fac(0) -> 1; % If 0, then return 1, otherwise (note the semicolon ; meaning 'else')
fac(N) when N > 0, is_integer(N) -> N * fac(N-1).
% Recursively determine, then return the result
% (note the period . meaning 'endif' or 'function end')
%% This function will crash if anything other than a nonnegative integer is given.
%% It illustrates the "Let it crash" philosophy of Erlang.

Fibonacci sequence

A tail recursive algorithm that produces the Fibonacci sequence (Opens in a new window):

%% The module declaration must match the file name "series.erl" 
-module(series).

%% The export statement contains a list of all those functions that form
%% the module's public API.  In this case, this module exposes a single
%% function called fib that takes 1 argument (I.E. has an arity of 1)
%% The general syntax for -export is a list containing the name and
%% arity of each public function
-export([fib/1]).

%% ---------------------------------------------------------------------
%% Public API
%% ---------------------------------------------------------------------

%% Handle cases in which fib/1 receives specific values
%% The order in which these function signatures are declared is a vital
%% part of this module's functionality

%% If fib/1 receives a negative number, then return the atom err_neg_val
%% Normally, such defensive coding is discouraged due to Erlang's 'Let
%% it Crash' philosophy, but here the result would be an infinite loop.
fib(N) when N < 0 -> err_neg_val;

%% If fib/1 is passed precisely the integer 0, then return 0
fib(0) -> 0;

%% For all other values, call the private function fib_int/3 to perform
%% the calculation
fib(N) -> fib_int(N-1, 0, 1).

%% ---------------------------------------------------------------------
%% Private API
%% ---------------------------------------------------------------------

%% If fib_int/3 receives 0 as its first argument, then we're done, so
%% return the value in argument B. The second argument is denoted _ to
%% disregard its value.
fib_int(0, _, B) -> B;

%% For all other argument combinations, recursively call fib_int/3
%% where each call does the following:
%%  - decrement counter N
%%  - pass the third argument as the new second argument
%%  - pass the sum of the second and third arguments as the new
%%    third argument
fib_int(N, A, B) -> fib_int(N-1, B, A+B).

Omitting the comments gives a much shorter program.

-module(series).
-export([fib/1]).

fib(N) when N < 0 -> err_neg_val;
fib(0) -> 0;
fib(N) -> fib_int(N-1, 0, 1).

fib_int(0, _, B) -> B;
fib_int(N, A, B) -> fib_int(N-1, B, A+B).

Quicksort

Quicksort (Opens in a new window) in Erlang, using list comprehension (Opens in a new window):[25] (Opens in a new window)

%% qsort:qsort(List)
%% Sort a list of items
-module(qsort).     % This is the file 'qsort.erl'
-export([qsort/1]). % A function 'qsort' with 1 parameter is exported (no type, no name)

qsort([]) -> []; % If the list [] is empty, return an empty list (nothing to sort)
qsort([Pivot|Rest]) ->
    % Compose recursively a list with 'Front' for all elements that should be before 'Pivot'
    % then 'Pivot' then 'Back' for all elements that should be after 'Pivot'
    qsort([Front || Front <- Rest, Front < Pivot]) ++ 
    [Pivot] ++
    qsort([Back || Back <- Rest, Back >= Pivot]).

The above example recursively invokes the function qsort until nothing remains to be sorted. The expression [Front || Front <- Rest, Front < Pivot] is a list comprehension (Opens in a new window), meaning "Construct a list of elements Front such that Front is a member of Rest, and Front is less than Pivot." ++ is the list concatenation operator.

A comparison function can be used for more complicated structures for the sake of readability.

The following code would sort lists according to length:

% This is file 'listsort.erl' (the compiler is made this way)
-module(listsort).
% Export 'by_length' with 1 parameter (don't care about the type and name)
-export([by_length/1]).

by_length(Lists) -> % Use 'qsort/2' and provides an anonymous function as a parameter
   qsort(Lists, fun(A,B) -> length(A) < length(B) end).

qsort([], _)-> []; % If list is empty, return an empty list (ignore the second parameter)
qsort([Pivot|Rest], Smaller) ->
    % Partition list with 'Smaller' elements in front of 'Pivot' and not-'Smaller' elements
    % after 'Pivot' and sort the sublists.
    qsort([X || X <- Rest, Smaller(X,Pivot)], Smaller)
    ++ [Pivot] ++
    qsort([Y || Y <- Rest, not(Smaller(Y, Pivot))], Smaller).

A Pivot is taken from the first parameter given to qsort() and the rest of Lists is named Rest. Note that the expression

[X || X <- Rest, Smaller(X,Pivot)]

is no different in form from

[Front || Front <- Rest, Front < Pivot]

(in the previous example) except for the use of a comparison function in the last part, saying "Construct a list of elements X such that X is a member of Rest, and Smaller is true", with Smaller being defined earlier as

fun(A,B) -> length(A) < length(B) end

The anonymous function (Opens in a new window) is named Smaller in the parameter list of the second definition of qsort so that it can be referenced by that name within that function. It is not named in the first definition of qsort, which deals with the base case of an empty list and thus has no need of this function, let alone a name for it.

Data types

Erlang has eight primitive data types (Opens in a new window):

Integers

Integers are written as sequences of decimal digits, for example, 12, 12375 and -23427 are integers. Integer arithmetic is exact and only limited by available memory on the machine. (This is called arbitrary-precision arithmetic (Opens in a new window).)

Atoms

Atoms are used within a program to denote distinguished values. They are written as strings of consecutive alphanumeric characters, the first character being lowercase. Atoms can contain any character if they are enclosed within single quotes and an escape convention exists which allows any character to be used within an atom. Atoms are never garbage collected and should be used with caution, especially if using dynamic atom generation.

Floats

Floating point numbers use the IEEE 754 64-bit representation (Opens in a new window).

References

References are globally unique symbols whose only property is that they can be compared for equality. They are created by evaluating the Erlang primitive make_ref().

Binaries

A binary is a sequence of bytes. Binaries provide a space-efficient way of storing binary data. Erlang primitives exist for composing and decomposing binaries and for efficient input/output of binaries.

Pids

Pid is short for process identifier – a Pid is created by the Erlang primitive spawn(...) Pids are references to Erlang processes.

Ports

Ports are used to communicate with the external world. Ports are created with the built-in function open_port. Messages can be sent to and received from ports, but these messages must obey the so-called "port protocol."

Funs

Funs are function closures (Opens in a new window). Funs are created by expressions of the form: fun(...) -> ... end.

And three compound data types:

Tuples

Tuples are containers for a fixed number of Erlang data types. The syntax {D1,D2,...,Dn} denotes a tuple whose arguments are D1, D2, ... Dn. The arguments can be primitive data types or compound data types. Any element of a tuple can be accessed in constant time.

Lists

Lists are containers for a variable number of Erlang data types. The syntax [Dh|Dt] denotes a list whose first element is Dh, and whose remaining elements are the list Dt. The syntax [] denotes an empty list. The syntax [D1,D2,..,Dn] is short for [D1|[D2|..|[Dn|[]]]]. The first element of a list can be accessed in constant time. The first element of a list is called the head of the list. The remainder of a list when its head has been removed is called the tail of the list.

Maps

Maps contain a variable number of key-value associations. The syntax is#{Key1=>Value1,...,KeyN=>ValueN}.

Two forms of syntactic sugar (Opens in a new window) are provided:

Strings

Strings are written as doubly quoted lists of characters. This is syntactic sugar for a list of the integer Unicode (Opens in a new window) code points for the characters in the string. Thus, for example, the string "cat" is shorthand for [99,97,116].[26] (Opens in a new window)

Records

Records provide a convenient way for associating a tag with each of the elements in a tuple. This allows one to refer to an element of a tuple by name and not by position. A pre-compiler takes the record definition and replaces it with the appropriate tuple reference.

Erlang has no method to define classes, although there are external libraries (Opens in a new window) available.[27] (Opens in a new window)

"Let it crash" coding style

Erlang is designed with a mechanism that makes it easy for external processes to monitor for crashes (or hardware failures), rather than an in-process mechanism like exception handling (Opens in a new window) used in many other programming languages. Crashes are reported like other messages, which is the only way processes can communicate with each other,[28] (Opens in a new window) and subprocesses can be spawned cheaply (see below (Opens in a new window)). The "let it crash" philosophy prefers that a process be completely restarted rather than trying to recover from a serious failure.[29] (Opens in a new window) Though it still requires handling of errors, this philosophy results in less code devoted to defensive programming (Opens in a new window) where error-handling code is highly contextual and specific.[28] (Opens in a new window)

Supervisor trees

A typical Erlang application is written in the form of a supervisor tree. This architecture is based on a hierarchy of processes in which the top level process is known as a "supervisor". The supervisor then spawns multiple child processes that act either as workers or more, lower level supervisors. Such hierarchies can exist to arbitrary depths and have proven to provide a highly scalable and fault-tolerant environment within which application functionality can be implemented.

Within a supervisor tree, all supervisor processes are responsible for managing the lifecycle of their child processes, and this includes handling situations in which those child processes crash. Any process can become a supervisor by first spawning a child process, then calling erlang:monitor/2 on that process. If the monitored process then crashes, the supervisor will receive a message containing a tuple whose first member is the atom 'DOWN'. The supervisor is responsible firstly for listening for such messages and for taking the appropriate action to correct the error condition.

Concurrency and distribution orientation

Erlang's main strength is support for concurrency (Opens in a new window). It has a small but powerful set of primitives to create processes and communicate among them. Erlang is conceptually similar to the language occam (Opens in a new window), though it recasts the ideas of communicating sequential processes (Opens in a new window) (CSP) in a functional framework and uses asynchronous message passing.[30] (Opens in a new window) Processes are the primary means to structure an Erlang application. They are neither operating system (Opens in a new window) processes (Opens in a new window) nor threads (Opens in a new window), but lightweight processes (Opens in a new window) that are scheduled by BEAM. Like operating system processes (but unlike operating system threads), they share no state with each other. The estimated minimal overhead for each is 300 words (Opens in a new window).[31] (Opens in a new window) Thus, many processes can be created without degrading performance. In 2005, a benchmark with 20 million processes was successfully performed with 64-bit Erlang on a machine with 16 GB random-access memory (Opens in a new window) (RAM; total 800 bytes/process).[32] (Opens in a new window) Erlang has supported symmetric multiprocessing (Opens in a new window) since release R11B of May 2006.

While threads (Opens in a new window) need external library support in most languages, Erlang provides language-level features to create and manage processes with the goal of simplifying concurrent programming. Though all concurrency is explicit in Erlang, processes communicate using message passing (Opens in a new window) instead of shared variables, which removes the need for explicit locks (Opens in a new window) (a locking scheme is still used internally by the VM).[33] (Opens in a new window)

Inter-process communication (Opens in a new window) works via a shared-nothing (Opens in a new window) asynchronous (Opens in a new window) message passing (Opens in a new window) system: every process has a "mailbox", a queue (Opens in a new window) of messages that have been sent by other processes and not yet consumed. A process uses the receive primitive to retrieve messages that match desired patterns. A message-handling routine tests messages in turn against each pattern, until one of them matches. When the message is consumed and removed from the mailbox the process resumes execution. A message may comprise any Erlang structure, including primitives (integers, floats, characters, atoms), tuples, lists, and functions.

The code example below shows the built-in support for distributed processes:

 % Create a process and invoke the function web:start_server(Port, MaxConnections)
 ServerProcess = spawn(web, start_server, [Port, MaxConnections]),

 % Create a remote process and invoke the function
 % web:start_server(Port, MaxConnections) on machine RemoteNode
 RemoteProcess = spawn(RemoteNode, web, start_server, [Port, MaxConnections]),

 % Send a message to ServerProcess (asynchronously). The message consists of a tuple
 % with the atom "pause" and the number "10".
 ServerProcess ! {pause, 10},

 % Receive messages sent to this process
 receive
         a_message -> do_something;
         {data, DataContent} -> handle(DataContent);
         {hello, Text} -> io:format("Got hello message: ~s", [Text]);
         {goodbye, Text} -> io:format("Got goodbye message: ~s", [Text])
 end.

As the example shows, processes may be created on remote nodes, and communication with them is transparent in the sense that communication with remote processes works exactly as communication with local processes.

Concurrency supports the primary method of error-handling in Erlang. When a process crashes, it neatly exits and sends a message to the controlling process which can then take action, such as starting a new process that takes over the old process's task.[34] (Opens in a new window)[35] (Opens in a new window)

Implementation

The official reference implementation of Erlang uses BEAM (Opens in a new window).[36] (Opens in a new window) BEAM is included in the official distribution of Erlang, called Erlang/OTP. BEAM executes bytecode (Opens in a new window) which is converted to threaded code (Opens in a new window) at load time. It also includes a native code compiler on most platforms, developed by the High Performance Erlang Project (HiPE) at Uppsala University (Opens in a new window). Since October 2001 the HiPE system is fully integrated in Ericsson's Open Source Erlang/OTP system.[37] (Opens in a new window) It also supports interpreting, directly from source code via abstract syntax tree (Opens in a new window), via script as of R11B-5 release of Erlang.

Hot code loading and modules

Erlang supports language-level Dynamic Software Updating (Opens in a new window). To implement this, code is loaded and managed as "module" units; the module is a compilation unit (Opens in a new window). The system can keep two versions of a module in memory at the same time, and processes can concurrently run code from each. The versions are referred to as the "new" and the "old" version. A process will not move into the new version until it makes an external call to its module.

An example of the mechanism of hot code loading:

  %% A process whose only job is to keep a counter.
  %% First version
  -module(counter).
  -export([start/0, codeswitch/1]).

  start() -> loop(0).

  loop(Sum) ->
    receive
       {increment, Count} ->
          loop(Sum+Count);
       {counter, Pid} ->
          Pid ! {counter, Sum},
          loop(Sum);
       code_switch ->
          ?MODULE:codeswitch(Sum)
          % Force the use of 'codeswitch/1' from the latest MODULE version
    end.

  codeswitch(Sum) -> loop(Sum).

For the second version, we add the possibility to reset the count to zero.

  %% Second version
  -module(counter).
  -export([start/0, codeswitch/1]).

  start() -> loop(0).

  loop(Sum) ->
    receive
       {increment, Count} ->
          loop(Sum+Count);
       reset ->
          loop(0);
       {counter, Pid} ->
          Pid ! {counter, Sum},
          loop(Sum);
       code_switch ->
          ?MODULE:codeswitch(Sum)
    end.

  codeswitch(Sum) -> loop(Sum).

Only when receiving a message consisting of the atom code_switch will the loop execute an external call to codeswitch/1 (?MODULE is a preprocessor macro for the current module). If there is a new version of the counter module in memory, then its codeswitch/1 function will be called. The practice of having a specific entry-point into a new version allows the programmer to transform state to what is needed in the newer version. In the example, the state is kept as an integer.

In practice, systems are built up using design principles from the Open Telecom Platform, which leads to more code upgradable designs. Successful hot code loading is exacting. Code must be written with care to make use of Erlang's facilities.

Distribution

In 1998, Ericsson released Erlang as free and open-source software (Opens in a new window) to ensure its independence from a single vendor and to increase awareness of the language. Erlang, together with libraries and the real-time distributed database Mnesia (Opens in a new window), forms the OTP collection of libraries. Ericsson and a few other companies support Erlang commercially.

Since the open source release, Erlang has been used by several firms worldwide, including Nortel (Opens in a new window) and Deutsche Telekom (Opens in a new window).[38] (Opens in a new window) Although Erlang was designed to fill a niche and has remained an obscure language for most of its existence, its popularity is growing due to demand for concurrent services.[39] (Opens in a new window)[40] (Opens in a new window) Erlang has found some use in fielding massively multiplayer online role-playing game (Opens in a new window) (MMORPG) servers.[41] (Opens in a new window)

See also

References

  1. Clarke, Gavin (5 February 2011). "Battlestar Galactica vets needed for online roleplay" (Opens in a new window). Music and Media. The Reg (Opens in a new window). Retrieved 8 February 2011.

Further reading

External links

(Opens in a new window)

Wikimedia Commons has media related to Erlang (programming language) (Opens in a new window).

(Opens in a new window)

Wikibooks has a book on the topic of: Erlang Programming (Opens in a new window)

0 comments

Would you like to be the first to write a comment?
Become a member of Jie's stick figures and start the conversation.
Become a member